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.

PageBreaker.java 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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.layoutmgr;
  19. import java.util.ArrayList;
  20. import java.util.Collections;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.ListIterator;
  24. import org.apache.fop.area.Block;
  25. import org.apache.fop.area.BodyRegion;
  26. import org.apache.fop.area.Footnote;
  27. import org.apache.fop.area.PageViewport;
  28. import org.apache.fop.fo.Constants;
  29. import org.apache.fop.fo.FObj;
  30. import org.apache.fop.fo.pagination.Region;
  31. import org.apache.fop.fo.pagination.RegionBody;
  32. import org.apache.fop.fo.pagination.StaticContent;
  33. import org.apache.fop.layoutmgr.BreakingAlgorithm.KnuthNode;
  34. import org.apache.fop.layoutmgr.PageBreakingAlgorithm.PageBreakingLayoutListener;
  35. import org.apache.fop.layoutmgr.list.ListItemLayoutManager;
  36. import org.apache.fop.traits.MinOptMax;
  37. /**
  38. * Handles the breaking of pages in an fo:flow
  39. */
  40. public class PageBreaker extends AbstractBreaker {
  41. private PageSequenceLayoutManager pslm;
  42. private boolean firstPart = true;
  43. private boolean pageBreakHandled;
  44. private boolean needColumnBalancing;
  45. private PageProvider pageProvider;
  46. private Block separatorArea;
  47. private boolean spanAllActive;
  48. private boolean layoutRedone;
  49. private int previousIndex;
  50. private boolean handlingStartOfFloat;
  51. private boolean handlingEndOfFloat;
  52. private int floatHeight;
  53. private int floatYOffset;
  54. private List relayedFootnotesList;
  55. private List relayedLengthList;
  56. private int relayedTotalFootnotesLength;
  57. private int relayedInsertedFootnotesLength;
  58. private boolean relayedFootnotesPending;
  59. private boolean relayedNewFootnotes;
  60. private int relayedFirstNewFootnoteIndex;
  61. private int relayedFootnoteListIndex;
  62. private int relayedFootnoteElementIndex = -1;
  63. private MinOptMax relayedFootnoteSeparatorLength;
  64. private int previousFootnoteListIndex = -2;
  65. private int previousFootnoteElementIndex = -2;
  66. /**
  67. * The FlowLayoutManager object, which processes
  68. * the single fo:flow of the fo:page-sequence
  69. */
  70. private FlowLayoutManager childFLM;
  71. private StaticContentLayoutManager footnoteSeparatorLM;
  72. /**
  73. * Construct page breaker.
  74. * @param pslm the page sequence layout manager
  75. */
  76. public PageBreaker(PageSequenceLayoutManager pslm) {
  77. this.pslm = pslm;
  78. this.pageProvider = pslm.getPageProvider();
  79. this.childFLM = pslm.getLayoutManagerMaker().makeFlowLayoutManager(
  80. pslm, pslm.getPageSequence().getMainFlow());
  81. }
  82. /** {@inheritDoc} */
  83. protected void updateLayoutContext(LayoutContext context) {
  84. int flowIPD = pslm.getCurrentColumnWidth();
  85. context.setRefIPD(flowIPD);
  86. }
  87. /** {@inheritDoc} */
  88. protected LayoutManager getTopLevelLM() {
  89. return pslm;
  90. }
  91. /** {@inheritDoc} */
  92. protected PageProvider getPageProvider() {
  93. return pslm.getPageProvider();
  94. }
  95. /**
  96. * Starts the page breaking process.
  97. * @param flowBPD the constant available block-progression-dimension (used for every part)
  98. */
  99. void doLayout(int flowBPD) {
  100. doLayout(flowBPD, false);
  101. }
  102. /** {@inheritDoc} */
  103. protected PageBreakingLayoutListener createLayoutListener() {
  104. return new PageBreakingLayoutListener() {
  105. public void notifyOverflow(int part, int amount, FObj obj) {
  106. Page p = pageProvider.getPageFromColumnIndex(part);
  107. RegionBody body = (RegionBody)p.getSimplePageMaster().getRegion(
  108. Region.FO_REGION_BODY);
  109. BlockLevelEventProducer eventProducer = BlockLevelEventProducer.Provider.get(
  110. body.getUserAgent().getEventBroadcaster());
  111. boolean canRecover = (body.getOverflow() != Constants.EN_ERROR_IF_OVERFLOW);
  112. boolean needClip = (body.getOverflow() == Constants.EN_HIDDEN
  113. || body.getOverflow() == Constants.EN_ERROR_IF_OVERFLOW);
  114. eventProducer.regionOverflow(this, body.getName(),
  115. p.getPageViewport().getPageNumberString(),
  116. amount, needClip, canRecover,
  117. body.getLocator());
  118. }
  119. };
  120. }
  121. /** {@inheritDoc} */
  122. protected int handleSpanChange(LayoutContext childLC, int nextSequenceStartsOn) {
  123. needColumnBalancing = false;
  124. if (childLC.getNextSpan() != Constants.NOT_SET) {
  125. //Next block list will have a different span.
  126. nextSequenceStartsOn = childLC.getNextSpan();
  127. needColumnBalancing = childLC.getNextSpan() == Constants.EN_ALL
  128. && childLC.getDisableColumnBalancing() == Constants.EN_FALSE;
  129. }
  130. if (needColumnBalancing) {
  131. AbstractBreaker.log.debug(
  132. "Column balancing necessary for the next element list!!!");
  133. }
  134. return nextSequenceStartsOn;
  135. }
  136. /** {@inheritDoc} */
  137. protected int getNextBlockList(LayoutContext childLC,
  138. int nextSequenceStartsOn) {
  139. return getNextBlockList(childLC, nextSequenceStartsOn, null, null, null);
  140. }
  141. /** {@inheritDoc} */
  142. protected int getNextBlockList(LayoutContext childLC, int nextSequenceStartsOn,
  143. Position positionAtIPDChange, LayoutManager restartLM, List firstElements) {
  144. if (!layoutRedone && !handlingFloat()) {
  145. if (!firstPart) {
  146. // if this is the first page that will be created by
  147. // the current BlockSequence, it could have a break
  148. // condition that must be satisfied;
  149. // otherwise, we may simply need a new page
  150. handleBreakTrait(nextSequenceStartsOn);
  151. }
  152. firstPart = false;
  153. pageBreakHandled = true;
  154. pageProvider.setStartOfNextElementList(pslm.getCurrentPageNum(), pslm.getCurrentPV()
  155. .getCurrentSpan().getCurrentFlowIndex(), this.spanAllActive);
  156. }
  157. return super.getNextBlockList(childLC, nextSequenceStartsOn, positionAtIPDChange,
  158. restartLM, firstElements);
  159. }
  160. private boolean containsFootnotes(List contentList, LayoutContext context) {
  161. boolean containsFootnotes = false;
  162. if (contentList != null) {
  163. ListIterator contentListIterator = contentList.listIterator();
  164. while (contentListIterator.hasNext()) {
  165. ListElement element = (ListElement) contentListIterator.next();
  166. if (element instanceof KnuthBlockBox
  167. && ((KnuthBlockBox) element).hasAnchors()) {
  168. // element represents a line with footnote citations
  169. containsFootnotes = true;
  170. KnuthBlockBox box = (KnuthBlockBox) element;
  171. List<List<KnuthElement>> footnotes = getFootnoteKnuthElements(childFLM, context,
  172. box.getFootnoteBodyLMs());
  173. for (List<KnuthElement> footnote : footnotes) {
  174. box.addElementList(footnote);
  175. }
  176. }
  177. }
  178. }
  179. return containsFootnotes;
  180. }
  181. public static List<List<KnuthElement>> getFootnoteKnuthElements(FlowLayoutManager flowLM, LayoutContext context,
  182. List<FootnoteBodyLayoutManager> footnoteBodyLMs) {
  183. List<List<KnuthElement>> footnotes = new ArrayList<List<KnuthElement>>();
  184. LayoutContext footnoteContext = LayoutContext.copyOf(context);
  185. footnoteContext.setStackLimitBP(context.getStackLimitBP());
  186. footnoteContext.setRefIPD(flowLM.getPSLM()
  187. .getCurrentPV().getRegionReference(Constants.FO_REGION_BODY).getIPD());
  188. for (FootnoteBodyLayoutManager fblm : footnoteBodyLMs) {
  189. fblm.setParent(flowLM);
  190. fblm.initialize();
  191. List<KnuthElement> footnote = fblm.getNextKnuthElements(footnoteContext, Constants.EN_START);
  192. // TODO this does not respect possible stacking constraints between footnotes
  193. SpaceResolver.resolveElementList(footnote);
  194. footnotes.add(footnote);
  195. }
  196. return footnotes;
  197. }
  198. private void handleFootnoteSeparator() {
  199. StaticContent footnoteSeparator;
  200. footnoteSeparator = pslm.getPageSequence().getStaticContent("xsl-footnote-separator");
  201. if (footnoteSeparator != null) {
  202. // the footnote separator can contain page-dependent content such as
  203. // page numbers or retrieve markers, so its areas cannot simply be
  204. // obtained now and repeated in each page;
  205. // we need to know in advance the separator bpd: the actual separator
  206. // could be different from page to page, but its bpd would likely be
  207. // always the same
  208. // create a Block area that will contain the separator areas
  209. separatorArea = new Block();
  210. separatorArea.setIPD(pslm.getCurrentPV()
  211. .getRegionReference(Constants.FO_REGION_BODY).getIPD());
  212. // create a StaticContentLM for the footnote separator
  213. footnoteSeparatorLM
  214. = pslm.getLayoutManagerMaker().makeStaticContentLayoutManager(
  215. pslm, footnoteSeparator, separatorArea);
  216. footnoteSeparatorLM.doLayout();
  217. footnoteSeparatorLength = MinOptMax.getInstance(separatorArea.getBPD());
  218. }
  219. }
  220. /** {@inheritDoc} */
  221. protected List getNextKnuthElements(LayoutContext context, int alignment) {
  222. List contentList = null;
  223. while (!childFLM.isFinished() && contentList == null) {
  224. contentList = childFLM.getNextKnuthElements(context, alignment);
  225. }
  226. // scan contentList, searching for footnotes
  227. if (containsFootnotes(contentList, context)) {
  228. // handle the footnote separator
  229. handleFootnoteSeparator();
  230. }
  231. return contentList;
  232. }
  233. /** {@inheritDoc} */
  234. protected List getNextKnuthElements(LayoutContext context, int alignment,
  235. Position positionAtIPDChange, LayoutManager restartAtLM) {
  236. List contentList = null;
  237. do {
  238. contentList = childFLM.getNextKnuthElements(context, alignment, positionAtIPDChange,
  239. restartAtLM);
  240. } while (!childFLM.isFinished() && contentList == null);
  241. // scan contentList, searching for footnotes
  242. if (containsFootnotes(contentList, context)) {
  243. // handle the footnote separator
  244. handleFootnoteSeparator();
  245. }
  246. return contentList;
  247. }
  248. /**
  249. * @return current display alignment
  250. */
  251. protected int getCurrentDisplayAlign() {
  252. return pslm.getCurrentPage().getSimplePageMaster().getRegion(
  253. Constants.FO_REGION_BODY).getDisplayAlign();
  254. }
  255. /**
  256. * @return whether or not this flow has more page break opportunities
  257. */
  258. protected boolean hasMoreContent() {
  259. return !childFLM.isFinished();
  260. }
  261. /**
  262. * Adds an area to the flow layout manager
  263. * @param posIter the position iterator
  264. * @param context the layout context
  265. */
  266. protected void addAreas(PositionIterator posIter, LayoutContext context) {
  267. if (footnoteSeparatorLM != null) {
  268. StaticContent footnoteSeparator = pslm.getPageSequence().getStaticContent(
  269. "xsl-footnote-separator");
  270. // create a Block area that will contain the separator areas
  271. separatorArea = new Block();
  272. separatorArea.setIPD(
  273. pslm.getCurrentPV().getRegionReference(Constants.FO_REGION_BODY).getIPD());
  274. // create a StaticContentLM for the footnote separator
  275. footnoteSeparatorLM = pslm.getLayoutManagerMaker().makeStaticContentLayoutManager(
  276. pslm, footnoteSeparator, separatorArea);
  277. footnoteSeparatorLM.doLayout();
  278. }
  279. childFLM.addAreas(posIter, context);
  280. }
  281. /**
  282. * {@inheritDoc}
  283. * This implementation checks whether to trigger column-balancing,
  284. * or whether to take into account a 'last-page' condition.
  285. */
  286. protected void doPhase3(PageBreakingAlgorithm alg, int partCount,
  287. BlockSequence originalList, BlockSequence effectiveList) {
  288. if (needColumnBalancing) {
  289. //column balancing for the last part
  290. redoLayout(alg, partCount, originalList, effectiveList);
  291. return;
  292. }
  293. if (shouldRedoLayout(partCount)) {
  294. redoLayout(alg, partCount, originalList, effectiveList);
  295. return;
  296. }
  297. //nothing special: just add the areas now
  298. addAreas(alg, partCount, originalList, effectiveList);
  299. }
  300. protected void prepareToRedoLayout(PageBreakingAlgorithm alg, int partCount,
  301. BlockSequence originalList,
  302. BlockSequence effectiveList) {
  303. int newStartPos = 0;
  304. int restartPoint = pageProvider.getStartingPartIndexForLastPage(partCount);
  305. if (restartPoint > 0 && !layoutRedone) {
  306. // Add definitive areas for the parts before the
  307. // restarting point
  308. addAreas(alg, restartPoint, originalList, effectiveList);
  309. // Get page break from which we restart
  310. PageBreakPosition pbp = alg.getPageBreaks().get(restartPoint - 1);
  311. newStartPos = alg.par.getFirstBoxIndex(pbp.getLeafPos() + 1);
  312. // Handle page break right here to avoid any side-effects
  313. if (newStartPos > 0) {
  314. handleBreakTrait(Constants.EN_PAGE);
  315. }
  316. }
  317. pageBreakHandled = true;
  318. // Update so the available BPD is reported correctly
  319. int currentPageNum = pslm.getCurrentPageNum();
  320. int currentColumn = pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex();
  321. pageProvider.setStartOfNextElementList(currentPageNum, currentColumn, spanAllActive);
  322. // Make sure we only add the areas we haven't added already
  323. effectiveList.ignoreAtStart = newStartPos;
  324. if (!layoutRedone) {
  325. // Handle special page-master for last page
  326. setLastPageIndex(currentPageNum);
  327. // BodyRegion lastBody = pageProvider.getPage(false, currentPageNum).getPageViewport().getBodyRegion();
  328. pslm.setCurrentPage(pageProvider.getPage(false, currentPageNum));
  329. previousIndex = pageProvider.getIndexOfCachedLastPage();
  330. } else {
  331. setLastPageIndex(currentPageNum + 1);
  332. // pslm.setCurrentPage(previousPage);
  333. pageProvider.discardCacheStartingWith(previousIndex);
  334. pslm.setCurrentPage(pageProvider.getPage(false, currentPageNum));
  335. }
  336. layoutRedone = true;
  337. }
  338. /**
  339. * Restart the algorithm at the break corresponding to the given partCount. Used to
  340. * re-do the part after the last break in case of either column-balancing or a last
  341. * page-master.
  342. */
  343. private void redoLayout(PageBreakingAlgorithm alg, int partCount,
  344. BlockSequence originalList, BlockSequence effectiveList) {
  345. int newStartPos = 0;
  346. int restartPoint = pageProvider.getStartingPartIndexForLastPage(partCount);
  347. if (restartPoint > 0) {
  348. //Add definitive areas for the parts before the
  349. //restarting point
  350. addAreas(alg, restartPoint, originalList, effectiveList);
  351. //Get page break from which we restart
  352. PageBreakPosition pbp = alg.getPageBreaks().get(restartPoint - 1);
  353. newStartPos = alg.par.getFirstBoxIndex(pbp.getLeafPos() + 1);
  354. //Handle page break right here to avoid any side-effects
  355. if (newStartPos > 0) {
  356. handleBreakTrait(Constants.EN_PAGE);
  357. }
  358. }
  359. AbstractBreaker.log.debug("Restarting at " + restartPoint
  360. + ", new start position: " + newStartPos);
  361. pageBreakHandled = true;
  362. //Update so the available BPD is reported correctly
  363. int currentPageNum = pslm.getCurrentPageNum();
  364. pageProvider.setStartOfNextElementList(currentPageNum,
  365. pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex(), this.spanAllActive);
  366. //Make sure we only add the areas we haven't added already
  367. effectiveList.ignoreAtStart = newStartPos;
  368. PageBreakingAlgorithm algRestart;
  369. if (needColumnBalancing) {
  370. AbstractBreaker.log.debug("Column balancing now!!!");
  371. AbstractBreaker.log.debug("===================================================");
  372. //Restart last page
  373. algRestart = new BalancingColumnBreakingAlgorithm(
  374. getTopLevelLM(), getPageProvider(), createLayoutListener(),
  375. alignment, Constants.EN_START, footnoteSeparatorLength,
  376. isPartOverflowRecoveryActivated(),
  377. pslm.getCurrentPV().getBodyRegion().getColumnCount());
  378. AbstractBreaker.log.debug("===================================================");
  379. } else {
  380. // Handle special page-master for last page
  381. BodyRegion currentBody = pageProvider.getPage(false, currentPageNum)
  382. .getPageViewport().getBodyRegion();
  383. setLastPageIndex(currentPageNum);
  384. BodyRegion lastBody = pageProvider.getPage(false, currentPageNum)
  385. .getPageViewport().getBodyRegion();
  386. lastBody.getMainReference().setSpans(currentBody.getMainReference().getSpans());
  387. AbstractBreaker.log.debug("Last page handling now!!!");
  388. AbstractBreaker.log.debug("===================================================");
  389. //Restart last page
  390. algRestart = new PageBreakingAlgorithm(
  391. getTopLevelLM(), getPageProvider(), createLayoutListener(),
  392. alg.getAlignment(), alg.getAlignmentLast(),
  393. footnoteSeparatorLength,
  394. isPartOverflowRecoveryActivated(), false, false);
  395. AbstractBreaker.log.debug("===================================================");
  396. }
  397. int optimalPageCount = algRestart.findBreakingPoints(effectiveList,
  398. newStartPos,
  399. 1, true, BreakingAlgorithm.ALL_BREAKS);
  400. AbstractBreaker.log.debug("restart: optimalPageCount= " + optimalPageCount
  401. + " pageBreaks.size()= " + algRestart.getPageBreaks().size());
  402. boolean fitsOnePage
  403. = optimalPageCount <= pslm.getCurrentPV()
  404. .getBodyRegion().getMainReference().getCurrentSpan().getColumnCount();
  405. if (needColumnBalancing) {
  406. if (!fitsOnePage) {
  407. AbstractBreaker.log.warn(
  408. "Breaking algorithm produced more columns than are available.");
  409. /* reenable when everything works
  410. throw new IllegalStateException(
  411. "Breaking algorithm must not produce more columns than available.");
  412. */
  413. }
  414. } else {
  415. if (fitsOnePage) {
  416. //Replace last page
  417. pslm.setCurrentPage(pageProvider.getPage(false, currentPageNum));
  418. } else {
  419. //Last page-master cannot hold the content.
  420. //Add areas now...
  421. addAreas(alg, restartPoint, partCount - restartPoint, originalList, effectiveList);
  422. //...and add a blank last page
  423. setLastPageIndex(currentPageNum + 1);
  424. pslm.setCurrentPage(pslm.makeNewPage(true));
  425. return;
  426. }
  427. }
  428. addAreas(algRestart, optimalPageCount, originalList, effectiveList);
  429. }
  430. private void setLastPageIndex(int currentPageNum) {
  431. int lastPageIndex = pslm.getForcedLastPageNum(currentPageNum);
  432. pageProvider.setLastPageIndex(lastPageIndex);
  433. }
  434. /** {@inheritDoc} */
  435. protected void startPart(BlockSequence list, int breakClass) {
  436. AbstractBreaker.log.debug("startPart() breakClass=" + getBreakClassName(breakClass));
  437. if (pslm.getCurrentPage() == null) {
  438. throw new IllegalStateException("curPage must not be null");
  439. }
  440. if (!pageBreakHandled) {
  441. //firstPart is necessary because we need the first page before we start the
  442. //algorithm so we have a BPD and IPD. This may subject to change later when we
  443. //start handling more complex cases.
  444. if (!firstPart) {
  445. // if this is the first page that will be created by
  446. // the current BlockSequence, it could have a break
  447. // condition that must be satisfied;
  448. // otherwise, we may simply need a new page
  449. handleBreakTrait(breakClass);
  450. }
  451. pageProvider.setStartOfNextElementList(pslm.getCurrentPageNum(),
  452. pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex(),
  453. this.spanAllActive);
  454. }
  455. pageBreakHandled = false;
  456. // add static areas and resolve any new id areas
  457. // finish page and add to area tree
  458. firstPart = false;
  459. }
  460. /** {@inheritDoc} */
  461. protected void handleEmptyContent() {
  462. pslm.getCurrentPV().getPage().fakeNonEmpty();
  463. }
  464. /** {@inheritDoc} */
  465. protected void finishPart(PageBreakingAlgorithm alg, PageBreakPosition pbp) {
  466. // add footnote areas
  467. if (!pslm.getTableHeaderFootnotes().isEmpty()
  468. || pbp.footnoteFirstListIndex < pbp.footnoteLastListIndex
  469. || pbp.footnoteFirstElementIndex <= pbp.footnoteLastElementIndex
  470. || !pslm.getTableFooterFootnotes().isEmpty()) {
  471. for (List<KnuthElement> footnote : pslm.getTableHeaderFootnotes()) {
  472. addFootnoteAreas(footnote);
  473. }
  474. // call addAreas() for each FootnoteBodyLM
  475. for (int i = pbp.footnoteFirstListIndex; i <= pbp.footnoteLastListIndex; i++) {
  476. List elementList = alg.getFootnoteList(i);
  477. int firstIndex = (i == pbp.footnoteFirstListIndex
  478. ? pbp.footnoteFirstElementIndex : 0);
  479. int lastIndex = (i == pbp.footnoteLastListIndex
  480. ? pbp.footnoteLastElementIndex : elementList.size() - 1);
  481. addFootnoteAreas(elementList, firstIndex, lastIndex + 1);
  482. }
  483. for (List<KnuthElement> footnote : pslm.getTableFooterFootnotes()) {
  484. addFootnoteAreas(footnote);
  485. }
  486. // set the offset from the top margin
  487. Footnote parentArea = pslm.getCurrentPV().getBodyRegion().getFootnote();
  488. int topOffset = pslm.getCurrentPV().getBodyRegion().getBPD() - parentArea.getBPD();
  489. if (separatorArea != null) {
  490. topOffset -= separatorArea.getBPD();
  491. }
  492. parentArea.setTop(topOffset);
  493. parentArea.setSeparator(separatorArea);
  494. }
  495. pslm.getCurrentPV().getCurrentSpan().notifyFlowsFinished();
  496. pslm.clearTableHeadingFootnotes();
  497. }
  498. private void addFootnoteAreas(List<KnuthElement> footnote) {
  499. addFootnoteAreas(footnote, 0, footnote.size());
  500. }
  501. private void addFootnoteAreas(List<KnuthElement> footnote, int startIndex, int endIndex) {
  502. SpaceResolver.performConditionalsNotification(footnote, startIndex, endIndex - 1, -1);
  503. LayoutContext childLC = LayoutContext.newInstance();
  504. AreaAdditionUtil.addAreas(null, new KnuthPossPosIter(footnote, startIndex, endIndex), childLC);
  505. }
  506. /** {@inheritDoc} */
  507. protected FlowLayoutManager getCurrentChildLM() {
  508. return childFLM;
  509. }
  510. /** {@inheritDoc} */
  511. protected void observeElementList(List elementList) {
  512. ElementListObserver.observe(elementList, "breaker",
  513. pslm.getFObj().getId());
  514. }
  515. /**
  516. * Depending on the kind of break condition, move to next column
  517. * or page. May need to make an empty page if next page would
  518. * not have the desired "handedness".
  519. * @param breakVal - value of break-before or break-after trait.
  520. */
  521. private void handleBreakTrait(int breakVal) {
  522. Page curPage = pslm.getCurrentPage();
  523. switch (breakVal) {
  524. case Constants.EN_ALL:
  525. //break due to span change in multi-column layout
  526. curPage.getPageViewport().createSpan(true);
  527. this.spanAllActive = true;
  528. return;
  529. case Constants.EN_NONE:
  530. curPage.getPageViewport().createSpan(false);
  531. this.spanAllActive = false;
  532. return;
  533. case Constants.EN_COLUMN:
  534. case Constants.EN_AUTO:
  535. case Constants.EN_PAGE:
  536. case -1:
  537. PageViewport pv = curPage.getPageViewport();
  538. //Check if previous page was spanned
  539. boolean forceNewPageWithSpan = false;
  540. RegionBody rb = (RegionBody)curPage.getSimplePageMaster().getRegion(
  541. Constants.FO_REGION_BODY);
  542. forceNewPageWithSpan
  543. = (rb.getColumnCount() > 1
  544. && pv.getCurrentSpan().getColumnCount() == 1);
  545. if (forceNewPageWithSpan) {
  546. log.trace("Forcing new page with span");
  547. curPage = pslm.makeNewPage(false);
  548. curPage.getPageViewport().createSpan(true);
  549. } else {
  550. if (breakVal == Constants.EN_PAGE) {
  551. handleBreakBeforeFollowingPage(breakVal);
  552. } else {
  553. if (pv.getCurrentSpan().hasMoreFlows()) {
  554. log.trace("Moving to next flow");
  555. pv.getCurrentSpan().moveToNextFlow();
  556. } else {
  557. log.trace("Making new page");
  558. pslm.makeNewPage(false);
  559. }
  560. }
  561. }
  562. return;
  563. default:
  564. handleBreakBeforeFollowingPage(breakVal);
  565. }
  566. }
  567. private void handleBreakBeforeFollowingPage(int breakVal) {
  568. log.debug("handling break-before after page " + pslm.getCurrentPageNum() + " breakVal="
  569. + getBreakClassName(breakVal));
  570. if (needBlankPageBeforeNew(breakVal)) {
  571. log.trace("Inserting blank page");
  572. /* curPage = */pslm.makeNewPage(true);
  573. }
  574. if (needNewPage(breakVal)) {
  575. log.trace("Making new page");
  576. /* curPage = */pslm.makeNewPage(false);
  577. }
  578. }
  579. /**
  580. * Check if a blank page is needed to accommodate
  581. * desired even or odd page number.
  582. * @param breakVal - value of break-before or break-after trait.
  583. */
  584. private boolean needBlankPageBeforeNew(int breakVal) {
  585. if (breakVal == Constants.EN_PAGE
  586. || (pslm.getCurrentPage().getPageViewport().getPage().isEmpty())) {
  587. // any page is OK or we already have an empty page
  588. return false;
  589. } else {
  590. /* IF we are on the kind of page we need, we'll need a new page. */
  591. if (pslm.getCurrentPageNum() % 2 == 0) { // even page
  592. return (breakVal == Constants.EN_EVEN_PAGE);
  593. } else { // odd page
  594. return (breakVal == Constants.EN_ODD_PAGE);
  595. }
  596. }
  597. }
  598. /**
  599. * See if need to generate a new page
  600. * @param breakVal - value of break-before or break-after trait.
  601. */
  602. private boolean needNewPage(int breakVal) {
  603. if (pslm.getCurrentPage().getPageViewport().getPage().isEmpty()) {
  604. if (breakVal == Constants.EN_PAGE) {
  605. return false;
  606. } else if (pslm.getCurrentPageNum() % 2 == 0) { // even page
  607. return (breakVal == Constants.EN_ODD_PAGE);
  608. } else { // odd page
  609. return (breakVal == Constants.EN_EVEN_PAGE);
  610. }
  611. } else {
  612. return true;
  613. }
  614. }
  615. protected boolean shouldRedoLayout() {
  616. return shouldRedoLayout(-1);
  617. }
  618. protected boolean shouldRedoLayout(int partCount) {
  619. boolean lastPageMasterDefined = pslm.getPageSequence().hasPagePositionLast();
  620. if (!lastPageMasterDefined && partCount != -1) {
  621. lastPageMasterDefined = pslm.getPageSequence().hasPagePositionOnly() && pslm.isOnFirstPage(partCount - 1);
  622. }
  623. return (!hasMoreContent() && lastPageMasterDefined && !layoutRedone);
  624. }
  625. protected boolean wasLayoutRedone() {
  626. return layoutRedone;
  627. }
  628. protected boolean lastPageHasIPDChange() {
  629. boolean lastPageMasterDefined = pslm.getPageSequence().hasPagePositionLast();
  630. boolean onlyPageMasterDefined = pslm.getPageSequence().hasPagePositionOnly();
  631. if (lastPageMasterDefined && !onlyPageMasterDefined) {
  632. // code not very robust and unable to handle situations were only and last are defined
  633. int currentIPD = this.pageProvider.getCurrentIPD();
  634. int lastPageIPD = this.pageProvider.getLastPageIPD();
  635. if (lastPageIPD != -1 && currentIPD != lastPageIPD) {
  636. return true;
  637. }
  638. }
  639. return false;
  640. }
  641. protected boolean handlingStartOfFloat() {
  642. return handlingStartOfFloat;
  643. }
  644. protected void handleStartOfFloat(int fHeight, int fYOffset) {
  645. handlingStartOfFloat = true;
  646. handlingEndOfFloat = false;
  647. floatHeight = fHeight;
  648. floatYOffset = fYOffset;
  649. childFLM.handleFloatOn();
  650. }
  651. protected int getFloatHeight() {
  652. return floatHeight;
  653. }
  654. protected int getFloatYOffset() {
  655. return floatYOffset;
  656. }
  657. protected boolean handlingEndOfFloat() {
  658. return handlingEndOfFloat;
  659. }
  660. protected void handleEndOfFloat(int fHeight) {
  661. handlingEndOfFloat = true;
  662. handlingStartOfFloat = false;
  663. floatHeight = fHeight;
  664. childFLM.handleFloatOff();
  665. }
  666. protected boolean handlingFloat() {
  667. return (handlingStartOfFloat || handlingEndOfFloat);
  668. }
  669. public int getOffsetDueToFloat() {
  670. handlingEndOfFloat = false;
  671. return floatHeight + floatYOffset;
  672. }
  673. protected int handleFloatLayout(PageBreakingAlgorithm alg, int optimalPageCount, BlockSequence blockList,
  674. LayoutContext childLC) {
  675. pageBreakHandled = true;
  676. List firstElements = Collections.EMPTY_LIST;
  677. KnuthNode floatNode = alg.getBestFloatEdgeNode();
  678. int floatPosition = floatNode.position;
  679. KnuthElement floatElem = alg.getElement(floatPosition);
  680. Position positionAtBreak = floatElem.getPosition();
  681. if (!(positionAtBreak instanceof SpaceResolver.SpaceHandlingBreakPosition)) {
  682. throw new UnsupportedOperationException("Don't know how to restart at position" + positionAtBreak);
  683. }
  684. /* Retrieve the original position wrapped into this space position */
  685. positionAtBreak = positionAtBreak.getPosition();
  686. addAreas(alg, optimalPageCount, blockList, blockList);
  687. blockLists.clear();
  688. blockListIndex = -1;
  689. LayoutManager restartAtLM = null;
  690. if (positionAtBreak != null && positionAtBreak.getIndex() == -1) {
  691. if (positionAtBreak instanceof ListItemLayoutManager.ListItemPosition) {
  692. restartAtLM = positionAtBreak.getLM();
  693. } else {
  694. Position position;
  695. Iterator iter = blockList.listIterator(floatPosition + 1);
  696. do {
  697. KnuthElement nextElement = (KnuthElement) iter.next();
  698. position = nextElement.getPosition();
  699. } while (position == null || position instanceof SpaceResolver.SpaceHandlingPosition
  700. || position instanceof SpaceResolver.SpaceHandlingBreakPosition
  701. && position.getPosition().getIndex() == -1);
  702. LayoutManager surroundingLM = positionAtBreak.getLM();
  703. while (position.getLM() != surroundingLM) {
  704. position = position.getPosition();
  705. }
  706. restartAtLM = position.getPosition().getLM();
  707. }
  708. }
  709. int nextSequenceStartsOn = getNextBlockList(childLC, Constants.EN_COLUMN, positionAtBreak,
  710. restartAtLM, firstElements);
  711. return nextSequenceStartsOn;
  712. }
  713. protected void addAreasForFloats(PageBreakingAlgorithm alg, int startPart, int partCount,
  714. BlockSequence originalList, BlockSequence effectiveList, final LayoutContext childLC,
  715. int lastBreak, int startElementIndex, int endElementIndex) {
  716. FloatPosition pbp = alg.getFloatPosition();
  717. // Check the last break position for forced breaks
  718. int lastBreakClass;
  719. if (startElementIndex == 0) {
  720. lastBreakClass = effectiveList.getStartOn();
  721. } else {
  722. ListElement lastBreakElement = effectiveList.getElement(endElementIndex);
  723. if (lastBreakElement.isPenalty()) {
  724. KnuthPenalty pen = (KnuthPenalty) lastBreakElement;
  725. if (pen.getPenalty() == KnuthPenalty.INFINITE) {
  726. /**
  727. * That means that there was a keep.within-page="always", but that
  728. * it's OK to break at a column. TODO The break class is being
  729. * abused to implement keep.within-column and keep.within-page.
  730. * This is very misleading and must be revised.
  731. */
  732. lastBreakClass = Constants.EN_COLUMN;
  733. } else {
  734. lastBreakClass = pen.getBreakClass();
  735. }
  736. } else {
  737. lastBreakClass = Constants.EN_COLUMN;
  738. }
  739. }
  740. // the end of the new part
  741. endElementIndex = pbp.getLeafPos();
  742. // ignore the first elements added by the
  743. // PageSequenceLayoutManager
  744. startElementIndex += (startElementIndex == 0) ? effectiveList.ignoreAtStart : 0;
  745. log.debug("PLM> part: " + (startPart + partCount + 1) + ", start at pos " + startElementIndex
  746. + ", break at pos " + endElementIndex + ", break class = "
  747. + getBreakClassName(lastBreakClass));
  748. startPart(effectiveList, lastBreakClass);
  749. int displayAlign = getCurrentDisplayAlign();
  750. // The following is needed by SpaceResolver.performConditionalsNotification()
  751. // further down as there may be important Position elements in the element list trailer
  752. int notificationEndElementIndex = endElementIndex;
  753. // ignore the last elements added by the
  754. // PageSequenceLayoutManager
  755. endElementIndex -= (endElementIndex == (originalList.size() - 1)) ? effectiveList.ignoreAtEnd : 0;
  756. // ignore the last element in the page if it is a KnuthGlue
  757. // object
  758. if (((KnuthElement) effectiveList.get(endElementIndex)).isGlue()) {
  759. endElementIndex--;
  760. }
  761. // ignore KnuthGlue and KnuthPenalty objects
  762. // at the beginning of the line
  763. startElementIndex = alg.par.getFirstBoxIndex(startElementIndex);
  764. if (startElementIndex <= endElementIndex) {
  765. if (log.isDebugEnabled()) {
  766. log.debug(" addAreas from " + startElementIndex + " to " + endElementIndex);
  767. }
  768. // set the space adjustment ratio
  769. childLC.setSpaceAdjust(pbp.bpdAdjust);
  770. // add space before if display-align is center or bottom
  771. // add space after if display-align is distribute and
  772. // this is not the last page
  773. if (pbp.difference != 0 && displayAlign == Constants.EN_CENTER) {
  774. childLC.setSpaceBefore(pbp.difference / 2);
  775. } else if (pbp.difference != 0 && displayAlign == Constants.EN_AFTER) {
  776. childLC.setSpaceBefore(pbp.difference);
  777. }
  778. // Handle SpaceHandling(Break)Positions, see SpaceResolver!
  779. SpaceResolver.performConditionalsNotification(effectiveList, startElementIndex,
  780. notificationEndElementIndex, lastBreak);
  781. // Add areas of lines, in the current page, before the float or during float
  782. addAreas(new KnuthPossPosIter(effectiveList, startElementIndex, endElementIndex + 1), childLC);
  783. // add areas for the float, if applicable
  784. if (alg.handlingStartOfFloat()) {
  785. for (int k = startElementIndex; k < endElementIndex + 1; k++) {
  786. ListElement le = effectiveList.getElement(k);
  787. if (le instanceof KnuthBlockBox) {
  788. KnuthBlockBox kbb = (KnuthBlockBox) le;
  789. for (FloatContentLayoutManager fclm : kbb.getFloatContentLMs()) {
  790. fclm.processAreas(childLC);
  791. int floatHeight = fclm.getFloatHeight();
  792. int floatYOffset = fclm.getFloatYOffset();
  793. PageSequenceLayoutManager pslm = (PageSequenceLayoutManager) getTopLevelLM();
  794. pslm.recordStartOfFloat(floatHeight, floatYOffset);
  795. }
  796. }
  797. }
  798. }
  799. if (alg.handlingEndOfFloat()) {
  800. PageSequenceLayoutManager pslm = (PageSequenceLayoutManager) getTopLevelLM();
  801. pslm.setEndIntrusionAdjustment(0);
  802. pslm.setStartIntrusionAdjustment(0);
  803. int effectiveFloatHeight = alg.getFloatHeight();
  804. pslm.recordEndOfFloat(effectiveFloatHeight);
  805. }
  806. if (alg.handlingFloat()) {
  807. PageSequenceLayoutManager pslm = (PageSequenceLayoutManager) getTopLevelLM();
  808. alg.relayFootnotes(pslm);
  809. }
  810. } else {
  811. // no content for this part
  812. handleEmptyContent();
  813. }
  814. pageBreakHandled = true;
  815. }
  816. public void holdFootnotes(List fl, List ll, int tfl, int ifl, boolean fp, boolean nf, int fnfi, int fli,
  817. int fei, MinOptMax fsl, int pfli, int pfei) {
  818. relayedFootnotesList = fl;
  819. relayedLengthList = ll;
  820. relayedTotalFootnotesLength = tfl;
  821. relayedInsertedFootnotesLength = ifl;
  822. relayedFootnotesPending = fp;
  823. relayedNewFootnotes = nf;
  824. relayedFirstNewFootnoteIndex = fnfi;
  825. relayedFootnoteListIndex = fli;
  826. relayedFootnoteElementIndex = fei;
  827. relayedFootnoteSeparatorLength = fsl;
  828. previousFootnoteListIndex = pfli;
  829. previousFootnoteElementIndex = pfei;
  830. }
  831. public void retrieveFootones(PageBreakingAlgorithm alg) {
  832. if (relayedFootnotesList != null && relayedFootnotesList.size() > 0) {
  833. alg.loadFootnotes(relayedFootnotesList, relayedLengthList, relayedTotalFootnotesLength,
  834. relayedInsertedFootnotesLength, relayedFootnotesPending, relayedNewFootnotes,
  835. relayedFirstNewFootnoteIndex, relayedFootnoteListIndex, relayedFootnoteElementIndex,
  836. relayedFootnoteSeparatorLength, previousFootnoteListIndex,
  837. previousFootnoteElementIndex);
  838. relayedFootnotesList = null;
  839. relayedLengthList = null;
  840. relayedTotalFootnotesLength = 0;
  841. relayedInsertedFootnotesLength = 0;
  842. relayedFootnotesPending = false;
  843. relayedNewFootnotes = false;
  844. relayedFirstNewFootnoteIndex = 0;
  845. relayedFootnoteListIndex = 0;
  846. relayedFootnoteElementIndex = -1;
  847. relayedFootnoteSeparatorLength = null;
  848. }
  849. }
  850. }