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

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