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

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