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.

LineLayoutManager.java 70KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  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.inline;
  19. import java.util.ArrayList;
  20. import java.util.Iterator;
  21. import java.util.LinkedList;
  22. import java.util.List;
  23. import java.util.ListIterator;
  24. import org.apache.commons.logging.Log;
  25. import org.apache.commons.logging.LogFactory;
  26. import org.apache.fop.area.Area;
  27. import org.apache.fop.area.LineArea;
  28. import org.apache.fop.area.Trait;
  29. import org.apache.fop.area.inline.InlineArea;
  30. import org.apache.fop.datatypes.Length;
  31. import org.apache.fop.datatypes.Numeric;
  32. import org.apache.fop.fo.Constants;
  33. import org.apache.fop.fo.flow.Block;
  34. import org.apache.fop.fo.properties.CommonHyphenation;
  35. import org.apache.fop.fo.properties.KeepProperty;
  36. import org.apache.fop.fonts.Font;
  37. import org.apache.fop.fonts.FontInfo;
  38. import org.apache.fop.fonts.FontTriplet;
  39. import org.apache.fop.hyphenation.Hyphenation;
  40. import org.apache.fop.hyphenation.Hyphenator;
  41. import org.apache.fop.layoutmgr.Adjustment;
  42. import org.apache.fop.layoutmgr.BlockLevelLayoutManager;
  43. import org.apache.fop.layoutmgr.BreakElement;
  44. import org.apache.fop.layoutmgr.BreakingAlgorithm;
  45. import org.apache.fop.layoutmgr.ElementListObserver;
  46. import org.apache.fop.layoutmgr.InlineKnuthSequence;
  47. import org.apache.fop.layoutmgr.Keep;
  48. import org.apache.fop.layoutmgr.KnuthBlockBox;
  49. import org.apache.fop.layoutmgr.KnuthBox;
  50. import org.apache.fop.layoutmgr.KnuthElement;
  51. import org.apache.fop.layoutmgr.KnuthGlue;
  52. import org.apache.fop.layoutmgr.KnuthPenalty;
  53. import org.apache.fop.layoutmgr.KnuthPossPosIter;
  54. import org.apache.fop.layoutmgr.KnuthSequence;
  55. import org.apache.fop.layoutmgr.LayoutContext;
  56. import org.apache.fop.layoutmgr.LayoutManager;
  57. import org.apache.fop.layoutmgr.LeafPosition;
  58. import org.apache.fop.layoutmgr.ListElement;
  59. import org.apache.fop.layoutmgr.NonLeafPosition;
  60. import org.apache.fop.layoutmgr.Position;
  61. import org.apache.fop.layoutmgr.PositionIterator;
  62. import org.apache.fop.layoutmgr.SpaceSpecifier;
  63. import org.apache.fop.traits.MinOptMax;
  64. /**
  65. * LayoutManager for lines. It builds one or more lines containing
  66. * inline areas generated by its sub layout managers.
  67. * A break is found for each line which may contain one of more
  68. * breaks from the child layout managers.
  69. * Once a break is found then it is return for the parent layout
  70. * manager to handle.
  71. * When the areas are being added to the page this manager
  72. * creates a line area to contain the inline areas added by the
  73. * child layout managers.
  74. */
  75. public class LineLayoutManager extends InlineStackingLayoutManager
  76. implements BlockLevelLayoutManager {
  77. /**
  78. * this constant is used to create elements when text-align is center:
  79. * every TextLM descendant of LineLM must use the same value,
  80. * otherwise the line breaking algorithm does not find the right
  81. * break point
  82. */
  83. public static final int DEFAULT_SPACE_WIDTH = 3336;
  84. /**
  85. * logging instance
  86. */
  87. private static Log log = LogFactory.getLog(LineLayoutManager.class);
  88. private final Block fobj;
  89. private boolean isFirstInBlock;
  90. /**
  91. * Private class to store information about inline breaks.
  92. * Each value holds the start and end indexes into a List of
  93. * inline break positions.
  94. */
  95. private static class LineBreakPosition extends LeafPosition {
  96. private final int parIndex; // index of the Paragraph this Position refers to
  97. private final int startIndex; //index of the first element this Position refers to
  98. private final int availableShrink;
  99. private final int availableStretch;
  100. private final int difference;
  101. private final double dAdjust; // Percentage to adjust (stretch or shrink)
  102. private final double ipdAdjust; // Percentage to adjust (stretch or shrink)
  103. private final int startIndent;
  104. private final int lineHeight;
  105. private final int lineWidth;
  106. private final int spaceBefore;
  107. private final int spaceAfter;
  108. private final int baseline;
  109. LineBreakPosition( // CSOK: ParameterNumber
  110. LayoutManager lm, int index, int startIndex, int breakIndex,
  111. int shrink, int stretch, int diff, double ipdA, double adjust, int ind,
  112. int lh, int lw, int sb, int sa, int bl) {
  113. super(lm, breakIndex);
  114. availableShrink = shrink;
  115. availableStretch = stretch;
  116. difference = diff;
  117. parIndex = index;
  118. this.startIndex = startIndex;
  119. ipdAdjust = ipdA;
  120. dAdjust = adjust;
  121. startIndent = ind;
  122. lineHeight = lh;
  123. lineWidth = lw;
  124. spaceBefore = sb;
  125. spaceAfter = sa;
  126. baseline = bl;
  127. }
  128. }
  129. private int textAlignment = EN_JUSTIFY;
  130. private int textAlignmentLast;
  131. private int effectiveAlignment;
  132. private Length textIndent;
  133. private Length lastLineEndIndent;
  134. private CommonHyphenation hyphenationProperties;
  135. private Numeric hyphenationLadderCount;
  136. private int wrapOption = EN_WRAP;
  137. private int whiteSpaceTreament;
  138. //private LayoutProps layoutProps;
  139. private final Length lineHeight;
  140. private final int lead;
  141. private final int follow;
  142. private AlignmentContext alignmentContext;
  143. private List<KnuthSequence> knuthParagraphs;
  144. private LineLayoutPossibilities lineLayouts;
  145. private LineLayoutPossibilities[] lineLayoutsList;
  146. private int ipd = 0;
  147. /**
  148. * When layout must be re-started due to a change of IPD, there is no need
  149. * to perform hyphenation on the remaining Knuth sequence once again.
  150. */
  151. private boolean hyphenationPerformed;
  152. /**
  153. * This class is used to remember
  154. * which was the first element in the paragraph
  155. * returned by each LM.
  156. */
  157. private final class Update {
  158. private final InlineLevelLayoutManager inlineLM;
  159. private final int firstIndex;
  160. private Update(InlineLevelLayoutManager lm, int index) {
  161. inlineLM = lm;
  162. firstIndex = index;
  163. }
  164. }
  165. // this class represents a paragraph
  166. private class Paragraph extends InlineKnuthSequence {
  167. private static final long serialVersionUID = 5862072380375189105L;
  168. /** Number of elements to ignore at the beginning of the list. */
  169. private int ignoreAtStart = 0;
  170. /** Number of elements to ignore at the end of the list. */
  171. private int ignoreAtEnd = 0;
  172. // space at the end of the last line (in millipoints)
  173. private MinOptMax lineFiller;
  174. private final int textAlignment;
  175. private final int textAlignmentLast;
  176. private final int textIndent;
  177. private final int lastLineEndIndent;
  178. // the LM which created the paragraph
  179. private final LineLayoutManager layoutManager;
  180. Paragraph(LineLayoutManager llm, int alignment, int alignmentLast,
  181. int indent, int endIndent) {
  182. super();
  183. layoutManager = llm;
  184. textAlignment = alignment;
  185. textAlignmentLast = alignmentLast;
  186. textIndent = indent;
  187. lastLineEndIndent = endIndent;
  188. }
  189. @Override
  190. public void startSequence() {
  191. // set the minimum amount of empty space at the end of the
  192. // last line
  193. if (textAlignment == EN_CENTER) {
  194. lineFiller = MinOptMax.getInstance(lastLineEndIndent);
  195. } else {
  196. lineFiller = MinOptMax.getInstance(lastLineEndIndent, lastLineEndIndent,
  197. layoutManager.ipd);
  198. }
  199. // add auxiliary elements at the beginning of the paragraph
  200. if (textAlignment == EN_CENTER && textAlignmentLast != EN_JUSTIFY) {
  201. this.add(new KnuthGlue(0, 3 * DEFAULT_SPACE_WIDTH, 0,
  202. null, false));
  203. ignoreAtStart++;
  204. }
  205. // add the element representing text indentation
  206. // at the beginning of the first paragraph
  207. if (isFirstInBlock && knuthParagraphs.size() == 0
  208. && textIndent != 0) {
  209. this.add(new KnuthInlineBox(textIndent, null,
  210. null, false));
  211. ignoreAtStart++;
  212. }
  213. }
  214. public void endParagraph() {
  215. KnuthSequence finishedPar = this.endSequence();
  216. if (finishedPar != null) {
  217. knuthParagraphs.add(finishedPar);
  218. }
  219. }
  220. @Override
  221. public KnuthSequence endSequence() {
  222. if (this.size() > ignoreAtStart) {
  223. if (textAlignment == EN_CENTER
  224. && textAlignmentLast != EN_JUSTIFY) {
  225. this.add(new KnuthGlue(0, 3 * DEFAULT_SPACE_WIDTH, 0,
  226. null, false));
  227. this.add(new KnuthPenalty(lineFiller.getOpt(), -KnuthElement.INFINITE,
  228. false, null, false));
  229. ignoreAtEnd = 2;
  230. } else if (textAlignmentLast != EN_JUSTIFY) {
  231. // add the elements representing the space
  232. // at the end of the last line
  233. // and the forced break
  234. this.add(new KnuthPenalty(0, KnuthElement.INFINITE,
  235. false, null, false));
  236. this.add(new KnuthGlue(0,
  237. lineFiller.getStretch(),
  238. lineFiller.getShrink(), null, false));
  239. this.add(new KnuthPenalty(lineFiller.getOpt(), -KnuthElement.INFINITE,
  240. false, null, false));
  241. ignoreAtEnd = 3;
  242. } else {
  243. // add only the element representing the forced break
  244. this.add(new KnuthPenalty(lineFiller.getOpt(), -KnuthElement.INFINITE,
  245. false, null, false));
  246. ignoreAtEnd = 1;
  247. }
  248. return this;
  249. } else {
  250. this.clear();
  251. return null;
  252. }
  253. }
  254. /**
  255. * @return true if the sequence contains a box
  256. */
  257. public boolean containsBox() {
  258. for (int i = 0; i < this.size(); i++) {
  259. KnuthElement el = (KnuthElement)this.get(i);
  260. if (el.isBox()) {
  261. return true;
  262. }
  263. }
  264. return false;
  265. }
  266. }
  267. private class LineBreakingAlgorithm extends BreakingAlgorithm {
  268. private final LineLayoutManager thisLLM;
  269. private final int pageAlignment;
  270. private int activePossibility;
  271. private int addedPositions;
  272. private final int textIndent;
  273. private final int lineHeight;
  274. private final int lead;
  275. private final int follow;
  276. private static final double MAX_DEMERITS = 10e6;
  277. public LineBreakingAlgorithm( // CSOK: ParameterNumber
  278. int pageAlign, int textAlign, int textAlignLast, int indent, int fillerWidth,
  279. int lh, int ld, int fl, boolean first, int maxFlagCount, LineLayoutManager llm) {
  280. super(textAlign, textAlignLast, first, false, maxFlagCount);
  281. pageAlignment = pageAlign;
  282. textIndent = indent;
  283. lineHeight = lh;
  284. lead = ld;
  285. follow = fl;
  286. thisLLM = llm;
  287. activePossibility = -1;
  288. }
  289. @Override
  290. public void updateData1(int lineCount, double demerits) {
  291. lineLayouts.addPossibility(lineCount, demerits);
  292. if (log.isTraceEnabled()) {
  293. log.trace("Layout possibility in " + lineCount + " lines; break at position:");
  294. }
  295. }
  296. @Override
  297. public void updateData2(KnuthNode bestActiveNode,
  298. KnuthSequence par,
  299. int total) {
  300. // compute indent and adjustment ratio, according to
  301. // the value of text-align and text-align-last
  302. int indent = 0;
  303. int difference = bestActiveNode.difference;
  304. int textAlign = (bestActiveNode.line < total) ? alignment : alignmentLast;
  305. indent += (textAlign == Constants.EN_CENTER)
  306. ? difference / 2 : (textAlign == Constants.EN_END) ? difference : 0;
  307. indent += (bestActiveNode.line == 1 && indentFirstPart && isFirstInBlock)
  308. ? textIndent : 0;
  309. double ratio = (textAlign == Constants.EN_JUSTIFY
  310. || difference < 0 && -difference <= bestActiveNode.availableShrink)
  311. ? bestActiveNode.adjustRatio : 0;
  312. // add nodes at the beginning of the list, as they are found
  313. // backwards, from the last one to the first one
  314. // the first time this method is called, initialize activePossibility
  315. if (activePossibility == -1) {
  316. activePossibility = 0;
  317. addedPositions = 0;
  318. }
  319. if (addedPositions == lineLayouts.getLineCount(activePossibility)) {
  320. activePossibility++;
  321. addedPositions = 0;
  322. }
  323. if (log.isWarnEnabled()) {
  324. int lack = difference + bestActiveNode.availableShrink;
  325. if (lack < 0) {
  326. InlineLevelEventProducer eventProducer
  327. = InlineLevelEventProducer.Provider.get(
  328. getFObj().getUserAgent().getEventBroadcaster());
  329. eventProducer.lineOverflows(this, bestActiveNode.line,
  330. -lack, getFObj().getLocator());
  331. }
  332. }
  333. //log.debug("LLM> (" + (lineLayouts.getLineNumber(activePossibility) - addedPositions)
  334. // + ") difference = " + difference + " ratio = " + ratio);
  335. lineLayouts.addBreakPosition(makeLineBreakPosition(par,
  336. (bestActiveNode.line > 1 ? bestActiveNode.previous.position + 1 : 0),
  337. bestActiveNode.position,
  338. bestActiveNode.availableShrink - (addedPositions > 0
  339. ? 0 : ((Paragraph) par).lineFiller.getShrink()),
  340. bestActiveNode.availableStretch,
  341. difference, ratio, indent), activePossibility);
  342. addedPositions++;
  343. }
  344. /* reset activePossibility, as if breakpoints have not yet been computed
  345. */
  346. public void resetAlgorithm() {
  347. activePossibility = -1;
  348. }
  349. private LineBreakPosition makeLineBreakPosition( // CSOK: ParameterNumber
  350. KnuthSequence par, int firstElementIndex, int lastElementIndex, int availableShrink,
  351. int availableStretch, int difference, double ratio, int indent) {
  352. // line height calculation - spaceBefore may differ from spaceAfter
  353. // by 1mpt due to rounding
  354. int spaceBefore = (lineHeight - lead - follow) / 2;
  355. int spaceAfter = lineHeight - lead - follow - spaceBefore;
  356. // height before the main baseline
  357. int lineLead = lead;
  358. // maximum follow
  359. int lineFollow = follow;
  360. // true if this line contains only zero-height, auxiliary boxes
  361. // and the actual line width is 0; in this case, the line "collapses"
  362. // i.e. the line area will have bpd = 0
  363. boolean isZeroHeightLine = (difference == ipd);
  364. // if line-stacking-strategy is "font-height", the line height
  365. // is not affected by its content
  366. if (fobj.getLineStackingStrategy() != EN_FONT_HEIGHT) {
  367. ListIterator inlineIterator
  368. = par.listIterator(firstElementIndex);
  369. AlignmentContext lastAC = null;
  370. int maxIgnoredHeight = 0; // See spec 7.13
  371. for (int j = firstElementIndex;
  372. j <= lastElementIndex;
  373. j++) {
  374. KnuthElement element = (KnuthElement) inlineIterator.next();
  375. if (element instanceof KnuthInlineBox ) {
  376. AlignmentContext ac = ((KnuthInlineBox) element).getAlignmentContext();
  377. if (ac != null && lastAC != ac) {
  378. if (!ac.usesInitialBaselineTable()
  379. || ac.getAlignmentBaselineIdentifier() != EN_BEFORE_EDGE
  380. && ac.getAlignmentBaselineIdentifier() != EN_AFTER_EDGE) {
  381. if (fobj.getLineHeightShiftAdjustment() == EN_CONSIDER_SHIFTS
  382. || ac.getBaselineShiftValue() == 0) {
  383. int alignmentOffset = ac.getTotalAlignmentBaselineOffset();
  384. if (alignmentOffset + ac.getAltitude() > lineLead) {
  385. lineLead = alignmentOffset + ac.getAltitude();
  386. }
  387. if (ac.getDepth() - alignmentOffset > lineFollow) {
  388. lineFollow = ac.getDepth() - alignmentOffset;
  389. }
  390. }
  391. } else {
  392. if (ac.getHeight() > maxIgnoredHeight) {
  393. maxIgnoredHeight = ac.getHeight();
  394. }
  395. }
  396. lastAC = ac;
  397. }
  398. if (isZeroHeightLine
  399. && (!element.isAuxiliary() || ac != null && ac.getHeight() > 0)) {
  400. isZeroHeightLine = false;
  401. }
  402. }
  403. }
  404. if (lineFollow < maxIgnoredHeight - lineLead) {
  405. lineFollow = maxIgnoredHeight - lineLead;
  406. }
  407. }
  408. constantLineHeight = lineLead + lineFollow;
  409. if (isZeroHeightLine) {
  410. return new LineBreakPosition(thisLLM,
  411. knuthParagraphs.indexOf(par),
  412. firstElementIndex, lastElementIndex,
  413. availableShrink, availableStretch,
  414. difference, ratio, 0, indent,
  415. 0, ipd, 0, 0, 0);
  416. } else {
  417. return new LineBreakPosition(thisLLM,
  418. knuthParagraphs.indexOf(par),
  419. firstElementIndex, lastElementIndex,
  420. availableShrink, availableStretch,
  421. difference, ratio, 0, indent,
  422. lineLead + lineFollow,
  423. ipd, spaceBefore, spaceAfter,
  424. lineLead);
  425. }
  426. }
  427. @Override
  428. protected int filterActiveNodes() {
  429. KnuthNode bestActiveNode = null;
  430. if (pageAlignment == EN_JUSTIFY) {
  431. // leave all active nodes and find the optimum line number
  432. //log.debug("LBA.filterActiveNodes> " + activeNodeCount + " layouts");
  433. for (int i = startLine; i < endLine; i++) {
  434. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  435. //log.debug(" + lines = "
  436. //+ node.line + " demerits = " + node.totalDemerits);
  437. bestActiveNode = compareNodes(bestActiveNode, node);
  438. }
  439. }
  440. // scan the node set once again and remove some nodes
  441. //log.debug("LBA.filterActiveList> layout selection");
  442. for (int i = startLine; i < endLine; i++) {
  443. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  444. //if (Math.abs(node.line - bestActiveNode.line) > maxDiff) {
  445. //if (false) {
  446. if (node.line != bestActiveNode.line
  447. && node.totalDemerits > MAX_DEMERITS) {
  448. //log.debug(" XXX lines = "
  449. //+ node.line + " demerits = " + node.totalDemerits);
  450. removeNode(i, node);
  451. } else {
  452. //log.debug(" ok lines = "
  453. //+ node.line + " demerits = " + node.totalDemerits);
  454. }
  455. }
  456. }
  457. } else {
  458. // leave only the active node with fewest total demerits
  459. for (int i = startLine; i < endLine; i++) {
  460. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  461. bestActiveNode = compareNodes(bestActiveNode, node);
  462. if (node != bestActiveNode) {
  463. removeNode(i, node);
  464. }
  465. }
  466. }
  467. }
  468. return bestActiveNode.line;
  469. }
  470. }
  471. private int constantLineHeight = 12000;
  472. /**
  473. * Create a new Line Layout Manager.
  474. * This is used by the block layout manager to create
  475. * line managers for handling inline areas flowing into line areas.
  476. * @param block the block formatting object
  477. * @param lh the default line height
  478. * @param l the default lead, from top to baseline
  479. * @param f the default follow, from baseline to bottom
  480. */
  481. public LineLayoutManager(Block block, Length lh, int l, int f) {
  482. super(block);
  483. fobj = block;
  484. // the child FObj are owned by the parent BlockLM
  485. // this LM has all its childLMs preloaded
  486. fobjIter = null;
  487. lineHeight = lh;
  488. lead = l;
  489. follow = f;
  490. }
  491. /** {@inheritDoc} */
  492. @Override
  493. public void initialize() {
  494. textAlignment = fobj.getTextAlign();
  495. textAlignmentLast = fobj.getTextAlignLast();
  496. textIndent = fobj.getTextIndent();
  497. lastLineEndIndent = fobj.getLastLineEndIndent();
  498. hyphenationProperties = fobj.getCommonHyphenation();
  499. hyphenationLadderCount = fobj.getHyphenationLadderCount();
  500. wrapOption = fobj.getWrapOption();
  501. whiteSpaceTreament = fobj.getWhitespaceTreatment();
  502. //
  503. effectiveAlignment = getEffectiveAlignment(textAlignment, textAlignmentLast);
  504. isFirstInBlock = (this == getParent().getChildLMs().get(0));
  505. }
  506. private int getEffectiveAlignment(int alignment, int alignmentLast) {
  507. if (textAlignment != EN_JUSTIFY && textAlignmentLast == EN_JUSTIFY) {
  508. return 0;
  509. } else {
  510. return textAlignment;
  511. }
  512. }
  513. /** {@inheritDoc} */
  514. @Override
  515. public List getNextKnuthElements(LayoutContext context, int alignment) {
  516. if (alignmentContext == null) {
  517. FontInfo fi = fobj.getFOEventHandler().getFontInfo();
  518. FontTriplet[] fontkeys = fobj.getCommonFont().getFontState(fi);
  519. Font fs = fi.getFontInstance(fontkeys[0], fobj.getCommonFont().fontSize.getValue(this));
  520. alignmentContext = new AlignmentContext(fs, lineHeight.getValue(this),
  521. context.getWritingMode());
  522. }
  523. context.setAlignmentContext(alignmentContext);
  524. ipd = context.getRefIPD();
  525. //PHASE 1: Create Knuth elements
  526. if (knuthParagraphs == null) {
  527. // it's the first time this method is called
  528. knuthParagraphs = new ArrayList<KnuthSequence>();
  529. // here starts Knuth's algorithm
  530. collectInlineKnuthElements(context);
  531. } else {
  532. // this method has been called before
  533. // all line breaks are already calculated
  534. }
  535. // return finished when there's no content
  536. if (knuthParagraphs.size() == 0) {
  537. setFinished(true);
  538. return null;
  539. }
  540. //PHASE 2: Create line breaks
  541. return createLineBreaks(context.getBPAlignment(), context);
  542. }
  543. /**
  544. * Get a sequence of KnuthElements representing the content
  545. * of the node assigned to the LM.
  546. * @param context the LayoutContext used to store layout information
  547. * @param alignment the desired text alignment
  548. * @param restartPosition position at restart
  549. * @return the list of KnuthElements
  550. * @see LayoutManager#getNextKnuthElements(LayoutContext,int)
  551. */
  552. public List getNextKnuthElements(LayoutContext context, int alignment,
  553. LeafPosition restartPosition) {
  554. log.trace("Restarting line breaking from index " + restartPosition.getIndex());
  555. int parIndex = restartPosition.getLeafPos();
  556. KnuthSequence paragraph = knuthParagraphs.get(parIndex);
  557. paragraph.subList(0, restartPosition.getIndex() + 1).clear();
  558. Iterator<KnuthElement> iter = paragraph.iterator();
  559. while (iter.hasNext() && !iter.next().isBox()) {
  560. iter.remove();
  561. }
  562. if (!iter.hasNext()) {
  563. knuthParagraphs.remove(parIndex);
  564. }
  565. // return finished when there's no content
  566. if (knuthParagraphs.size() == 0) {
  567. setFinished(true);
  568. return null;
  569. }
  570. ipd = context.getRefIPD();
  571. //PHASE 2: Create line breaks
  572. return createLineBreaks(context.getBPAlignment(), context);
  573. }
  574. /**
  575. * Phase 1 of Knuth algorithm: Collect all inline Knuth elements before determining line breaks.
  576. * @param context the LayoutContext
  577. */
  578. private void collectInlineKnuthElements(LayoutContext context) {
  579. LayoutContext inlineLC = new LayoutContext(context);
  580. // convert all the text in a sequence of paragraphs made
  581. // of KnuthBox, KnuthGlue and KnuthPenalty objects
  582. boolean previousIsBox = false;
  583. StringBuffer trace = new StringBuffer("LineLM:");
  584. Paragraph lastPar = null;
  585. InlineLevelLayoutManager curLM;
  586. while ((curLM = (InlineLevelLayoutManager) getChildLM()) != null) {
  587. List inlineElements = curLM.getNextKnuthElements(inlineLC, effectiveAlignment);
  588. if (inlineElements == null || inlineElements.size() == 0) {
  589. /* curLM.getNextKnuthElements() returned null or an empty list;
  590. * this can happen if there is nothing more to layout,
  591. * so just iterate once more to see if there are other children */
  592. continue;
  593. }
  594. if (lastPar != null) {
  595. KnuthSequence firstSeq = (KnuthSequence) inlineElements.get(0);
  596. // finish last paragraph before a new block sequence
  597. if (!firstSeq.isInlineSequence()) {
  598. lastPar.endParagraph();
  599. ElementListObserver.observe(lastPar, "line", null);
  600. lastPar = null;
  601. if (log.isTraceEnabled()) {
  602. trace.append(" ]");
  603. }
  604. previousIsBox = false;
  605. }
  606. // does the first element of the first paragraph add to an existing word?
  607. if (lastPar != null) {
  608. KnuthElement thisElement;
  609. thisElement = (KnuthElement) firstSeq.get(0);
  610. if (thisElement.isBox() && !thisElement.isAuxiliary()
  611. && previousIsBox) {
  612. lastPar.addALetterSpace();
  613. }
  614. }
  615. }
  616. // loop over the KnuthSequences (and single KnuthElements) in returnedList
  617. ListIterator iter = inlineElements.listIterator();
  618. while (iter.hasNext()) {
  619. KnuthSequence sequence = (KnuthSequence) iter.next();
  620. // the sequence contains inline Knuth elements
  621. if (sequence.isInlineSequence()) {
  622. // look at the last element
  623. ListElement lastElement = sequence.getLast();
  624. assert lastElement != null;
  625. previousIsBox = lastElement.isBox()
  626. && !((KnuthElement) lastElement).isAuxiliary()
  627. && ((KnuthElement) lastElement).getWidth() != 0;
  628. // if last paragraph is open, add the new elements to the paragraph
  629. // else this is the last paragraph
  630. if (lastPar == null) {
  631. lastPar = new Paragraph(this,
  632. textAlignment, textAlignmentLast,
  633. textIndent.getValue(this),
  634. lastLineEndIndent.getValue(this));
  635. lastPar.startSequence();
  636. if (log.isTraceEnabled()) {
  637. trace.append(" [");
  638. }
  639. } else {
  640. if (log.isTraceEnabled()) {
  641. trace.append(" +");
  642. }
  643. }
  644. lastPar.addAll(sequence);
  645. if (log.isTraceEnabled()) {
  646. trace.append(" I");
  647. }
  648. // finish last paragraph if it was closed with a linefeed
  649. if (lastElement.isPenalty()
  650. && ((KnuthPenalty) lastElement).getPenalty()
  651. == -KnuthPenalty.INFINITE) {
  652. // a penalty item whose value is -inf
  653. // represents a preserved linefeed,
  654. // which forces a line break
  655. lastPar.removeLast();
  656. if (!lastPar.containsBox()) {
  657. //only a forced linefeed on this line
  658. //-> compensate with an auxiliary glue
  659. lastPar.add(new KnuthGlue(ipd, 0, ipd, null, true));
  660. }
  661. lastPar.endParagraph();
  662. ElementListObserver.observe(lastPar, "line", null);
  663. lastPar = null;
  664. if (log.isTraceEnabled()) {
  665. trace.append(" ]");
  666. }
  667. previousIsBox = false;
  668. }
  669. } else { // the sequence is a block sequence
  670. // the positions will be wrapped with this LM in postProcessLineBreaks
  671. knuthParagraphs.add(sequence);
  672. if (log.isTraceEnabled()) {
  673. trace.append(" B");
  674. }
  675. }
  676. } // end of loop over returnedList
  677. }
  678. if (lastPar != null) {
  679. lastPar.endParagraph();
  680. ElementListObserver.observe(lastPar, "line", fobj.getId());
  681. if (log.isTraceEnabled()) {
  682. trace.append(" ]");
  683. }
  684. }
  685. log.trace(trace);
  686. }
  687. /**
  688. * Phase 2 of Knuth algorithm: find optimal break points.
  689. * @param alignment alignment in BP direction of the paragraph
  690. * @param context the layout context
  691. * @return a list of Knuth elements representing broken lines
  692. */
  693. private List<ListElement> createLineBreaks(int alignment, LayoutContext context) {
  694. // find the optimal line breaking points for each paragraph
  695. Iterator<KnuthSequence> paragraphsIterator = knuthParagraphs.iterator();
  696. lineLayoutsList = new LineLayoutPossibilities[knuthParagraphs.size()];
  697. LineLayoutPossibilities llPoss;
  698. for (int i = 0; paragraphsIterator.hasNext(); i++) {
  699. KnuthSequence seq = paragraphsIterator.next();
  700. if (!seq.isInlineSequence()) {
  701. // This set of line layout possibilities does not matter;
  702. // we only need an entry in lineLayoutsList.
  703. llPoss = new LineLayoutPossibilities();
  704. } else {
  705. llPoss = findOptimalBreakingPoints(alignment, (Paragraph) seq,
  706. !paragraphsIterator.hasNext());
  707. }
  708. lineLayoutsList[i] = llPoss;
  709. }
  710. setFinished(true);
  711. //Post-process the line breaks found
  712. return postProcessLineBreaks(alignment, context);
  713. }
  714. /**
  715. * Find the optimal linebreaks for a paragraph
  716. * @param alignment alignment of the paragraph
  717. * @param currPar the Paragraph for which the linebreaks are found
  718. * @param isLastPar flag indicating whether currPar is the last paragraph
  719. * @return the line layout possibilities for the paragraph
  720. */
  721. private LineLayoutPossibilities findOptimalBreakingPoints(int alignment, Paragraph currPar,
  722. boolean isLastPar) {
  723. // use the member lineLayouts, which is read by LineBreakingAlgorithm.updateData1 and 2
  724. lineLayouts = new LineLayoutPossibilities();
  725. double maxAdjustment = 1;
  726. LineBreakingAlgorithm alg = new LineBreakingAlgorithm(alignment,
  727. textAlignment, textAlignmentLast,
  728. textIndent.getValue(this), currPar.lineFiller.getOpt(),
  729. lineHeight.getValue(this), lead, follow,
  730. (knuthParagraphs.indexOf(currPar) == 0),
  731. hyphenationLadderCount.getEnum() == EN_NO_LIMIT
  732. ? 0 : hyphenationLadderCount.getValue(),
  733. this);
  734. alg.setConstantLineWidth(ipd);
  735. boolean canWrap = (wrapOption != EN_NO_WRAP);
  736. boolean canHyphenate = (canWrap && hyphenationProperties.hyphenate.getEnum() == EN_TRUE);
  737. // find hyphenation points, if allowed and not yet done
  738. if (canHyphenate && !hyphenationPerformed) {
  739. // make sure findHyphenationPoints() is bypassed if
  740. // the method is called twice (e.g. due to changing page-ipd)
  741. hyphenationPerformed = isLastPar;
  742. findHyphenationPoints(currPar);
  743. }
  744. // first try: do not consider hyphenation points as legal breaks
  745. int allowedBreaks = (canWrap ? BreakingAlgorithm.NO_FLAGGED_PENALTIES
  746. : BreakingAlgorithm.ONLY_FORCED_BREAKS);
  747. int breakingPoints = alg.findBreakingPoints(currPar, maxAdjustment, false, allowedBreaks);
  748. if (breakingPoints == 0 || alignment == EN_JUSTIFY) {
  749. // if the first try found a set of breaking points, save them
  750. if (breakingPoints > 0) {
  751. alg.resetAlgorithm();
  752. lineLayouts.savePossibilities(false);
  753. } else {
  754. // the first try failed
  755. log.debug("No set of breaking points found with maxAdjustment = " + maxAdjustment);
  756. }
  757. // now try something different
  758. log.debug("Hyphenation possible? " + canHyphenate);
  759. // Note: if allowedBreaks is guaranteed to be unchanged by alg.findBreakingPoints(),
  760. // the below check can be simplified to 'if (canHyphenate) ...'
  761. if (canHyphenate && allowedBreaks != BreakingAlgorithm.ONLY_FORCED_BREAKS) {
  762. // consider every hyphenation point as a legal break
  763. allowedBreaks = BreakingAlgorithm.ALL_BREAKS;
  764. } else {
  765. // try with a higher threshold
  766. maxAdjustment = 5;
  767. }
  768. breakingPoints = alg.findBreakingPoints(currPar, maxAdjustment, false, allowedBreaks);
  769. if (breakingPoints == 0) {
  770. // the second try failed too, try with a huge threshold
  771. // and force the algorithm to find a set of breaking points
  772. if (log.isDebugEnabled()) {
  773. log.debug("No set of breaking points found with maxAdjustment = "
  774. + maxAdjustment + (canHyphenate ? " and hyphenation" : ""));
  775. }
  776. maxAdjustment = 20;
  777. alg.findBreakingPoints(currPar, maxAdjustment, true, allowedBreaks);
  778. }
  779. // use non-hyphenated breaks, when possible
  780. lineLayouts.restorePossibilities();
  781. }
  782. return lineLayouts;
  783. }
  784. /**
  785. * Creates the element list in BP direction for the broken lines.
  786. * @param alignment the currently applicable vertical alignment
  787. * @param context the layout context
  788. * @return the newly built element list
  789. */
  790. private List<ListElement> postProcessLineBreaks(int alignment, LayoutContext context) {
  791. List<ListElement> returnList = new LinkedList<ListElement>();
  792. int endIndex = -1;
  793. for (int p = 0; p < knuthParagraphs.size(); p++) {
  794. // penalty between paragraphs
  795. if (p > 0) {
  796. Keep keep = getKeepTogether();
  797. returnList.add(new BreakElement(
  798. new Position(this),
  799. keep.getPenalty(),
  800. keep.getContext(),
  801. context));
  802. }
  803. LineLayoutPossibilities llPoss = lineLayoutsList[p];
  804. KnuthSequence seq = knuthParagraphs.get(p);
  805. if (!seq.isInlineSequence()) {
  806. List<ListElement> targetList = new LinkedList<ListElement>();
  807. ListIterator listIter = seq.listIterator();
  808. while (listIter.hasNext()) {
  809. ListElement tempElement;
  810. tempElement = (ListElement) listIter.next();
  811. if (tempElement.getLayoutManager() != this) {
  812. tempElement.setPosition(notifyPos(new NonLeafPosition(this,
  813. tempElement.getPosition())));
  814. }
  815. targetList.add(tempElement);
  816. }
  817. returnList.addAll(targetList);
  818. } else if (seq.isInlineSequence() && alignment == EN_JUSTIFY) {
  819. /* justified vertical alignment (not in the XSL FO recommendation):
  820. create a multi-layout sequence whose elements will contain
  821. a conventional Position */
  822. Position returnPosition = new LeafPosition(this, p);
  823. createElements(returnList, llPoss, returnPosition);
  824. } else {
  825. /* "normal" vertical alignment: create a sequence whose boxes
  826. represent effective lines, and contain LineBreakPositions */
  827. int startIndex = 0;
  828. for (int i = 0;
  829. i < llPoss.getChosenLineCount();
  830. i++) {
  831. if (returnList.size() > 0
  832. && i > 0 //if i==0 break generated above already
  833. && i >= fobj.getOrphans()
  834. && i <= llPoss.getChosenLineCount() - fobj.getWidows()) {
  835. // penalty allowing a page break between lines
  836. Keep keep = getKeepTogether();
  837. returnList.add(new BreakElement(
  838. new LeafPosition(this, p, endIndex),
  839. keep.getPenalty(),
  840. keep.getContext(),
  841. context));
  842. }
  843. endIndex = ((LineBreakPosition) llPoss.getChosenPosition(i)).getLeafPos();
  844. // create a list of the FootnoteBodyLM handling footnotes
  845. // whose citations are in this line
  846. List<LayoutManager> footnoteList = new LinkedList<LayoutManager>();
  847. ListIterator<KnuthElement> elementIterator = seq.listIterator(startIndex);
  848. while (elementIterator.nextIndex() <= endIndex) {
  849. KnuthElement element = elementIterator.next();
  850. if (element instanceof KnuthInlineBox
  851. && ((KnuthInlineBox) element).isAnchor()) {
  852. footnoteList.add(((KnuthInlineBox) element).getFootnoteBodyLM());
  853. } else if (element instanceof KnuthBlockBox) {
  854. footnoteList.addAll(((KnuthBlockBox) element).getFootnoteBodyLMs());
  855. }
  856. }
  857. startIndex = endIndex + 1;
  858. LineBreakPosition lbp = (LineBreakPosition) llPoss.getChosenPosition(i);
  859. returnList.add(new KnuthBlockBox
  860. (lbp.lineHeight + lbp.spaceBefore + lbp.spaceAfter,
  861. footnoteList, lbp, false));
  862. }
  863. }
  864. }
  865. return returnList;
  866. }
  867. private void createElements(List<ListElement> list, LineLayoutPossibilities llPoss,
  868. Position elementPosition) {
  869. /* number of normal, inner lines */
  870. int innerLines = 0;
  871. /* number of lines that can be used in order to fill more space */
  872. int optionalLines = 0;
  873. /* number of lines that can be used in order to fill more space
  874. only if the paragraph is not parted */
  875. int conditionalOptionalLines = 0;
  876. /* number of lines that can be omitted in order to fill less space */
  877. int eliminableLines = 0;
  878. /* number of lines that can be omitted in order to fill less space
  879. only if the paragraph is not parted */
  880. int conditionalEliminableLines = 0;
  881. /* number of the first unbreakable lines */
  882. int firstLines = fobj.getOrphans();
  883. /* number of the last unbreakable lines */
  884. int lastLines = fobj.getWidows();
  885. /* sub-sequence used to separate the elements representing different lines */
  886. List<KnuthElement> breaker = new LinkedList<KnuthElement>();
  887. /* comment out the next lines in order to test particular situations */
  888. if (fobj.getOrphans() + fobj.getWidows() <= llPoss.getMinLineCount()) {
  889. innerLines = llPoss.getMinLineCount() - (fobj.getOrphans() + fobj.getWidows());
  890. optionalLines = llPoss.getMaxLineCount() - llPoss.getOptLineCount();
  891. eliminableLines = llPoss.getOptLineCount() - llPoss.getMinLineCount();
  892. } else if (fobj.getOrphans() + fobj.getWidows() <= llPoss.getOptLineCount()) {
  893. optionalLines = llPoss.getMaxLineCount() - llPoss.getOptLineCount();
  894. eliminableLines = llPoss.getOptLineCount() - (fobj.getOrphans() + fobj.getWidows());
  895. conditionalEliminableLines
  896. = (fobj.getOrphans() + fobj.getWidows()) - llPoss.getMinLineCount();
  897. } else if (fobj.getOrphans() + fobj.getWidows() <= llPoss.getMaxLineCount()) {
  898. optionalLines = llPoss.getMaxLineCount() - (fobj.getOrphans() + fobj.getWidows());
  899. conditionalOptionalLines
  900. = (fobj.getOrphans() + fobj.getWidows()) - llPoss.getOptLineCount();
  901. conditionalEliminableLines = llPoss.getOptLineCount() - llPoss.getMinLineCount();
  902. firstLines -= conditionalOptionalLines;
  903. } else {
  904. conditionalOptionalLines = llPoss.getMaxLineCount() - llPoss.getOptLineCount();
  905. conditionalEliminableLines = llPoss.getOptLineCount() - llPoss.getMinLineCount();
  906. firstLines = llPoss.getOptLineCount();
  907. lastLines = 0;
  908. }
  909. /* comment out the previous lines in order to test particular situations */
  910. /* use these lines to test particular situations
  911. innerLines = 0;
  912. optionalLines = 1;
  913. conditionalOptionalLines = 2;
  914. eliminableLines = 0;
  915. conditionalEliminableLines = 0;
  916. firstLines = 1;
  917. lastLines = 3;
  918. */
  919. if (lastLines != 0
  920. && (conditionalOptionalLines > 0 || conditionalEliminableLines > 0)) {
  921. breaker.add(new KnuthPenalty(0, KnuthElement.INFINITE, false, elementPosition, false));
  922. breaker.add(new KnuthGlue(0, -conditionalOptionalLines * constantLineHeight,
  923. -conditionalEliminableLines * constantLineHeight,
  924. Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
  925. breaker.add(new KnuthPenalty(conditionalOptionalLines * constantLineHeight,
  926. 0, false, elementPosition, false));
  927. breaker.add(new KnuthGlue(0, conditionalOptionalLines * constantLineHeight,
  928. conditionalEliminableLines * constantLineHeight,
  929. Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
  930. } else if (lastLines != 0) {
  931. breaker.add(new KnuthPenalty(0, 0, false, elementPosition, false));
  932. }
  933. // creation of the elements:
  934. // first group of lines
  935. list.add(new KnuthBox(firstLines * constantLineHeight, elementPosition,
  936. (lastLines == 0
  937. && conditionalOptionalLines == 0
  938. && conditionalEliminableLines == 0)));
  939. if (conditionalOptionalLines > 0
  940. || conditionalEliminableLines > 0) {
  941. list.add(new KnuthPenalty(0, KnuthElement.INFINITE, false, elementPosition, false));
  942. list.add(new KnuthGlue(0, conditionalOptionalLines * constantLineHeight,
  943. conditionalEliminableLines * constantLineHeight,
  944. Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
  945. list.add(new KnuthBox(0, elementPosition, (lastLines == 0)));
  946. }
  947. // optional lines
  948. for (int i = 0; i < optionalLines; i++) {
  949. list.addAll(breaker);
  950. list.add(new KnuthBox(0, elementPosition, false));
  951. list.add(new KnuthPenalty(0, KnuthElement.INFINITE, false, elementPosition, false));
  952. list.add(new KnuthGlue(0, constantLineHeight, 0,
  953. Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
  954. list.add(new KnuthBox(0, elementPosition, false));
  955. }
  956. // eliminable lines
  957. for (int i = 0; i < eliminableLines; i++) {
  958. list.addAll(breaker);
  959. list.add(new KnuthBox(constantLineHeight, elementPosition, false));
  960. list.add(new KnuthPenalty(0, KnuthElement.INFINITE, false, elementPosition, false));
  961. list.add(new KnuthGlue(0, 0, constantLineHeight,
  962. Adjustment.LINE_NUMBER_ADJUSTMENT, elementPosition, false));
  963. list.add(new KnuthBox(0, elementPosition, false));
  964. }
  965. // inner lines
  966. for (int i = 0; i < innerLines; i++) {
  967. list.addAll(breaker);
  968. list.add(new KnuthBox(constantLineHeight, elementPosition, false));
  969. }
  970. // last group of lines
  971. if (lastLines > 0) {
  972. list.addAll(breaker);
  973. list.add(new KnuthBox(lastLines * constantLineHeight,
  974. elementPosition, true));
  975. }
  976. }
  977. /** {@inheritDoc} */
  978. public boolean mustKeepTogether() {
  979. return ((BlockLevelLayoutManager) getParent()).mustKeepTogether();
  980. }
  981. /** {@inheritDoc} */
  982. public KeepProperty getKeepTogetherProperty() {
  983. return ((BlockLevelLayoutManager) getParent()).getKeepTogetherProperty();
  984. }
  985. /** {@inheritDoc} */
  986. public KeepProperty getKeepWithPreviousProperty() {
  987. return ((BlockLevelLayoutManager) getParent()).getKeepWithPreviousProperty();
  988. }
  989. /** {@inheritDoc} */
  990. public KeepProperty getKeepWithNextProperty() {
  991. return ((BlockLevelLayoutManager) getParent()).getKeepWithNextProperty();
  992. }
  993. /** {@inheritDoc} */
  994. public Keep getKeepTogether() {
  995. return ((BlockLevelLayoutManager) getParent()).getKeepTogether();
  996. }
  997. /** {@inheritDoc} */
  998. public boolean mustKeepWithPrevious() {
  999. return !getKeepWithPrevious().isAuto();
  1000. }
  1001. /** {@inheritDoc} */
  1002. public boolean mustKeepWithNext() {
  1003. return !getKeepWithNext().isAuto();
  1004. }
  1005. /** {@inheritDoc} */
  1006. public Keep getKeepWithNext() {
  1007. return Keep.KEEP_AUTO;
  1008. }
  1009. /** {@inheritDoc} */
  1010. public Keep getKeepWithPrevious() {
  1011. return Keep.KEEP_AUTO;
  1012. }
  1013. /** {@inheritDoc} */
  1014. public int negotiateBPDAdjustment(int adj, KnuthElement lastElement) {
  1015. LeafPosition pos = (LeafPosition)lastElement.getPosition();
  1016. //if (lastElement.isPenalty()) {
  1017. // totalAdj += lastElement.getWidth();
  1018. //}
  1019. //int lineNumberDifference = (int)((double) totalAdj / constantLineHeight);
  1020. int lineNumberDifference = (int) Math.round((double) adj / constantLineHeight
  1021. + (adj > 0 ? -0.4 : 0.4));
  1022. //log.debug(" LLM> variazione calcolata = " + ((double) totalAdj / constantLineHeight)
  1023. //+ " variazione applicata = " + lineNumberDifference);
  1024. LineLayoutPossibilities llPoss;
  1025. llPoss = lineLayoutsList[pos.getLeafPos()];
  1026. lineNumberDifference = llPoss.applyLineCountAdjustment(lineNumberDifference);
  1027. return lineNumberDifference * constantLineHeight;
  1028. }
  1029. /** {@inheritDoc} */
  1030. public void discardSpace(KnuthGlue spaceGlue) {
  1031. }
  1032. /** {@inheritDoc} */
  1033. @Override
  1034. public List getChangedKnuthElements(List oldList, int alignment, int depth) {
  1035. return getChangedKnuthElements(oldList, alignment);
  1036. }
  1037. /** {@inheritDoc} */
  1038. @Override
  1039. public List getChangedKnuthElements(List oldList, int alignment) {
  1040. List<KnuthElement> returnList = new LinkedList<KnuthElement>();
  1041. for (int p = 0; p < knuthParagraphs.size(); p++) {
  1042. LineLayoutPossibilities llPoss = lineLayoutsList[p];
  1043. //log.debug("demerits of the chosen layout: " + llPoss.getChosenDemerits());
  1044. for (int i = 0; i < llPoss.getChosenLineCount(); i++) {
  1045. if (!((BlockLevelLayoutManager) parentLayoutManager).mustKeepTogether()
  1046. && i >= fobj.getOrphans()
  1047. && i <= llPoss.getChosenLineCount() - fobj.getWidows()) {
  1048. // null penalty allowing a page break between lines
  1049. returnList.add(new KnuthPenalty(0, 0, false, new Position(this), false));
  1050. }
  1051. LineBreakPosition lbp = (LineBreakPosition) llPoss.getChosenPosition(i);
  1052. //log.debug("LLM.getChangedKnuthElements> lineWidth= "
  1053. // + lbp.lineWidth + " difference= " + lbp.difference);
  1054. //log.debug(" shrink= "
  1055. // + lbp.availableShrink + " stretch= " + lbp.availableStretch);
  1056. //log.debug("linewidth= " + lbp.lineWidth + " difference= "
  1057. //+ lbp.difference + " indent= " + lbp.startIndent);
  1058. MinOptMax contentIPD;
  1059. if (alignment == EN_JUSTIFY) {
  1060. contentIPD = MinOptMax.getInstance(
  1061. lbp.lineWidth - lbp.difference - lbp.availableShrink,
  1062. lbp.lineWidth - lbp.difference,
  1063. lbp.lineWidth - lbp.difference + lbp.availableStretch);
  1064. } else if (alignment == EN_CENTER) {
  1065. contentIPD = MinOptMax.getInstance(lbp.lineWidth - 2 * lbp.startIndent);
  1066. } else if (alignment == EN_END) {
  1067. contentIPD = MinOptMax.getInstance(lbp.lineWidth - lbp.startIndent);
  1068. } else {
  1069. contentIPD
  1070. = MinOptMax.getInstance(lbp.lineWidth - lbp.difference + lbp.startIndent);
  1071. }
  1072. returnList.add(new KnuthBlockBox(lbp.lineHeight, contentIPD, (lbp.ipdAdjust != 0
  1073. ? lbp.lineWidth - lbp.difference : 0),
  1074. lbp, false));
  1075. }
  1076. }
  1077. return returnList;
  1078. }
  1079. /**
  1080. * Find hyphenation points for every word in the current paragraph.
  1081. *
  1082. * @param currPar the paragraph whose words will be hyphenated
  1083. */
  1084. private void findHyphenationPoints(Paragraph currPar) {
  1085. // hyphenate every word
  1086. ListIterator currParIterator = currPar.listIterator(currPar.ignoreAtStart);
  1087. // list of TLM involved in hyphenation
  1088. List updateList = new LinkedList();
  1089. KnuthElement firstElement, nextElement;
  1090. // current InlineLevelLayoutManager
  1091. InlineLevelLayoutManager currLM = null;
  1092. // number of KnuthBox elements containing word fragments
  1093. int boxCount;
  1094. // number of auxiliary KnuthElements between KnuthBoxes
  1095. int auxCount;
  1096. StringBuffer sbChars;
  1097. // find all hyphenation points
  1098. while (currParIterator.hasNext()) {
  1099. firstElement = (KnuthElement) currParIterator.next();
  1100. //
  1101. if (firstElement.getLayoutManager() != currLM) {
  1102. currLM = (InlineLevelLayoutManager) firstElement.getLayoutManager();
  1103. if (currLM != null) {
  1104. updateList.add(new Update(currLM, currParIterator.previousIndex()));
  1105. } else {
  1106. break;
  1107. }
  1108. } else if (currLM == null) {
  1109. break;
  1110. }
  1111. // collect word fragments, ignoring auxiliary elements;
  1112. // each word fragment was created by a different TextLM
  1113. if (firstElement.isBox() && !firstElement.isAuxiliary()) {
  1114. boxCount = 1;
  1115. auxCount = 0;
  1116. sbChars = new StringBuffer();
  1117. sbChars.append(currLM.getWordChars(firstElement.getPosition()));
  1118. // look if next elements are boxes too
  1119. while (currParIterator.hasNext()) {
  1120. nextElement = (KnuthElement) currParIterator.next();
  1121. if (nextElement.isBox() && !nextElement.isAuxiliary()) {
  1122. // a non-auxiliary KnuthBox: append word chars
  1123. if (currLM != nextElement.getLayoutManager()) {
  1124. currLM = (InlineLevelLayoutManager) nextElement.getLayoutManager();
  1125. updateList.add(new Update(currLM, currParIterator.previousIndex()));
  1126. }
  1127. // append text to recreate the whole word
  1128. boxCount++;
  1129. sbChars.append(currLM.getWordChars(nextElement.getPosition()));
  1130. } else if (!nextElement.isAuxiliary()) {
  1131. // a non-auxiliary non-box KnuthElement: stop
  1132. // go back to the last box or auxiliary element
  1133. currParIterator.previous();
  1134. break;
  1135. } else {
  1136. if (currLM != nextElement.getLayoutManager()) {
  1137. currLM = (InlineLevelLayoutManager) nextElement.getLayoutManager();
  1138. updateList.add(new Update(currLM, currParIterator.previousIndex()));
  1139. }
  1140. // an auxiliary KnuthElement: simply ignore it
  1141. auxCount++;
  1142. }
  1143. }
  1144. if (log.isTraceEnabled()) {
  1145. log.trace(" Word to hyphenate: " + sbChars.toString());
  1146. }
  1147. // find hyphenation points
  1148. HyphContext hc = getHyphenContext(sbChars);
  1149. // ask each LM to hyphenate its word fragment
  1150. if (hc != null) {
  1151. KnuthElement element = null;
  1152. for (int i = 0; i < (boxCount + auxCount); i++) {
  1153. currParIterator.previous();
  1154. }
  1155. for (int i = 0; i < (boxCount + auxCount); i++) {
  1156. element = (KnuthElement) currParIterator.next();
  1157. if (element.isBox() && !element.isAuxiliary()) {
  1158. ((InlineLevelLayoutManager)
  1159. element.getLayoutManager()).hyphenate(element.getPosition(), hc);
  1160. } else {
  1161. // nothing to do, element is an auxiliary KnuthElement
  1162. }
  1163. }
  1164. }
  1165. }
  1166. }
  1167. processUpdates(currPar, updateList);
  1168. }
  1169. private void processUpdates(Paragraph par, List updateList) {
  1170. // create iterator for the updateList
  1171. ListIterator updateListIterator = updateList.listIterator();
  1172. Update currUpdate;
  1173. int elementsAdded = 0;
  1174. while (updateListIterator.hasNext()) {
  1175. // ask the LMs to apply the changes and return
  1176. // the new KnuthElements to replace the old ones
  1177. currUpdate = (Update) updateListIterator.next();
  1178. int fromIndex = currUpdate.firstIndex;
  1179. int toIndex;
  1180. if (updateListIterator.hasNext()) {
  1181. Update nextUpdate = (Update) updateListIterator.next();
  1182. toIndex = nextUpdate.firstIndex;
  1183. updateListIterator.previous();
  1184. } else {
  1185. // maybe this is not always correct!
  1186. toIndex = par.size() - par.ignoreAtEnd
  1187. - elementsAdded;
  1188. }
  1189. // applyChanges() returns true if the LM modifies its data,
  1190. // so it must return new KnuthElements to replace the old ones
  1191. if (currUpdate.inlineLM
  1192. .applyChanges(par.subList(fromIndex + elementsAdded,
  1193. toIndex + elementsAdded))) {
  1194. // insert the new KnuthElements
  1195. List newElements = currUpdate.inlineLM.getChangedKnuthElements
  1196. (par.subList(fromIndex + elementsAdded,
  1197. toIndex + elementsAdded),
  1198. /*flaggedPenalty,*/ effectiveAlignment);
  1199. // remove the old elements
  1200. par.subList(fromIndex + elementsAdded,
  1201. toIndex + elementsAdded).clear();
  1202. // insert the new elements
  1203. par.addAll(fromIndex + elementsAdded, newElements);
  1204. elementsAdded += newElements.size() - (toIndex - fromIndex);
  1205. }
  1206. }
  1207. updateList.clear();
  1208. }
  1209. /**
  1210. * Line area is always considered to act as a fence.
  1211. * @param isNotFirst ignored
  1212. * @return always true
  1213. */
  1214. @Override
  1215. protected boolean hasLeadingFence(boolean isNotFirst) {
  1216. return true;
  1217. }
  1218. /**
  1219. * Line area is always considered to act as a fence.
  1220. * @param isNotLast ignored
  1221. * @return always true
  1222. */
  1223. @Override
  1224. protected boolean hasTrailingFence(boolean isNotLast) {
  1225. return true;
  1226. }
  1227. private HyphContext getHyphenContext(StringBuffer sbChars) {
  1228. // Find all hyphenation points in this word
  1229. // (get in an array of offsets)
  1230. // hyphenationProperties are from the block level?.
  1231. // Note that according to the spec,
  1232. // they also "apply to" fo:character.
  1233. // I don't know what that means, since
  1234. // if we change language in the middle of a "word",
  1235. // the effect would seem quite strange!
  1236. // Or perhaps in that case, we say that it's several words.
  1237. // We probably should bring the hyphenation props up from the actual
  1238. // TextLM which generate the hyphenation buffer,
  1239. // since these properties inherit and could be specified
  1240. // on an inline or wrapper below the block level.
  1241. Hyphenation hyph
  1242. = Hyphenator.hyphenate(hyphenationProperties.language.getString(),
  1243. hyphenationProperties.country.getString(),
  1244. getFObj().getUserAgent().getFactory().getHyphenationTreeResolver(),
  1245. getFObj().getUserAgent().getFactory().getHyphPatNames(),
  1246. sbChars.toString(),
  1247. hyphenationProperties.hyphenationRemainCharacterCount.getValue(),
  1248. hyphenationProperties.hyphenationPushCharacterCount.getValue());
  1249. // They hyph structure contains the information we need
  1250. // Now start from prev: reset to that position, ask that LM to get
  1251. // a Position for the first hyphenation offset. If the offset isn't in
  1252. // its characters, it returns null,
  1253. // but must tell how many chars it had.
  1254. // Keep looking at currentBP using next hyphenation point until the
  1255. // returned size is greater than the available size
  1256. // or no more hyphenation points remain. Choose the best break.
  1257. if (hyph != null) {
  1258. return new HyphContext(hyph.getHyphenationPoints());
  1259. } else {
  1260. return null;
  1261. }
  1262. }
  1263. /**
  1264. * Add the areas with the break points.
  1265. *
  1266. * @param parentIter the iterator of break positions
  1267. * @param context the context for adding areas
  1268. */
  1269. @Override
  1270. public void addAreas(PositionIterator parentIter,
  1271. LayoutContext context) {
  1272. while (parentIter.hasNext()) {
  1273. Position pos = parentIter.next();
  1274. boolean isLastPosition = !parentIter.hasNext();
  1275. if (pos instanceof LineBreakPosition) {
  1276. addInlineArea(context, (LineBreakPosition) pos, isLastPosition);
  1277. } else if ((pos instanceof NonLeafPosition) && pos.generatesAreas()) {
  1278. addBlockArea(context, pos, isLastPosition);
  1279. } else {
  1280. /*
  1281. * pos was the Position inside a penalty item, nothing to do;
  1282. * or Pos does not generate an area,
  1283. * i.e. it stand for spaces, borders and padding.
  1284. */
  1285. }
  1286. }
  1287. setCurrentArea(null); // ?? necessary
  1288. }
  1289. /**
  1290. * Add a line with inline content
  1291. * @param context the context for adding areas
  1292. * @param lbp the position for which the line is generated
  1293. * @param isLastPosition true if this is the last position of this LM
  1294. */
  1295. private void addInlineArea(LayoutContext context, LineBreakPosition lbp,
  1296. boolean isLastPosition) {
  1297. KnuthSequence seq = knuthParagraphs.get(lbp.parIndex);
  1298. int startElementIndex = lbp.startIndex;
  1299. int endElementIndex = lbp.getLeafPos();
  1300. LineArea lineArea = new LineArea(
  1301. (lbp.getLeafPos() < seq.size() - 1 ? textAlignment : textAlignmentLast),
  1302. lbp.difference, lbp.availableStretch, lbp.availableShrink);
  1303. if (lbp.startIndent != 0) {
  1304. lineArea.addTrait(Trait.START_INDENT, lbp.startIndent);
  1305. }
  1306. lineArea.setBPD(lbp.lineHeight);
  1307. lineArea.setIPD(lbp.lineWidth);
  1308. lineArea.addTrait(Trait.SPACE_BEFORE, lbp.spaceBefore);
  1309. lineArea.addTrait(Trait.SPACE_AFTER, lbp.spaceAfter);
  1310. alignmentContext.resizeLine(lbp.lineHeight, lbp.baseline);
  1311. if (seq instanceof Paragraph) {
  1312. Paragraph currPar = (Paragraph) seq;
  1313. // ignore the first elements added by the LineLayoutManager
  1314. startElementIndex += (startElementIndex == 0) ? currPar.ignoreAtStart : 0;
  1315. // if this is the last line area that for this paragraph,
  1316. // ignore the last elements added by the LineLayoutManager and
  1317. // subtract the last-line-end-indent from the area ipd
  1318. if (endElementIndex == (currPar.size() - 1)) {
  1319. endElementIndex -= currPar.ignoreAtEnd;
  1320. lineArea.setIPD(lineArea.getIPD() - lastLineEndIndent.getValue(this));
  1321. }
  1322. }
  1323. // ignore the last element in the line if it is a KnuthGlue object
  1324. ListIterator seqIterator = seq.listIterator(endElementIndex);
  1325. KnuthElement lastElement = (KnuthElement) seqIterator.next();
  1326. // the TLM which created the last KnuthElement in this line
  1327. LayoutManager lastLM = lastElement.getLayoutManager();
  1328. if (lastElement.isGlue()) {
  1329. // Remove trailing spaces if allowed so
  1330. if (whiteSpaceTreament == EN_IGNORE_IF_SURROUNDING_LINEFEED
  1331. || whiteSpaceTreament == EN_IGNORE
  1332. || whiteSpaceTreament == EN_IGNORE_IF_BEFORE_LINEFEED) {
  1333. endElementIndex--;
  1334. // this returns the same KnuthElement
  1335. seqIterator.previous();
  1336. if (seqIterator.hasPrevious()) {
  1337. lastLM = ((KnuthElement) seqIterator.previous()).getLayoutManager();
  1338. }
  1339. }
  1340. }
  1341. // Remove leading spaces if allowed so
  1342. if (whiteSpaceTreament == EN_IGNORE_IF_SURROUNDING_LINEFEED
  1343. || whiteSpaceTreament == EN_IGNORE
  1344. || whiteSpaceTreament == EN_IGNORE_IF_AFTER_LINEFEED) {
  1345. // ignore KnuthGlue and KnuthPenalty objects
  1346. // at the beginning of the line
  1347. seqIterator = seq.listIterator(startElementIndex);
  1348. while (seqIterator.hasNext() && !((KnuthElement) seqIterator.next()).isBox()) {
  1349. startElementIndex++;
  1350. }
  1351. }
  1352. // Add the inline areas to lineArea
  1353. PositionIterator inlinePosIter = new KnuthPossPosIter(seq, startElementIndex,
  1354. endElementIndex + 1);
  1355. LayoutContext lc = new LayoutContext(0);
  1356. lc.setAlignmentContext(alignmentContext);
  1357. lc.setSpaceAdjust(lbp.dAdjust);
  1358. lc.setIPDAdjust(lbp.ipdAdjust);
  1359. lc.setLeadingSpace(new SpaceSpecifier(true));
  1360. lc.setTrailingSpace(new SpaceSpecifier(false));
  1361. lc.setFlags(LayoutContext.RESOLVE_LEADING_SPACE, true);
  1362. setCurrentArea(lineArea);
  1363. setChildContext(lc);
  1364. LayoutManager childLM;
  1365. while ((childLM = inlinePosIter.getNextChildLM()) != null) {
  1366. lc.setFlags(LayoutContext.LAST_AREA, (childLM == lastLM));
  1367. childLM.addAreas(inlinePosIter, lc);
  1368. lc.setLeadingSpace(lc.getTrailingSpace());
  1369. lc.setTrailingSpace(new SpaceSpecifier(false));
  1370. }
  1371. // if display-align is distribute, add space after
  1372. if (context.getSpaceAfter() > 0
  1373. && (!context.isLastArea() || !isLastPosition)) {
  1374. lineArea.setBPD(lineArea.getBPD() + context.getSpaceAfter());
  1375. }
  1376. lineArea.finalise();
  1377. parentLayoutManager.addChildArea(lineArea);
  1378. }
  1379. /**
  1380. * Add a line with block content
  1381. * @param context the context for adding areas
  1382. * @param pos the position for which the line is generated
  1383. * @param isLastPosition true if this is the last position of this LM
  1384. */
  1385. private void addBlockArea(LayoutContext context, Position pos, boolean isLastPosition) {
  1386. /* Nested block-level content;
  1387. * go down the LM stack again;
  1388. * "unwrap" the positions and put the child positions in a new list.
  1389. * The positionList must contain one area-generating position,
  1390. * which creates one line area.
  1391. */
  1392. List positionList = new ArrayList(1);
  1393. Position innerPosition = pos.getPosition();
  1394. positionList.add(innerPosition);
  1395. // do we have the last LM?
  1396. LayoutManager lastLM = null;
  1397. if (isLastPosition) {
  1398. lastLM = innerPosition.getLM();
  1399. }
  1400. LineArea lineArea = new LineArea();
  1401. setCurrentArea(lineArea);
  1402. LayoutContext lc = new LayoutContext(0);
  1403. lc.setAlignmentContext(alignmentContext);
  1404. setChildContext(lc);
  1405. PositionIterator childPosIter = new PositionIterator(positionList.listIterator());
  1406. LayoutContext blocklc = new LayoutContext(0);
  1407. blocklc.setLeadingSpace(new SpaceSpecifier(true));
  1408. blocklc.setTrailingSpace(new SpaceSpecifier(false));
  1409. blocklc.setFlags(LayoutContext.RESOLVE_LEADING_SPACE, true);
  1410. LayoutManager childLM;
  1411. while ((childLM = childPosIter.getNextChildLM()) != null) {
  1412. // set last area flag
  1413. blocklc.setFlags(LayoutContext.LAST_AREA,
  1414. (context.isLastArea() && childLM == lastLM));
  1415. blocklc.setStackLimitBP(context.getStackLimitBP());
  1416. // Add the line areas to Area
  1417. childLM.addAreas(childPosIter, blocklc);
  1418. blocklc.setLeadingSpace(blocklc.getTrailingSpace());
  1419. blocklc.setTrailingSpace(new SpaceSpecifier(false));
  1420. }
  1421. lineArea.updateExtentsFromChildren();
  1422. parentLayoutManager.addChildArea(lineArea);
  1423. }
  1424. /** {@inheritDoc} */
  1425. @Override
  1426. public void addChildArea(Area childArea) {
  1427. // Make sure childArea is inline area
  1428. if (childArea instanceof InlineArea) {
  1429. Area parent = getCurrentArea();
  1430. if (getContext().resolveLeadingSpace()) {
  1431. addSpace(parent, getContext().getLeadingSpace().resolve(false),
  1432. getContext().getSpaceAdjust());
  1433. }
  1434. parent.addChildArea(childArea);
  1435. }
  1436. }
  1437. // --------- Property Resolution related functions --------- //
  1438. /** {@inheritDoc} */
  1439. @Override
  1440. public boolean getGeneratesBlockArea() {
  1441. return true;
  1442. }
  1443. /** {@inheritDoc} */
  1444. @Override
  1445. public boolean getGeneratesLineArea() {
  1446. return true;
  1447. }
  1448. /** {@inheritDoc} */
  1449. @Override
  1450. public boolean isRestartable() {
  1451. return true;
  1452. }
  1453. }