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.

FOTreeBuilder.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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.fo;
  19. import java.io.OutputStream;
  20. import org.xml.sax.Attributes;
  21. import org.xml.sax.ContentHandler;
  22. import org.xml.sax.Locator;
  23. import org.xml.sax.SAXException;
  24. import org.xml.sax.SAXParseException;
  25. import org.xml.sax.helpers.DefaultHandler;
  26. import org.apache.commons.logging.Log;
  27. import org.apache.commons.logging.LogFactory;
  28. import org.apache.xmlgraphics.util.QName;
  29. import org.apache.fop.accessibility.fo.FO2StructureTreeConverter;
  30. import org.apache.fop.apps.FOPException;
  31. import org.apache.fop.apps.FOUserAgent;
  32. import org.apache.fop.apps.FormattingResults;
  33. import org.apache.fop.area.AreaTreeHandler;
  34. import org.apache.fop.fo.ElementMapping.Maker;
  35. import org.apache.fop.fo.extensions.ExtensionElementMapping;
  36. import org.apache.fop.fo.pagination.Root;
  37. import org.apache.fop.util.ContentHandlerFactory;
  38. import org.apache.fop.util.ContentHandlerFactory.ObjectBuiltListener;
  39. import org.apache.fop.util.ContentHandlerFactory.ObjectSource;
  40. /**
  41. * SAX Handler that passes parsed data to the various
  42. * FO objects, where they can be used either to build
  43. * an FO Tree, or used by Structure Renderers to build
  44. * other data structures.
  45. */
  46. public class FOTreeBuilder extends DefaultHandler {
  47. /** logging instance */
  48. protected Log log = LogFactory.getLog(FOTreeBuilder.class);
  49. /** The registry for ElementMapping instances */
  50. protected ElementMappingRegistry elementMappingRegistry;
  51. /** The root of the formatting object tree */
  52. protected Root rootFObj = null;
  53. /** Main DefaultHandler that handles the FO namespace. */
  54. protected MainFOHandler mainFOHandler;
  55. /** Current delegate ContentHandler to receive the SAX events */
  56. protected ContentHandler delegate;
  57. /** Provides information used during tree building stage. */
  58. private FOTreeBuilderContext builderContext;
  59. /** The object that handles formatting and rendering to a stream */
  60. private FOEventHandler foEventHandler;
  61. /** The SAX locator object managing the line and column counters */
  62. private Locator locator;
  63. /** The user agent for this processing run. */
  64. private FOUserAgent userAgent;
  65. private boolean used = false;
  66. private boolean empty = true;
  67. private int depth;
  68. /**
  69. * <code>FOTreeBuilder</code> constructor
  70. *
  71. * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
  72. * @param foUserAgent the {@link FOUserAgent} in effect for this process
  73. * @param stream the <code>OutputStream</code> to direct the results to
  74. * @throws FOPException if the <code>FOTreeBuilder</code> cannot be properly created
  75. */
  76. public FOTreeBuilder(
  77. String outputFormat,
  78. FOUserAgent foUserAgent,
  79. OutputStream stream)
  80. throws FOPException {
  81. this.userAgent = foUserAgent;
  82. this.elementMappingRegistry = userAgent.getFactory().getElementMappingRegistry();
  83. //This creates either an AreaTreeHandler and ultimately a Renderer, or
  84. //one of the RTF-, MIF- etc. Handlers.
  85. foEventHandler = foUserAgent.getRendererFactory().createFOEventHandler(
  86. foUserAgent, outputFormat, stream);
  87. if (userAgent.isAccessibilityEnabled()) {
  88. foEventHandler = new FO2StructureTreeConverter(
  89. foUserAgent.getStructureTreeEventHandler(), foEventHandler);
  90. }
  91. builderContext = new FOTreeBuilderContext();
  92. builderContext.setPropertyListMaker(new PropertyListMaker() {
  93. public PropertyList make(FObj fobj, PropertyList parentPropertyList) {
  94. return new StaticPropertyList(fobj, parentPropertyList);
  95. }
  96. });
  97. }
  98. /** {@inheritDoc} */
  99. public void setDocumentLocator(Locator locator) {
  100. this.locator = locator;
  101. }
  102. /**
  103. * @return a {@link Locator} instance if it is available and not disabled
  104. */
  105. protected Locator getEffectiveLocator() {
  106. return (userAgent.isLocatorEnabled() ? this.locator : null);
  107. }
  108. /** {@inheritDoc} */
  109. public void characters(char[] data, int start, int length)
  110. throws SAXException {
  111. delegate.characters(data, start, length);
  112. }
  113. /** {@inheritDoc} */
  114. public void startDocument() throws SAXException {
  115. if (used) {
  116. throw new IllegalStateException("FOTreeBuilder (and the Fop class) cannot be reused."
  117. + " Please instantiate a new instance.");
  118. }
  119. used = true;
  120. empty = true;
  121. rootFObj = null; // allows FOTreeBuilder to be reused
  122. if (log.isDebugEnabled()) {
  123. log.debug("Building formatting object tree");
  124. }
  125. foEventHandler.startDocument();
  126. this.mainFOHandler = new MainFOHandler();
  127. this.mainFOHandler.startDocument();
  128. this.delegate = this.mainFOHandler;
  129. }
  130. /** {@inheritDoc} */
  131. public void endDocument() throws SAXException {
  132. this.delegate.endDocument();
  133. if (this.rootFObj == null && empty) {
  134. FOValidationEventProducer eventProducer
  135. = FOValidationEventProducer.Provider.get(userAgent.getEventBroadcaster());
  136. eventProducer.emptyDocument(this);
  137. }
  138. rootFObj = null;
  139. if (log.isDebugEnabled()) {
  140. log.debug("Parsing of document complete");
  141. }
  142. foEventHandler.endDocument();
  143. }
  144. /** {@inheritDoc} */
  145. public void startElement(String namespaceURI, String localName, String rawName,
  146. Attributes attlist) throws SAXException {
  147. this.depth++;
  148. delegate.startElement(namespaceURI, localName, rawName, attlist);
  149. }
  150. /** {@inheritDoc} */
  151. public void endElement(String uri, String localName, String rawName)
  152. throws SAXException {
  153. this.delegate.endElement(uri, localName, rawName);
  154. this.depth--;
  155. if (depth == 0) {
  156. if (delegate != mainFOHandler) {
  157. //Return from sub-handler back to main handler
  158. delegate.endDocument();
  159. delegate = mainFOHandler;
  160. delegate.endElement(uri, localName, rawName);
  161. }
  162. }
  163. }
  164. /** {@inheritDoc} */
  165. public void warning(SAXParseException e) {
  166. log.warn(e.getLocalizedMessage());
  167. }
  168. /** {@inheritDoc} */
  169. public void error(SAXParseException e) {
  170. log.error(e.toString());
  171. }
  172. /** {@inheritDoc} */
  173. public void fatalError(SAXParseException e) throws SAXException {
  174. log.error(e.toString());
  175. throw e;
  176. }
  177. /**
  178. * Provides access to the underlying {@link FOEventHandler} object.
  179. *
  180. * @return the FOEventHandler object
  181. */
  182. public FOEventHandler getEventHandler() {
  183. return foEventHandler;
  184. }
  185. /**
  186. * Returns the results of the rendering process. Information includes
  187. * the total number of pages generated and the number of pages per
  188. * page-sequence.
  189. *
  190. * @return the results of the rendering process.
  191. */
  192. public FormattingResults getResults() {
  193. if (getEventHandler() instanceof AreaTreeHandler) {
  194. return ((AreaTreeHandler) getEventHandler()).getResults();
  195. } else {
  196. //No formatting results available for output formats no
  197. //involving the layout engine.
  198. return null;
  199. }
  200. }
  201. /**
  202. * Main <code>DefaultHandler</code> implementation which builds the FO tree.
  203. */
  204. private class MainFOHandler extends DefaultHandler {
  205. /** Current formatting object being handled */
  206. protected FONode currentFObj = null;
  207. /** Current propertyList for the node being handled */
  208. protected PropertyList currentPropertyList;
  209. /** Current marker nesting-depth */
  210. private int nestedMarkerDepth = 0;
  211. /** {@inheritDoc} */
  212. public void startElement(String namespaceURI, String localName, String rawName,
  213. Attributes attlist) throws SAXException {
  214. /* the node found in the FO document */
  215. FONode foNode;
  216. PropertyList propertyList = null;
  217. // Check to ensure first node encountered is an fo:root
  218. if (rootFObj == null) {
  219. empty = false;
  220. if (!namespaceURI.equals(FOElementMapping.URI)
  221. || !localName.equals("root")) {
  222. FOValidationEventProducer eventProducer
  223. = FOValidationEventProducer.Provider.get(
  224. userAgent.getEventBroadcaster());
  225. eventProducer.invalidFORoot(this, FONode.getNodeString(namespaceURI, localName),
  226. getEffectiveLocator());
  227. }
  228. } else { // check that incoming node is valid for currentFObj
  229. if (currentFObj.getNamespaceURI().equals(FOElementMapping.URI)
  230. || currentFObj.getNamespaceURI().equals(ExtensionElementMapping.URI)) {
  231. currentFObj.validateChildNode(locator, namespaceURI, localName);
  232. }
  233. }
  234. ElementMapping.Maker fobjMaker = findFOMaker(namespaceURI, localName);
  235. try {
  236. foNode = fobjMaker.make(currentFObj);
  237. if (rootFObj == null) {
  238. rootFObj = (Root) foNode;
  239. rootFObj.setBuilderContext(builderContext);
  240. rootFObj.setFOEventHandler(foEventHandler);
  241. }
  242. propertyList = foNode.createPropertyList(
  243. currentPropertyList, foEventHandler);
  244. foNode.processNode(localName, getEffectiveLocator(),
  245. attlist, propertyList);
  246. if (foNode.getNameId() == Constants.FO_MARKER) {
  247. if (builderContext.inMarker()) {
  248. nestedMarkerDepth++;
  249. } else {
  250. builderContext.switchMarkerContext(true);
  251. }
  252. }
  253. if (foNode.getNameId() == Constants.FO_PAGE_SEQUENCE) {
  254. builderContext.getXMLWhiteSpaceHandler().reset();
  255. }
  256. } catch (IllegalArgumentException e) {
  257. throw new SAXException(e);
  258. }
  259. ContentHandlerFactory chFactory = foNode.getContentHandlerFactory();
  260. if (chFactory != null) {
  261. ContentHandler subHandler = chFactory.createContentHandler();
  262. if (subHandler instanceof ObjectSource
  263. && foNode instanceof ObjectBuiltListener) {
  264. ((ObjectSource) subHandler).setObjectBuiltListener(
  265. (ObjectBuiltListener) foNode);
  266. }
  267. subHandler.startDocument();
  268. subHandler.startElement(namespaceURI, localName,
  269. rawName, attlist);
  270. depth = 1;
  271. delegate = subHandler;
  272. }
  273. if (currentFObj != null) {
  274. currentFObj.addChildNode(foNode);
  275. }
  276. currentFObj = foNode;
  277. if (propertyList != null && !builderContext.inMarker()) {
  278. currentPropertyList = propertyList;
  279. }
  280. // fo:characters can potentially be removed during
  281. // white-space handling.
  282. // Do not notify the FOEventHandler.
  283. if (currentFObj.getNameId() != Constants.FO_CHARACTER) {
  284. currentFObj.startOfNode();
  285. }
  286. }
  287. /** {@inheritDoc} */
  288. public void endElement(String uri, String localName, String rawName)
  289. throws SAXException {
  290. if (currentFObj == null) {
  291. throw new SAXException(
  292. "endElement() called for " + rawName
  293. + " where there is no current element.");
  294. } else if (!currentFObj.getLocalName().equals(localName)
  295. || !currentFObj.getNamespaceURI().equals(uri)) {
  296. throw new SAXException("Mismatch: " + currentFObj.getLocalName()
  297. + " (" + currentFObj.getNamespaceURI()
  298. + ") vs. " + localName + " (" + uri + ")");
  299. }
  300. // fo:characters can potentially be removed during
  301. // white-space handling.
  302. // Do not notify the FOEventHandler.
  303. if (currentFObj.getNameId() != Constants.FO_CHARACTER) {
  304. currentFObj.endOfNode();
  305. }
  306. if (currentPropertyList != null
  307. && currentPropertyList.getFObj() == currentFObj
  308. && !builderContext.inMarker()) {
  309. currentPropertyList = currentPropertyList.getParentPropertyList();
  310. }
  311. if (currentFObj.getNameId() == Constants.FO_MARKER) {
  312. if (nestedMarkerDepth == 0) {
  313. builderContext.switchMarkerContext(false);
  314. } else {
  315. nestedMarkerDepth--;
  316. }
  317. }
  318. if (currentFObj.getParent() == null) {
  319. log.debug("endElement for top-level " + currentFObj.getName());
  320. }
  321. currentFObj = currentFObj.getParent();
  322. }
  323. /** {@inheritDoc} */
  324. public void characters(char[] data, int start, int length)
  325. throws FOPException {
  326. if (currentFObj != null) {
  327. currentFObj.characters(data, start, length,
  328. currentPropertyList, getEffectiveLocator());
  329. }
  330. }
  331. /** {@inheritDoc} */
  332. public void endDocument() throws SAXException {
  333. currentFObj = null;
  334. }
  335. /**
  336. * Finds the {@link Maker} used to create {@link FONode} objects of a particular type
  337. *
  338. * @param namespaceURI URI for the namespace of the element
  339. * @param localName name of the Element
  340. * @return the ElementMapping.Maker that can create an FO object for this element
  341. * @throws FOPException if a Maker could not be found for a bound namespace.
  342. */
  343. private Maker findFOMaker(String namespaceURI, String localName) throws FOPException {
  344. Maker maker = elementMappingRegistry.findFOMaker(namespaceURI, localName, locator);
  345. if (maker instanceof UnknownXMLObj.Maker) {
  346. FOValidationEventProducer eventProducer
  347. = FOValidationEventProducer.Provider.get(
  348. userAgent.getEventBroadcaster());
  349. String name = (currentFObj != null ? currentFObj.getName()
  350. : "{" + namespaceURI + "}" + localName);
  351. eventProducer.unknownFormattingObject(this, name,
  352. new QName(namespaceURI, localName),
  353. getEffectiveLocator());
  354. }
  355. return maker;
  356. }
  357. }
  358. }