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 22KB

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