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

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