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

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