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.

PageBreakingAlgorithm.java 57KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  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.LinkedList;
  21. import java.util.List;
  22. import java.util.ListIterator;
  23. import org.apache.commons.logging.Log;
  24. import org.apache.commons.logging.LogFactory;
  25. import org.apache.fop.fo.Constants;
  26. import org.apache.fop.fo.FObj;
  27. import org.apache.fop.layoutmgr.AbstractBreaker.FloatPosition;
  28. import org.apache.fop.layoutmgr.AbstractBreaker.PageBreakPosition;
  29. import org.apache.fop.layoutmgr.WhitespaceManagementPenalty.Variant;
  30. import org.apache.fop.traits.MinOptMax;
  31. import org.apache.fop.util.ListUtil;
  32. class PageBreakingAlgorithm extends BreakingAlgorithm {
  33. /** the logger for the class */
  34. private static Log log = LogFactory.getLog(PageBreakingAlgorithm.class);
  35. private final LayoutManager topLevelLM;
  36. private final PageProvider pageProvider;
  37. private final PageBreakingLayoutListener layoutListener;
  38. /** List of PageBreakPosition elements. */
  39. private LinkedList<PageBreakPosition> pageBreaks;
  40. /** Footnotes which are cited between the currently considered active node (previous
  41. * break) and the current considered break. Its type is
  42. * List&lt;List&lt;KnuthElement&gt;&gt;, it contains the sequences of KnuthElement
  43. * representing the footnotes bodies.
  44. */
  45. private List<List<KnuthElement>> footnotesList;
  46. /** Cumulated bpd of unhandled footnotes. */
  47. private List<Integer> lengthList;
  48. /** Length of all the footnotes which will be put on the current page. */
  49. private int totalFootnotesLength;
  50. /**
  51. * Length of all the footnotes which have already been inserted, up to the currently
  52. * considered element. That is, footnotes from the currently considered page plus
  53. * footnotes from its preceding pages.
  54. */
  55. private int insertedFootnotesLength;
  56. /** True if footnote citations have been met since the beginning of the page sequence. */
  57. private boolean footnotesPending;
  58. /** True if the elements met after the previous break point contain footnote citations. */
  59. private boolean newFootnotes;
  60. /** Index of the first footnote met after the previous break point. */
  61. private int firstNewFootnoteIndex;
  62. /** Index of the last footnote inserted on the current page. */
  63. private int footnoteListIndex;
  64. /** Index of the last element of the last footnote inserted on the current page. */
  65. private int footnoteElementIndex = -1;
  66. // demerits for a page break that splits a footnote
  67. private final int splitFootnoteDemerits = 5000;
  68. // demerits for a page break that defers a whole footnote to the following page
  69. private final int deferredFootnoteDemerits = 10000;
  70. private MinOptMax footnoteSeparatorLength;
  71. // the method noBreakBetween(int, int) uses these variables
  72. // to store parameters and result of the last call, in order
  73. // to reuse them and take less time
  74. private int storedPrevBreakIndex = -1;
  75. private int storedBreakIndex = -1;
  76. private boolean storedValue;
  77. //Controls whether overflows should be warned about or not
  78. private boolean autoHeight;
  79. //Controls whether a single part should be forced if possible (ex. block-container)
  80. private boolean favorSinglePart;
  81. private int ipdDifference;
  82. private KnuthNode bestNodeForIPDChange;
  83. public KnuthNode bestNodeForLastPage;
  84. //Used to keep track of switches in keep-context
  85. private int currentKeepContext = Constants.EN_AUTO;
  86. private KnuthNode lastBeforeKeepContextSwitch;
  87. // just one float for now...
  88. private boolean handlingStartOfFloat;
  89. private boolean handlingEndOfFloat;
  90. private int floatHeight;
  91. private KnuthNode bestFloatEdgeNode;
  92. private FloatPosition floatPosition;
  93. private int previousFootnoteListIndex = -2;
  94. private int previousFootnoteElementIndex = -2;
  95. private boolean relayingFootnotes;
  96. /**
  97. * Construct a page breaking algorithm.
  98. * @param topLevelLM the top level layout manager
  99. * @param pageProvider the page provider
  100. * @param layoutListener the layout listener
  101. * @param alignment alignment of the paragraph/page. One of {@link Constants#EN_START},
  102. * {@link Constants#EN_JUSTIFY}, {@link Constants#EN_CENTER},
  103. * {@link Constants#EN_END}.
  104. * For pages, {@link Constants#EN_BEFORE} and {@link Constants#EN_AFTER}
  105. * are mapped to the corresponding inline properties,
  106. * {@link Constants#EN_START} and {@link Constants#EN_END}.
  107. * @param alignmentLast alignment of the paragraph's last line
  108. * @param footnoteSeparatorLength length of footnote separator
  109. * @param partOverflowRecovery {@code true} if too long elements should be moved to
  110. * the next line/part
  111. * @param autoHeight true if auto height
  112. * @param favorSinglePart true if favoring single part
  113. * @see BreakingAlgorithm
  114. */
  115. public PageBreakingAlgorithm(LayoutManager topLevelLM,
  116. PageProvider pageProvider,
  117. PageBreakingLayoutListener layoutListener,
  118. int alignment, int alignmentLast,
  119. MinOptMax footnoteSeparatorLength,
  120. boolean partOverflowRecovery, boolean autoHeight,
  121. boolean favorSinglePart) {
  122. super(alignment, alignmentLast, true, partOverflowRecovery, 0);
  123. this.topLevelLM = topLevelLM;
  124. this.pageProvider = pageProvider;
  125. this.layoutListener = layoutListener;
  126. best = new BestPageRecords();
  127. this.footnoteSeparatorLength = footnoteSeparatorLength;
  128. this.autoHeight = autoHeight;
  129. this.favorSinglePart = favorSinglePart;
  130. }
  131. /**
  132. * This class represents a feasible breaking point
  133. * with extra information about footnotes.
  134. */
  135. protected class KnuthPageNode extends KnuthNode {
  136. /** Additional length due to already inserted footnotes. */
  137. public int insertedFootnotes;
  138. /** Total length of the footnotes. */
  139. public int totalFootnotes;
  140. /** Index of the last inserted footnote. */
  141. public int footnoteListIndex;
  142. /** Index of the last inserted element of the last inserted footnote. */
  143. public int footnoteElementIndex;
  144. /**
  145. * Pending variants of dynamic contents that were evaluated WRT this node.
  146. * When computing page difference for a break element, the total width of these variants
  147. * will be added to 'actualWidth'.
  148. */
  149. private final List<Variant> pendingVariants = new ArrayList<Variant>();
  150. private int totalVariantsWidth;
  151. public KnuthPageNode(int position,
  152. int line, int fitness,
  153. int totalWidth, int totalStretch, int totalShrink,
  154. int insertedFootnotes, int totalFootnotes,
  155. int footnoteListIndex, int footnoteElementIndex,
  156. double adjustRatio, int availableShrink, int availableStretch,
  157. int difference, double totalDemerits, KnuthNode previous) {
  158. super(position, line, fitness,
  159. totalWidth, totalStretch, totalShrink,
  160. adjustRatio, availableShrink, availableStretch,
  161. difference, totalDemerits, previous);
  162. this.totalFootnotes = totalFootnotes;
  163. this.insertedFootnotes = insertedFootnotes;
  164. this.footnoteListIndex = footnoteListIndex;
  165. this.footnoteElementIndex = footnoteElementIndex;
  166. }
  167. public void addVariant(Variant variant) {
  168. pendingVariants.add(variant);
  169. totalVariantsWidth += variant.width;
  170. }
  171. }
  172. /**
  173. * this class stores information about how the nodes
  174. * which could start a line ending at the current element
  175. */
  176. protected class BestPageRecords extends BestRecords {
  177. private final int[] bestInsertedFootnotesLength = new int[4];
  178. private final int[] bestTotalFootnotesLength = new int[4];
  179. private final int[] bestFootnoteListIndex = new int[4];
  180. private final int[] bestFootnoteElementIndex = new int[4];
  181. @Override
  182. public void addRecord(double demerits, KnuthNode node, double adjust,
  183. int availableShrink, int availableStretch,
  184. int difference, int fitness) {
  185. super.addRecord(demerits, node, adjust,
  186. availableShrink, availableStretch,
  187. difference, fitness);
  188. bestInsertedFootnotesLength[fitness] = insertedFootnotesLength;
  189. bestTotalFootnotesLength[fitness] = totalFootnotesLength;
  190. bestFootnoteListIndex[fitness] = footnoteListIndex;
  191. bestFootnoteElementIndex[fitness] = footnoteElementIndex;
  192. }
  193. public int getInsertedFootnotesLength(int fitness) {
  194. return bestInsertedFootnotesLength[fitness];
  195. }
  196. public int getTotalFootnotesLength(int fitness) {
  197. return bestTotalFootnotesLength[fitness];
  198. }
  199. public int getFootnoteListIndex(int fitness) {
  200. return bestFootnoteListIndex[fitness];
  201. }
  202. public int getFootnoteElementIndex(int fitness) {
  203. return bestFootnoteElementIndex[fitness];
  204. }
  205. }
  206. /** {@inheritDoc} */
  207. @Override
  208. protected void initialize() {
  209. super.initialize();
  210. insertedFootnotesLength = 0;
  211. footnoteListIndex = 0;
  212. footnoteElementIndex = -1;
  213. if (topLevelLM instanceof PageSequenceLayoutManager) {
  214. PageSequenceLayoutManager pslm = (PageSequenceLayoutManager) topLevelLM;
  215. if (pslm.handlingStartOfFloat() || pslm.handlingEndOfFloat()) {
  216. pslm.retrieveFootnotes(this);
  217. }
  218. if (pslm.handlingStartOfFloat()) {
  219. floatHeight = Math.min(pslm.getFloatHeight(), lineWidth - pslm.getFloatYOffset());
  220. }
  221. if (pslm.handlingEndOfFloat()) {
  222. totalWidth += pslm.getOffsetDueToFloat() + insertedFootnotesLength;
  223. }
  224. }
  225. }
  226. /**
  227. * Overridden to defer a part to the next page, if it
  228. * must be kept within one page, but is too large to fit in
  229. * the last column.
  230. * {@inheritDoc}
  231. */
  232. @Override
  233. protected KnuthNode recoverFromTooLong(KnuthNode lastTooLong) {
  234. if (log.isDebugEnabled()) {
  235. log.debug("Recovering from too long: " + lastTooLong);
  236. log.debug("\tlastTooShort = " + getLastTooShort());
  237. log.debug("\tlastBeforeKeepContextSwitch = " + lastBeforeKeepContextSwitch);
  238. log.debug("\tcurrentKeepContext = "
  239. + AbstractBreaker.getBreakClassName(currentKeepContext));
  240. }
  241. if (lastBeforeKeepContextSwitch == null
  242. || currentKeepContext == Constants.EN_AUTO) {
  243. return super.recoverFromTooLong(lastTooLong);
  244. }
  245. KnuthNode node = lastBeforeKeepContextSwitch;
  246. lastBeforeKeepContextSwitch = null;
  247. // content would overflow, insert empty page/column(s) and try again
  248. while (!pageProvider.endPage(node.line - 1)) {
  249. log.trace("Adding node for empty column");
  250. node = createNode(
  251. node.position,
  252. node.line + 1, 1,
  253. 0, 0, 0,
  254. 0, 0, 0,
  255. 0, 0, node);
  256. }
  257. return node;
  258. }
  259. /**
  260. * Compare two KnuthNodes and return the node with the least demerit.
  261. *
  262. * @param node1 The first knuth node.
  263. * @param node2 The other knuth node.
  264. * @return the node with the least demerit.
  265. */
  266. @Override
  267. protected KnuthNode compareNodes(KnuthNode node1, KnuthNode node2) {
  268. /* if either node is null, return the other one */
  269. if (node1 == null || node2 == null) {
  270. return (node1 == null) ? node2 : node1;
  271. }
  272. /* if either one of the nodes corresponds to a mere column-break,
  273. * and the other one corresponds to a page-break, return the page-break node
  274. */
  275. if (pageProvider != null) {
  276. if (pageProvider.endPage(node1.line - 1)
  277. && !pageProvider.endPage(node2.line - 1)) {
  278. return node1;
  279. } else if (pageProvider.endPage(node2.line - 1)
  280. && !pageProvider.endPage(node1.line - 1)) {
  281. return node2;
  282. }
  283. }
  284. /* all other cases: use superclass implementation */
  285. return super.compareNodes(node1, node2);
  286. }
  287. /** {@inheritDoc} */
  288. @Override
  289. protected KnuthNode createNode(int position,
  290. int line, int fitness,
  291. int totalWidth, int totalStretch, int totalShrink,
  292. double adjustRatio, int availableShrink, int availableStretch,
  293. int difference, double totalDemerits, KnuthNode previous) {
  294. return new KnuthPageNode(position, line, fitness,
  295. totalWidth, totalStretch, totalShrink,
  296. insertedFootnotesLength, totalFootnotesLength,
  297. footnoteListIndex, footnoteElementIndex,
  298. adjustRatio, availableShrink, availableStretch,
  299. difference, totalDemerits, previous);
  300. }
  301. /** {@inheritDoc} */
  302. @Override
  303. protected KnuthNode createNode(int position, int line, int fitness,
  304. int totalWidth, int totalStretch, int totalShrink) {
  305. return new KnuthPageNode(position, line, fitness,
  306. totalWidth, totalStretch, totalShrink,
  307. ((BestPageRecords) best).getInsertedFootnotesLength(fitness),
  308. ((BestPageRecords) best).getTotalFootnotesLength(fitness),
  309. ((BestPageRecords) best).getFootnoteListIndex(fitness),
  310. ((BestPageRecords) best).getFootnoteElementIndex(fitness),
  311. best.getAdjust(fitness), best.getAvailableShrink(fitness),
  312. best.getAvailableStretch(fitness), best.getDifference(fitness),
  313. best.getDemerits(fitness), best.getNode(fitness));
  314. }
  315. /**
  316. * Page-breaking specific handling of the given box. Currently it adds the footnotes
  317. * cited in the given box to the list of to-be-handled footnotes.
  318. * {@inheritDoc}
  319. */
  320. @Override
  321. protected void handleBox(KnuthBox box) {
  322. super.handleBox(box);
  323. if (box instanceof KnuthBlockBox
  324. && ((KnuthBlockBox) box).hasAnchors()) {
  325. handleFootnotes(((KnuthBlockBox) box).getElementLists());
  326. if (!newFootnotes) {
  327. newFootnotes = true;
  328. firstNewFootnoteIndex = footnotesList.size() - 1;
  329. }
  330. }
  331. if (box instanceof KnuthBlockBox && ((KnuthBlockBox) box).hasFloatAnchors()) {
  332. handlingStartOfFloat = true;
  333. }
  334. if (floatHeight != 0 && totalWidth >= floatHeight) {
  335. handlingEndOfFloat = true;
  336. }
  337. }
  338. /**
  339. * Overridden to consider penalties with value {@link KnuthElement#INFINITE}
  340. * as legal break-points, if the current keep-context allows this
  341. * (a keep-*.within-page="always" constraint still permits column-breaks)
  342. * {@inheritDoc}
  343. */
  344. @Override
  345. protected void handlePenaltyAt(KnuthPenalty penalty, int position,
  346. int allowedBreaks) {
  347. super.handlePenaltyAt(penalty, position, allowedBreaks);
  348. /* if the penalty had value INFINITE, default implementation
  349. * will not have considered it a legal break, but it could still
  350. * be one.
  351. */
  352. if (penalty.getPenalty() == KnuthPenalty.INFINITE) {
  353. int breakClass = penalty.getBreakClass();
  354. if (breakClass == Constants.EN_PAGE
  355. || breakClass == Constants.EN_COLUMN) {
  356. considerLegalBreak(penalty, position);
  357. }
  358. }
  359. }
  360. /**
  361. * Handles the footnotes cited inside a block-level box. Updates footnotesList and the
  362. * value of totalFootnotesLength with the lengths of the given footnotes.
  363. * @param elementLists list of KnuthElement sequences corresponding to the footnotes
  364. * bodies
  365. */
  366. private void handleFootnotes(List<List<KnuthElement>> elementLists) {
  367. // initialization
  368. if (!footnotesPending) {
  369. footnotesPending = true;
  370. footnotesList = new ArrayList<List<KnuthElement>>();
  371. lengthList = new ArrayList<Integer>();
  372. totalFootnotesLength = 0;
  373. }
  374. if (!newFootnotes) {
  375. newFootnotes = true;
  376. firstNewFootnoteIndex = footnotesList.size();
  377. }
  378. // compute the total length of the footnotes
  379. for (List<KnuthElement> noteList : elementLists) {
  380. int noteLength = 0;
  381. footnotesList.add(noteList);
  382. for (KnuthElement element : noteList) {
  383. if (element.isBox() || element.isGlue()) {
  384. noteLength += element.getWidth();
  385. }
  386. }
  387. int prevLength = (lengthList == null || lengthList.isEmpty())
  388. ? 0
  389. : ListUtil.getLast(lengthList);
  390. if (lengthList != null) {
  391. lengthList.add(prevLength + noteLength);
  392. }
  393. totalFootnotesLength += noteLength;
  394. }
  395. }
  396. /** {@inheritDoc} */
  397. @Override
  398. protected int restartFrom(KnuthNode restartingNode, int currentIndex) {
  399. int returnValue = super.restartFrom(restartingNode, currentIndex);
  400. newFootnotes = false;
  401. if (footnotesPending) {
  402. // remove from footnotesList the note lists that will be met
  403. // after the restarting point
  404. for (int j = currentIndex; j >= restartingNode.position; j--) {
  405. final KnuthElement resetElement = getElement(j);
  406. if (resetElement instanceof KnuthBlockBox
  407. && ((KnuthBlockBox) resetElement).hasAnchors()) {
  408. resetFootnotes(((KnuthBlockBox) resetElement).getElementLists());
  409. }
  410. }
  411. assert restartingNode instanceof KnuthPageNode;
  412. KnuthPageNode restartingPageNode = (KnuthPageNode) restartingNode;
  413. footnoteElementIndex = restartingPageNode.footnoteElementIndex;
  414. footnoteListIndex = restartingPageNode.footnoteListIndex;
  415. totalFootnotesLength = restartingPageNode.totalFootnotes;
  416. insertedFootnotesLength = restartingPageNode.insertedFootnotes;
  417. }
  418. return returnValue;
  419. }
  420. private void resetFootnotes(List<List<KnuthElement>> elementLists) {
  421. for (int i = 0; i < elementLists.size(); i++) {
  422. ListUtil.removeLast(footnotesList);
  423. ListUtil.removeLast(lengthList);
  424. }
  425. // update footnotesPending;
  426. if (footnotesList.size() == 0) {
  427. footnotesPending = false;
  428. }
  429. }
  430. /** {@inheritDoc} */
  431. @Override
  432. protected void considerLegalBreak(KnuthElement element, int elementIdx) {
  433. if (element.isPenalty()) {
  434. int breakClass = ((KnuthPenalty) element).getBreakClass();
  435. switch (breakClass) {
  436. case Constants.EN_PAGE:
  437. if (this.currentKeepContext != breakClass) {
  438. this.lastBeforeKeepContextSwitch = getLastTooShort();
  439. }
  440. this.currentKeepContext = breakClass;
  441. break;
  442. case Constants.EN_COLUMN:
  443. if (this.currentKeepContext != breakClass) {
  444. this.lastBeforeKeepContextSwitch = getLastTooShort();
  445. }
  446. this.currentKeepContext = breakClass;
  447. break;
  448. case Constants.EN_AUTO:
  449. this.currentKeepContext = breakClass;
  450. break;
  451. default:
  452. //nop
  453. }
  454. }
  455. super.considerLegalBreak(element, elementIdx);
  456. newFootnotes = false;
  457. }
  458. /** {@inheritDoc} */
  459. @Override
  460. protected boolean elementCanEndLine(KnuthElement element, int line, int difference) {
  461. if (!(element.isPenalty()) || pageProvider == null) {
  462. return true;
  463. } else {
  464. KnuthPenalty p = (KnuthPenalty) element;
  465. if (p.getPenalty() <= 0) {
  466. return true;
  467. } else {
  468. int context = p.getBreakClass();
  469. switch (context) {
  470. case Constants.EN_LINE:
  471. case Constants.EN_COLUMN:
  472. return p.getPenalty() < KnuthPenalty.INFINITE;
  473. case Constants.EN_PAGE:
  474. return p.getPenalty() < KnuthPenalty.INFINITE
  475. || !pageProvider.endPage(line - 1);
  476. case Constants.EN_AUTO:
  477. log.debug("keep is not auto but context is");
  478. return true;
  479. default:
  480. if (p.getPenalty() < KnuthPenalty.INFINITE) {
  481. log.debug("Non recognized keep context:" + context);
  482. return true;
  483. } else {
  484. return false;
  485. }
  486. }
  487. }
  488. }
  489. }
  490. /** {@inheritDoc} */
  491. @Override
  492. protected int computeDifference(KnuthNode activeNode, KnuthElement element,
  493. int elementIndex) {
  494. KnuthPageNode pageNode = (KnuthPageNode) activeNode;
  495. int actualWidth = totalWidth - pageNode.totalWidth;
  496. int footnoteSplit;
  497. boolean canDeferOldFN;
  498. actualWidth += pageNode.totalVariantsWidth;
  499. if (element instanceof WhitespaceManagementPenalty) {
  500. actualWidth += handleWhitespaceManagementPenalty(pageNode,
  501. (WhitespaceManagementPenalty) element, elementIndex);
  502. } else if (element.isPenalty()) {
  503. actualWidth += element.getWidth();
  504. }
  505. if (footnotesPending) {
  506. // compute the total length of the footnotes not yet inserted
  507. int allFootnotes = totalFootnotesLength - pageNode.insertedFootnotes;
  508. if (allFootnotes > 0) {
  509. // this page contains some footnote citations
  510. // add the footnote separator width
  511. actualWidth += footnoteSeparatorLength.getOpt();
  512. if (actualWidth + allFootnotes <= getLineWidth(activeNode.line)) {
  513. // there is enough space to insert all footnotes:
  514. // add the whole allFootnotes length
  515. actualWidth += allFootnotes;
  516. insertedFootnotesLength = pageNode.insertedFootnotes + allFootnotes;
  517. footnoteListIndex = footnotesList.size() - 1;
  518. footnoteElementIndex
  519. = getFootnoteList(footnoteListIndex).size() - 1;
  520. } else if (((canDeferOldFN = canDeferOldFootnotes(
  521. pageNode, elementIndex))
  522. || newFootnotes)
  523. && (footnoteSplit = getFootnoteSplit(
  524. pageNode, getLineWidth(activeNode.line) - actualWidth,
  525. canDeferOldFN)) > 0) {
  526. // it is allowed to break or even defer footnotes if either:
  527. // - there are new footnotes in the last piece of content, and
  528. // there is space to add at least a piece of the first one
  529. // - or the previous page break deferred some footnote lines, and
  530. // this is the first feasible break; in this case it is allowed
  531. // to break and defer, if necessary, old and new footnotes
  532. actualWidth += footnoteSplit;
  533. insertedFootnotesLength = pageNode.insertedFootnotes + footnoteSplit;
  534. // footnoteListIndex has been set in getFootnoteSplit()
  535. // footnoteElementIndex has been set in getFootnoteSplit()
  536. } else {
  537. // there is no space to add the smallest piece of footnote,
  538. // or we are trying to add a piece of content with no footnotes and
  539. // it does not fit in the page, because of previous footnote bodies
  540. // that cannot be broken:
  541. // add the whole allFootnotes length, so this breakpoint will be discarded
  542. actualWidth += allFootnotes;
  543. insertedFootnotesLength = pageNode.insertedFootnotes + allFootnotes;
  544. footnoteListIndex = footnotesList.size() - 1;
  545. footnoteElementIndex
  546. = getFootnoteList(footnoteListIndex).size() - 1;
  547. }
  548. } else {
  549. // all footnotes have already been placed on previous pages
  550. }
  551. } else {
  552. // there are no footnotes
  553. }
  554. int diff = getLineWidth(activeNode.line) - actualWidth;
  555. if (autoHeight && diff < 0) {
  556. //getLineWidth() for auto-height parts return 0 so the diff will be negative
  557. return 0; //...but we don't want to shrink in this case. Stick to optimum.
  558. } else {
  559. return diff;
  560. }
  561. }
  562. /**
  563. * Evaluates the variants corresponding to the given penalty until one that
  564. * leads to an acceptable adjustment ratio is found. That variant will
  565. * be added to the list of pending variants in the given active node.
  566. */
  567. private int handleWhitespaceManagementPenalty(KnuthPageNode activeNode,
  568. WhitespaceManagementPenalty penalty, int elementIndex) {
  569. for (Variant var : penalty.getVariants()) {
  570. int difference = computeDifference(activeNode, var.getPenalty(), elementIndex);
  571. double r = computeAdjustmentRatio(activeNode, difference);
  572. if (r >= -1.0) {
  573. activeNode.addVariant(var);
  574. return var.width;
  575. }
  576. }
  577. return 0;
  578. }
  579. /**
  580. * Checks whether footnotes from preceding pages may be deferred to the page after
  581. * the given element.
  582. * @param node active node for the preceding page break
  583. * @param contentElementIndex index of the Knuth element considered for the
  584. * current page break
  585. * @return true if footnotes can be deferred
  586. */
  587. private boolean canDeferOldFootnotes(KnuthPageNode node, int contentElementIndex) {
  588. return (noBreakBetween(node.position, contentElementIndex)
  589. && deferredFootnotes(node.footnoteListIndex,
  590. node.footnoteElementIndex, node.insertedFootnotes));
  591. }
  592. /**
  593. * Returns true if there may be no breakpoint between the two given elements.
  594. * @param prevBreakIndex index of the element from the currently considered active
  595. * node
  596. * @param breakIndex index of the currently considered breakpoint
  597. * @return true if no element between the two can be a breakpoint
  598. */
  599. private boolean noBreakBetween(int prevBreakIndex, int breakIndex) {
  600. // this method stores the parameters and the return value from previous calls
  601. // in order to avoid scanning the element list unnecessarily:
  602. // - if there is no break between element #i and element #j
  603. // there will not be a break between #(i+h) and #j too
  604. // - if there is a break between element #i and element #j
  605. // there will be a break between #(i-h) and #(j+k) too
  606. if (storedPrevBreakIndex != -1
  607. && ((prevBreakIndex >= storedPrevBreakIndex
  608. && breakIndex == storedBreakIndex
  609. && storedValue)
  610. || (prevBreakIndex <= storedPrevBreakIndex
  611. && breakIndex >= storedBreakIndex
  612. && !storedValue))) {
  613. // use the stored value, do nothing
  614. } else {
  615. // compute the new value
  616. int index;
  617. // ignore suppressed elements
  618. for (index = prevBreakIndex + 1;
  619. !par.getElement(index).isBox();
  620. index++) {
  621. //nop
  622. }
  623. // find the next break
  624. for (;
  625. index < breakIndex;
  626. index++) {
  627. if (par.getElement(index).isGlue() && par.getElement(index - 1).isBox()
  628. || par.getElement(index).isPenalty()
  629. && ((KnuthElement) par
  630. .getElement(index)).getPenalty() < KnuthElement.INFINITE) {
  631. // break found
  632. break;
  633. }
  634. }
  635. // update stored parameters and value
  636. storedPrevBreakIndex = prevBreakIndex;
  637. storedBreakIndex = breakIndex;
  638. storedValue = (index == breakIndex);
  639. }
  640. return storedValue;
  641. }
  642. /**
  643. * Returns true if their are (pieces of) footnotes to be typeset on the current page.
  644. * @param listIndex index of the last inserted footnote for the currently considered
  645. * active node
  646. * @param elementIndex index of the last element of the last inserted footnote
  647. * @param length total length of all footnotes inserted so far
  648. */
  649. private boolean deferredFootnotes(int listIndex, int elementIndex, int length) {
  650. return ((newFootnotes
  651. && firstNewFootnoteIndex != 0
  652. && (listIndex < firstNewFootnoteIndex - 1
  653. || elementIndex < getFootnoteList(listIndex).size() - 1))
  654. || length < totalFootnotesLength);
  655. }
  656. /**
  657. * Tries to split the flow of footnotes to put one part on the current page.
  658. * @param activeNode currently considered previous page break
  659. * @param availableLength available space for footnotes
  660. * @param canDeferOldFootnotes
  661. * @return ...
  662. */
  663. private int getFootnoteSplit(KnuthPageNode activeNode, int availableLength,
  664. boolean canDeferOldFootnotes) {
  665. return getFootnoteSplit(activeNode.footnoteListIndex,
  666. activeNode.footnoteElementIndex,
  667. activeNode.insertedFootnotes,
  668. availableLength, canDeferOldFootnotes);
  669. }
  670. /**
  671. * Tries to split the flow of footnotes to put one part on the current page.
  672. * @param prevListIndex index of the last footnote on the previous page
  673. * @param prevElementIndex index of the last element of the last footnote
  674. * @param prevLength total length of footnotes inserted so far
  675. * @param availableLength available space for footnotes on this page
  676. * @param canDeferOldFootnotes
  677. * @return ...
  678. */
  679. private int getFootnoteSplit(int prevListIndex, int prevElementIndex, int prevLength,
  680. int availableLength, boolean canDeferOldFootnotes) {
  681. if (availableLength <= 0) {
  682. return 0;
  683. } else {
  684. // the split should contain a piece of the last footnote
  685. // together with all previous, not yet inserted footnotes;
  686. // but if this is not possible, try adding as much content as possible
  687. int splitLength = 0;
  688. ListIterator<KnuthElement> noteListIterator;
  689. KnuthElement element;
  690. boolean somethingAdded = false;
  691. // prevListIndex and prevElementIndex points to the last footnote element
  692. // already placed in a page: advance to the next element
  693. int listIndex = prevListIndex;
  694. int elementIndex = prevElementIndex;
  695. if (elementIndex == getFootnoteList(listIndex).size() - 1) {
  696. listIndex++;
  697. elementIndex = 0;
  698. } else {
  699. elementIndex++;
  700. }
  701. // try adding whole notes
  702. if (footnotesList.size() - 1 > listIndex) {
  703. // add the previous footnotes: these cannot be broken or deferred
  704. if (!canDeferOldFootnotes && newFootnotes && firstNewFootnoteIndex > 0) {
  705. splitLength = lengthList.get(firstNewFootnoteIndex - 1) - prevLength;
  706. listIndex = firstNewFootnoteIndex;
  707. elementIndex = 0;
  708. }
  709. // try adding the new footnotes
  710. while (lengthList.get(listIndex) - prevLength
  711. <= availableLength) {
  712. splitLength = lengthList.get(listIndex) - prevLength;
  713. somethingAdded = true;
  714. listIndex++;
  715. elementIndex = 0;
  716. }
  717. // as this method is called only if it is not possible to insert
  718. // all footnotes, at this point listIndex and elementIndex points to
  719. // an existing element, the next one we will try to insert
  720. }
  721. // try adding a split of the next note
  722. noteListIterator = getFootnoteList(listIndex).listIterator(elementIndex);
  723. int prevSplitLength = 0;
  724. int prevIndex = -1;
  725. int index = -1;
  726. while (splitLength <= availableLength) {
  727. if (somethingAdded) {
  728. prevSplitLength = splitLength;
  729. prevIndex = index;
  730. }
  731. // get a sub-sequence from the note element list
  732. boolean boxPreceding = false;
  733. while (noteListIterator.hasNext()) {
  734. // as this method is called only if it is not possible to insert
  735. // all footnotes, and we have already tried (and failed) to insert
  736. // this whole footnote, the while loop will never reach the end
  737. // of the note sequence
  738. element = noteListIterator.next();
  739. if (element.isBox()) {
  740. // element is a box
  741. splitLength += element.getWidth();
  742. boxPreceding = true;
  743. if (splitLength > prevSplitLength) {
  744. // and it is non-empty
  745. somethingAdded = true;
  746. }
  747. } else if (element.isGlue()) {
  748. // element is a glue
  749. if (boxPreceding) {
  750. // end of the sub-sequence
  751. index = noteListIterator.previousIndex();
  752. break;
  753. }
  754. boxPreceding = false;
  755. splitLength += element.getWidth();
  756. } else {
  757. // element is a penalty
  758. if (element.getPenalty() < KnuthElement.INFINITE) {
  759. // end of the sub-sequence
  760. index = noteListIterator.previousIndex();
  761. break;
  762. }
  763. boxPreceding = false;
  764. }
  765. }
  766. }
  767. // if prevSplitLength is 0, this means that the available length isn't enough
  768. // to insert even the smallest split of the last footnote, so we cannot end a
  769. // page here
  770. // if prevSplitLength is > 0 we can insert some footnote content in this page
  771. // and insert the remaining in the following one
  772. if (!somethingAdded) {
  773. // there was not enough space to add a piece of the first new footnote
  774. // this is not a good break
  775. prevSplitLength = 0;
  776. } else if (prevSplitLength > 0) {
  777. // prevIndex is -1 if we have added only some whole footnotes
  778. footnoteListIndex = (prevIndex != -1) ? listIndex : listIndex - 1;
  779. footnoteElementIndex = (prevIndex != -1)
  780. ? prevIndex
  781. : getFootnoteList(footnoteListIndex).size() - 1;
  782. }
  783. return prevSplitLength;
  784. }
  785. }
  786. /** {@inheritDoc} */
  787. @Override
  788. protected double computeAdjustmentRatio(KnuthNode activeNode, int difference) {
  789. // compute the adjustment ratio
  790. if (difference > 0) {
  791. int maxAdjustment = totalStretch - activeNode.totalStretch;
  792. // add the footnote separator stretch if some footnote content will be added
  793. if (((KnuthPageNode) activeNode).insertedFootnotes < totalFootnotesLength) {
  794. maxAdjustment += footnoteSeparatorLength.getStretch();
  795. }
  796. if (maxAdjustment > 0) {
  797. return (double) difference / maxAdjustment;
  798. } else {
  799. return INFINITE_RATIO;
  800. }
  801. } else if (difference < 0) {
  802. int maxAdjustment = totalShrink - activeNode.totalShrink;
  803. // add the footnote separator shrink if some footnote content will be added
  804. if (((KnuthPageNode) activeNode).insertedFootnotes < totalFootnotesLength) {
  805. maxAdjustment += footnoteSeparatorLength.getShrink();
  806. }
  807. if (maxAdjustment > 0) {
  808. return (double) difference / maxAdjustment;
  809. } else {
  810. return -INFINITE_RATIO;
  811. }
  812. } else {
  813. return 0;
  814. }
  815. }
  816. /** {@inheritDoc} */
  817. @Override
  818. protected double computeDemerits(KnuthNode activeNode, KnuthElement element,
  819. int fitnessClass, double r) {
  820. double demerits = 0;
  821. // compute demerits
  822. double f = Math.abs(r);
  823. f = 1 + 100 * f * f * f;
  824. if (element.isPenalty()) {
  825. double penalty = element.getPenalty();
  826. if (penalty >= 0) {
  827. f += penalty;
  828. demerits = f * f;
  829. } else if (!element.isForcedBreak()) {
  830. demerits = f * f - penalty * penalty;
  831. } else {
  832. demerits = f * f;
  833. }
  834. } else {
  835. demerits = f * f;
  836. }
  837. if (element.isPenalty() && ((KnuthPenalty) element).isPenaltyFlagged()
  838. && getElement(activeNode.position).isPenalty()
  839. && ((KnuthPenalty) getElement(activeNode.position)).isPenaltyFlagged()) {
  840. // add demerit for consecutive breaks at flagged penalties
  841. demerits += repeatedFlaggedDemerit;
  842. }
  843. if (Math.abs(fitnessClass - activeNode.fitness) > 1) {
  844. // add demerit for consecutive breaks
  845. // with very different fitness classes
  846. demerits += incompatibleFitnessDemerit;
  847. }
  848. if (footnotesPending) {
  849. if (footnoteListIndex < footnotesList.size() - 1) {
  850. // add demerits for the deferred footnotes
  851. demerits += (footnotesList.size() - 1 - footnoteListIndex)
  852. * deferredFootnoteDemerits;
  853. }
  854. if (footnoteListIndex < footnotesList.size()) {
  855. if (footnoteElementIndex
  856. < getFootnoteList(footnoteListIndex).size() - 1) {
  857. // add demerits for the footnote split between pages
  858. demerits += splitFootnoteDemerits;
  859. }
  860. } else {
  861. //TODO Why can this happen in the first place? Does anybody know? See #44160
  862. }
  863. }
  864. demerits += activeNode.totalDemerits;
  865. return demerits;
  866. }
  867. /** {@inheritDoc} */
  868. @Override
  869. protected void finish() {
  870. for (int i = startLine; i < endLine; i++) {
  871. // @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
  872. for (KnuthPageNode node = (KnuthPageNode) getNode(i);
  873. node != null;
  874. node = (KnuthPageNode) node.next) {
  875. if (node.insertedFootnotes < totalFootnotesLength) {
  876. // layout remaining footnote bodies
  877. createFootnotePages(node);
  878. }
  879. }
  880. }
  881. }
  882. private void createFootnotePages(KnuthPageNode lastNode) {
  883. insertedFootnotesLength = lastNode.insertedFootnotes;
  884. footnoteListIndex = lastNode.footnoteListIndex;
  885. footnoteElementIndex = lastNode.footnoteElementIndex;
  886. int availableBPD = getLineWidth(lastNode.line);
  887. int split = 0;
  888. KnuthPageNode prevNode = lastNode;
  889. // create pages containing the remaining footnote bodies
  890. while (insertedFootnotesLength < totalFootnotesLength) {
  891. if (totalFootnotesLength - insertedFootnotesLength <= availableBPD) {
  892. // All the remaining footnotes fit
  893. insertedFootnotesLength = totalFootnotesLength;
  894. footnoteListIndex = lengthList.size() - 1;
  895. footnoteElementIndex = getFootnoteList(footnoteListIndex).size() - 1;
  896. } else if ((split = getFootnoteSplit(
  897. footnoteListIndex, footnoteElementIndex,
  898. insertedFootnotesLength, availableBPD, true)) > 0) {
  899. // add a piece of a footnote
  900. availableBPD -= split;
  901. insertedFootnotesLength += split;
  902. // footnoteListIndex has already been set in getFootnoteSplit()
  903. // footnoteElementIndex has already been set in getFootnoteSplit()
  904. } else {
  905. // cannot add any content: create a new node and start again
  906. // @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
  907. KnuthPageNode node = (KnuthPageNode)
  908. createNode(lastNode.position, prevNode.line + 1, 1,
  909. insertedFootnotesLength - prevNode.insertedFootnotes,
  910. 0, 0,
  911. 0, 0, 0,
  912. 0, 0, prevNode);
  913. addNode(node.line, node);
  914. removeNode(prevNode.line, prevNode);
  915. prevNode = node;
  916. availableBPD = getLineWidth(node.line);
  917. }
  918. }
  919. // create the last node
  920. // @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
  921. KnuthPageNode node = (KnuthPageNode)
  922. createNode(lastNode.position, prevNode.line + 1, 1,
  923. totalFootnotesLength - prevNode.insertedFootnotes, 0, 0,
  924. 0, 0, 0,
  925. 0, 0, prevNode);
  926. addNode(node.line, node);
  927. removeNode(prevNode.line, prevNode);
  928. }
  929. /**
  930. * @return a list of {@link PageBreakPosition} elements
  931. * corresponding to the computed page- and column-breaks
  932. */
  933. public LinkedList<PageBreakPosition> getPageBreaks() {
  934. return pageBreaks;
  935. }
  936. /**
  937. * Insert the given {@link PageBreakPosition} as the first
  938. * element in the list of page-breaks
  939. *
  940. * @param pageBreak the position to insert
  941. */
  942. public void insertPageBreakAsFirst(PageBreakPosition pageBreak) {
  943. if (pageBreaks == null) {
  944. pageBreaks = new LinkedList<PageBreakPosition>();
  945. }
  946. pageBreaks.addFirst(pageBreak);
  947. }
  948. /**
  949. * Removes all page breaks from the result list. This is used by block-containers and
  950. * static-content when it is only desired to know where there is an overflow but later the
  951. * whole content should be painted as one part.
  952. */
  953. public void removeAllPageBreaks() {
  954. if (pageBreaks == null || pageBreaks.isEmpty()) {
  955. return;
  956. }
  957. pageBreaks.subList(0, pageBreaks.size() - 1).clear();
  958. }
  959. /** {@inheritDoc} */
  960. @Override
  961. public void updateData1(int total, double demerits) {
  962. }
  963. /** {@inheritDoc} */
  964. @Override
  965. public void updateData2(KnuthNode bestActiveNode,
  966. KnuthSequence sequence,
  967. int total) {
  968. //int difference = (bestActiveNode.line < total)
  969. // ? bestActiveNode.difference : bestActiveNode.difference + fillerMinWidth;
  970. // Check if the given node has an attached variant of a dynamic content
  971. KnuthPageNode pageNode = (KnuthPageNode) bestActiveNode;
  972. KnuthPageNode previousPageNode = ((KnuthPageNode) pageNode.previous);
  973. for (Variant var : previousPageNode.pendingVariants) {
  974. WhitespaceManagementPenalty penalty = var.getWhitespaceManagementPenalty();
  975. // A WMPenalty should not be activated more than once. The reason is simply
  976. // because a dynamic content cannot occupy multiple pages at the same time.
  977. if (!penalty.hasActiveVariant()) {
  978. penalty.setActiveVariant(var);
  979. }
  980. }
  981. int difference = bestActiveNode.difference;
  982. if (difference + bestActiveNode.availableShrink < 0) {
  983. if (!autoHeight) {
  984. if (layoutListener != null) {
  985. layoutListener.notifyOverflow(bestActiveNode.line - 1, -difference, getFObj());
  986. }
  987. }
  988. }
  989. boolean isNonLastPage = (bestActiveNode.line < total);
  990. int blockAlignment = isNonLastPage ? alignment : alignmentLast;
  991. // it is always allowed to adjust space, so the ratio must be set regardless of
  992. // the value of the property display-align; the ratio must be <= 1
  993. double ratio = bestActiveNode.adjustRatio;
  994. if (ratio < 0) {
  995. // page break with a negative difference:
  996. // spaces always have enough shrink
  997. difference = 0;
  998. } else if (ratio <= 1 && isNonLastPage) {
  999. // not-last page break with a positive difference smaller than the available stretch:
  1000. // spaces can stretch to fill the whole difference
  1001. difference = 0;
  1002. } else if (ratio > 1) {
  1003. // not-last page with a positive difference greater than the available stretch
  1004. // spaces can stretch to fill the difference only partially
  1005. ratio = 1;
  1006. difference -= bestActiveNode.availableStretch;
  1007. } else {
  1008. // last page with a positive difference:
  1009. // spaces do not need to stretch
  1010. if (blockAlignment != Constants.EN_JUSTIFY) {
  1011. ratio = 0;
  1012. } else {
  1013. //Stretch as much as possible on last page
  1014. difference = 0;
  1015. }
  1016. }
  1017. // add nodes at the beginning of the list, as they are found
  1018. // backwards, from the last one to the first one
  1019. if (log.isDebugEnabled()) {
  1020. log.debug("BBA> difference=" + difference + " ratio=" + ratio
  1021. + " position=" + bestActiveNode.position);
  1022. }
  1023. if (handlingFloat() && floatPosition == null) {
  1024. floatPosition = new FloatPosition(this.topLevelLM, bestActiveNode.position, ratio, difference);
  1025. } else {
  1026. boolean useRelayedFootnotes = relayingFootnotes && bestActiveNode.previous.position == 0;
  1027. // compute the indexes of the first footnote list and the first element in that list
  1028. int firstListIndex = (useRelayedFootnotes) ? previousFootnoteListIndex
  1029. : ((KnuthPageNode) bestActiveNode.previous).footnoteListIndex;
  1030. int firstElementIndex = (useRelayedFootnotes) ? previousFootnoteElementIndex
  1031. : ((KnuthPageNode) bestActiveNode.previous).footnoteElementIndex;
  1032. if (useRelayedFootnotes) {
  1033. previousFootnoteListIndex = -2;
  1034. previousFootnoteElementIndex = -2;
  1035. relayingFootnotes = false;
  1036. }
  1037. if (footnotesList != null && firstElementIndex == getFootnoteList(firstListIndex).size() - 1) {
  1038. // advance to the next list
  1039. firstListIndex++;
  1040. firstElementIndex = 0;
  1041. } else {
  1042. firstElementIndex++;
  1043. }
  1044. insertPageBreakAsFirst(new PageBreakPosition(this.topLevelLM, bestActiveNode.position,
  1045. firstListIndex, firstElementIndex, ((KnuthPageNode) bestActiveNode).footnoteListIndex,
  1046. ((KnuthPageNode) bestActiveNode).footnoteElementIndex, ratio, difference));
  1047. }
  1048. }
  1049. /** {@inheritDoc} */
  1050. @Override
  1051. protected int filterActiveNodes() {
  1052. // leave only the active node with fewest total demerits
  1053. KnuthNode bestActiveNode = null;
  1054. for (int i = startLine; i < endLine; i++) {
  1055. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  1056. if (favorSinglePart
  1057. && node.line > 1
  1058. && bestActiveNode != null
  1059. && Math.abs(bestActiveNode.difference) < bestActiveNode.availableShrink) {
  1060. //favor current best node, so just skip the current node because it would
  1061. //result in more than one part
  1062. } else {
  1063. bestActiveNode = compareNodes(bestActiveNode, node);
  1064. }
  1065. if (node != bestActiveNode) {
  1066. removeNode(i, node);
  1067. }
  1068. }
  1069. }
  1070. assert (bestActiveNode != null);
  1071. return bestActiveNode.line;
  1072. }
  1073. /**
  1074. * Obtain the element-list corresponding to the footnote at the given index.
  1075. *
  1076. * @param index the index in the list of footnotes
  1077. * @return the element-list
  1078. */
  1079. protected final List<KnuthElement> getFootnoteList(int index) {
  1080. return footnotesList.get(index);
  1081. }
  1082. /** @return the associated top-level formatting object. */
  1083. public FObj getFObj() {
  1084. return topLevelLM.getFObj();
  1085. }
  1086. /** {@inheritDoc} */
  1087. @Override
  1088. protected int getLineWidth(int line) {
  1089. int bpd;
  1090. if (pageProvider != null) {
  1091. bpd = pageProvider.getAvailableBPD(line);
  1092. } else {
  1093. bpd = super.getLineWidth(line);
  1094. }
  1095. if (log.isTraceEnabled()) {
  1096. log.trace("getLineWidth(" + line + ") -> " + bpd);
  1097. }
  1098. return bpd;
  1099. }
  1100. /**
  1101. * Interface to notify about layout events during page breaking.
  1102. */
  1103. public interface PageBreakingLayoutListener {
  1104. /**
  1105. * Issued when an overflow is detected
  1106. * @param part the number of the part (page) this happens on
  1107. * @param amount the amount by which the area overflows (in mpt)
  1108. * @param obj the root FO object where this happens
  1109. */
  1110. void notifyOverflow(int part, int amount, FObj obj);
  1111. }
  1112. @Override
  1113. protected KnuthNode recoverFromOverflow() {
  1114. if (compareIPDs(getLastTooLong().line - 1) != 0) {
  1115. /**
  1116. * If the IPD of the next page changes, disable the recovery mechanism as the
  1117. * inline content has to be re-laid out according to the new IPD anyway.
  1118. */
  1119. return getLastTooLong();
  1120. } else {
  1121. return super.recoverFromOverflow();
  1122. }
  1123. }
  1124. /** {@inheritDoc} */
  1125. @Override
  1126. protected int getIPDdifference() {
  1127. return ipdDifference;
  1128. }
  1129. /** {@inheritDoc} */
  1130. @Override
  1131. protected int handleIpdChange() {
  1132. log.trace("Best node for ipd change:" + bestNodeForIPDChange);
  1133. // TODO finish()
  1134. /*
  1135. * The third parameter is used to determine if this is the last page, so
  1136. * if the content must be vertically justified or not. If we are here
  1137. * this means that there is further content and the next page has a
  1138. * different ipd. So tweak the parameter to fall into the non-last-page
  1139. * case.
  1140. */
  1141. calculateBreakPoints(bestNodeForIPDChange, par, bestNodeForIPDChange.line + 1);
  1142. activeLines = null;
  1143. return bestNodeForIPDChange.line;
  1144. }
  1145. /**
  1146. * Add a node at the end of the given line's existing active nodes.
  1147. * If this is the first node in the line, adjust endLine accordingly.
  1148. * @param line number of the line ending at the node's corresponding breakpoint
  1149. * @param node the active node to add
  1150. */
  1151. @Override
  1152. protected void addNode(int line, KnuthNode node) {
  1153. if (node.position < par.size() - 1 && line > 0
  1154. && (ipdDifference = compareIPDs(line - 1)) != 0) {
  1155. log.trace("IPD changes at page " + line);
  1156. if (bestNodeForIPDChange == null
  1157. || node.totalDemerits < bestNodeForIPDChange.totalDemerits) {
  1158. bestNodeForIPDChange = node;
  1159. }
  1160. } else {
  1161. if (node.position == par.size() - 1) {
  1162. /*
  1163. * The whole sequence could actually fit on the last page before
  1164. * the IPD change. No need to do any special handling.
  1165. */
  1166. ipdDifference = 0;
  1167. } else if (line > 0 /*&& (bestNodeForLastPage == null
  1168. || node.totalDemerits < bestNodeForLastPage.totalDemerits)*/) {
  1169. bestNodeForLastPage = node;
  1170. }
  1171. super.addNode(line, node);
  1172. }
  1173. }
  1174. KnuthNode getBestNodeBeforeIPDChange() {
  1175. return bestNodeForIPDChange;
  1176. }
  1177. private int compareIPDs(int line) {
  1178. if (pageProvider == null) {
  1179. return 0;
  1180. }
  1181. return pageProvider.compareIPDs(line);
  1182. }
  1183. KnuthNode getBestNodeForLastPage() {
  1184. return bestNodeForLastPage;
  1185. }
  1186. protected boolean handlingFloat() {
  1187. return (handlingStartOfFloat || handlingEndOfFloat);
  1188. }
  1189. protected void createForcedNodes(KnuthNode node, int line, int elementIdx, int difference, double r,
  1190. double demerits, int fitnessClass, int availableShrink, int availableStretch, int newWidth,
  1191. int newStretch, int newShrink) {
  1192. if (handlingFloat()) {
  1193. if (bestFloatEdgeNode == null || demerits <= bestFloatEdgeNode.totalDemerits) {
  1194. bestFloatEdgeNode = createNode(elementIdx, line + 1, fitnessClass, newWidth, newStretch,
  1195. newShrink, r, availableShrink, availableStretch, difference, demerits, node);
  1196. }
  1197. } else {
  1198. super.createForcedNodes(node, line, elementIdx, difference, r, demerits, fitnessClass,
  1199. availableShrink, availableStretch, newWidth, newStretch, newShrink);
  1200. }
  1201. }
  1202. protected int handleFloat() {
  1203. calculateBreakPoints(bestFloatEdgeNode, par, bestFloatEdgeNode.line);
  1204. activeLines = null;
  1205. return bestFloatEdgeNode.line - 1;
  1206. }
  1207. protected KnuthNode getBestFloatEdgeNode() {
  1208. return bestFloatEdgeNode;
  1209. }
  1210. protected FloatPosition getFloatPosition() {
  1211. return floatPosition;
  1212. }
  1213. protected int getFloatHeight() {
  1214. return floatHeight;
  1215. }
  1216. protected boolean handlingStartOfFloat() {
  1217. return handlingStartOfFloat;
  1218. }
  1219. protected boolean handlingEndOfFloat() {
  1220. return handlingEndOfFloat;
  1221. }
  1222. /**
  1223. * Deactivate the given node
  1224. *
  1225. * @param node the node
  1226. * @param line the line number
  1227. */
  1228. protected void deactivateNode(KnuthNode node, int line) {
  1229. super.deactivateNode(node, line);
  1230. if (handlingEndOfFloat) {
  1231. floatHeight = totalWidth;
  1232. }
  1233. }
  1234. protected void disableFloatHandling() {
  1235. handlingEndOfFloat = false;
  1236. handlingStartOfFloat = false;
  1237. }
  1238. public void loadFootnotes(List fl, List ll, int tfl, int ifl, boolean fp, boolean nf, int fnfi, int fli,
  1239. int fei, MinOptMax fsl, int pfli, int pfei) {
  1240. footnotesList = fl;
  1241. lengthList = ll;
  1242. totalFootnotesLength = tfl;
  1243. insertedFootnotesLength = ifl;
  1244. footnotesPending = fp;
  1245. newFootnotes = nf;
  1246. firstNewFootnoteIndex = fnfi;
  1247. footnoteListIndex = fli;
  1248. footnoteElementIndex = fei;
  1249. footnoteSeparatorLength = fsl;
  1250. previousFootnoteListIndex = pfli;
  1251. previousFootnoteElementIndex = pfei;
  1252. relayingFootnotes = !(previousFootnoteListIndex == -2 && previousFootnoteElementIndex == -2);
  1253. }
  1254. public void relayFootnotes(PageSequenceLayoutManager pslm) {
  1255. if (!relayingFootnotes) {
  1256. previousFootnoteListIndex = ((KnuthPageNode) bestFloatEdgeNode.previous).footnoteListIndex;
  1257. previousFootnoteElementIndex = ((KnuthPageNode) bestFloatEdgeNode.previous).footnoteElementIndex;
  1258. }
  1259. pslm.holdFootnotes(footnotesList, lengthList, totalFootnotesLength, insertedFootnotesLength,
  1260. footnotesPending, newFootnotes, firstNewFootnoteIndex, footnoteListIndex,
  1261. footnoteElementIndex, footnoteSeparatorLength, previousFootnoteListIndex,
  1262. previousFootnoteElementIndex);
  1263. }
  1264. }