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.

AreaTreeHandler.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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.area;
  19. // Java
  20. import java.io.OutputStream;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import org.xml.sax.SAXException;
  24. import org.apache.commons.logging.Log;
  25. import org.apache.commons.logging.LogFactory;
  26. import org.apache.fop.apps.FOPException;
  27. import org.apache.fop.apps.FOUserAgent;
  28. import org.apache.fop.apps.FormattingResults;
  29. import org.apache.fop.datatypes.Numeric;
  30. import org.apache.fop.fo.FOEventHandler;
  31. import org.apache.fop.fo.extensions.ExtensionAttachment;
  32. import org.apache.fop.fo.extensions.ExternalDocument;
  33. import org.apache.fop.fo.extensions.destination.Destination;
  34. import org.apache.fop.fo.pagination.AbstractPageSequence;
  35. import org.apache.fop.fo.pagination.PageSequence;
  36. import org.apache.fop.fo.pagination.Root;
  37. import org.apache.fop.fo.pagination.bookmarks.BookmarkTree;
  38. import org.apache.fop.layoutmgr.ExternalDocumentLayoutManager;
  39. import org.apache.fop.layoutmgr.LayoutManagerMaker;
  40. import org.apache.fop.layoutmgr.LayoutManagerMapping;
  41. import org.apache.fop.layoutmgr.PageSequenceLayoutManager;
  42. import org.apache.fop.layoutmgr.TopLevelLayoutManager;
  43. /**
  44. * Area tree handler for formatting objects.
  45. *
  46. * Concepts: The area tree is to be as small as possible. With minimal classes
  47. * and data to fully represent an area tree for formatting objects. The area
  48. * tree needs to be simple to render and follow the spec closely. This area tree
  49. * has the concept of page sequences. Wherever possible information is discarded
  50. * or optimized to keep memory use low. The data is also organized to make it
  51. * possible for renderers to minimize their output. A page can be saved if not
  52. * fully resolved and once rendered a page contains only size and id reference
  53. * information. The area tree pages are organized in a model that depends on the
  54. * type of renderer.
  55. */
  56. public class AreaTreeHandler extends FOEventHandler {
  57. private static Log log = LogFactory.getLog(AreaTreeHandler.class);
  58. // Recorder of debug statistics
  59. private Statistics statistics = null;
  60. // The LayoutManager maker
  61. private LayoutManagerMaker lmMaker;
  62. /** The AreaTreeModel in use */
  63. protected AreaTreeModel model;
  64. // Keeps track of all meaningful id references
  65. private IDTracker idTracker;
  66. // The fo:root node of the document
  67. private Root rootFObj;
  68. // The formatting results to be handed back to the caller.
  69. private FormattingResults results = new FormattingResults();
  70. private TopLevelLayoutManager prevPageSeqLM;
  71. private int idGen = 0;
  72. /**
  73. * Constructor.
  74. *
  75. * @param userAgent FOUserAgent object for process
  76. * @param outputFormat the MIME type of the output format to use (ex.
  77. * "application/pdf").
  78. * @param stream OutputStream
  79. * @throws FOPException if the RenderPagesModel cannot be created
  80. */
  81. public AreaTreeHandler(FOUserAgent userAgent, String outputFormat,
  82. OutputStream stream) throws FOPException {
  83. super(userAgent);
  84. setupModel(userAgent, outputFormat, stream);
  85. lmMaker = userAgent.getFactory().getLayoutManagerMakerOverride();
  86. if (lmMaker == null) {
  87. lmMaker = new LayoutManagerMapping();
  88. }
  89. idTracker = new IDTracker();
  90. if (log.isDebugEnabled()) {
  91. statistics = new Statistics();
  92. }
  93. }
  94. /**
  95. * Sets up the AreaTreeModel instance for use by the AreaTreeHandler.
  96. *
  97. * @param userAgent FOUserAgent object for process
  98. * @param outputFormat the MIME type of the output format to use (ex.
  99. * "application/pdf").
  100. * @param stream OutputStream
  101. * @throws FOPException if the RenderPagesModel cannot be created
  102. */
  103. protected void setupModel(FOUserAgent userAgent, String outputFormat,
  104. OutputStream stream) throws FOPException {
  105. model = new RenderPagesModel(userAgent, outputFormat, fontInfo, stream);
  106. }
  107. /**
  108. * Get the area tree model for this area tree.
  109. *
  110. * @return AreaTreeModel the model being used for this area tree
  111. */
  112. public AreaTreeModel getAreaTreeModel() {
  113. return model;
  114. }
  115. /**
  116. * Get the LayoutManager maker for this area tree.
  117. *
  118. * @return LayoutManagerMaker the LayoutManager maker being used for this
  119. * area tree
  120. */
  121. public LayoutManagerMaker getLayoutManagerMaker() {
  122. return lmMaker;
  123. }
  124. /**
  125. * Get the IDTracker for this area tree.
  126. *
  127. * @return IDTracker used to track reference ids for items in this area tree
  128. */
  129. public IDTracker getIDTracker() {
  130. return idTracker;
  131. }
  132. /**
  133. * Get information about the rendered output, like number of pages created.
  134. *
  135. * @return the results structure
  136. */
  137. public FormattingResults getResults() {
  138. return this.results;
  139. }
  140. /**
  141. * Prepare AreaTreeHandler for document processing This is called from
  142. * FOTreeBuilder.startDocument()
  143. *
  144. * @throws SAXException
  145. * if there is an error
  146. */
  147. public void startDocument() throws SAXException {
  148. // Initialize statistics
  149. if (statistics != null) {
  150. statistics.start();
  151. }
  152. }
  153. /**
  154. * finish the previous pageSequence
  155. */
  156. private void finishPrevPageSequence(Numeric initialPageNumber) {
  157. if (prevPageSeqLM != null) {
  158. prevPageSeqLM.doForcePageCount(initialPageNumber);
  159. prevPageSeqLM.finishPageSequence();
  160. prevPageSeqLM = null;
  161. }
  162. }
  163. /** {@inheritDoc} */
  164. public void startPageSequence(PageSequence pageSequence) {
  165. startAbstractPageSequence(pageSequence);
  166. }
  167. private void startAbstractPageSequence(AbstractPageSequence pageSequence) {
  168. rootFObj = pageSequence.getRoot();
  169. finishPrevPageSequence(pageSequence.getInitialPageNumber());
  170. pageSequence.initPageNumber();
  171. // extension attachments from fo:root
  172. wrapAndAddExtensionAttachments(rootFObj.getExtensionAttachments());
  173. // extension attachments from fo:declarations
  174. if (rootFObj.getDeclarations() != null) {
  175. wrapAndAddExtensionAttachments(rootFObj.getDeclarations().getExtensionAttachments());
  176. }
  177. }
  178. private void wrapAndAddExtensionAttachments(List list) {
  179. Iterator i = list.iterator();
  180. while (i.hasNext()) {
  181. ExtensionAttachment attachment = (ExtensionAttachment) i.next();
  182. addOffDocumentItem(new OffDocumentExtensionAttachment(attachment));
  183. }
  184. }
  185. /**
  186. * End the PageSequence. The PageSequence formats Pages and adds them to the
  187. * AreaTree. The area tree then handles what happens with the pages.
  188. *
  189. * @param pageSequence the page sequence ending
  190. */
  191. public void endPageSequence(PageSequence pageSequence) {
  192. if (statistics != null) {
  193. statistics.end();
  194. }
  195. // If no main flow, nothing to layout!
  196. if (pageSequence.getMainFlow() != null) {
  197. PageSequenceLayoutManager pageSLM;
  198. pageSLM = getLayoutManagerMaker().makePageSequenceLayoutManager(
  199. this, pageSequence);
  200. pageSLM.activateLayout();
  201. // preserve the current PageSequenceLayoutManger for the
  202. // force-page-count check at the beginning of the next PageSequence
  203. prevPageSeqLM = pageSLM;
  204. }
  205. }
  206. /** {@inheritDoc} */
  207. public void startExternalDocument(ExternalDocument document) {
  208. startAbstractPageSequence(document);
  209. }
  210. /** {@inheritDoc} */
  211. public void endExternalDocument(ExternalDocument document) {
  212. if (statistics != null) {
  213. statistics.end();
  214. }
  215. ExternalDocumentLayoutManager edLM;
  216. edLM = getLayoutManagerMaker().makeExternalDocumentLayoutManager(this, document);
  217. edLM.activateLayout();
  218. // preserve the current PageSequenceLayoutManger for the
  219. // force-page-count check at the beginning of the next PageSequence
  220. prevPageSeqLM = edLM;
  221. }
  222. /**
  223. * Called by the PageSequenceLayoutManager when it is finished with a
  224. * page-sequence.
  225. *
  226. * @param pageSequence the page-sequence just finished
  227. * @param pageCount The number of pages generated for the page-sequence
  228. */
  229. public void notifyPageSequenceFinished(AbstractPageSequence pageSequence,
  230. int pageCount) {
  231. this.results.haveFormattedPageSequence(pageSequence, pageCount);
  232. if (log.isDebugEnabled()) {
  233. log.debug("Last page-sequence produced " + pageCount + " pages.");
  234. }
  235. }
  236. /**
  237. * End the document.
  238. *
  239. * @throws SAXException if there is some error
  240. */
  241. public void endDocument() throws SAXException {
  242. finishPrevPageSequence(null);
  243. // process fox:destination elements
  244. if (rootFObj != null) {
  245. List destinationList = rootFObj.getDestinationList();
  246. if (destinationList != null) {
  247. while (destinationList.size() > 0) {
  248. Destination destination = (Destination) destinationList.remove(0);
  249. DestinationData destinationData = new DestinationData(destination);
  250. addOffDocumentItem(destinationData);
  251. }
  252. }
  253. // process fo:bookmark-tree
  254. BookmarkTree bookmarkTree = rootFObj.getBookmarkTree();
  255. if (bookmarkTree != null) {
  256. BookmarkData data = new BookmarkData(bookmarkTree);
  257. addOffDocumentItem(data);
  258. if (!data.isResolved()) {
  259. // bookmarks did not fully resolve, add anyway. (hacky? yeah)
  260. model.handleOffDocumentItem(data);
  261. }
  262. }
  263. }
  264. model.endDocument();
  265. if (statistics != null) {
  266. statistics.logResults();
  267. }
  268. }
  269. /**
  270. * Add a OffDocumentItem to the area tree model. This checks if the
  271. * OffDocumentItem is resolvable and attempts to resolve or add the
  272. * resolvable ids for later resolution.
  273. *
  274. * @param odi the OffDocumentItem to add.
  275. */
  276. private void addOffDocumentItem(OffDocumentItem odi) {
  277. if (odi instanceof Resolvable) {
  278. Resolvable res = (Resolvable) odi;
  279. String[] ids = res.getIDRefs();
  280. for (int count = 0; count < ids.length; count++) {
  281. List pageVPList = idTracker.getPageViewportsContainingID(ids[count]);
  282. if (pageVPList != null) {
  283. res.resolveIDRef(ids[count], pageVPList);
  284. } else {
  285. AreaEventProducer eventProducer = AreaEventProducer.Provider.get(
  286. getUserAgent().getEventBroadcaster());
  287. eventProducer.unresolvedIDReference(this, odi.getName(), ids[count]);
  288. idTracker.addUnresolvedIDRef(ids[count], res);
  289. }
  290. }
  291. // check to see if ODI is now fully resolved, if so process it
  292. if (res.isResolved()) {
  293. model.handleOffDocumentItem(odi);
  294. }
  295. } else {
  296. model.handleOffDocumentItem(odi);
  297. }
  298. }
  299. /**
  300. * Generates and returns a unique key for a page viewport.
  301. *
  302. * @return the generated key.
  303. */
  304. public String generatePageViewportKey() {
  305. this.idGen++;
  306. return "P" + this.idGen;
  307. }
  308. /**
  309. * Tie a PageViewport with an ID found on a child area of the PV. Note that
  310. * an area with a given ID may be on more than one PV, hence an ID may have
  311. * more than one PV associated with it.
  312. *
  313. * @param id the property ID of the area
  314. * @param pv a page viewport that contains the area with this ID
  315. * @deprecated use getIdTracker().associateIDWithPageViewport(id, pv) instead
  316. */
  317. public void associateIDWithPageViewport(String id, PageViewport pv) {
  318. idTracker.associateIDWithPageViewport(id, pv);
  319. }
  320. /**
  321. * This method tie an ID to the areaTreeHandler until this one is ready to
  322. * be processed. This is used in page-number-citation-last processing so we
  323. * know when an id can be resolved.
  324. *
  325. * @param id the id of the object being processed
  326. * @deprecated use getIdTracker().signalPendingID(id) instead
  327. */
  328. public void signalPendingID(String id) {
  329. idTracker.signalPendingID(id);
  330. }
  331. /**
  332. * Signals that all areas for the formatting object with the given ID have
  333. * been generated. This is used to determine when page-number-citation-last
  334. * ref-ids can be resolved.
  335. *
  336. * @param id the id of the formatting object which was just finished
  337. * @deprecated use getIdTracker().signalIDProcessed(id) instead
  338. */
  339. public void signalIDProcessed(String id) {
  340. idTracker.signalIDProcessed(id);
  341. }
  342. /**
  343. * Check if an ID has already been resolved
  344. *
  345. * @param id the id to check
  346. * @return true if the ID has been resolved
  347. * @deprecated use getIdTracker().alreadyResolvedID(id) instead
  348. */
  349. public boolean alreadyResolvedID(String id) {
  350. return idTracker.alreadyResolvedID(id);
  351. }
  352. /**
  353. * Tries to resolve all unresolved ID references on the given page.
  354. *
  355. * @param pv page viewport whose ID refs to resolve
  356. * @deprecated use getIdTracker().tryIDResolution(pv) instead
  357. */
  358. public void tryIDResolution(PageViewport pv) {
  359. idTracker.tryIDResolution(pv);
  360. }
  361. /**
  362. * Get the list of page viewports that have an area with a given id.
  363. *
  364. * @param id the id to lookup
  365. * @return the list of PageViewports
  366. * @deprecated use getIdTracker().getPageViewportsContainingID(id) instead
  367. */
  368. public List getPageViewportsContainingID(String id) {
  369. return idTracker.getPageViewportsContainingID(id);
  370. }
  371. /**
  372. * Add an Resolvable object with an unresolved idref
  373. *
  374. * @param idref the idref whose target id has not yet been located
  375. * @param res the Resolvable object needing the idref to be resolved
  376. * @deprecated use getIdTracker().addUnresolvedIDRef(idref, res) instead
  377. */
  378. public void addUnresolvedIDRef(String idref, Resolvable res) {
  379. idTracker.addUnresolvedIDRef(idref, res);
  380. }
  381. private class Statistics {
  382. // for statistics gathering
  383. private Runtime runtime;
  384. // heap memory allocated (for statistics)
  385. private long initialMemory;
  386. // time used in rendering (for statistics)
  387. private long startTime;
  388. /**
  389. * Default constructor
  390. * @param areaTreeHandler area tree handler
  391. */
  392. protected Statistics() {
  393. this.runtime = Runtime.getRuntime();
  394. }
  395. /**
  396. * starts the area tree handler statistics gathering
  397. */
  398. protected void start() {
  399. this.initialMemory = runtime.totalMemory() - runtime.freeMemory();
  400. this.startTime = System.currentTimeMillis();
  401. }
  402. /**
  403. * ends the area tree handler statistics gathering
  404. */
  405. protected void end() {
  406. long memoryNow = runtime.totalMemory() - runtime.freeMemory();
  407. log.debug("Current heap size: " + (memoryNow / 1024L) + "KB");
  408. }
  409. /**
  410. * logs the results of the area tree handler statistics gathering
  411. */
  412. protected void logResults() {
  413. long memoryNow = runtime.totalMemory() - runtime.freeMemory();
  414. long memoryUsed = (memoryNow - initialMemory) / 1024L;
  415. long timeUsed = System.currentTimeMillis() - startTime;
  416. int pageCount = rootFObj.getTotalPagesGenerated();
  417. log.debug("Initial heap size: " + (initialMemory / 1024L) + "KB");
  418. log.debug("Current heap size: " + (memoryNow / 1024L) + "KB");
  419. log.debug("Total memory used: " + memoryUsed + "KB");
  420. log.debug("Total time used: " + timeUsed + "ms");
  421. log.debug("Pages rendered: " + pageCount);
  422. if (pageCount > 0) {
  423. long perPage = (timeUsed / pageCount);
  424. long ppm = (timeUsed != 0 ? Math.round(60000 * pageCount
  425. / (double) timeUsed) : -1);
  426. log.debug("Avg render time: " + perPage + "ms/page (" + ppm + "pages/min)");
  427. }
  428. }
  429. }
  430. }