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.

BreakingAlgorithm.java 57KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  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 org.apache.commons.logging.Log;
  20. import org.apache.commons.logging.LogFactory;
  21. import org.apache.fop.fo.Constants;
  22. /**
  23. * The set of nodes is sorted into lines indexed into activeLines.
  24. * The nodes in each line are linked together in a single linked list by the
  25. * {@link KnuthNode#next} field. The activeLines array contains a link to the head of
  26. * the linked list in index 'line*2' and a link to the tail at index 'line*2+1'.
  27. * <p>
  28. * The set of active nodes can be traversed by
  29. * <pre>
  30. * for (int line = startLine; line &lt; endLine; line++) {
  31. * for (KnuthNode node = getNode(line); node != null; node = node.next) {
  32. * // Do something with 'node'
  33. * }
  34. * }
  35. * </pre>
  36. */
  37. public abstract class BreakingAlgorithm {
  38. /** the logger for the class */
  39. protected static final Log log = LogFactory.getLog(BreakingAlgorithm.class);
  40. /** Maximum adjustment ration */
  41. protected static final int INFINITE_RATIO = 1000;
  42. private static final int MAX_RECOVERY_ATTEMPTS = 5;
  43. // constants identifying a subset of the feasible breaks
  44. /** All feasible breaks are ok. */
  45. public static final int ALL_BREAKS = 0;
  46. /** This forbids hyphenation. */
  47. public static final int NO_FLAGGED_PENALTIES = 1;
  48. /** wrap-option = "no-wrap". */
  49. public static final int ONLY_FORCED_BREAKS = 2;
  50. /** Holder for symbolic literals for the fitness classes */
  51. static final class FitnessClasses {
  52. private FitnessClasses() {
  53. }
  54. static final int VERY_TIGHT = 0;
  55. static final int TIGHT = 1;
  56. static final int LOOSE = 2;
  57. static final int VERY_LOOSE = 3;
  58. static final String[] NAMES = {
  59. "VERY TIGHT", "TIGHT", "LOOSE", "VERY LOOSE"
  60. };
  61. /**
  62. * Figure out the fitness class of this line (tight, loose,
  63. * very tight or very loose).
  64. * See the section on "More Bells and Whistles" in Knuth's
  65. * "Breaking Paragraphs Into Lines".
  66. *
  67. * @param adjustRatio the adjustment ratio
  68. * @return the fitness class
  69. */
  70. static int computeFitness(double adjustRatio) {
  71. if (adjustRatio < -0.5) {
  72. return FitnessClasses.VERY_TIGHT;
  73. } else if (adjustRatio <= 0.5) {
  74. return FitnessClasses.TIGHT;
  75. } else if (adjustRatio <= 1.0) {
  76. return FitnessClasses.LOOSE;
  77. } else {
  78. return FitnessClasses.VERY_LOOSE;
  79. }
  80. }
  81. }
  82. // parameters of Knuth's algorithm:
  83. /** Demerit for consecutive lines ending at flagged penalties. */
  84. protected int repeatedFlaggedDemerit = KnuthPenalty.FLAGGED_PENALTY;
  85. /** Demerit for consecutive lines belonging to incompatible fitness classes . */
  86. protected int incompatibleFitnessDemerit = KnuthPenalty.FLAGGED_PENALTY;
  87. /** Maximum number of consecutive lines ending with a flagged penalty.
  88. * Only a value >= 1 is a significant limit.
  89. */
  90. protected int maxFlaggedPenaltiesCount;
  91. /**
  92. * The threshold for considering breaks to be acceptable. The adjustment ratio must be
  93. * inferior to this threshold.
  94. */
  95. private double threshold;
  96. /**
  97. * The paragraph of KnuthElements.
  98. */
  99. protected KnuthSequence par;
  100. /**
  101. * The width of a line (or height of a column in page-breaking mode).
  102. * -1 indicates that the line widths are different for each line.
  103. */
  104. protected int lineWidth = -1;
  105. /** Force the algorithm to find a set of breakpoints, even if no feasible breakpoints
  106. * exist.
  107. */
  108. private boolean force = false;
  109. /** If set to true, doesn't ignore break possibilities which are definitely too short. */
  110. protected boolean considerTooShort = false;
  111. /** When in forced mode, the best node leading to a too long line. The line will be
  112. * too long anyway, but this one will lead to a paragraph with fewest demerits.
  113. */
  114. private KnuthNode lastTooLong;
  115. /** When in forced mode, the best node leading to a too short line. The line will be
  116. * too short anyway, but this one will lead to a paragraph with fewest demerits.
  117. */
  118. private KnuthNode lastTooShort;
  119. /** The node to be reactivated if no set of feasible breakpoints can be found for this
  120. * paragraph.
  121. */
  122. private KnuthNode lastDeactivated;
  123. /** Alignment of the paragraph/page. One of EN_START, EN_JUSTIFY, etc. */
  124. protected int alignment;
  125. /** Alignment of the paragraph's last line. */
  126. protected int alignmentLast;
  127. /** Used to handle the text-indent property (indent the first line of a paragraph). */
  128. protected boolean indentFirstPart;
  129. /**
  130. * The set of active nodes in ascending line order. For each line l, activeLines[2l] contains a
  131. * link to l's first active node, and activeLines[2l+1] a link to l's last active node. The
  132. * line number l corresponds to the number of the line ending at the node's breakpoint.
  133. */
  134. protected KnuthNode[] activeLines;
  135. /**
  136. * The number of active nodes.
  137. */
  138. protected int activeNodeCount;
  139. /**
  140. * The lowest available line in the set of active nodes.
  141. */
  142. protected int startLine = 0;
  143. /**
  144. * The highest + 1 available line in the set of active nodes.
  145. */
  146. protected int endLine = 0;
  147. /**
  148. * The total width of all elements handled so far.
  149. */
  150. protected int totalWidth;
  151. /**
  152. * The total stretch of all elements handled so far.
  153. */
  154. protected int totalStretch = 0;
  155. /**
  156. * The total shrink of all elements handled so far.
  157. */
  158. protected int totalShrink = 0;
  159. /**
  160. * Best records.
  161. */
  162. protected BestRecords best;
  163. private boolean partOverflowRecoveryActivated = true;
  164. private KnuthNode lastRecovered;
  165. /**
  166. * Create a new instance.
  167. *
  168. * @param align alignment of the paragraph/page. One of {@link Constants#EN_START},
  169. * {@link Constants#EN_JUSTIFY}, {@link Constants#EN_CENTER},
  170. * {@link Constants#EN_END}.
  171. * For pages, {@link Constants#EN_BEFORE} and {@link Constants#EN_AFTER}
  172. * are mapped to the corresponding inline properties,
  173. * {@link Constants#EN_START} and {@link Constants#EN_END}.
  174. * @param alignLast alignment of the paragraph's last line
  175. * @param first for the text-indent property ({@code true} if the first line
  176. * of a paragraph should be indented)
  177. * @param partOverflowRecovery {@code true} if too long elements should be moved to
  178. * the next line/part
  179. * @param maxFlagCount maximum allowed number of consecutive lines ending at a flagged penalty
  180. * item
  181. */
  182. public BreakingAlgorithm(int align, int alignLast,
  183. boolean first, boolean partOverflowRecovery,
  184. int maxFlagCount) {
  185. this.alignment = align;
  186. this.alignmentLast = alignLast;
  187. this.indentFirstPart = first;
  188. this.partOverflowRecoveryActivated = partOverflowRecovery;
  189. this.best = new BestRecords();
  190. this.maxFlaggedPenaltiesCount = maxFlagCount;
  191. }
  192. /**
  193. * Class recording all the informations of a feasible breaking point.
  194. */
  195. public class KnuthNode {
  196. /** index of the breakpoint represented by this node */
  197. public final int position; // CSOK: VisibilityModifier
  198. /** number of the line ending at this breakpoint */
  199. public final int line; // CSOK: VisibilityModifier
  200. /** fitness class of the line ending at this breakpoint. One of 0, 1, 2, 3. */
  201. public final int fitness; // CSOK: VisibilityModifier
  202. /** accumulated width of the KnuthElements up to after this breakpoint. */
  203. public final int totalWidth; // CSOK: VisibilityModifier
  204. /** accumulated stretchability of the KnuthElements up to after this breakpoint. */
  205. public final int totalStretch; // CSOK: VisibilityModifier
  206. /** accumulated shrinkability of the KnuthElements up to after this breakpoint. */
  207. public final int totalShrink; // CSOK: VisibilityModifier
  208. /** adjustment ratio if the line ends at this breakpoint */
  209. public final double adjustRatio; // CSOK: VisibilityModifier
  210. /** available stretch of the line ending at this breakpoint */
  211. public final int availableShrink; // CSOK: VisibilityModifier
  212. /** available shrink of the line ending at this breakpoint */
  213. public final int availableStretch; // CSOK: VisibilityModifier
  214. /** difference between target and actual line width */
  215. public final int difference; // CSOK: VisibilityModifier
  216. /** minimum total demerits up to this breakpoint */
  217. public double totalDemerits; // CSOK: VisibilityModifier
  218. /** best node for the preceding breakpoint */
  219. public KnuthNode previous; // CSOK: VisibilityModifier
  220. /** next possible node in the same line */
  221. public KnuthNode next; // CSOK: VisibilityModifier
  222. /**
  223. * Holds the number of subsequent recovery attempty that are made to get content fit
  224. * into a line.
  225. */
  226. public int fitRecoveryCounter = 0; // CSOK: VisibilityModifier
  227. /**
  228. * Construct node.
  229. * @param position an integer
  230. * @param line an integer
  231. * @param fitness an integer
  232. * @param totalWidth an integer
  233. * @param totalStretch an integer
  234. * @param totalShrink an integer
  235. * @param adjustRatio a real number
  236. * @param availableShrink an integer
  237. * @param availableStretch an integer
  238. * @param difference an integer
  239. * @param totalDemerits a real number
  240. * @param previous a node
  241. */
  242. public KnuthNode( // CSOK: ParameterNumber
  243. int position, int line, int fitness,
  244. int totalWidth, int totalStretch, int totalShrink,
  245. double adjustRatio, int availableShrink, int availableStretch,
  246. int difference, double totalDemerits, KnuthNode previous) {
  247. this.position = position;
  248. this.line = line;
  249. this.fitness = fitness;
  250. this.totalWidth = totalWidth;
  251. this.totalStretch = totalStretch;
  252. this.totalShrink = totalShrink;
  253. this.adjustRatio = adjustRatio;
  254. this.availableShrink = availableShrink;
  255. this.availableStretch = availableStretch;
  256. this.difference = difference;
  257. this.totalDemerits = totalDemerits;
  258. this.previous = previous;
  259. }
  260. /** {@inheritDoc} */
  261. public String toString() {
  262. return "<KnuthNode at " + position + " "
  263. + totalWidth + "+" + totalStretch + "-" + totalShrink
  264. + " line:" + line + " prev:" + (previous != null ? previous.position : -1)
  265. + " dem:" + totalDemerits
  266. + " fitness:" + FitnessClasses.NAMES[fitness] + ">";
  267. }
  268. }
  269. /** Class that stores, for each fitness class, the best active node that could start
  270. * a line of the corresponding fitness ending at the current element.
  271. */
  272. protected class BestRecords {
  273. private static final double INFINITE_DEMERITS = Double.POSITIVE_INFINITY;
  274. private double[] bestDemerits = new double[4];
  275. private KnuthNode[] bestNode = new KnuthNode[4];
  276. private double[] bestAdjust = new double[4];
  277. private int[] bestDifference = new int[4];
  278. private int[] bestAvailableShrink = new int[4];
  279. private int[] bestAvailableStretch = new int[4];
  280. /** Points to the fitness class which currently leads to the best demerits. */
  281. private int bestIndex = -1;
  282. /** default constructor */
  283. public BestRecords() {
  284. reset();
  285. }
  286. /** Registers the new best active node for the given fitness class.
  287. * @param demerits the total demerits of the new optimal set of breakpoints
  288. * @param node the node starting the line ending at the current element
  289. * @param adjust adjustment ratio of the current line
  290. * @param availableShrink how much the current line can be shrinked
  291. * @param availableStretch how much the current line can be stretched
  292. * @param difference difference between the width of the considered line and the
  293. * width of the "real" line
  294. * @param fitness fitness class of the current line
  295. */
  296. public void addRecord(double demerits, KnuthNode node, double adjust,
  297. int availableShrink, int availableStretch,
  298. int difference, int fitness) {
  299. if (demerits > bestDemerits[fitness]) {
  300. log.error("New demerits value greater than the old one");
  301. }
  302. bestDemerits[fitness] = demerits;
  303. bestNode[fitness] = node;
  304. bestAdjust[fitness] = adjust;
  305. bestAvailableShrink[fitness] = availableShrink;
  306. bestAvailableStretch[fitness] = availableStretch;
  307. bestDifference[fitness] = difference;
  308. if (bestIndex == -1 || demerits < bestDemerits[bestIndex]) {
  309. bestIndex = fitness;
  310. }
  311. }
  312. /** @return true if has records (best index not -1) */
  313. public boolean hasRecords() {
  314. return (bestIndex != -1);
  315. }
  316. /**
  317. * @param fitness fitness class (0, 1, 2 or 3, i.e. "tight" to "very loose")
  318. * @return true if there is a set of feasible breakpoints registered for the
  319. * given fitness.
  320. */
  321. public boolean notInfiniteDemerits(int fitness) {
  322. return (bestDemerits[fitness] != INFINITE_DEMERITS);
  323. }
  324. /**
  325. * @param fitness to use
  326. * @return best demerits
  327. */
  328. public double getDemerits(int fitness) {
  329. return bestDemerits[fitness];
  330. }
  331. /**
  332. * @param fitness to use
  333. * @return best node
  334. */
  335. public KnuthNode getNode(int fitness) {
  336. return bestNode[fitness];
  337. }
  338. /**
  339. * @param fitness to use
  340. * @return adjustment
  341. */
  342. public double getAdjust(int fitness) {
  343. return bestAdjust[fitness];
  344. }
  345. /**
  346. * @param fitness to use
  347. * @return available shrink
  348. */
  349. public int getAvailableShrink(int fitness) {
  350. return bestAvailableShrink[fitness];
  351. }
  352. /**
  353. * @param fitness to use
  354. * @return available stretch
  355. */
  356. public int getAvailableStretch(int fitness) {
  357. return bestAvailableStretch[fitness];
  358. }
  359. /**
  360. * @param fitness to use
  361. * @return difference
  362. */
  363. public int getDifference(int fitness) {
  364. return bestDifference[fitness];
  365. }
  366. /** @return minimum demerits */
  367. public double getMinDemerits() {
  368. if (bestIndex != -1) {
  369. return getDemerits(bestIndex);
  370. } else {
  371. // anyway, this should never happen
  372. return INFINITE_DEMERITS;
  373. }
  374. }
  375. /** Reset when a new breakpoint is being considered. */
  376. public void reset() {
  377. for (int i = 0; i < 4; i++) {
  378. bestDemerits[i] = INFINITE_DEMERITS;
  379. // there is no need to reset the other arrays
  380. }
  381. bestIndex = -1;
  382. }
  383. }
  384. /**
  385. * @return the number of times the algorithm should try to move overflowing content to the
  386. * next line/page.
  387. */
  388. protected int getMaxRecoveryAttempts() {
  389. return MAX_RECOVERY_ATTEMPTS;
  390. }
  391. /**
  392. * Controls the behaviour of the algorithm in cases where the first element of a part
  393. * overflows a line/page.
  394. * @return true if the algorithm should try to send the element to the next line/page.
  395. */
  396. protected boolean isPartOverflowRecoveryActivated() {
  397. return this.partOverflowRecoveryActivated;
  398. }
  399. /**
  400. * Empty method, hook for subclasses. Called before determining the optimal
  401. * breakpoints corresponding to a given active node.
  402. * @param total number of lines for the active node
  403. * @param demerits total demerits of the paragraph for the active node
  404. */
  405. public abstract void updateData1(int total, double demerits);
  406. /**
  407. * Empty method, hook for subclasses. Called when determining the optimal breakpoints
  408. * for a given active node.
  409. * @param bestActiveNode a node in the chain of best active nodes, corresponding to
  410. * one of the optimal breakpoints
  411. * @param sequence the corresponding paragraph
  412. * @param total the number of lines into which the paragraph will be broken
  413. */
  414. public abstract void updateData2(KnuthNode bestActiveNode,
  415. KnuthSequence sequence,
  416. int total);
  417. /** @param lineWidth the line width */
  418. public void setConstantLineWidth(int lineWidth) {
  419. this.lineWidth = lineWidth;
  420. }
  421. /**
  422. * @param par the paragraph to break
  423. * @param threshold upper bound of the adjustment ratio
  424. * @param force {@code true} if a set of breakpoints must be found, even
  425. * if there are no feasible ones
  426. * @param allowedBreaks the type(s) of breaks allowed. One of {@link #ONLY_FORCED_BREAKS},
  427. * {@link #NO_FLAGGED_PENALTIES} or {@link #ALL_BREAKS}.
  428. *
  429. * @return the number of effective breaks
  430. * @see #findBreakingPoints(KnuthSequence, int, double, boolean, int)
  431. */
  432. public int findBreakingPoints(KnuthSequence par,
  433. double threshold,
  434. boolean force,
  435. int allowedBreaks) {
  436. return findBreakingPoints(par, 0, threshold, force, allowedBreaks);
  437. }
  438. /**
  439. * Finds an optimal set of breakpoints for the given paragraph.
  440. *
  441. * @param par the paragraph to break
  442. * @param startIndex index of the Knuth element at which the breaking must start
  443. * @param threshold upper bound of the adjustment ratio
  444. * @param force {@code true} if a set of breakpoints must be found, even
  445. * if there are no feasible ones
  446. * @param allowedBreaks the type(s) of breaks allowed. One of {@link #ONLY_FORCED_BREAKS},
  447. * {@link #NO_FLAGGED_PENALTIES} or {@link #ALL_BREAKS}.
  448. *
  449. * @return the number of effective breaks
  450. */
  451. public int findBreakingPoints(KnuthSequence par, int startIndex,
  452. double threshold, boolean force,
  453. int allowedBreaks) {
  454. this.par = par;
  455. this.threshold = threshold;
  456. this.force = force;
  457. // initialize the algorithm
  458. initialize();
  459. // previous element in the paragraph is a KnuthBox?
  460. boolean previousIsBox = false;
  461. // index of the first KnuthBox in the sequence, in case of non-centered
  462. // alignment. For centered alignment, we need to take into account preceding
  463. // penalties+glues used for the filler spaces
  464. int firstBoxIndex = startIndex;
  465. if (alignment != Constants.EN_CENTER) {
  466. firstBoxIndex = par.getFirstBoxIndex(startIndex);
  467. }
  468. firstBoxIndex = (firstBoxIndex < 0) ? 0 : firstBoxIndex;
  469. // create an active node representing the starting point
  470. addNode(0, createNode(firstBoxIndex, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, null));
  471. KnuthNode lastForced = getNode(0);
  472. if (log.isTraceEnabled()) {
  473. log.trace("Looping over " + (par.size() - startIndex) + " elements");
  474. log.trace(par);
  475. }
  476. // main loop
  477. for (int elementIndex = startIndex; elementIndex < par.size(); elementIndex++) {
  478. previousIsBox = handleElementAt(
  479. elementIndex, previousIsBox, allowedBreaks).isBox();
  480. if (activeNodeCount == 0) {
  481. if (getIPDdifference() != 0) {
  482. return handleIpdChange();
  483. }
  484. if (!force) {
  485. log.debug("Could not find a set of breaking points " + threshold);
  486. return 0;
  487. }
  488. // lastDeactivated was a "good" break, while lastTooShort and lastTooLong
  489. // were "bad" breaks since the beginning;
  490. // if it is not the node we just restarted from, lastDeactivated can
  491. // replace either lastTooShort or lastTooLong
  492. if (lastDeactivated != null
  493. && lastDeactivated != lastForced) {
  494. replaceLastDeactivated();
  495. }
  496. if (lastTooShort == null
  497. || lastForced.position == lastTooShort.position) {
  498. lastForced = recoverFromOverflow();
  499. } else {
  500. lastForced = lastTooShort;
  501. this.lastRecovered = null;
  502. }
  503. elementIndex = restartFrom(lastForced, elementIndex);
  504. }
  505. }
  506. finish();
  507. // there is at least one set of breaking points
  508. // select one or more active nodes, removing the others from the list
  509. int line = filterActiveNodes();
  510. // for each active node, create a set of breaking points
  511. for (int i = startLine; i < endLine; i++) {
  512. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  513. updateData1(node.line, node.totalDemerits);
  514. calculateBreakPoints(node, par, node.line);
  515. }
  516. }
  517. activeLines = null;
  518. return line;
  519. }
  520. /**
  521. * obtain ipd difference
  522. * @return an integer
  523. */
  524. protected int getIPDdifference() {
  525. return 0;
  526. }
  527. /**
  528. * handle ipd change
  529. * @return an integer
  530. */
  531. protected int handleIpdChange() {
  532. throw new IllegalStateException();
  533. }
  534. /**
  535. * Recover from a {@link KnuthNode} leading to a line that is too long.
  536. * The default implementation creates a new node corresponding to a break
  537. * point after the previous node that led to a line that was too short.
  538. *
  539. * @param lastTooLong the node that leads to a "too long" line
  540. * @return node corresponding to a breakpoint after the previous "too short" line
  541. */
  542. protected KnuthNode recoverFromTooLong(KnuthNode lastTooLong) {
  543. if (log.isDebugEnabled()) {
  544. log.debug("Recovering from too long: " + lastTooLong);
  545. }
  546. // content would overflow, insert empty line/page and try again
  547. return createNode(
  548. lastTooLong.previous.position, lastTooLong.previous.line + 1, 1,
  549. 0, 0, 0,
  550. 0, 0, 0,
  551. 0, 0, lastTooLong.previous);
  552. }
  553. /** Initializes the algorithm's variables. */
  554. protected void initialize() {
  555. this.totalWidth = 0;
  556. this.totalStretch = 0;
  557. this.totalShrink = 0;
  558. this.lastTooShort = null;
  559. this.lastTooLong = null;
  560. this.startLine = 0;
  561. this.endLine = 0;
  562. this.activeLines = new KnuthNode[20];
  563. }
  564. /**
  565. * Creates a new active node for a feasible breakpoint at the given position. Only
  566. * called in forced mode.
  567. *
  568. * @param position index of the element in the Knuth sequence
  569. * @param line number of the line ending at the breakpoint
  570. * @param fitness fitness class of the line ending at the breakpoint. One of 0, 1, 2, 3.
  571. * @param totalWidth accumulated width of the KnuthElements up to after the breakpoint
  572. * @param totalStretch accumulated stretchability of the KnuthElements up to after the
  573. * breakpoint
  574. * @param totalShrink accumulated shrinkability of the KnuthElements up to after the
  575. * breakpoint
  576. * @param adjustRatio adjustment ratio if the line ends at this breakpoint
  577. * @param availableShrink available stretch of the line ending at this breakpoint
  578. * @param availableStretch available shrink of the line ending at this breakpoint
  579. * @param difference difference between target and actual line width
  580. * @param totalDemerits minimum total demerits up to the breakpoint
  581. * @param previous active node for the preceding breakpoint
  582. * @return a new node
  583. */
  584. protected KnuthNode createNode( // CSOK: ParameterNumber
  585. int position, int line, int fitness,
  586. int totalWidth, int totalStretch, int totalShrink,
  587. double adjustRatio, int availableShrink, int availableStretch,
  588. int difference, double totalDemerits, KnuthNode previous) {
  589. return new KnuthNode(position, line, fitness,
  590. totalWidth, totalStretch, totalShrink,
  591. adjustRatio, availableShrink, availableStretch,
  592. difference, totalDemerits, previous);
  593. }
  594. /** Creates a new active node for a break from the best active node of the given
  595. * fitness class to the element at the given position.
  596. * @param position index of the element in the Knuth sequence
  597. * @param line number of the line ending at the breakpoint
  598. * @param fitness fitness class of the line ending at the breakpoint. One of 0, 1, 2, 3.
  599. * @param totalWidth accumulated width of the KnuthElements up to after the breakpoint
  600. * @param totalStretch accumulated stretchability of the KnuthElements up to after the
  601. * breakpoint
  602. * @param totalShrink accumulated shrinkability of the KnuthElements up to after the
  603. * breakpoint
  604. * @return a new node
  605. * @see #createNode(int, int, int, int, int, int, double, int, int, int, double,
  606. * org.apache.fop.layoutmgr.BreakingAlgorithm.KnuthNode)
  607. * @see BreakingAlgorithm.BestRecords
  608. */
  609. protected KnuthNode createNode(int position, int line, int fitness,
  610. int totalWidth, int totalStretch, int totalShrink) {
  611. return new KnuthNode(position, line, fitness,
  612. totalWidth, totalStretch, totalShrink, best.getAdjust(fitness),
  613. best.getAvailableShrink(fitness), best.getAvailableStretch(fitness),
  614. best.getDifference(fitness), best.getDemerits(fitness),
  615. best.getNode(fitness));
  616. }
  617. /**
  618. * Return the last node that yielded a too short line.
  619. * @return the node corresponding to the last too short line
  620. */
  621. protected final KnuthNode getLastTooShort() {
  622. return this.lastTooShort;
  623. }
  624. /**
  625. * Generic handler for a {@link KnuthElement} at the given {@code position},
  626. * taking into account whether the preceding element was a box, and which
  627. * type(s) of breaks are allowed.
  628. * Non-overridable. This method simply serves to route the call to one of the
  629. * more specific handlers ({@link #handleBox(KnuthBox)},
  630. * {@link #handleGlueAt(KnuthGlue,int,boolean,int)} or
  631. * {@link #handlePenaltyAt(KnuthPenalty,int,int)}. The specialized handlers
  632. * can be overridden by subclasses to add to or modify the default behavior
  633. * for the different types of elements.
  634. *
  635. * @param position the position index of the element in the paragraph
  636. * @param previousIsBox {@code true} if the previous element is a box
  637. * @param allowedBreaks the type(s) of breaks allowed; should be one
  638. * of {@link #ALL_BREAKS}, {@link #NO_FLAGGED_PENALTIES}
  639. * or {@link #ONLY_FORCED_BREAKS}
  640. * @return the handled element
  641. */
  642. protected final KnuthElement handleElementAt(int position,
  643. boolean previousIsBox,
  644. int allowedBreaks) {
  645. KnuthElement element = getElement(position);
  646. if (element.isBox()) {
  647. handleBox((KnuthBox) element);
  648. } else if (element.isGlue()) {
  649. handleGlueAt((KnuthGlue) element, position, previousIsBox, allowedBreaks);
  650. } else if (element.isPenalty()) {
  651. handlePenaltyAt((KnuthPenalty) element, position, allowedBreaks);
  652. } else {
  653. throw new IllegalArgumentException(
  654. "Unknown KnuthElement type: expecting KnuthBox, KnuthGlue or KnuthPenalty");
  655. }
  656. return element;
  657. }
  658. /**
  659. * Handle a {@link KnuthBox}.
  660. * <br/><em>Note: default implementation just adds the box's width
  661. * to the total content width. Subclasses that do not keep track
  662. * of this themselves, but override this method, should remember
  663. * to call {@code super.handleBox(box)} to avoid unwanted side-effects.</em>
  664. *
  665. * @param box the {@link KnuthBox} to handle
  666. */
  667. protected void handleBox(KnuthBox box) {
  668. // a KnuthBox object is not a legal line break,
  669. // just add the width to the total
  670. totalWidth += box.getWidth();
  671. }
  672. /**
  673. * Handle a {@link KnuthGlue} at the given position,
  674. * taking into account the additional parameters.
  675. *
  676. * @param glue the {@link KnuthGlue} to handle
  677. * @param position the position of the glue in the list
  678. * @param previousIsBox {@code true} if the preceding element is a box
  679. * @param allowedBreaks the type of breaks that are allowed
  680. */
  681. protected void handleGlueAt(KnuthGlue glue, int position,
  682. boolean previousIsBox, int allowedBreaks) {
  683. // a KnuthGlue object is a legal line break
  684. // only if the previous object is a KnuthBox
  685. // consider these glues according to the value of allowedBreaks
  686. if (previousIsBox
  687. && !(allowedBreaks == ONLY_FORCED_BREAKS)) {
  688. considerLegalBreak(glue, position);
  689. }
  690. totalWidth += glue.getWidth();
  691. totalStretch += glue.getStretch();
  692. totalShrink += glue.getShrink();
  693. }
  694. /**
  695. * Handle a {@link KnuthPenalty} at the given position,
  696. * taking into account the type of breaks allowed.
  697. *
  698. * @param penalty the {@link KnuthPenalty} to handle
  699. * @param position the position of the penalty in the list
  700. * @param allowedBreaks the type of breaks that are allowed
  701. */
  702. protected void handlePenaltyAt(KnuthPenalty penalty, int position,
  703. int allowedBreaks) {
  704. // a KnuthPenalty is a legal line break
  705. // only if its penalty is not infinite;
  706. // consider all penalties, non-flagged penalties or non-forcing penalties
  707. // according to the value of allowedBreaks
  708. if (((penalty.getPenalty() < KnuthElement.INFINITE)
  709. && (!(allowedBreaks == NO_FLAGGED_PENALTIES) || !penalty.isPenaltyFlagged())
  710. && (!(allowedBreaks == ONLY_FORCED_BREAKS)
  711. || penalty.isForcedBreak()))) {
  712. considerLegalBreak(penalty, position);
  713. }
  714. }
  715. /**
  716. * Replace the last too-long or too-short node by the last deactivated
  717. * node, if applicable.
  718. */
  719. protected final void replaceLastDeactivated() {
  720. if (lastDeactivated.adjustRatio > 0) {
  721. //last deactivated was too short
  722. lastTooShort = lastDeactivated;
  723. } else {
  724. //last deactivated was too long or exactly the right width
  725. lastTooLong = lastDeactivated;
  726. }
  727. }
  728. /**
  729. * Recover from an overflow condition.
  730. *
  731. * @return the new {@code lastForced} node
  732. */
  733. protected KnuthNode recoverFromOverflow() {
  734. KnuthNode lastForced;
  735. if (isPartOverflowRecoveryActivated()) {
  736. if (lastRecovered == null) {
  737. lastRecovered = lastTooLong;
  738. if (log.isDebugEnabled()) {
  739. log.debug("Recovery point: " + lastRecovered);
  740. }
  741. }
  742. KnuthNode node = recoverFromTooLong(lastTooLong);
  743. lastForced = node;
  744. node.fitRecoveryCounter = lastTooLong.previous.fitRecoveryCounter + 1;
  745. if (log.isDebugEnabled()) {
  746. log.debug("first part doesn't fit into line, recovering: "
  747. + node.fitRecoveryCounter);
  748. }
  749. if (node.fitRecoveryCounter > getMaxRecoveryAttempts()) {
  750. while (lastForced.fitRecoveryCounter > 0
  751. && lastForced.previous != null) {
  752. lastForced = lastForced.previous;
  753. lastDeactivated = lastForced.previous;
  754. }
  755. lastForced = lastRecovered;
  756. lastRecovered = null;
  757. startLine = lastForced.line;
  758. endLine = lastForced.line;
  759. log.debug("rolled back...");
  760. }
  761. } else {
  762. lastForced = lastTooLong;
  763. }
  764. return lastForced;
  765. }
  766. /**
  767. * Restart from the given node at the given index.
  768. *
  769. * @param restartingNode the {@link KnuthNode} to restart from
  770. * @param currentIndex the current position index
  771. * @return the index of the restart point
  772. */
  773. protected int restartFrom(KnuthNode restartingNode, int currentIndex) {
  774. if (log.isDebugEnabled()) {
  775. log.debug("Restarting at node " + restartingNode);
  776. }
  777. restartingNode.totalDemerits = 0;
  778. addNode(restartingNode.line, restartingNode);
  779. startLine = restartingNode.line;
  780. endLine = startLine + 1;
  781. totalWidth = restartingNode.totalWidth;
  782. totalStretch = restartingNode.totalStretch;
  783. totalShrink = restartingNode.totalShrink;
  784. lastTooShort = null;
  785. lastTooLong = null;
  786. // the width, stretch and shrink already include the width,
  787. // stretch and shrink of the suppressed glues;
  788. // advance in the sequence in order to avoid taking into account
  789. // these elements twice
  790. int restartingIndex = restartingNode.position;
  791. while (restartingIndex + 1 < par.size()
  792. && !(getElement(restartingIndex + 1).isBox())) {
  793. restartingIndex++;
  794. }
  795. return restartingIndex;
  796. }
  797. /**
  798. * Determines if the given breakpoint is a feasible breakpoint. That is, if a decent
  799. * line may be built between one of the currently active nodes and this breakpoint.
  800. * @param element the paragraph's element to consider
  801. * @param elementIdx the element's index inside the paragraph
  802. */
  803. protected void considerLegalBreak(KnuthElement element, int elementIdx) {
  804. if (log.isTraceEnabled()) {
  805. log.trace("considerLegalBreak() at " + elementIdx
  806. + " (" + totalWidth + "+" + totalStretch + "-" + totalShrink
  807. + "), parts/lines: " + startLine + "-" + endLine);
  808. log.trace("\tCurrent active node list: " + activeNodeCount + " " + this.toString("\t"));
  809. }
  810. lastDeactivated = null;
  811. lastTooLong = null;
  812. for (int line = startLine; line < endLine; line++) {
  813. for (KnuthNode node = getNode(line); node != null; node = node.next) {
  814. if (node.position == elementIdx) {
  815. continue;
  816. }
  817. int difference = computeDifference(node, element, elementIdx);
  818. if (!elementCanEndLine(element, endLine, difference)) {
  819. log.trace("Skipping legal break");
  820. break;
  821. }
  822. double r = computeAdjustmentRatio(node, difference);
  823. int availableShrink = totalShrink - node.totalShrink;
  824. int availableStretch = totalStretch - node.totalStretch;
  825. if (log.isTraceEnabled()) {
  826. log.trace("\tr=" + r + " difference=" + difference);
  827. log.trace("\tline=" + line);
  828. }
  829. // The line would be too long.
  830. if (r < -1 || element.isForcedBreak()) {
  831. deactivateNode(node, line);
  832. }
  833. int fitnessClass = FitnessClasses.computeFitness(r);
  834. double demerits = computeDemerits(node, element, fitnessClass, r);
  835. // The line is within the available shrink and the threshold.
  836. if (r >= -1 && r <= threshold) {
  837. activateNode(node, difference, r,
  838. demerits, fitnessClass, availableShrink, availableStretch);
  839. }
  840. // The line is way too short/long, but we are in forcing mode, so a node is
  841. // calculated and stored in lastValidNode.
  842. if (force && (r <= -1 || r > threshold)) {
  843. forceNode(node, line, elementIdx, difference, r,
  844. demerits, fitnessClass, availableShrink, availableStretch);
  845. }
  846. }
  847. addBreaks(line, elementIdx);
  848. }
  849. }
  850. /**
  851. * Check if the given {@link KnuthElement} can end the line with the given
  852. * number.
  853. * @param element the element
  854. * @param line the line number
  855. * @param difference an integer
  856. * @return {@code true} if the element can end the line
  857. */
  858. protected boolean elementCanEndLine(KnuthElement element, int line, int difference) {
  859. return (!element.isPenalty()
  860. || element.getPenalty() < KnuthElement.INFINITE);
  861. }
  862. /**
  863. * Force the given {@link KnuthNode}, and register it.
  864. *
  865. * @param node the node
  866. * @param line the line number
  867. * @param elementIdx the position index of the element
  868. * @param difference the difference between content-length and avaialable width
  869. * @param r the adjustment ratio
  870. * @param demerits demerits produced by the node
  871. * @param fitnessClass the fitness class
  872. * @param availableShrink the available amount of shrink
  873. * @param availableStretch tha available amount of stretch
  874. */
  875. protected void forceNode(KnuthNode node, // CSOK: ParameterNumber
  876. int line,
  877. int elementIdx,
  878. int difference,
  879. double r,
  880. double demerits,
  881. int fitnessClass,
  882. int availableShrink,
  883. int availableStretch) {
  884. int newWidth = totalWidth;
  885. int newStretch = totalStretch;
  886. int newShrink = totalShrink;
  887. // add the width, stretch and shrink of glue elements after
  888. // the break
  889. // this does not affect the dimension of the line / page, only
  890. // the values stored in the node; these would be as if the break
  891. // was just before the next box element, thus ignoring glues and
  892. // penalties between the "real" break and the following box
  893. for (int i = elementIdx; i < par.size(); i++) {
  894. KnuthElement tempElement = getElement(i);
  895. if (tempElement.isBox()) {
  896. break;
  897. } else if (tempElement.isGlue()) {
  898. newWidth += tempElement.getWidth();
  899. newStretch += tempElement.getStretch();
  900. newShrink += tempElement.getShrink();
  901. } else if (tempElement.isForcedBreak() && i != elementIdx) {
  902. break;
  903. }
  904. }
  905. if (r <= -1) {
  906. log.debug("Considering tooLong, demerits=" + demerits);
  907. if (lastTooLong == null || demerits < lastTooLong.totalDemerits) {
  908. lastTooLong = createNode(elementIdx, line + 1, fitnessClass,
  909. newWidth, newStretch, newShrink,
  910. r, availableShrink, availableStretch,
  911. difference, demerits, node);
  912. if (log.isTraceEnabled()) {
  913. log.trace("Picking tooLong " + lastTooLong);
  914. }
  915. }
  916. } else {
  917. if (lastTooShort == null || demerits <= lastTooShort.totalDemerits) {
  918. if (considerTooShort) {
  919. //consider possibilities which are too short
  920. best.addRecord(demerits, node, r,
  921. availableShrink, availableStretch,
  922. difference, fitnessClass);
  923. }
  924. lastTooShort = createNode(elementIdx, line + 1, fitnessClass,
  925. newWidth, newStretch, newShrink,
  926. r, availableShrink, availableStretch,
  927. difference, demerits, node);
  928. if (log.isTraceEnabled()) {
  929. log.trace("Picking tooShort " + lastTooShort);
  930. }
  931. }
  932. }
  933. }
  934. /**
  935. * Activate the given node. Will result in the given {@link KnuthNode}
  936. * being registered as a feasible breakpoint, if the {@code demerits} are better
  937. * than that of the best node registered for the given {@code fitnessClass}.
  938. *
  939. * @param node the node
  940. * @param difference the difference between content-length and available width
  941. * @param r the adjustment ratio
  942. * @param demerits demerits produced by the node
  943. * @param fitnessClass the fitness class
  944. * @param availableShrink the available amount of shrink
  945. * @param availableStretch the available amount of stretch
  946. */
  947. protected void activateNode(KnuthNode node,
  948. int difference,
  949. double r,
  950. double demerits,
  951. int fitnessClass,
  952. int availableShrink,
  953. int availableStretch) {
  954. if (log.isTraceEnabled()) {
  955. log.trace("\tDemerits=" + demerits);
  956. log.trace("\tFitness class=" + FitnessClasses.NAMES[fitnessClass]);
  957. }
  958. if (demerits < best.getDemerits(fitnessClass)) {
  959. // updates best demerits data
  960. best.addRecord(demerits, node, r, availableShrink, availableStretch,
  961. difference, fitnessClass);
  962. lastTooShort = null;
  963. }
  964. }
  965. /**
  966. * Deactivate the given node
  967. *
  968. * @param node the node
  969. * @param line the line number
  970. */
  971. protected void deactivateNode(KnuthNode node, int line) {
  972. // Deactivate node...
  973. if (log.isTraceEnabled()) {
  974. log.trace("Removing " + node);
  975. }
  976. removeNode(line, node);
  977. // ... and remember it, if it was a good candidate
  978. lastDeactivated = compareNodes(lastDeactivated, node);
  979. }
  980. /**
  981. * Adds new active nodes for breaks at the given element.
  982. * @param line number of the previous line; this element will end line number (line+1)
  983. * @param elementIdx the element's index
  984. */
  985. private void addBreaks(int line, int elementIdx) {
  986. if (!best.hasRecords()) {
  987. return;
  988. }
  989. int newWidth = totalWidth;
  990. int newStretch = totalStretch;
  991. int newShrink = totalShrink;
  992. // add the width, stretch and shrink of glue elements after
  993. // the break
  994. // this does not affect the dimension of the line / page, only
  995. // the values stored in the node; these would be as if the break
  996. // was just before the next box element, thus ignoring glues and
  997. // penalties between the "real" break and the following box
  998. for (int i = elementIdx; i < par.size(); i++) {
  999. KnuthElement tempElement = getElement(i);
  1000. if (tempElement.isBox()) {
  1001. break;
  1002. } else if (tempElement.isGlue()) {
  1003. newWidth += tempElement.getWidth();
  1004. newStretch += tempElement.getStretch();
  1005. newShrink += tempElement.getShrink();
  1006. } else if (tempElement.isForcedBreak() && i != elementIdx) {
  1007. break;
  1008. }
  1009. }
  1010. // add nodes to the active nodes list
  1011. double minimumDemerits = best.getMinDemerits() + incompatibleFitnessDemerit;
  1012. for (int i = 0; i <= 3; i++) {
  1013. if (best.notInfiniteDemerits(i) && best.getDemerits(i) <= minimumDemerits) {
  1014. // the nodes in activeList must be ordered
  1015. // by line number and position;
  1016. if (log.isTraceEnabled()) {
  1017. log.trace("\tInsert new break in list of " + activeNodeCount
  1018. + " from fitness class " + FitnessClasses.NAMES[i]);
  1019. }
  1020. KnuthNode newNode = createNode(elementIdx, line + 1, i,
  1021. newWidth, newStretch, newShrink);
  1022. addNode(line + 1, newNode);
  1023. }
  1024. }
  1025. best.reset();
  1026. }
  1027. /**
  1028. * Return the difference between the natural width of a line that would be made
  1029. * between the given active node and the given element, and the available width of the
  1030. * real line.
  1031. * @param activeNode node for the previous breakpoint
  1032. * @param element currently considered breakpoint
  1033. * @param elementIndex index of the element that is considered as a breakpoint
  1034. * @return The difference in width. Positive numbers mean extra space in the line,
  1035. * negative number that the line overflows.
  1036. */
  1037. protected int computeDifference(KnuthNode activeNode, KnuthElement element,
  1038. int elementIndex) {
  1039. // compute the adjustment ratio
  1040. int actualWidth = totalWidth - activeNode.totalWidth;
  1041. if (element.isPenalty()) {
  1042. actualWidth += element.getWidth();
  1043. }
  1044. return getLineWidth() - actualWidth;
  1045. }
  1046. /**
  1047. * Return the adjustment ratio needed to make up for the difference. A ratio of
  1048. * <ul>
  1049. * <li>0 means that the break has the exact right width</li>
  1050. * <li>&gt;= -1 &amp;&amp; &lt; 0 means that the break is wider than the line,
  1051. * but within the minimim values of the glues.</li>
  1052. * <li>&gt;0 &amp;&amp; &lt; 1 means that the break is smaller than the line width,
  1053. * but within the maximum values of the glues.</li>
  1054. * <li>&gt; 1 means that the break is too small to make up for the glues.</li>
  1055. * </ul>
  1056. * @param activeNode the currently active node
  1057. * @param difference the difference between content-length and available width
  1058. * @return The adjustment ratio.
  1059. */
  1060. protected double computeAdjustmentRatio(KnuthNode activeNode, int difference) {
  1061. // compute the adjustment ratio
  1062. if (difference > 0) {
  1063. int maxAdjustment = totalStretch - activeNode.totalStretch;
  1064. if (maxAdjustment > 0) {
  1065. return (double) difference / maxAdjustment;
  1066. } else {
  1067. return INFINITE_RATIO;
  1068. }
  1069. } else if (difference < 0) {
  1070. int maxAdjustment = totalShrink - activeNode.totalShrink;
  1071. if (maxAdjustment > 0) {
  1072. return (double) difference / maxAdjustment;
  1073. } else {
  1074. return -INFINITE_RATIO;
  1075. }
  1076. } else {
  1077. return 0;
  1078. }
  1079. }
  1080. /**
  1081. * Computes the demerits of the current breaking (that is, up to the given element),
  1082. * if the next-to-last chosen breakpoint is the given active node. This adds to the
  1083. * total demerits of the given active node, the demerits of a line starting at this
  1084. * node and ending at the given element.
  1085. * @param activeNode considered preceding line break
  1086. * @param element considered current line break
  1087. * @param fitnessClass fitness of the current line
  1088. * @param r adjustment ratio for the current line
  1089. * @return the demerit of the current line
  1090. */
  1091. protected double computeDemerits(KnuthNode activeNode, KnuthElement element,
  1092. int fitnessClass, double r) {
  1093. double demerits = 0;
  1094. // compute demerits
  1095. double f = Math.abs(r);
  1096. f = 1 + 100 * f * f * f;
  1097. if (element.isPenalty()) {
  1098. double penalty = element.getPenalty();
  1099. if (penalty >= 0) {
  1100. f += penalty;
  1101. demerits = f * f;
  1102. } else if (!element.isForcedBreak()) {
  1103. demerits = f * f - penalty * penalty;
  1104. } else {
  1105. demerits = f * f;
  1106. }
  1107. } else {
  1108. demerits = f * f;
  1109. }
  1110. if (element.isPenalty() && ((KnuthPenalty) element).isPenaltyFlagged()
  1111. && getElement(activeNode.position).isPenalty()
  1112. && ((KnuthPenalty) getElement(activeNode.position)).isPenaltyFlagged()) {
  1113. // add demerit for consecutive breaks at flagged penalties
  1114. demerits += repeatedFlaggedDemerit;
  1115. // there are at least two consecutive lines ending with a flagged penalty;
  1116. // check if the previous line end with a flagged penalty too,
  1117. // and if this situation is allowed
  1118. int flaggedPenaltiesCount = 2;
  1119. for (KnuthNode prevNode = activeNode.previous;
  1120. prevNode != null && flaggedPenaltiesCount <= maxFlaggedPenaltiesCount;
  1121. prevNode = prevNode.previous) {
  1122. KnuthElement prevElement = getElement(prevNode.position);
  1123. if (prevElement.isPenalty()
  1124. && ((KnuthPenalty) prevElement).isPenaltyFlagged()) {
  1125. // the previous line ends with a flagged penalty too
  1126. flaggedPenaltiesCount++;
  1127. } else {
  1128. // the previous line does not end with a flagged penalty,
  1129. // exit the loop
  1130. break;
  1131. }
  1132. }
  1133. if (maxFlaggedPenaltiesCount >= 1
  1134. && flaggedPenaltiesCount > maxFlaggedPenaltiesCount) {
  1135. // add infinite demerits, so this break will not be chosen
  1136. // unless there isn't any alternative break
  1137. demerits += BestRecords.INFINITE_DEMERITS;
  1138. }
  1139. }
  1140. if (Math.abs(fitnessClass - activeNode.fitness) > 1) {
  1141. // add demerit for consecutive breaks
  1142. // with very different fitness classes
  1143. demerits += incompatibleFitnessDemerit;
  1144. }
  1145. demerits += activeNode.totalDemerits;
  1146. return demerits;
  1147. }
  1148. /**
  1149. * Hook for subclasses to trigger special behavior after ending the
  1150. * main loop in {@link #findBreakingPoints(KnuthSequence,int,double,boolean,int)}
  1151. */
  1152. protected void finish() {
  1153. if (log.isTraceEnabled()) {
  1154. log.trace("Main loop completed " + activeNodeCount);
  1155. log.trace("Active nodes=" + toString(""));
  1156. }
  1157. }
  1158. /**
  1159. * Return the element at index idx in the paragraph.
  1160. * @param idx index of the element.
  1161. * @return the element at index idx in the paragraph.
  1162. */
  1163. protected KnuthElement getElement(int idx) {
  1164. return (KnuthElement) par.get(idx);
  1165. }
  1166. /**
  1167. * Compare two KnuthNodes and return the node with the least demerit.
  1168. * @param node1 The first knuth node.
  1169. * @param node2 The other knuth node.
  1170. * @return the node with the least demerit.
  1171. */
  1172. protected KnuthNode compareNodes(KnuthNode node1, KnuthNode node2) {
  1173. if (node1 == null || node2.position > node1.position) {
  1174. return node2;
  1175. }
  1176. if (node2.position == node1.position) {
  1177. if (node2.totalDemerits < node1.totalDemerits) {
  1178. return node2;
  1179. }
  1180. }
  1181. return node1;
  1182. }
  1183. /**
  1184. * Add a node at the end of the given line's existing active nodes.
  1185. * If this is the first node in the line, adjust endLine accordingly.
  1186. * @param line number of the line ending at the node's corresponding breakpoint
  1187. * @param node the active node to add
  1188. */
  1189. protected void addNode(int line, KnuthNode node) {
  1190. int headIdx = line * 2;
  1191. if (headIdx >= activeLines.length) {
  1192. KnuthNode[] oldList = activeLines;
  1193. activeLines = new KnuthNode[headIdx + headIdx];
  1194. System.arraycopy(oldList, 0, activeLines, 0, oldList.length);
  1195. }
  1196. node.next = null;
  1197. if (activeLines[headIdx + 1] != null) {
  1198. activeLines[headIdx + 1].next = node;
  1199. } else {
  1200. activeLines[headIdx] = node;
  1201. endLine = line + 1;
  1202. }
  1203. activeLines[headIdx + 1] = node;
  1204. activeNodeCount++;
  1205. }
  1206. /**
  1207. * Remove the given active node registered for the given line. If there are no more active nodes
  1208. * for this line, adjust the startLine accordingly.
  1209. * @param line number of the line ending at the node's corresponding breakpoint
  1210. * @param node the node to deactivate
  1211. */
  1212. protected void removeNode(int line, KnuthNode node) {
  1213. int headIdx = line * 2;
  1214. KnuthNode n = getNode(line);
  1215. if (n != node) {
  1216. // nodes could be rightly deactivated in a different order
  1217. KnuthNode prevNode = null;
  1218. while (n != node) {
  1219. prevNode = n;
  1220. n = n.next;
  1221. }
  1222. prevNode.next = n.next;
  1223. if (prevNode.next == null) {
  1224. activeLines[headIdx + 1] = prevNode;
  1225. }
  1226. } else {
  1227. activeLines[headIdx] = node.next;
  1228. if (node.next == null) {
  1229. activeLines[headIdx + 1] = null;
  1230. }
  1231. while (startLine < endLine && getNode(startLine) == null) {
  1232. startLine++;
  1233. }
  1234. }
  1235. activeNodeCount--;
  1236. }
  1237. /**
  1238. * Returns the first active node for the given line.
  1239. * @param line the line/part number
  1240. * @return the requested active node
  1241. */
  1242. protected KnuthNode getNode(int line) {
  1243. return activeLines[line * 2];
  1244. }
  1245. /**
  1246. * Returns the line/part width of a given line/part.
  1247. * @param line the line/part number
  1248. * @return the width/length in millipoints
  1249. */
  1250. protected int getLineWidth(int line) {
  1251. assert lineWidth >= 0;
  1252. return this.lineWidth;
  1253. }
  1254. /** @return the constant line/part width or -1 if there is no such value */
  1255. protected int getLineWidth() {
  1256. return this.lineWidth;
  1257. }
  1258. /**
  1259. * Creates a string representation of the active nodes. Used for debugging.
  1260. * @param prepend a string to prepend on each entry
  1261. * @return the requested string
  1262. */
  1263. public String toString(String prepend) {
  1264. StringBuffer sb = new StringBuffer();
  1265. sb.append("[\n");
  1266. for (int i = startLine; i < endLine; i++) {
  1267. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  1268. sb.append(prepend).append('\t').append(node).append(",\n");
  1269. }
  1270. }
  1271. sb.append(prepend).append("]");
  1272. return sb.toString();
  1273. }
  1274. /**
  1275. * Filter active nodes.
  1276. * @return an integer
  1277. */
  1278. protected abstract int filterActiveNodes();
  1279. /**
  1280. * Determines the set of optimal breakpoints corresponding to the given active node.
  1281. * @param node the active node
  1282. * @param par the corresponding paragraph
  1283. * @param total the number of lines into which the paragraph will be broken
  1284. */
  1285. protected void calculateBreakPoints(KnuthNode node, KnuthSequence par,
  1286. int total) {
  1287. KnuthNode bestActiveNode = node;
  1288. // use bestActiveNode to determine the optimum breakpoints
  1289. for (int i = node.line; i > 0; i--) {
  1290. updateData2(bestActiveNode, par, total);
  1291. bestActiveNode = bestActiveNode.previous;
  1292. }
  1293. }
  1294. /** @return the alignment for normal lines/parts */
  1295. public int getAlignment() {
  1296. return this.alignment;
  1297. }
  1298. /** @return the alignment for the last line/part */
  1299. public int getAlignmentLast() {
  1300. return this.alignmentLast;
  1301. }
  1302. }