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.

FOUserAgent.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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.apps;
  19. // Java
  20. import java.io.File;
  21. import java.util.Date;
  22. import java.util.Map;
  23. import javax.xml.transform.Source;
  24. import javax.xml.transform.TransformerException;
  25. import javax.xml.transform.URIResolver;
  26. import org.apache.commons.logging.Log;
  27. import org.apache.commons.logging.LogFactory;
  28. import org.apache.xmlgraphics.image.loader.ImageContext;
  29. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  30. import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext;
  31. import org.apache.fop.Version;
  32. import org.apache.fop.events.DefaultEventBroadcaster;
  33. import org.apache.fop.events.Event;
  34. import org.apache.fop.events.EventBroadcaster;
  35. import org.apache.fop.events.EventListener;
  36. import org.apache.fop.events.FOPEventListenerProxy;
  37. import org.apache.fop.events.LoggingEventListener;
  38. import org.apache.fop.fo.FOEventHandler;
  39. import org.apache.fop.render.Renderer;
  40. import org.apache.fop.render.RendererFactory;
  41. import org.apache.fop.render.XMLHandlerRegistry;
  42. import org.apache.fop.render.intermediate.IFDocumentHandler;
  43. /**
  44. * This is the user agent for FOP.
  45. * It is the entity through which you can interact with the XSL-FO processing and is
  46. * used by the processing to obtain user configurable options.
  47. * <p>
  48. * Renderer specific extensions (that do not produce normal areas on
  49. * the output) will be done like so:
  50. * <br>
  51. * The extension will create an area, custom if necessary
  52. * <br>
  53. * this area will be added to the user agent with a key
  54. * <br>
  55. * the renderer will know keys for particular extensions
  56. * <br>
  57. * eg. bookmarks will be held in a special hierarchical area representing
  58. * the title and bookmark structure
  59. * <br>
  60. * These areas may contain resolvable areas that will be processed
  61. * with other resolvable areas
  62. */
  63. public class FOUserAgent {
  64. /** Defines the default target resolution (72dpi) for FOP */
  65. public static final float DEFAULT_TARGET_RESOLUTION
  66. = FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION;
  67. private static Log log = LogFactory.getLog("FOP");
  68. private FopFactory factory;
  69. /**
  70. * The base URL for all URL resolutions, especially for
  71. * external-graphics.
  72. */
  73. private String base = null;
  74. /** The base URL for all font URL resolutions. */
  75. private String fontBase = null;
  76. /** A user settable URI Resolver */
  77. private URIResolver uriResolver = null;
  78. private float targetResolution = FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION;
  79. private Map rendererOptions = new java.util.HashMap();
  80. private File outputFile = null;
  81. private IFDocumentHandler documentHandlerOverride = null;
  82. private Renderer rendererOverride = null;
  83. private FOEventHandler foEventHandlerOverride = null;
  84. private boolean locatorEnabled = true; // true by default (for error messages).
  85. private boolean conserveMemoryPolicy = false;
  86. private EventBroadcaster eventBroadcaster = new FOPEventBroadcaster();
  87. /** Producer: Metadata element for the system/software that produces
  88. * the document. (Some renderers can store this in the document.)
  89. */
  90. protected String producer = "Apache FOP Version " + Version.getVersion();
  91. /** Creator: Metadata element for the user that created the
  92. * document. (Some renderers can store this in the document.)
  93. */
  94. protected String creator = null;
  95. /** Creation Date: Override of the date the document was created.
  96. * (Some renderers can store this in the document.)
  97. */
  98. protected Date creationDate = null;
  99. /** Author of the content of the document. */
  100. protected String author = null;
  101. /** Title of the document. */
  102. protected String title = null;
  103. /** Subject of the document. */
  104. protected String subject = null;
  105. /** Set of keywords applicable to this document. */
  106. protected String keywords = null;
  107. private ImageSessionContext imageSessionContext = new AbstractImageSessionContext() {
  108. public ImageContext getParentContext() {
  109. return getFactory();
  110. }
  111. public float getTargetResolution() {
  112. return FOUserAgent.this.getTargetResolution();
  113. }
  114. public Source resolveURI(String uri) {
  115. return FOUserAgent.this.resolveURI(uri);
  116. }
  117. };
  118. /**
  119. * Main constructor. <b>This constructor should not be called directly. Please use the
  120. * methods from FopFactory to construct FOUserAgent instances!</b>
  121. * @param factory the factory that provides environment-level information
  122. * @see org.apache.fop.apps.FopFactory
  123. */
  124. public FOUserAgent(FopFactory factory) {
  125. if (factory == null) {
  126. throw new NullPointerException("The factory parameter must not be null");
  127. }
  128. this.factory = factory;
  129. setBaseURL(factory.getBaseURL());
  130. setFontBaseURL(factory.getFontManager().getFontBaseURL());
  131. setTargetResolution(factory.getTargetResolution());
  132. }
  133. /** @return the associated FopFactory instance */
  134. public FopFactory getFactory() {
  135. return this.factory;
  136. }
  137. // ---------------------------------------------- rendering-run dependent stuff
  138. /**
  139. * Sets an explicit document handler to use which overrides the one that would be
  140. * selected by default.
  141. * @param documentHandler the document handler instance to use
  142. */
  143. public void setDocumentHandlerOverride(IFDocumentHandler documentHandler) {
  144. this.documentHandlerOverride = documentHandler;
  145. }
  146. /**
  147. * Returns the overriding {@link IFDocumentHandler} instance, if any.
  148. * @return the overriding document handler or null
  149. */
  150. public IFDocumentHandler getDocumentHandlerOverride() {
  151. return this.documentHandlerOverride;
  152. }
  153. /**
  154. * Sets an explicit renderer to use which overrides the one defined by the
  155. * render type setting.
  156. * @param renderer the Renderer instance to use
  157. */
  158. public void setRendererOverride(Renderer renderer) {
  159. this.rendererOverride = renderer;
  160. }
  161. /**
  162. * Returns the overriding Renderer instance, if any.
  163. * @return the overriding Renderer or null
  164. */
  165. public Renderer getRendererOverride() {
  166. return rendererOverride;
  167. }
  168. /**
  169. * Sets an explicit FOEventHandler instance which overrides the one
  170. * defined by the render type setting.
  171. * @param handler the FOEventHandler instance
  172. */
  173. public void setFOEventHandlerOverride(FOEventHandler handler) {
  174. this.foEventHandlerOverride = handler;
  175. }
  176. /**
  177. * Returns the overriding FOEventHandler instance, if any.
  178. * @return the overriding FOEventHandler or null
  179. */
  180. public FOEventHandler getFOEventHandlerOverride() {
  181. return this.foEventHandlerOverride;
  182. }
  183. /**
  184. * Sets the producer of the document.
  185. * @param producer source of document
  186. */
  187. public void setProducer(String producer) {
  188. this.producer = producer;
  189. }
  190. /**
  191. * Returns the producer of the document
  192. * @return producer name
  193. */
  194. public String getProducer() {
  195. return producer;
  196. }
  197. /**
  198. * Sets the creator of the document.
  199. * @param creator of document
  200. */
  201. public void setCreator(String creator) {
  202. this.creator = creator;
  203. }
  204. /**
  205. * Returns the creator of the document
  206. * @return creator name
  207. */
  208. public String getCreator() {
  209. return creator;
  210. }
  211. /**
  212. * Sets the creation date of the document.
  213. * @param creationDate date of document
  214. */
  215. public void setCreationDate(Date creationDate) {
  216. this.creationDate = creationDate;
  217. }
  218. /**
  219. * Returns the creation date of the document
  220. * @return creation date of document
  221. */
  222. public Date getCreationDate() {
  223. return creationDate;
  224. }
  225. /**
  226. * Sets the author of the document.
  227. * @param author of document
  228. */
  229. public void setAuthor(String author) {
  230. this.author = author;
  231. }
  232. /**
  233. * Returns the author of the document
  234. * @return author name
  235. */
  236. public String getAuthor() {
  237. return author;
  238. }
  239. /**
  240. * Sets the title of the document. This will override any title coming from
  241. * an fo:title element.
  242. * @param title of document
  243. */
  244. public void setTitle(String title) {
  245. this.title = title;
  246. }
  247. /**
  248. * Returns the title of the document
  249. * @return title name
  250. */
  251. public String getTitle() {
  252. return title;
  253. }
  254. /**
  255. * Sets the subject of the document.
  256. * @param subject of document
  257. */
  258. public void setSubject(String subject) {
  259. this.subject = subject;
  260. }
  261. /**
  262. * Returns the subject of the document
  263. * @return the subject
  264. */
  265. public String getSubject() {
  266. return subject;
  267. }
  268. /**
  269. * Sets the keywords for the document.
  270. * @param keywords for the document
  271. */
  272. public void setKeywords(String keywords) {
  273. this.keywords = keywords;
  274. }
  275. /**
  276. * Returns the keywords for the document
  277. * @return the keywords
  278. */
  279. public String getKeywords() {
  280. return keywords;
  281. }
  282. /**
  283. * Returns the renderer options
  284. * @return renderer options
  285. */
  286. public Map getRendererOptions() {
  287. return rendererOptions;
  288. }
  289. /**
  290. * Sets the base URL.
  291. * @param baseUrl base URL
  292. */
  293. public void setBaseURL(String baseUrl) {
  294. this.base = baseUrl;
  295. }
  296. /**
  297. * sets font base URL
  298. * @param fontBaseUrl font base URL
  299. */
  300. public void setFontBaseURL(String fontBaseUrl) {
  301. this.fontBase = fontBaseUrl;
  302. }
  303. /**
  304. * Returns the base URL.
  305. * @return the base URL
  306. */
  307. public String getBaseURL() {
  308. return this.base;
  309. }
  310. /**
  311. * Sets the URI Resolver.
  312. * @param resolver the new URI resolver
  313. */
  314. public void setURIResolver(URIResolver resolver) {
  315. this.uriResolver = resolver;
  316. }
  317. /**
  318. * Returns the URI Resolver.
  319. * @return the URI Resolver
  320. */
  321. public URIResolver getURIResolver() {
  322. return this.uriResolver;
  323. }
  324. /**
  325. * Attempts to resolve the given URI.
  326. * Will use the configured resolver and if not successful fall back
  327. * to the default resolver.
  328. * @param uri URI to access
  329. * @return A {@link javax.xml.transform.Source} object, or null if the URI
  330. * cannot be resolved.
  331. * @see org.apache.fop.apps.FOURIResolver
  332. */
  333. public Source resolveURI(String uri) {
  334. return resolveURI(uri, getBaseURL());
  335. }
  336. /**
  337. * Attempts to resolve the given URI.
  338. * Will use the configured resolver and if not successful fall back
  339. * to the default resolver.
  340. * @param href URI to access
  341. * @param base the base URI to resolve against
  342. * @return A {@link javax.xml.transform.Source} object, or null if the URI
  343. * cannot be resolved.
  344. * @see org.apache.fop.apps.FOURIResolver
  345. */
  346. public Source resolveURI(String href, String base) {
  347. Source source = null;
  348. //RFC 2397 data URLs don't need to be resolved, just decode them through FOP's default
  349. //URIResolver.
  350. boolean bypassURIResolution = href.startsWith("data:");
  351. if (!bypassURIResolution && uriResolver != null) {
  352. try {
  353. source = uriResolver.resolve(href, base);
  354. } catch (TransformerException te) {
  355. log.error("Attempt to resolve URI '" + href + "' failed: ", te);
  356. }
  357. }
  358. if (source == null) {
  359. // URI Resolver not configured or returned null, use default resolver from the factory
  360. source = getFactory().resolveURI(href, base);
  361. }
  362. return source;
  363. }
  364. /**
  365. * Sets the output File.
  366. * @param f the output File
  367. */
  368. public void setOutputFile(File f) {
  369. this.outputFile = f;
  370. }
  371. /**
  372. * Gets the output File.
  373. * @return the output File
  374. */
  375. public File getOutputFile() {
  376. return outputFile;
  377. }
  378. /**
  379. * Returns the conversion factor from pixel units to millimeters. This
  380. * depends on the desired target resolution.
  381. * @return float conversion factor
  382. * @see #getTargetResolution()
  383. */
  384. public float getTargetPixelUnitToMillimeter() {
  385. return 25.4f / this.targetResolution;
  386. }
  387. /** @return the resolution for resolution-dependant output */
  388. public float getTargetResolution() {
  389. return this.targetResolution;
  390. }
  391. /**
  392. * Sets the target resolution in dpi. This value defines the target resolution of
  393. * bitmap images generated by the bitmap renderers (such as the TIFF renderer) and of
  394. * bitmap images generated by filter effects in Apache Batik.
  395. * @param dpi resolution in dpi
  396. */
  397. public void setTargetResolution(float dpi) {
  398. this.targetResolution = dpi;
  399. if (log.isDebugEnabled()) {
  400. log.debug("target-resolution set to: " + targetResolution
  401. + "dpi (px2mm=" + getTargetPixelUnitToMillimeter() + ")");
  402. }
  403. }
  404. /**
  405. * Sets the target resolution in dpi. This value defines the target resolution of
  406. * bitmap images generated by the bitmap renderers (such as the TIFF renderer) and of
  407. * bitmap images generated by filter effects in Apache Batik.
  408. * @param dpi resolution in dpi
  409. */
  410. public void setTargetResolution(int dpi) {
  411. setTargetResolution((float)dpi);
  412. }
  413. /**
  414. * Returns the image session context for the image package.
  415. * @return the ImageSessionContext instance for this rendering run
  416. */
  417. public ImageSessionContext getImageSessionContext() {
  418. return this.imageSessionContext;
  419. }
  420. // ---------------------------------------------- environment-level stuff
  421. // (convenience access to FopFactory methods)
  422. /** @return the font base URL */
  423. public String getFontBaseURL() {
  424. return fontBase != null ? fontBase : getBaseURL();
  425. }
  426. /**
  427. * Returns the conversion factor from pixel units to millimeters. This
  428. * depends on the desired source resolution.
  429. * @return float conversion factor
  430. * @see #getSourceResolution()
  431. */
  432. public float getSourcePixelUnitToMillimeter() {
  433. return getFactory().getSourcePixelUnitToMillimeter();
  434. }
  435. /** @return the resolution for resolution-dependant input */
  436. public float getSourceResolution() {
  437. return getFactory().getSourceResolution();
  438. }
  439. /**
  440. * Gets the default page-height to use as fallback,
  441. * in case page-height="auto"
  442. *
  443. * @return the page-height, as a String
  444. * @see FopFactory#getPageHeight()
  445. */
  446. public String getPageHeight() {
  447. return getFactory().getPageHeight();
  448. }
  449. /**
  450. * Gets the default page-width to use as fallback,
  451. * in case page-width="auto"
  452. *
  453. * @return the page-width, as a String
  454. * @see FopFactory#getPageWidth()
  455. */
  456. public String getPageWidth() {
  457. return getFactory().getPageWidth();
  458. }
  459. /**
  460. * Returns whether FOP is strictly validating input XSL
  461. * @return true of strict validation turned on, false otherwise
  462. * @see FopFactory#validateStrictly()
  463. */
  464. public boolean validateStrictly() {
  465. return getFactory().validateStrictly();
  466. }
  467. /**
  468. * @return true if the indent inheritance should be broken when crossing reference area
  469. * boundaries (for more info, see the javadoc for the relative member variable)
  470. * @see FopFactory#isBreakIndentInheritanceOnReferenceAreaBoundary()
  471. */
  472. public boolean isBreakIndentInheritanceOnReferenceAreaBoundary() {
  473. return getFactory().isBreakIndentInheritanceOnReferenceAreaBoundary();
  474. }
  475. /**
  476. * @return the RendererFactory
  477. */
  478. public RendererFactory getRendererFactory() {
  479. return getFactory().getRendererFactory();
  480. }
  481. /**
  482. * @return the XML handler registry
  483. */
  484. public XMLHandlerRegistry getXMLHandlerRegistry() {
  485. return getFactory().getXMLHandlerRegistry();
  486. }
  487. /**
  488. * Controls the use of SAXLocators to provide location information in error
  489. * messages.
  490. *
  491. * @param enableLocator <code>false</code> if SAX Locators should be disabled
  492. */
  493. public void setLocatorEnabled(boolean enableLocator) {
  494. locatorEnabled = enableLocator;
  495. }
  496. /**
  497. * Checks if the use of Locators is enabled
  498. * @return true if context information should be stored on each node in the FO tree.
  499. */
  500. public boolean isLocatorEnabled() {
  501. return locatorEnabled;
  502. }
  503. /**
  504. * Returns the event broadcaster that control events sent inside a processing run. Clients
  505. * can register event listeners with the event broadcaster to listen for events that occur
  506. * while a document is being processed.
  507. * @return the event broadcaster.
  508. */
  509. public EventBroadcaster getEventBroadcaster() {
  510. return this.eventBroadcaster;
  511. }
  512. private class FOPEventBroadcaster extends DefaultEventBroadcaster {
  513. private EventListener rootListener;
  514. public FOPEventBroadcaster() {
  515. //Install a temporary event listener that catches the first event to
  516. //do some initialization.
  517. this.rootListener = new EventListener() {
  518. public void processEvent(Event event) {
  519. if (!listeners.hasEventListeners()) {
  520. //Backwards-compatibility: Make sure at least the LoggingEventListener is
  521. //plugged in so no events are just silently swallowed.
  522. addEventListener(
  523. new LoggingEventListener(LogFactory.getLog(FOUserAgent.class)));
  524. }
  525. //Replace with final event listener
  526. rootListener = new FOPEventListenerProxy(
  527. listeners, FOUserAgent.this);
  528. rootListener.processEvent(event);
  529. }
  530. };
  531. }
  532. /** {@inheritDoc} */
  533. public void broadcastEvent(Event event) {
  534. rootListener.processEvent(event);
  535. }
  536. }
  537. /**
  538. * Check whether memory-conservation is enabled.
  539. *
  540. * @return true if FOP is to conserve as much as possible
  541. */
  542. public boolean isConserveMemoryPolicyEnabled() {
  543. return this.conserveMemoryPolicy;
  544. }
  545. /**
  546. * Control whether memory-conservation should be enabled
  547. *
  548. * @param conserveMemoryPolicy the cachingEnabled to set
  549. */
  550. public void setConserveMemoryPolicy(boolean conserveMemoryPolicy) {
  551. this.conserveMemoryPolicy = conserveMemoryPolicy;
  552. }
  553. }