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 49KB

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