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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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. class PageBreakingAlgorithm extends BreakingAlgorithm {
  30. /** the logger for the class */
  31. private static Log log = LogFactory.getLog(PageBreakingAlgorithm.class);
  32. private LayoutManager topLevelLM;
  33. private PageProvider pageProvider;
  34. private PageBreakingLayoutListener layoutListener;
  35. /** List of PageBreakPosition elements. */
  36. private LinkedList pageBreaks = null;
  37. /** Footnotes which are cited between the currently considered active node (previous
  38. * break) and the current considered break. Its type is
  39. * List<List<KnuthElement>>, it contains the sequences of KnuthElement
  40. * representing the footnotes bodies.
  41. */
  42. private ArrayList footnotesList = null;
  43. /** Cumulated bpd of unhandled footnotes. */
  44. private ArrayList lengthList = null;
  45. /** Length of all the footnotes which will be put on the current page. */
  46. private int totalFootnotesLength = 0;
  47. /**
  48. * Length of all the footnotes which have already been inserted, up to the currently
  49. * considered element. That is, footnotes from the currently considered page plus
  50. * footnotes from its preceding pages.
  51. */
  52. private int insertedFootnotesLength = 0;
  53. /** True if footnote citations have been met since the beginning of the page sequence. */
  54. private boolean footnotesPending = false;
  55. /**
  56. * True if the elements met after the previous break point contain footnote citations.
  57. */
  58. private boolean newFootnotes = false;
  59. /**
  60. * Index of the first footnote met after the previous break point.
  61. */
  62. private int firstNewFootnoteIndex = 0;
  63. /** Index of the last footnote inserted on the current page. */
  64. private int footnoteListIndex = 0;
  65. /** Index of the last element of the last footnote inserted on the current page. */
  66. private int footnoteElementIndex = -1;
  67. // demerits for a page break that splits a footnote
  68. private int splitFootnoteDemerits = 5000;
  69. // demerits for a page break that defers a whole footnote to the following page
  70. private int deferredFootnoteDemerits = 10000;
  71. private MinOptMax footnoteSeparatorLength = null;
  72. // the method noBreakBetween(int, int) uses these variables
  73. // to store parameters and result of the last call, in order
  74. // to reuse them and take less time
  75. private int storedPrevBreakIndex = -1;
  76. private int storedBreakIndex = -1;
  77. private boolean storedValue = false;
  78. //Controls whether overflows should be warned about or not
  79. private boolean autoHeight = false;
  80. //Controls whether a single part should be forced if possible (ex. block-container)
  81. private boolean favorSinglePart = false;
  82. public PageBreakingAlgorithm(LayoutManager topLevelLM,
  83. PageProvider pageProvider,
  84. PageBreakingLayoutListener layoutListener,
  85. int alignment, int alignmentLast,
  86. MinOptMax footnoteSeparatorLength,
  87. boolean partOverflowRecovery, boolean autoHeight,
  88. boolean favorSinglePart) {
  89. super(alignment, alignmentLast, true, partOverflowRecovery, 0);
  90. this.topLevelLM = topLevelLM;
  91. this.pageProvider = pageProvider;
  92. this.layoutListener = layoutListener;
  93. best = new BestPageRecords();
  94. this.footnoteSeparatorLength = (MinOptMax) footnoteSeparatorLength.clone();
  95. // add some stretch, to avoid a restart for every page containing footnotes
  96. if (footnoteSeparatorLength.min == footnoteSeparatorLength.max) {
  97. footnoteSeparatorLength.max += 10000;
  98. }
  99. this.autoHeight = autoHeight;
  100. this.favorSinglePart = favorSinglePart;
  101. }
  102. /**
  103. * This class represents a feasible breaking point
  104. * with extra information about footnotes.
  105. */
  106. protected class KnuthPageNode extends KnuthNode {
  107. /** Additional length due to footnotes. */
  108. public int totalFootnotes;
  109. /** Index of the last inserted footnote. */
  110. public int footnoteListIndex;
  111. /** Index of the last inserted element of the last inserted footnote. */
  112. public int footnoteElementIndex;
  113. public KnuthPageNode(int position, int line, int fitness,
  114. int totalWidth, int totalStretch, int totalShrink,
  115. int totalFootnotes, int footnoteListIndex, int footnoteElementIndex,
  116. double adjustRatio, int availableShrink, int availableStretch,
  117. int difference, double totalDemerits, KnuthNode previous) {
  118. super(position, line, fitness,
  119. totalWidth, totalStretch, totalShrink,
  120. adjustRatio, availableShrink, availableStretch,
  121. difference, totalDemerits, previous);
  122. this.totalFootnotes = totalFootnotes;
  123. this.footnoteListIndex = footnoteListIndex;
  124. this.footnoteElementIndex = footnoteElementIndex;
  125. }
  126. }
  127. /**
  128. * this class stores information about how the nodes
  129. * which could start a line ending at the current element
  130. */
  131. protected class BestPageRecords extends BestRecords {
  132. private int[] bestFootnotesLength = new int[4];
  133. private int[] bestFootnoteListIndex = new int[4];
  134. private int[] bestFootnoteElementIndex = new int[4];
  135. public void addRecord(double demerits, KnuthNode node, double adjust,
  136. int availableShrink, int availableStretch,
  137. int difference, int fitness) {
  138. super.addRecord(demerits, node, adjust,
  139. availableShrink, availableStretch,
  140. difference, fitness);
  141. bestFootnotesLength[fitness] = insertedFootnotesLength;
  142. bestFootnoteListIndex[fitness] = footnoteListIndex;
  143. bestFootnoteElementIndex[fitness] = footnoteElementIndex;
  144. }
  145. public int getFootnotesLength(int fitness) {
  146. return bestFootnotesLength[fitness];
  147. }
  148. public int getFootnoteListIndex(int fitness) {
  149. return bestFootnoteListIndex[fitness];
  150. }
  151. public int getFootnoteElementIndex(int fitness) {
  152. return bestFootnoteElementIndex[fitness];
  153. }
  154. }
  155. protected void initialize() {
  156. super.initialize();
  157. insertedFootnotesLength = 0;
  158. footnoteListIndex = 0;
  159. footnoteElementIndex = -1;
  160. }
  161. protected KnuthNode createNode(int position, int line, int fitness,
  162. int totalWidth, int totalStretch, int totalShrink,
  163. double adjustRatio, int availableShrink, int availableStretch,
  164. int difference, double totalDemerits, KnuthNode previous) {
  165. return new KnuthPageNode(position, line, fitness,
  166. totalWidth, totalStretch, totalShrink,
  167. insertedFootnotesLength, footnoteListIndex, footnoteElementIndex,
  168. adjustRatio, availableShrink, availableStretch,
  169. difference, totalDemerits, previous);
  170. }
  171. protected KnuthNode createNode(int position, int line, int fitness,
  172. int totalWidth, int totalStretch, int totalShrink) {
  173. return new KnuthPageNode(position, line, fitness,
  174. totalWidth, totalStretch, totalShrink,
  175. ((BestPageRecords) best).getFootnotesLength(fitness),
  176. ((BestPageRecords) best).getFootnoteListIndex(fitness),
  177. ((BestPageRecords) best).getFootnoteElementIndex(fitness),
  178. best.getAdjust(fitness), best.getAvailableShrink(fitness),
  179. best.getAvailableStretch(fitness), best.getDifference(fitness),
  180. best.getDemerits(fitness), best.getNode(fitness));
  181. }
  182. /**
  183. * Page-breaking specific handling of the given box. Currently it adds the footnotes
  184. * cited in the given box to the list of to-be-handled footnotes.
  185. * @param box a block-level element possibly containing foonotes citations
  186. */
  187. protected void handleBox(KnuthBox box) {
  188. if (box instanceof KnuthBlockBox
  189. && ((KnuthBlockBox) box).hasAnchors()) {
  190. handleFootnotes(((KnuthBlockBox) box).getElementLists());
  191. if (!newFootnotes) {
  192. newFootnotes = true;
  193. firstNewFootnoteIndex = footnotesList.size() - 1;
  194. }
  195. }
  196. }
  197. /**
  198. * Handles the footnotes cited inside a block-level box. Updates footnotesList and the
  199. * value of totalFootnotesLength with the lengths of the given footnotes.
  200. * @param elementLists list of KnuthElement sequences corresponding to the footnotes
  201. * bodies
  202. */
  203. private void handleFootnotes(List elementLists) {
  204. // initialization
  205. if (!footnotesPending) {
  206. footnotesPending = true;
  207. footnotesList = new ArrayList();
  208. lengthList = new ArrayList();
  209. totalFootnotesLength = 0;
  210. }
  211. if (!newFootnotes) {
  212. newFootnotes = true;
  213. firstNewFootnoteIndex = footnotesList.size();
  214. }
  215. // compute the total length of the footnotes
  216. ListIterator elementListsIterator = elementLists.listIterator();
  217. while (elementListsIterator.hasNext()) {
  218. LinkedList noteList = (LinkedList) elementListsIterator.next();
  219. //Space resolution (Note: this does not respect possible stacking constraints
  220. //between footnotes!)
  221. SpaceResolver.resolveElementList(noteList);
  222. int noteLength = 0;
  223. footnotesList.add(noteList);
  224. ListIterator noteListIterator = noteList.listIterator();
  225. while (noteListIterator.hasNext()) {
  226. KnuthElement element = (KnuthElement) noteListIterator.next();
  227. if (element.isBox() || element.isGlue()) {
  228. noteLength += element.getW();
  229. }
  230. }
  231. int prevLength = (lengthList.size() == 0
  232. ? 0
  233. : ((Integer) lengthList.get(lengthList.size() - 1)).intValue());
  234. lengthList.add(new Integer(prevLength + noteLength));
  235. totalFootnotesLength += noteLength;
  236. }
  237. }
  238. protected int restartFrom(KnuthNode restartingNode, int currentIndex) {
  239. int returnValue = super.restartFrom(restartingNode, currentIndex);
  240. newFootnotes = false;
  241. if (footnotesPending) {
  242. // remove from footnotesList the note lists that will be met
  243. // after the restarting point
  244. for (int j = currentIndex; j >= restartingNode.position; j--) {
  245. KnuthElement resettedElement = getElement(j);
  246. if (resettedElement instanceof KnuthBlockBox
  247. && ((KnuthBlockBox) resettedElement).hasAnchors()) {
  248. resetFootnotes(((KnuthBlockBox) resettedElement).getElementLists());
  249. }
  250. }
  251. }
  252. return returnValue;
  253. }
  254. private void resetFootnotes(List elementLists) {
  255. for (int i = 0; i < elementLists.size(); i++) {
  256. /*LinkedList removedList = (LinkedList)*/footnotesList.remove(footnotesList.size() - 1);
  257. lengthList.remove(lengthList.size() - 1);
  258. // update totalFootnotesLength
  259. if (lengthList.size() > 0) {
  260. totalFootnotesLength = ((Integer) lengthList.get(lengthList.size() - 1)).intValue();
  261. } else {
  262. totalFootnotesLength = 0;
  263. }
  264. }
  265. // update footnotesPending;
  266. if (footnotesList.size() == 0) {
  267. footnotesPending = false;
  268. }
  269. }
  270. protected void considerLegalBreak(KnuthElement element, int elementIdx) {
  271. super.considerLegalBreak(element, elementIdx);
  272. newFootnotes = false;
  273. }
  274. protected int computeDifference(KnuthNode activeNode, KnuthElement element,
  275. int elementIndex) {
  276. KnuthPageNode pageNode = (KnuthPageNode) activeNode;
  277. int actualWidth = totalWidth - pageNode.totalWidth;
  278. int footnoteSplit;
  279. boolean canDeferOldFootnotes;
  280. if (element.isPenalty()) {
  281. actualWidth += element.getW();
  282. }
  283. if (footnotesPending) {
  284. // compute the total length of the footnotes not yet inserted
  285. int allFootnotes = totalFootnotesLength - pageNode.totalFootnotes;
  286. if (allFootnotes > 0) {
  287. // this page contains some footnote citations
  288. // add the footnote separator width
  289. actualWidth += footnoteSeparatorLength.opt;
  290. if (actualWidth + allFootnotes <= getLineWidth(activeNode.line)) {
  291. // there is enough space to insert all footnotes:
  292. // add the whole allFootnotes length
  293. actualWidth += allFootnotes;
  294. insertedFootnotesLength = pageNode.totalFootnotes + allFootnotes;
  295. footnoteListIndex = footnotesList.size() - 1;
  296. footnoteElementIndex
  297. = ((LinkedList) footnotesList.get(footnoteListIndex)).size() - 1;
  298. } else if (((canDeferOldFootnotes
  299. = checkCanDeferOldFootnotes(pageNode, elementIndex))
  300. || newFootnotes)
  301. && (footnoteSplit = getFootnoteSplit(pageNode,
  302. getLineWidth(activeNode.line) - actualWidth, canDeferOldFootnotes)) > 0) {
  303. // it is allowed to break or even defer footnotes if either:
  304. // - there are new footnotes in the last piece of content, and
  305. // there is space to add at least a piece of the first one
  306. // - or the previous page break deferred some footnote lines, and
  307. // this is the first feasible break; in this case it is allowed
  308. // to break and defer, if necessary, old and new footnotes
  309. actualWidth += footnoteSplit;
  310. insertedFootnotesLength = pageNode.totalFootnotes + footnoteSplit;
  311. // footnoteListIndex has been set in getFootnoteSplit()
  312. // footnoteElementIndex has been set in getFootnoteSplit()
  313. } else {
  314. // there is no space to add the smallest piece of footnote,
  315. // or we are trying to add a piece of content with no footnotes and
  316. // it does not fit in the page, because of previous footnote bodies
  317. // that cannot be broken:
  318. // add the whole allFootnotes length, so this breakpoint will be discarded
  319. actualWidth += allFootnotes;
  320. insertedFootnotesLength = pageNode.totalFootnotes + allFootnotes;
  321. footnoteListIndex = footnotesList.size() - 1;
  322. footnoteElementIndex
  323. = ((LinkedList) footnotesList.get(footnoteListIndex)).size() - 1;
  324. }
  325. } else {
  326. // all footnotes have already been placed on previous pages
  327. }
  328. } else {
  329. // there are no footnotes
  330. }
  331. int diff = getLineWidth(activeNode.line) - actualWidth;
  332. if (autoHeight && diff < 0) {
  333. //getLineWidth() for auto-height parts return 0 so the diff will be negative
  334. return 0; //...but we don't want to shrink in this case. Stick to optimum.
  335. } else {
  336. return diff;
  337. }
  338. }
  339. /** Checks whether footnotes from preceding pages may be deferred to the page after
  340. * the given element.
  341. * @param node active node for the preceding page break
  342. * @param contentElementIndex index of the Knuth element considered for the
  343. * current page break
  344. */
  345. private boolean checkCanDeferOldFootnotes(KnuthPageNode node, int contentElementIndex) {
  346. return (noBreakBetween(node.position, contentElementIndex)
  347. && deferredFootnotes(node.footnoteListIndex,
  348. node.footnoteElementIndex, node.totalFootnotes));
  349. }
  350. /**
  351. * Returns true if there may be no breakpoint between the two given elements.
  352. * @param prevBreakIndex index of the element from the currently considered active
  353. * node
  354. * @param breakIndex index of the currently considered breakpoint
  355. * @return true if no element between the two can be a breakpoint
  356. */
  357. private boolean noBreakBetween(int prevBreakIndex, int breakIndex) {
  358. // this method stores the parameters and the return value from previous calls
  359. // in order to avoid scanning the element list unnecessarily:
  360. // - if there is no break between element #i and element #j
  361. // there will not be a break between #(i+h) and #j too
  362. // - if there is a break between element #i and element #j
  363. // there will be a break between #(i-h) and #(j+k) too
  364. if (storedPrevBreakIndex != -1
  365. && ((prevBreakIndex >= storedPrevBreakIndex
  366. && breakIndex == storedBreakIndex
  367. && storedValue)
  368. || (prevBreakIndex <= storedPrevBreakIndex
  369. && breakIndex >= storedBreakIndex
  370. && !storedValue))) {
  371. // use the stored value, do nothing
  372. } else {
  373. // compute the new value
  374. int index;
  375. // ignore suppressed elements
  376. for (index = prevBreakIndex + 1;
  377. !par.getElement(index).isBox();
  378. index++) {
  379. //nop
  380. }
  381. // find the next break
  382. for (;
  383. index < breakIndex;
  384. index++) {
  385. if (par.getElement(index).isGlue() && par.getElement(index - 1).isBox()
  386. || par.getElement(index).isPenalty()
  387. && ((KnuthElement) par.getElement(index)).getP() < KnuthElement.INFINITE) {
  388. // break found
  389. break;
  390. }
  391. }
  392. // update stored parameters and value
  393. storedPrevBreakIndex = prevBreakIndex;
  394. storedBreakIndex = breakIndex;
  395. storedValue = (index == breakIndex);
  396. }
  397. return storedValue;
  398. }
  399. /**
  400. * Returns true if their are (pieces of) footnotes to be typeset on the current page.
  401. * @param listIndex index of the last inserted footnote for the currently considered
  402. * active node
  403. * @param elementIndex index of the last element of the last inserted footnote
  404. * @param length total length of all footnotes inserted so far
  405. */
  406. private boolean deferredFootnotes(int listIndex, int elementIndex, int length) {
  407. return ((newFootnotes
  408. && firstNewFootnoteIndex != 0
  409. && (listIndex < firstNewFootnoteIndex - 1
  410. || elementIndex < ((LinkedList) footnotesList.get(listIndex)).size() - 1))
  411. || length < totalFootnotesLength);
  412. }
  413. /**
  414. * Tries to split the flow of footnotes to put one part on the current page.
  415. * @param activeNode currently considered previous page break
  416. * @param availableLength available space for footnotes
  417. * @param canDeferOldFootnotes
  418. */
  419. private int getFootnoteSplit(KnuthPageNode activeNode, int availableLength,
  420. boolean canDeferOldFootnotes) {
  421. return getFootnoteSplit(activeNode.footnoteListIndex,
  422. activeNode.footnoteElementIndex,
  423. activeNode.totalFootnotes,
  424. availableLength, canDeferOldFootnotes);
  425. }
  426. /**
  427. * Tries to split the flow of footnotes to put one part on the current page.
  428. * @param prevListIndex index of the last footnote on the previous page
  429. * @param prevElementIndex index of the last element of the last footnote
  430. * @param prevLength total length of footnotes inserted so far
  431. * @param availableLength available space for footnotes on this page
  432. * @param canDeferOldFootnotes
  433. */
  434. private int getFootnoteSplit(int prevListIndex, int prevElementIndex, int prevLength,
  435. int availableLength, boolean canDeferOldFootnotes) {
  436. if (availableLength <= 0) {
  437. return 0;
  438. } else {
  439. // the split should contain a piece of the last footnote
  440. // together with all previous, not yet inserted footnotes;
  441. // but if this is not possible, try adding as much content as possible
  442. int splitLength = 0;
  443. ListIterator noteListIterator = null;
  444. KnuthElement element = null;
  445. boolean somethingAdded = false;
  446. // prevListIndex and prevElementIndex points to the last footnote element
  447. // already placed in a page: advance to the next element
  448. int listIndex = prevListIndex;
  449. int elementIndex = prevElementIndex;
  450. if (elementIndex == ((LinkedList) footnotesList.get(listIndex)).size() - 1) {
  451. listIndex++;
  452. elementIndex = 0;
  453. } else {
  454. elementIndex++;
  455. }
  456. // try adding whole notes
  457. if (footnotesList.size() - 1 > listIndex) {
  458. // add the previous footnotes: these cannot be broken or deferred
  459. if (!canDeferOldFootnotes
  460. && newFootnotes
  461. && firstNewFootnoteIndex > 0) {
  462. splitLength = ((Integer) lengthList.get(firstNewFootnoteIndex - 1)).intValue()
  463. - prevLength;
  464. listIndex = firstNewFootnoteIndex;
  465. elementIndex = 0;
  466. }
  467. // try adding the new footnotes
  468. while (((Integer) lengthList.get(listIndex)).intValue() - prevLength
  469. <= availableLength) {
  470. splitLength = ((Integer) lengthList.get(listIndex)).intValue()
  471. - prevLength;
  472. somethingAdded = true;
  473. listIndex++;
  474. elementIndex = 0;
  475. }
  476. // as this method is called only if it is not possible to insert
  477. // all footnotes, at this point listIndex and elementIndex points to
  478. // an existing element, the next one we will try to insert
  479. }
  480. // try adding a split of the next note
  481. noteListIterator = ((LinkedList) footnotesList.get(listIndex))
  482. .listIterator(elementIndex);
  483. int prevSplitLength = 0;
  484. int prevIndex = -1;
  485. int index = -1;
  486. while (!(somethingAdded && splitLength > availableLength)) {
  487. if (!somethingAdded) {
  488. somethingAdded = true;
  489. } else {
  490. prevSplitLength = splitLength;
  491. prevIndex = index;
  492. }
  493. // get a sub-sequence from the note element list
  494. boolean bPrevIsBox = false;
  495. while (noteListIterator.hasNext()) {
  496. // as this method is called only if it is not possible to insert
  497. // all footnotes, and we have already tried (and failed) to insert
  498. // this whole footnote, the while loop will never reach the end
  499. // of the note sequence
  500. element = (KnuthElement) noteListIterator.next();
  501. if (element.isBox()) {
  502. // element is a box
  503. splitLength += element.getW();
  504. bPrevIsBox = true;
  505. } else if (element.isGlue()) {
  506. // element is a glue
  507. if (bPrevIsBox) {
  508. // end of the sub-sequence
  509. index = noteListIterator.previousIndex();
  510. break;
  511. }
  512. bPrevIsBox = false;
  513. splitLength += element.getW();
  514. } else {
  515. // element is a penalty
  516. if (element.getP() < KnuthElement.INFINITE) {
  517. // end of the sub-sequence
  518. index = noteListIterator.previousIndex();
  519. break;
  520. }
  521. }
  522. }
  523. }
  524. // if prevSplitLength is 0, this means that the available length isn't enough
  525. // to insert even the smallest split of the last footnote, so we cannot end a
  526. // page here
  527. // if prevSplitLength is > 0 we can insert some footnote content in this page
  528. // and insert the remaining in the following one
  529. if (!somethingAdded) {
  530. // there was not enough space to add a piece of the first new footnote
  531. // this is not a good break
  532. prevSplitLength = 0;
  533. } else if (prevSplitLength > 0) {
  534. // prevIndex is -1 if we have added only some whole footnotes
  535. footnoteListIndex = (prevIndex != -1) ? listIndex : listIndex - 1;
  536. footnoteElementIndex = (prevIndex != -1)
  537. ? prevIndex
  538. : ((LinkedList) footnotesList.get(footnoteListIndex)).size() - 1;
  539. }
  540. return prevSplitLength;
  541. }
  542. }
  543. protected double computeAdjustmentRatio(KnuthNode activeNode, int difference) {
  544. // compute the adjustment ratio
  545. if (difference > 0) {
  546. int maxAdjustment = totalStretch - activeNode.totalStretch;
  547. // add the footnote separator stretch if some footnote content will be added
  548. if (((KnuthPageNode) activeNode).totalFootnotes < totalFootnotesLength) {
  549. maxAdjustment += footnoteSeparatorLength.max - footnoteSeparatorLength.opt;
  550. }
  551. if (maxAdjustment > 0) {
  552. return (double) difference / maxAdjustment;
  553. } else {
  554. return INFINITE_RATIO;
  555. }
  556. } else if (difference < 0) {
  557. int maxAdjustment = totalShrink - activeNode.totalShrink;
  558. // add the footnote separator shrink if some footnote content will be added
  559. if (((KnuthPageNode) activeNode).totalFootnotes < totalFootnotesLength) {
  560. maxAdjustment += footnoteSeparatorLength.opt - footnoteSeparatorLength.min;
  561. }
  562. if (maxAdjustment > 0) {
  563. return (double) difference / maxAdjustment;
  564. } else {
  565. return -INFINITE_RATIO;
  566. }
  567. } else {
  568. return 0;
  569. }
  570. }
  571. protected double computeDemerits(KnuthNode activeNode, KnuthElement element,
  572. int fitnessClass, double r) {
  573. double demerits = 0;
  574. // compute demerits
  575. double f = Math.abs(r);
  576. f = 1 + 100 * f * f * f;
  577. if (element.isPenalty() && element.getP() >= 0) {
  578. f += element.getP();
  579. demerits = f * f;
  580. } else if (element.isPenalty() && !element.isForcedBreak()) {
  581. double penalty = element.getP();
  582. demerits = f * f - penalty * penalty;
  583. } else {
  584. demerits = f * f;
  585. }
  586. if (element.isPenalty() && ((KnuthPenalty) element).isFlagged()
  587. && getElement(activeNode.position).isPenalty()
  588. && ((KnuthPenalty) getElement(activeNode.position)).isFlagged()) {
  589. // add demerit for consecutive breaks at flagged penalties
  590. demerits += repeatedFlaggedDemerit;
  591. }
  592. if (Math.abs(fitnessClass - activeNode.fitness) > 1) {
  593. // add demerit for consecutive breaks
  594. // with very different fitness classes
  595. demerits += incompatibleFitnessDemerit;
  596. }
  597. if (footnotesPending) {
  598. if (footnoteListIndex < footnotesList.size() - 1) {
  599. // add demerits for the deferred footnotes
  600. demerits += (footnotesList.size() - 1 - footnoteListIndex)
  601. * deferredFootnoteDemerits;
  602. }
  603. if (footnoteListIndex < footnotesList.size()) {
  604. if (footnoteElementIndex
  605. < ((LinkedList) footnotesList.get(footnoteListIndex)).size() - 1) {
  606. // add demerits for the footnote split between pages
  607. demerits += splitFootnoteDemerits;
  608. }
  609. } else {
  610. //TODO Why can this happen in the first place? Does anybody know? See #44160
  611. }
  612. }
  613. demerits += activeNode.totalDemerits;
  614. return demerits;
  615. }
  616. protected void finish() {
  617. for (int i = startLine; i < endLine; i++) {
  618. for (KnuthPageNode node = (KnuthPageNode) getNode(i);
  619. node != null;
  620. node = (KnuthPageNode) node.next) {
  621. if (node.totalFootnotes < totalFootnotesLength) {
  622. // layout remaining footnote bodies
  623. createFootnotePages(node);
  624. }
  625. }
  626. }
  627. }
  628. private void createFootnotePages(KnuthPageNode lastNode) {
  629. insertedFootnotesLength = lastNode.totalFootnotes;
  630. footnoteListIndex = lastNode.footnoteListIndex;
  631. footnoteElementIndex = lastNode.footnoteElementIndex;
  632. int availableBPD = getLineWidth(lastNode.line);
  633. int split = 0;
  634. KnuthPageNode prevNode = lastNode;
  635. // create pages containing the remaining footnote bodies
  636. while (insertedFootnotesLength < totalFootnotesLength) {
  637. // try adding some more content
  638. if (((Integer) lengthList.get(footnoteListIndex)).intValue() - insertedFootnotesLength
  639. <= availableBPD) {
  640. // add a whole footnote
  641. availableBPD -= ((Integer) lengthList.get(footnoteListIndex)).intValue()
  642. - insertedFootnotesLength;
  643. insertedFootnotesLength = ((Integer)lengthList.get(footnoteListIndex)).intValue();
  644. footnoteElementIndex
  645. = ((LinkedList)footnotesList.get(footnoteListIndex)).size() - 1;
  646. } else if ((split = getFootnoteSplit(footnoteListIndex, footnoteElementIndex,
  647. insertedFootnotesLength, availableBPD, true))
  648. > 0) {
  649. // add a piece of a footnote
  650. availableBPD -= split;
  651. insertedFootnotesLength += split;
  652. // footnoteListIndex has already been set in getFootnoteSplit()
  653. // footnoteElementIndex has already been set in getFootnoteSplit()
  654. } else {
  655. // cannot add any content: create a new node and start again
  656. KnuthPageNode node = (KnuthPageNode)
  657. createNode(lastNode.position, prevNode.line + 1, 1,
  658. insertedFootnotesLength - prevNode.totalFootnotes,
  659. 0, 0,
  660. 0, 0, 0,
  661. 0, 0, prevNode);
  662. addNode(node.line, node);
  663. removeNode(prevNode.line, prevNode);
  664. prevNode = node;
  665. availableBPD = getLineWidth(node.line);
  666. }
  667. }
  668. // create the last node
  669. KnuthPageNode node = (KnuthPageNode)
  670. createNode(lastNode.position, prevNode.line + 1, 1,
  671. totalFootnotesLength - prevNode.totalFootnotes, 0, 0,
  672. 0, 0, 0,
  673. 0, 0, prevNode);
  674. addNode(node.line, node);
  675. removeNode(prevNode.line, prevNode);
  676. }
  677. /**
  678. * @return a list of PageBreakPosition elements
  679. */
  680. public LinkedList getPageBreaks() {
  681. return pageBreaks;
  682. }
  683. public void insertPageBreakAsFirst(PageBreakPosition pageBreak) {
  684. if (pageBreaks == null) {
  685. pageBreaks = new LinkedList();
  686. }
  687. pageBreaks.addFirst(pageBreak);
  688. }
  689. /**
  690. * Removes all page breaks from the result list. This is used by block-containers and
  691. * static-content when it is only desired to know where there is an overflow but later the
  692. * whole content should be painted as one part.
  693. */
  694. public void removeAllPageBreaks() {
  695. if (pageBreaks == null) {
  696. return;
  697. }
  698. while (pageBreaks.size() > 1) {
  699. pageBreaks.removeFirst();
  700. }
  701. }
  702. public void updateData1(int total, double demerits) {
  703. }
  704. public void updateData2(KnuthNode bestActiveNode,
  705. KnuthSequence sequence,
  706. int total) {
  707. //int difference = (bestActiveNode.line < total)
  708. // ? bestActiveNode.difference : bestActiveNode.difference + fillerMinWidth;
  709. int difference = bestActiveNode.difference;
  710. if (difference + bestActiveNode.availableShrink < 0) {
  711. if (!autoHeight) {
  712. if (layoutListener != null) {
  713. layoutListener.notifyOverflow(bestActiveNode.line - 1, -difference, getFObj());
  714. }
  715. }
  716. }
  717. boolean isNonLastPage = (bestActiveNode.line < total);
  718. int blockAlignment = isNonLastPage ? alignment : alignmentLast;
  719. // it is always allowed to adjust space, so the ratio must be set regardless of
  720. // the value of the property display-align; the ratio must be <= 1
  721. double ratio = bestActiveNode.adjustRatio;
  722. if (ratio < 0) {
  723. // page break with a negative difference:
  724. // spaces always have enough shrink
  725. difference = 0;
  726. } else if (ratio <= 1 && isNonLastPage) {
  727. // not-last page break with a positive difference smaller than the available stretch:
  728. // spaces can stretch to fill the whole difference
  729. difference = 0;
  730. } else if (ratio > 1) {
  731. // not-last page with a positive difference greater than the available stretch
  732. // spaces can stretch to fill the difference only partially
  733. ratio = 1;
  734. difference -= bestActiveNode.availableStretch;
  735. } else {
  736. // last page with a positive difference:
  737. // spaces do not need to stretch
  738. if (blockAlignment != Constants.EN_JUSTIFY) {
  739. ratio = 0;
  740. } else {
  741. //Stretch as much as possible on last page
  742. difference = 0;
  743. }
  744. }
  745. // compute the indexes of the first footnote list and the first element in that list
  746. int firstListIndex = ((KnuthPageNode) bestActiveNode.previous).footnoteListIndex;
  747. int firstElementIndex = ((KnuthPageNode) bestActiveNode.previous).footnoteElementIndex;
  748. if (footnotesList != null
  749. && firstElementIndex == ((LinkedList) footnotesList.get(firstListIndex)).size() - 1) {
  750. // advance to the next list
  751. firstListIndex++;
  752. firstElementIndex = 0;
  753. } else {
  754. firstElementIndex++;
  755. }
  756. // add nodes at the beginning of the list, as they are found
  757. // backwards, from the last one to the first one
  758. if (log.isDebugEnabled()) {
  759. log.debug("BBA> difference=" + difference + " ratio=" + ratio
  760. + " position=" + bestActiveNode.position);
  761. }
  762. insertPageBreakAsFirst(new PageBreakPosition(this.topLevelLM,
  763. bestActiveNode.position,
  764. firstListIndex, firstElementIndex,
  765. ((KnuthPageNode) bestActiveNode).footnoteListIndex,
  766. ((KnuthPageNode) bestActiveNode).footnoteElementIndex,
  767. ratio, difference));
  768. }
  769. protected int filterActiveNodes() {
  770. // leave only the active node with fewest total demerits
  771. KnuthNode bestActiveNode = null;
  772. for (int i = startLine; i < endLine; i++) {
  773. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  774. if (favorSinglePart
  775. && node.line > 1
  776. && bestActiveNode != null
  777. && Math.abs(bestActiveNode.difference) < bestActiveNode.availableShrink) {
  778. //favor current best node, so just skip the current node because it would
  779. //result in more than one part
  780. } else {
  781. bestActiveNode = compareNodes(bestActiveNode, node);
  782. }
  783. if (node != bestActiveNode) {
  784. removeNode(i, node);
  785. }
  786. }
  787. }
  788. return bestActiveNode.line;
  789. }
  790. public LinkedList getFootnoteList(int index) {
  791. return (LinkedList) footnotesList.get(index);
  792. }
  793. /** @return the associated top-level formatting object. */
  794. public FObj getFObj() {
  795. return topLevelLM.getFObj();
  796. }
  797. /** {@inheritDoc} */
  798. protected int getLineWidth(int line) {
  799. int bpd;
  800. if (pageProvider != null) {
  801. bpd = pageProvider.getAvailableBPD(line);
  802. } else {
  803. bpd = super.getLineWidth(line);
  804. }
  805. if (log.isTraceEnabled()) {
  806. log.trace("getLineWidth(" + line + ") -> " + bpd);
  807. }
  808. return bpd;
  809. }
  810. /**
  811. * Interface to notify about layout events during page breaking.
  812. */
  813. public interface PageBreakingLayoutListener {
  814. /**
  815. * Issued when an overflow is detected
  816. * @param part the number of the part (page) this happens on
  817. * @param amount the amount by which the area overflows (in mpt)
  818. * @param obj the root FO object where this happens
  819. */
  820. void notifyOverflow(int part, int amount, FObj obj);
  821. }
  822. }