Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

PageBreakingAlgorithm.java 52KB

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