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

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