You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ResourceHandler.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.render.ps;
  19. import java.awt.geom.Dimension2D;
  20. import java.awt.geom.Rectangle2D;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.OutputStream;
  24. import java.util.Iterator;
  25. import java.util.Map;
  26. import java.util.Set;
  27. import org.apache.commons.logging.Log;
  28. import org.apache.commons.logging.LogFactory;
  29. import org.apache.xmlgraphics.image.loader.ImageException;
  30. import org.apache.xmlgraphics.image.loader.ImageFlavor;
  31. import org.apache.xmlgraphics.image.loader.ImageInfo;
  32. import org.apache.xmlgraphics.image.loader.ImageManager;
  33. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  34. import org.apache.xmlgraphics.image.loader.util.ImageUtil;
  35. import org.apache.xmlgraphics.ps.DSCConstants;
  36. import org.apache.xmlgraphics.ps.FormGenerator;
  37. import org.apache.xmlgraphics.ps.PSGenerator;
  38. import org.apache.xmlgraphics.ps.PSResource;
  39. import org.apache.xmlgraphics.ps.dsc.DSCException;
  40. import org.apache.xmlgraphics.ps.dsc.DSCFilter;
  41. import org.apache.xmlgraphics.ps.dsc.DSCListener;
  42. import org.apache.xmlgraphics.ps.dsc.DSCParser;
  43. import org.apache.xmlgraphics.ps.dsc.DSCParserConstants;
  44. import org.apache.xmlgraphics.ps.dsc.DefaultNestedDocumentHandler;
  45. import org.apache.xmlgraphics.ps.dsc.ResourceTracker;
  46. import org.apache.xmlgraphics.ps.dsc.events.DSCComment;
  47. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentBoundingBox;
  48. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentDocumentNeededResources;
  49. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentDocumentSuppliedResources;
  50. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentHiResBoundingBox;
  51. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentIncludeResource;
  52. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentLanguageLevel;
  53. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPage;
  54. import org.apache.xmlgraphics.ps.dsc.events.DSCCommentPages;
  55. import org.apache.xmlgraphics.ps.dsc.events.DSCEvent;
  56. import org.apache.xmlgraphics.ps.dsc.events.DSCHeaderComment;
  57. import org.apache.xmlgraphics.ps.dsc.events.PostScriptComment;
  58. import org.apache.xmlgraphics.ps.dsc.events.PostScriptLine;
  59. import org.apache.xmlgraphics.ps.dsc.tools.DSCTools;
  60. import org.apache.fop.ResourceEventProducer;
  61. import org.apache.fop.apps.FOUserAgent;
  62. import org.apache.fop.fonts.FontInfo;
  63. import org.apache.fop.render.ImageHandler;
  64. import org.apache.fop.render.ImageHandlerRegistry;
  65. /**
  66. * This class is used when two-pass production is used to generate the PostScript file (setting
  67. * "optimize-resources"). It uses the DSC parser from XML Graphics Commons to go over the
  68. * temporary file generated by the PSRenderer and adds all used fonts and images as resources
  69. * to the PostScript file.
  70. */
  71. public class ResourceHandler implements DSCParserConstants, PSSupportedFlavors {
  72. /** logging instance */
  73. private static Log log = LogFactory.getLog(ResourceHandler.class);
  74. private FOUserAgent userAgent;
  75. private FontInfo fontInfo;
  76. private ResourceTracker resTracker;
  77. //key: URI, values PSImageFormResource
  78. private Map globalFormResources = new java.util.HashMap();
  79. //key: PSResource, values PSImageFormResource
  80. private Map inlineFormResources = new java.util.HashMap();
  81. /**
  82. * Main constructor.
  83. * @param userAgent the FO user agent
  84. * @param fontInfo the font information
  85. * @param resTracker the resource tracker to use
  86. * @param formResources Contains all forms used by this document (maintained by PSRenderer)
  87. */
  88. public ResourceHandler(FOUserAgent userAgent, FontInfo fontInfo,
  89. ResourceTracker resTracker, Map formResources) {
  90. this.userAgent = userAgent;
  91. this.fontInfo = fontInfo;
  92. this.resTracker = resTracker;
  93. determineInlineForms(formResources);
  94. }
  95. /**
  96. * This method splits up the form resources map into two. One for global forms which
  97. * have been referenced more than once, and one for inline forms which have only been
  98. * used once. The latter is to conserve memory in the PostScript interpreter.
  99. * @param formResources the original form resources map
  100. */
  101. private void determineInlineForms(Map formResources) {
  102. if (formResources == null) {
  103. return;
  104. }
  105. Iterator iter = formResources.entrySet().iterator();
  106. while (iter.hasNext()) {
  107. Map.Entry entry = (Map.Entry)iter.next();
  108. PSResource res = (PSResource)entry.getValue();
  109. long count = resTracker.getUsageCount(res);
  110. if (count > 1) {
  111. //Make global form
  112. this.globalFormResources.put(entry.getKey(), res);
  113. } else {
  114. //Inline resource
  115. this.inlineFormResources.put(res, res);
  116. resTracker.declareInlined(res);
  117. }
  118. }
  119. }
  120. /**
  121. * Rewrites the temporary PostScript file generated by PSRenderer adding all needed resources
  122. * (fonts and images).
  123. * @param in the InputStream for the temporary PostScript file
  124. * @param out the OutputStream to write the finished file to
  125. * @param pageCount the number of pages (given here because PSRenderer writes an "(atend)")
  126. * @param documentBoundingBox the document's bounding box
  127. * (given here because PSRenderer writes an "(atend)")
  128. * @throws DSCException If there's an error in the DSC structure of the PS file
  129. * @throws IOException In case of an I/O error
  130. */
  131. public void process(InputStream in, OutputStream out,
  132. int pageCount, Rectangle2D documentBoundingBox)
  133. throws DSCException, IOException {
  134. DSCParser parser = new DSCParser(in);
  135. PSGenerator gen = new PSGenerator(out);
  136. parser.addListener(new DefaultNestedDocumentHandler(gen));
  137. parser.addListener(new IncludeResourceListener(gen));
  138. //Skip DSC header
  139. DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser);
  140. header.generate(gen);
  141. parser.setFilter(new DSCFilter() {
  142. private final Set filtered = new java.util.HashSet();
  143. {
  144. //We rewrite those as part of the processing
  145. filtered.add(DSCConstants.PAGES);
  146. filtered.add(DSCConstants.BBOX);
  147. filtered.add(DSCConstants.HIRES_BBOX);
  148. filtered.add(DSCConstants.DOCUMENT_NEEDED_RESOURCES);
  149. filtered.add(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES);
  150. }
  151. public boolean accept(DSCEvent event) {
  152. if (event.isDSCComment()) {
  153. //Filter %%Pages which we add manually from a parameter
  154. return !(filtered.contains(event.asDSCComment().getName()));
  155. } else {
  156. return true;
  157. }
  158. }
  159. });
  160. //Get PostScript language level (may be missing)
  161. while (true) {
  162. DSCEvent event = parser.nextEvent();
  163. if (event == null) {
  164. reportInvalidDSC();
  165. }
  166. if (DSCTools.headerCommentsEndHere(event)) {
  167. //Set number of pages
  168. DSCCommentPages pages = new DSCCommentPages(pageCount);
  169. pages.generate(gen);
  170. new DSCCommentBoundingBox(documentBoundingBox).generate(gen);
  171. new DSCCommentHiResBoundingBox(documentBoundingBox).generate(gen);
  172. PSFontUtils.determineSuppliedFonts(resTracker, fontInfo, fontInfo.getUsedFonts());
  173. registerSuppliedForms(resTracker, globalFormResources);
  174. //Supplied Resources
  175. DSCCommentDocumentSuppliedResources supplied
  176. = new DSCCommentDocumentSuppliedResources(
  177. resTracker.getDocumentSuppliedResources());
  178. supplied.generate(gen);
  179. //Needed Resources
  180. DSCCommentDocumentNeededResources needed
  181. = new DSCCommentDocumentNeededResources(
  182. resTracker.getDocumentNeededResources());
  183. needed.generate(gen);
  184. //Write original comment that ends the header comments
  185. event.generate(gen);
  186. break;
  187. }
  188. if (event.isDSCComment()) {
  189. DSCComment comment = event.asDSCComment();
  190. if (DSCConstants.LANGUAGE_LEVEL.equals(comment.getName())) {
  191. DSCCommentLanguageLevel level = (DSCCommentLanguageLevel)comment;
  192. gen.setPSLevel(level.getLanguageLevel());
  193. }
  194. }
  195. event.generate(gen);
  196. }
  197. //Skip to the FOPFontSetup
  198. PostScriptComment fontSetupPlaceholder = parser.nextPSComment("FOPFontSetup", gen);
  199. if (fontSetupPlaceholder == null) {
  200. throw new DSCException("Didn't find %FOPFontSetup comment in stream");
  201. }
  202. PSFontUtils.writeFontDict(gen, fontInfo, fontInfo.getUsedFonts());
  203. generateForms(globalFormResources, gen);
  204. //Skip the prolog and to the first page
  205. DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen);
  206. if (pageOrTrailer == null) {
  207. throw new DSCException("Page expected, but none found");
  208. }
  209. //Process individual pages (and skip as necessary)
  210. while (true) {
  211. DSCCommentPage page = (DSCCommentPage)pageOrTrailer;
  212. page.generate(gen);
  213. pageOrTrailer = DSCTools.nextPageOrTrailer(parser, gen);
  214. if (pageOrTrailer == null) {
  215. reportInvalidDSC();
  216. } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) {
  217. pageOrTrailer.generate(gen);
  218. break;
  219. }
  220. }
  221. //Write the rest
  222. while (parser.hasNext()) {
  223. DSCEvent event = parser.nextEvent();
  224. event.generate(gen);
  225. }
  226. gen.flush();
  227. }
  228. private static void reportInvalidDSC() throws DSCException {
  229. throw new DSCException("File is not DSC-compliant: Unexpected end of file");
  230. }
  231. private static void registerSuppliedForms(ResourceTracker resTracker, Map formResources)
  232. throws IOException {
  233. if (formResources == null) {
  234. return;
  235. }
  236. Iterator iter = formResources.values().iterator();
  237. while (iter.hasNext()) {
  238. PSImageFormResource form = (PSImageFormResource)iter.next();
  239. resTracker.registerSuppliedResource(form);
  240. }
  241. }
  242. private void generateForms(Map formResources, PSGenerator gen) throws IOException {
  243. if (formResources == null) {
  244. return;
  245. }
  246. Iterator iter = formResources.values().iterator();
  247. while (iter.hasNext()) {
  248. PSImageFormResource form = (PSImageFormResource)iter.next();
  249. generateFormForImage(gen, form);
  250. }
  251. }
  252. private void generateFormForImage(PSGenerator gen, PSImageFormResource form)
  253. throws IOException {
  254. final String uri = form.getImageUri();
  255. ImageManager manager = userAgent.getFactory().getImageManager();
  256. ImageInfo info = null;
  257. try {
  258. ImageSessionContext sessionContext = userAgent.getImageSessionContext();
  259. info = manager.getImageInfo(uri, sessionContext);
  260. //Create a rendering context for form creation
  261. PSRenderingContext formContext = new PSRenderingContext(
  262. userAgent, gen, fontInfo, true);
  263. ImageFlavor[] flavors;
  264. ImageHandlerRegistry imageHandlerRegistry
  265. = userAgent.getFactory().getImageHandlerRegistry();
  266. flavors = imageHandlerRegistry.getSupportedFlavors(formContext);
  267. Map hints = ImageUtil.getDefaultHints(sessionContext);
  268. org.apache.xmlgraphics.image.loader.Image img = manager.getImage(
  269. info, flavors, hints, sessionContext);
  270. ImageHandler basicHandler = imageHandlerRegistry.getHandler(formContext, img);
  271. if (basicHandler == null) {
  272. throw new UnsupportedOperationException(
  273. "No ImageHandler available for image: "
  274. + img.getInfo() + " (" + img.getClass().getName() + ")");
  275. }
  276. if (!(basicHandler instanceof PSImageHandler)) {
  277. throw new IllegalStateException(
  278. "ImageHandler implementation doesn't behave properly."
  279. + " It should have returned false in isCompatible(). Class: "
  280. + basicHandler.getClass().getName());
  281. }
  282. PSImageHandler handler = (PSImageHandler)basicHandler;
  283. if (log.isTraceEnabled()) {
  284. log.trace("Using ImageHandler: " + handler.getClass().getName());
  285. }
  286. handler.generateForm(formContext, img, form);
  287. } catch (ImageException ie) {
  288. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  289. userAgent.getEventBroadcaster());
  290. eventProducer.imageError(resTracker, (info != null ? info.toString() : uri),
  291. ie, null);
  292. }
  293. }
  294. private static FormGenerator createMissingForm(String formName, final Dimension2D dimensions) {
  295. FormGenerator formGen = new FormGenerator(formName, null, dimensions) {
  296. protected void generatePaintProc(PSGenerator gen) throws IOException {
  297. gen.writeln("0 setgray");
  298. gen.writeln("0 setlinewidth");
  299. String w = gen.formatDouble(dimensions.getWidth());
  300. String h = gen.formatDouble(dimensions.getHeight());
  301. gen.writeln(w + " " + h + " scale");
  302. gen.writeln("0 0 1 1 rectstroke");
  303. gen.writeln("newpath");
  304. gen.writeln("0 0 moveto");
  305. gen.writeln("1 1 lineto");
  306. gen.writeln("stroke");
  307. gen.writeln("newpath");
  308. gen.writeln("0 1 moveto");
  309. gen.writeln("1 0 lineto");
  310. gen.writeln("stroke");
  311. }
  312. };
  313. return formGen;
  314. }
  315. private class IncludeResourceListener implements DSCListener {
  316. private PSGenerator gen;
  317. public IncludeResourceListener(PSGenerator gen) {
  318. this.gen = gen;
  319. }
  320. /** {@inheritDoc} */
  321. public void processEvent(DSCEvent event, DSCParser parser)
  322. throws IOException, DSCException {
  323. if (event.isDSCComment() && event instanceof DSCCommentIncludeResource) {
  324. DSCCommentIncludeResource include = (DSCCommentIncludeResource)event;
  325. PSResource res = include.getResource();
  326. if (res.getType().equals(PSResource.TYPE_FORM)) {
  327. if (inlineFormResources.containsValue(res)) {
  328. PSImageFormResource form = (PSImageFormResource)
  329. inlineFormResources.get(res);
  330. //Create an inline form
  331. //Wrap in save/restore pair to release memory
  332. gen.writeln("save");
  333. generateFormForImage(gen, form);
  334. boolean execformFound = false;
  335. DSCEvent next = parser.nextEvent();
  336. if (next.isLine()) {
  337. PostScriptLine line = next.asLine();
  338. if (line.getLine().endsWith(" execform")) {
  339. line.generate(gen);
  340. execformFound = true;
  341. }
  342. }
  343. if (!execformFound) {
  344. throw new IOException(
  345. "Expected a PostScript line in the form: <form> execform");
  346. }
  347. gen.writeln("restore");
  348. } else {
  349. //Do nothing
  350. }
  351. parser.next();
  352. }
  353. }
  354. }
  355. }
  356. }