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

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