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

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