Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

FOTreeBuilder.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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.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. private static final 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.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. if (userAgent.isAccessibilityEnabled()) {
  87. foEventHandler = new FO2StructureTreeConverter(
  88. foUserAgent.getStructureTreeEventHandler(), foEventHandler);
  89. }
  90. builderContext = new FOTreeBuilderContext();
  91. builderContext.setPropertyListMaker(new PropertyListMaker() {
  92. public PropertyList make(FObj fobj, PropertyList parentPropertyList) {
  93. return new StaticPropertyList(fobj, parentPropertyList);
  94. }
  95. });
  96. }
  97. /** {@inheritDoc} */
  98. public void setDocumentLocator(Locator locator) {
  99. this.locator = locator;
  100. }
  101. /**
  102. * @return a {@link Locator} instance if it is available and not disabled
  103. */
  104. protected Locator getEffectiveLocator() {
  105. return (userAgent.isLocatorEnabled() ? this.locator : null);
  106. }
  107. /** {@inheritDoc} */
  108. public void characters(char[] data, int start, int length)
  109. throws SAXException {
  110. delegate.characters(data, start, length);
  111. }
  112. /** {@inheritDoc} */
  113. public void startDocument() throws SAXException {
  114. if (used) {
  115. throw new IllegalStateException("FOTreeBuilder (and the Fop class) cannot be reused."
  116. + " Please instantiate a new instance.");
  117. }
  118. used = true;
  119. empty = true;
  120. rootFObj = null; // allows FOTreeBuilder to be reused
  121. if (LOG.isDebugEnabled()) {
  122. LOG.debug("Building formatting object tree");
  123. }
  124. foEventHandler.startDocument();
  125. this.mainFOHandler = new MainFOHandler();
  126. this.mainFOHandler.startDocument();
  127. this.delegate = this.mainFOHandler;
  128. }
  129. /** {@inheritDoc} */
  130. public void endDocument() throws SAXException {
  131. this.delegate.endDocument();
  132. if (this.rootFObj == null && empty) {
  133. FOValidationEventProducer eventProducer
  134. = FOValidationEventProducer.Provider.get(userAgent.getEventBroadcaster());
  135. eventProducer.emptyDocument(this);
  136. }
  137. rootFObj = null;
  138. if (LOG.isDebugEnabled()) {
  139. LOG.debug("Parsing of document complete");
  140. }
  141. foEventHandler.endDocument();
  142. }
  143. /** {@inheritDoc} */
  144. public void startElement(String namespaceURI, String localName, String rawName,
  145. Attributes attlist) throws SAXException {
  146. this.depth++;
  147. delegate.startElement(namespaceURI, localName, rawName, attlist);
  148. }
  149. /** {@inheritDoc} */
  150. public void endElement(String uri, String localName, String rawName)
  151. throws SAXException {
  152. this.delegate.endElement(uri, localName, rawName);
  153. this.depth--;
  154. if (depth == 0) {
  155. if (delegate != mainFOHandler) {
  156. //Return from sub-handler back to main handler
  157. delegate.endDocument();
  158. delegate = mainFOHandler;
  159. delegate.endElement(uri, localName, rawName);
  160. }
  161. }
  162. }
  163. /** {@inheritDoc} */
  164. public void warning(SAXParseException e) {
  165. LOG.warn(e.getLocalizedMessage());
  166. }
  167. /** {@inheritDoc} */
  168. public void error(SAXParseException e) {
  169. LOG.error(e.toString());
  170. }
  171. /** {@inheritDoc} */
  172. public void fatalError(SAXParseException e) throws SAXException {
  173. LOG.error(e.toString());
  174. throw e;
  175. }
  176. /**
  177. * Provides access to the underlying {@link FOEventHandler} object.
  178. *
  179. * @return the FOEventHandler object
  180. */
  181. public FOEventHandler getEventHandler() {
  182. return foEventHandler;
  183. }
  184. /**
  185. * Returns the results of the rendering process. Information includes
  186. * the total number of pages generated and the number of pages per
  187. * page-sequence.
  188. *
  189. * @return the results of the rendering process.
  190. */
  191. public FormattingResults getResults() {
  192. return getEventHandler().getResults();
  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.Provider.get(
  217. userAgent.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.setBuilderContext(builderContext);
  233. rootFObj.setFOEventHandler(foEventHandler);
  234. }
  235. propertyList = foNode.createPropertyList(
  236. currentPropertyList, foEventHandler);
  237. foNode.processNode(localName, getEffectiveLocator(),
  238. attlist, propertyList);
  239. if (foNode.getNameId() == Constants.FO_MARKER) {
  240. if (builderContext.inMarker()) {
  241. nestedMarkerDepth++;
  242. } else {
  243. builderContext.switchMarkerContext(true);
  244. }
  245. }
  246. if (foNode.getNameId() == Constants.FO_PAGE_SEQUENCE) {
  247. builderContext.getXMLWhiteSpaceHandler().reset();
  248. }
  249. } catch (IllegalArgumentException e) {
  250. throw new SAXException(e);
  251. }
  252. ContentHandlerFactory chFactory = foNode.getContentHandlerFactory();
  253. if (chFactory != null) {
  254. ContentHandler subHandler = chFactory.createContentHandler();
  255. if (subHandler instanceof ObjectSource
  256. && foNode instanceof ObjectBuiltListener) {
  257. ((ObjectSource) subHandler).setObjectBuiltListener(
  258. (ObjectBuiltListener) foNode);
  259. }
  260. subHandler.startDocument();
  261. subHandler.startElement(namespaceURI, localName,
  262. rawName, attlist);
  263. depth = 1;
  264. delegate = subHandler;
  265. }
  266. if (currentFObj != null) {
  267. currentFObj.addChildNode(foNode);
  268. }
  269. currentFObj = foNode;
  270. if (propertyList != null && !builderContext.inMarker()) {
  271. currentPropertyList = propertyList;
  272. }
  273. // fo:characters can potentially be removed during
  274. // white-space handling.
  275. // Do not notify the FOEventHandler.
  276. if (currentFObj.getNameId() != Constants.FO_CHARACTER) {
  277. currentFObj.startOfNode();
  278. }
  279. }
  280. /** {@inheritDoc} */
  281. public void endElement(String uri, String localName, String rawName)
  282. throws SAXException {
  283. if (currentFObj == null) {
  284. throw new SAXException(
  285. "endElement() called for " + rawName
  286. + " where there is no current element.");
  287. } else if (!currentFObj.getLocalName().equals(localName)
  288. || !currentFObj.getNamespaceURI().equals(uri)) {
  289. throw new SAXException("Mismatch: " + currentFObj.getLocalName()
  290. + " (" + currentFObj.getNamespaceURI()
  291. + ") vs. " + localName + " (" + uri + ")");
  292. }
  293. // fo:characters can potentially be removed during
  294. // white-space handling.
  295. // Do not notify the FOEventHandler.
  296. if (currentFObj.getNameId() != Constants.FO_CHARACTER) {
  297. currentFObj.endOfNode();
  298. }
  299. if (currentPropertyList != null
  300. && currentPropertyList.getFObj() == currentFObj
  301. && !builderContext.inMarker()) {
  302. currentPropertyList = currentPropertyList.getParentPropertyList();
  303. }
  304. if (currentFObj.getNameId() == Constants.FO_MARKER) {
  305. if (nestedMarkerDepth == 0) {
  306. builderContext.switchMarkerContext(false);
  307. } else {
  308. nestedMarkerDepth--;
  309. }
  310. }
  311. if (currentFObj.getParent() == null) {
  312. LOG.debug("endElement for top-level " + currentFObj.getName());
  313. }
  314. currentFObj = currentFObj.getParent();
  315. }
  316. /** {@inheritDoc} */
  317. public void characters(char[] data, int start, int length)
  318. throws FOPException {
  319. if (currentFObj != null) {
  320. currentFObj.characters(data, start, length,
  321. currentPropertyList, getEffectiveLocator());
  322. }
  323. }
  324. /** {@inheritDoc} */
  325. public void endDocument() throws SAXException {
  326. currentFObj = null;
  327. }
  328. /**
  329. * Finds the {@link Maker} used to create {@link FONode} objects of a particular type
  330. *
  331. * @param namespaceURI URI for the namespace of the element
  332. * @param localName name of the Element
  333. * @return the ElementMapping.Maker that can create an FO object for this element
  334. * @throws FOPException if a Maker could not be found for a bound namespace.
  335. */
  336. private Maker findFOMaker(String namespaceURI, String localName) throws FOPException {
  337. Maker maker = elementMappingRegistry.findFOMaker(namespaceURI, localName, locator);
  338. if (maker instanceof UnknownXMLObj.Maker) {
  339. FOValidationEventProducer eventProducer
  340. = FOValidationEventProducer.Provider.get(
  341. userAgent.getEventBroadcaster());
  342. String name = (currentFObj != null ? currentFObj.getName()
  343. : "{" + namespaceURI + "}" + localName);
  344. eventProducer.unknownFormattingObject(this, name,
  345. new QName(namespaceURI, localName),
  346. getEffectiveLocator());
  347. }
  348. return maker;
  349. }
  350. }
  351. }