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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  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 org.apache.commons.logging.Log;
  20. import org.apache.commons.logging.LogFactory;
  21. import org.apache.fop.datatypes.Length;
  22. import org.apache.fop.datatypes.Numeric;
  23. import org.apache.fop.fo.Constants;
  24. import org.apache.fop.fo.FONode;
  25. import org.apache.fop.fo.flow.Block;
  26. import org.apache.fop.fo.properties.CommonHyphenation;
  27. import org.apache.fop.hyphenation.Hyphenation;
  28. import org.apache.fop.hyphenation.Hyphenator;
  29. import org.apache.fop.layoutmgr.BlockLevelLayoutManager;
  30. import org.apache.fop.layoutmgr.BreakElement;
  31. import org.apache.fop.layoutmgr.BreakingAlgorithm;
  32. import org.apache.fop.layoutmgr.ElementListObserver;
  33. import org.apache.fop.layoutmgr.InlineKnuthSequence;
  34. import org.apache.fop.layoutmgr.KnuthBlockBox;
  35. import org.apache.fop.layoutmgr.KnuthBox;
  36. import org.apache.fop.layoutmgr.KnuthElement;
  37. import org.apache.fop.layoutmgr.KnuthGlue;
  38. import org.apache.fop.layoutmgr.KnuthPenalty;
  39. import org.apache.fop.layoutmgr.KnuthPossPosIter;
  40. import org.apache.fop.layoutmgr.KnuthSequence;
  41. import org.apache.fop.layoutmgr.LayoutContext;
  42. import org.apache.fop.layoutmgr.LayoutManager;
  43. import org.apache.fop.layoutmgr.LeafPosition;
  44. import org.apache.fop.layoutmgr.ListElement;
  45. import org.apache.fop.layoutmgr.NonLeafPosition;
  46. import org.apache.fop.layoutmgr.Position;
  47. import org.apache.fop.layoutmgr.PositionIterator;
  48. import org.apache.fop.layoutmgr.SpaceSpecifier;
  49. import org.apache.fop.area.Area;
  50. import org.apache.fop.area.LineArea;
  51. import org.apache.fop.area.inline.InlineArea;
  52. import java.util.ListIterator;
  53. import java.util.List;
  54. import java.util.ArrayList;
  55. import java.util.LinkedList;
  56. import org.apache.fop.area.Trait;
  57. import org.apache.fop.fonts.Font;
  58. import org.apache.fop.traits.MinOptMax;
  59. /**
  60. * LayoutManager for lines. It builds one or more lines containing
  61. * inline areas generated by its sub layout managers.
  62. * A break is found for each line which may contain one of more
  63. * breaks from the child layout managers.
  64. * Once a break is found then it is return for the parent layout
  65. * manager to handle.
  66. * When the areas are being added to the page this manager
  67. * creates a line area to contain the inline areas added by the
  68. * child layout managers.
  69. */
  70. public class LineLayoutManager extends InlineStackingLayoutManager
  71. implements BlockLevelLayoutManager {
  72. /**
  73. * logging instance
  74. */
  75. private static Log log = LogFactory.getLog(LineLayoutManager.class);
  76. private Block fobj;
  77. private boolean isFirstInBlock;
  78. /** @see org.apache.fop.layoutmgr.LayoutManager#initialize() */
  79. public void initialize() {
  80. textAlignment = fobj.getTextAlign();
  81. textAlignmentLast = fobj.getTextAlignLast();
  82. textIndent = fobj.getTextIndent();
  83. lastLineEndIndent = fobj.getLastLineEndIndent();
  84. hyphenationProperties = fobj.getCommonHyphenation();
  85. hyphenationLadderCount = fobj.getHyphenationLadderCount();
  86. wrapOption = fobj.getWrapOption();
  87. whiteSpaceTreament = fobj.getWhitespaceTreatment();
  88. //
  89. effectiveAlignment = getEffectiveAlignment(textAlignment, textAlignmentLast);
  90. isFirstInBlock = (this == getParent().getChildLMs().get(0));
  91. }
  92. private int getEffectiveAlignment(int alignment, int alignmentLast) {
  93. if (textAlignment != EN_JUSTIFY && textAlignmentLast == EN_JUSTIFY) {
  94. return 0;
  95. } else {
  96. return textAlignment;
  97. }
  98. }
  99. /**
  100. * Private class to store information about inline breaks.
  101. * Each value holds the start and end indexes into a List of
  102. * inline break positions.
  103. */
  104. private static class LineBreakPosition extends LeafPosition {
  105. private int iParIndex; // index of the Paragraph this Position refers to
  106. private int iStartIndex; //index of the first element this Position refers to
  107. private int availableShrink;
  108. private int availableStretch;
  109. private int difference;
  110. private double dAdjust; // Percentage to adjust (stretch or shrink)
  111. private double ipdAdjust; // Percentage to adjust (stretch or shrink)
  112. private int startIndent;
  113. private int lineHeight;
  114. private int lineWidth;
  115. private int spaceBefore;
  116. private int spaceAfter;
  117. private int baseline;
  118. LineBreakPosition(LayoutManager lm, int index, int iStartIndex, int iBreakIndex,
  119. int shrink, int stretch, int diff,
  120. double ipdA, double adjust, int ind,
  121. int lh, int lw, int sb, int sa, int bl) {
  122. super(lm, iBreakIndex);
  123. availableShrink = shrink;
  124. availableStretch = stretch;
  125. difference = diff;
  126. iParIndex = index;
  127. this.iStartIndex = iStartIndex;
  128. ipdAdjust = ipdA;
  129. dAdjust = adjust;
  130. startIndent = ind;
  131. lineHeight = lh;
  132. lineWidth = lw;
  133. spaceBefore = sb;
  134. spaceAfter = sa;
  135. baseline = bl;
  136. }
  137. }
  138. private int textAlignment = EN_JUSTIFY;
  139. private int textAlignmentLast;
  140. private int effectiveAlignment;
  141. private Length textIndent;
  142. private Length lastLineEndIndent;
  143. private CommonHyphenation hyphenationProperties;
  144. private Numeric hyphenationLadderCount;
  145. private int wrapOption = EN_WRAP;
  146. private int whiteSpaceTreament;
  147. //private LayoutProps layoutProps;
  148. private Length lineHeight;
  149. private int lead;
  150. private int follow;
  151. private AlignmentContext alignmentContext = null;
  152. private List knuthParagraphs = null;
  153. private int iReturnedLBP = 0;
  154. // parameters of Knuth's algorithm:
  155. // penalty value for flagged penalties
  156. private int flaggedPenalty = 50;
  157. private LineLayoutPossibilities lineLayouts;
  158. private List lineLayoutsList;
  159. private int iLineWidth = 0;
  160. /**
  161. * this constant is used to create elements when text-align is center:
  162. * every TextLM descendant of LineLM must use the same value,
  163. * otherwise the line breaking algorithm does not find the right
  164. * break point
  165. */
  166. public static final int DEFAULT_SPACE_WIDTH = 3336;
  167. /**
  168. * This class is used to remember
  169. * which was the first element in the paragraph
  170. * returned by each LM.
  171. */
  172. private class Update {
  173. private InlineLevelLayoutManager inlineLM;
  174. private int iFirstIndex;
  175. public Update(InlineLevelLayoutManager lm, int index) {
  176. inlineLM = lm;
  177. iFirstIndex = index;
  178. }
  179. }
  180. // this class represents a paragraph
  181. private class Paragraph extends InlineKnuthSequence {
  182. /** Number of elements to ignore at the beginning of the list. */
  183. private int ignoreAtStart = 0;
  184. /** Number of elements to ignore at the end of the list. */
  185. private int ignoreAtEnd = 0;
  186. // space at the end of the last line (in millipoints)
  187. private MinOptMax lineFiller;
  188. private int textAlignment;
  189. private int textAlignmentLast;
  190. private int textIndent;
  191. private int lastLineEndIndent;
  192. // the LM which created the paragraph
  193. private LineLayoutManager layoutManager;
  194. public Paragraph(LineLayoutManager llm, int alignment, int alignmentLast,
  195. int indent, int endIndent) {
  196. super();
  197. layoutManager = llm;
  198. textAlignment = alignment;
  199. textAlignmentLast = alignmentLast;
  200. textIndent = indent;
  201. lastLineEndIndent = endIndent;
  202. }
  203. public void startParagraph() {
  204. startSequence();
  205. }
  206. public void startSequence() {
  207. // set the minimum amount of empty space at the end of the
  208. // last line
  209. if (textAlignment == EN_CENTER) {
  210. lineFiller = new MinOptMax(lastLineEndIndent);
  211. } else {
  212. lineFiller = new MinOptMax(lastLineEndIndent,
  213. lastLineEndIndent,
  214. layoutManager.iLineWidth);
  215. }
  216. // add auxiliary elements at the beginning of the paragraph
  217. if (textAlignment == EN_CENTER && textAlignmentLast != EN_JUSTIFY) {
  218. this.add(new KnuthGlue(0, 3 * DEFAULT_SPACE_WIDTH, 0,
  219. null, false));
  220. ignoreAtStart++;
  221. }
  222. // add the element representing text indentation
  223. // at the beginning of the first paragraph
  224. if (isFirstInBlock && knuthParagraphs.size() == 0
  225. && textIndent != 0) {
  226. this.add(new KnuthInlineBox(textIndent, null,
  227. null, false));
  228. ignoreAtStart++;
  229. }
  230. }
  231. public void endParagraph() {
  232. KnuthSequence finishedPar = this.endSequence();
  233. if (finishedPar != null) {
  234. knuthParagraphs.add(finishedPar);
  235. }
  236. }
  237. public KnuthSequence endSequence() {
  238. if (this.size() > ignoreAtStart) {
  239. if (textAlignment == EN_CENTER
  240. && textAlignmentLast != EN_JUSTIFY) {
  241. this.add(new KnuthGlue(0, 3 * DEFAULT_SPACE_WIDTH, 0,
  242. null, false));
  243. this.add(new KnuthPenalty(lineFiller.opt, -KnuthElement.INFINITE,
  244. false, null, false));
  245. ignoreAtEnd = 2;
  246. } else if (textAlignmentLast != EN_JUSTIFY) {
  247. // add the elements representing the space
  248. // at the end of the last line
  249. // and the forced break
  250. this.add(new KnuthPenalty(0, KnuthElement.INFINITE,
  251. false, null, false));
  252. this.add(new KnuthGlue(0,
  253. lineFiller.max - lineFiller.opt,
  254. lineFiller.opt - lineFiller.min, null, false));
  255. this.add(new KnuthPenalty(lineFiller.opt, -KnuthElement.INFINITE,
  256. false, null, false));
  257. ignoreAtEnd = 3;
  258. } else {
  259. // add only the element representing the forced break
  260. this.add(new KnuthPenalty(lineFiller.opt, -KnuthElement.INFINITE,
  261. false, null, false));
  262. ignoreAtEnd = 1;
  263. }
  264. return this;
  265. } else {
  266. this.clear();
  267. return null;
  268. }
  269. }
  270. /**
  271. * @return true if the sequence contains a box
  272. */
  273. public boolean containsBox() {
  274. for (int i = 0; i < this.size(); i++) {
  275. KnuthElement el = (KnuthElement)this.get(i);
  276. if (el.isBox()) {
  277. return true;
  278. }
  279. }
  280. return false;
  281. }
  282. }
  283. private class LineBreakingAlgorithm extends BreakingAlgorithm {
  284. private LineLayoutManager thisLLM;
  285. private int pageAlignment;
  286. private int activePossibility;
  287. private int addedPositions;
  288. private int textIndent;
  289. private int fillerMinWidth;
  290. private int lineHeight;
  291. private int lead;
  292. private int follow;
  293. private int maxDiff;
  294. private static final double MAX_DEMERITS = 10e6;
  295. public LineBreakingAlgorithm (int pageAlign,
  296. int textAlign, int textAlignLast,
  297. int indent, int fillerWidth,
  298. int lh, int ld, int fl, boolean first,
  299. int maxFlagCount, LineLayoutManager llm) {
  300. super(textAlign, textAlignLast, first, false, maxFlagCount);
  301. pageAlignment = pageAlign;
  302. textIndent = indent;
  303. fillerMinWidth = fillerWidth;
  304. lineHeight = lh;
  305. lead = ld;
  306. follow = fl;
  307. thisLLM = llm;
  308. activePossibility = -1;
  309. maxDiff = fobj.getWidows() >= fobj.getOrphans()
  310. ? fobj.getWidows()
  311. : fobj.getOrphans();
  312. }
  313. public void updateData1(int lineCount, double demerits) {
  314. lineLayouts.addPossibility(lineCount, demerits);
  315. if (super.log.isTraceEnabled()) {
  316. super.log.trace(
  317. "Layout possibility in " + lineCount + " lines; break at position:");
  318. }
  319. }
  320. public void updateData2(KnuthNode bestActiveNode,
  321. KnuthSequence par,
  322. int total) {
  323. // compute indent and adjustment ratio, according to
  324. // the value of text-align and text-align-last
  325. int indent = 0;
  326. int difference = bestActiveNode.difference;
  327. int textAlign = (bestActiveNode.line < total) ? alignment : alignmentLast;
  328. indent += (textAlign == Constants.EN_CENTER)
  329. ? difference / 2 : (textAlign == Constants.EN_END) ? difference : 0;
  330. indent += (bestActiveNode.line == 1 && bFirst && isFirstInBlock) ? textIndent : 0;
  331. double ratio = (textAlign == Constants.EN_JUSTIFY
  332. || difference < 0 && -difference <= bestActiveNode.availableShrink)
  333. ? bestActiveNode.adjustRatio : 0;
  334. // add nodes at the beginning of the list, as they are found
  335. // backwards, from the last one to the first one
  336. // the first time this method is called, initialize activePossibility
  337. if (activePossibility == -1) {
  338. activePossibility = 0;
  339. addedPositions = 0;
  340. }
  341. if (addedPositions == lineLayouts.getLineCount(activePossibility)) {
  342. activePossibility++;
  343. addedPositions = 0;
  344. }
  345. if (difference + bestActiveNode.availableShrink < 0) {
  346. if (super.log.isWarnEnabled()) {
  347. super.log.warn(FONode.decorateWithContextInfo(
  348. "Line " + (addedPositions + 1)
  349. + " of a paragraph overflows the available area.", getFObj()));
  350. }
  351. }
  352. //log.debug("LLM> (" + (lineLayouts.getLineNumber(activePossibility) - addedPositions)
  353. // + ") difference = " + difference + " ratio = " + ratio);
  354. lineLayouts.addBreakPosition(makeLineBreakPosition(par,
  355. (bestActiveNode.line > 1 ? bestActiveNode.previous.position + 1 : 0),
  356. bestActiveNode.position,
  357. bestActiveNode.availableShrink - (addedPositions > 0
  358. ? 0 : ((Paragraph)par).lineFiller.opt - ((Paragraph)par).lineFiller.min),
  359. bestActiveNode.availableStretch,
  360. difference, ratio, indent), activePossibility);
  361. addedPositions++;
  362. }
  363. /* reset activePossibility, as if breakpoints have not yet been computed
  364. */
  365. public void resetAlgorithm() {
  366. activePossibility = -1;
  367. }
  368. private LineBreakPosition makeLineBreakPosition(KnuthSequence par,
  369. int firstElementIndex,
  370. int lastElementIndex,
  371. int availableShrink,
  372. int availableStretch,
  373. int difference,
  374. double ratio,
  375. int indent) {
  376. // line height calculation - spaceBefore may differ from spaceAfter
  377. // by 1mpt due to rounding
  378. int spaceBefore = (lineHeight - lead - follow) / 2;
  379. int spaceAfter = lineHeight - lead - follow - spaceBefore;
  380. // height before the main baseline
  381. int lineLead = lead;
  382. // maximum follow
  383. int lineFollow = follow;
  384. // true if this line contains only zero-height, auxiliary boxes
  385. // and the actual line width is 0; in this case, the line "collapses"
  386. // i.e. the line area will have bpd = 0
  387. boolean bZeroHeightLine = (difference == iLineWidth);
  388. // if line-stacking-strategy is "font-height", the line height
  389. // is not affected by its content
  390. if (fobj.getLineStackingStrategy() != EN_FONT_HEIGHT) {
  391. ListIterator inlineIterator
  392. = par.listIterator(firstElementIndex);
  393. AlignmentContext lastAC = null;
  394. int maxIgnoredHeight = 0; // See spec 7.13
  395. for (int j = firstElementIndex;
  396. j <= lastElementIndex;
  397. j++) {
  398. KnuthElement element = (KnuthElement) inlineIterator.next();
  399. if (element instanceof KnuthInlineBox ) {
  400. AlignmentContext ac = ((KnuthInlineBox) element).getAlignmentContext();
  401. if (ac != null && lastAC != ac) {
  402. if (!ac.usesInitialBaselineTable()
  403. || ac.getAlignmentBaselineIdentifier() != EN_BEFORE_EDGE
  404. && ac.getAlignmentBaselineIdentifier() != EN_AFTER_EDGE) {
  405. if (fobj.getLineHeightShiftAdjustment() == EN_CONSIDER_SHIFTS
  406. || ac.getBaselineShiftValue() == 0) {
  407. int alignmentOffset = ac.getTotalAlignmentBaselineOffset();
  408. if (alignmentOffset + ac.getAltitude() > lineLead) {
  409. lineLead = alignmentOffset + ac.getAltitude();
  410. }
  411. if (ac.getDepth() - alignmentOffset > lineFollow) {
  412. lineFollow = ac.getDepth() - alignmentOffset;
  413. }
  414. }
  415. } else {
  416. if (ac.getHeight() > maxIgnoredHeight) {
  417. maxIgnoredHeight = ac.getHeight();
  418. }
  419. }
  420. lastAC = ac;
  421. }
  422. if (bZeroHeightLine
  423. && (!element.isAuxiliary() || ac != null && ac.getHeight() > 0)) {
  424. bZeroHeightLine = false;
  425. }
  426. }
  427. }
  428. if (lineFollow < maxIgnoredHeight - lineLead) {
  429. lineFollow = maxIgnoredHeight - lineLead;
  430. }
  431. }
  432. constantLineHeight = lineLead + lineFollow;
  433. if (bZeroHeightLine) {
  434. return new LineBreakPosition(thisLLM,
  435. knuthParagraphs.indexOf(par),
  436. firstElementIndex, lastElementIndex,
  437. availableShrink, availableStretch,
  438. difference, ratio, 0, indent,
  439. 0, iLineWidth, 0, 0, 0);
  440. } else {
  441. return new LineBreakPosition(thisLLM,
  442. knuthParagraphs.indexOf(par),
  443. firstElementIndex, lastElementIndex,
  444. availableShrink, availableStretch,
  445. difference, ratio, 0, indent,
  446. lineLead + lineFollow,
  447. iLineWidth, spaceBefore, spaceAfter,
  448. lineLead);
  449. }
  450. }
  451. public int findBreakingPoints(Paragraph par, /*int lineWidth,*/
  452. double threshold, boolean force,
  453. int allowedBreaks) {
  454. return super.findBreakingPoints(par, /*lineWidth,*/
  455. threshold, force, allowedBreaks);
  456. }
  457. protected int filterActiveNodes() {
  458. KnuthNode bestActiveNode = null;
  459. if (pageAlignment == EN_JUSTIFY) {
  460. // leave all active nodes and find the optimum line number
  461. //log.debug("LBA.filterActiveNodes> " + activeNodeCount + " layouts");
  462. for (int i = startLine; i < endLine; i++) {
  463. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  464. //log.debug(" + lines = " + node.line + " demerits = " + node.totalDemerits);
  465. bestActiveNode = compareNodes(bestActiveNode, node);
  466. }
  467. }
  468. // scan the node set once again and remove some nodes
  469. //log.debug("LBA.filterActiveList> layout selection");
  470. for (int i = startLine; i < endLine; i++) {
  471. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  472. //if (Math.abs(node.line - bestActiveNode.line) > maxDiff) {
  473. //if (false) {
  474. if (node.line != bestActiveNode.line
  475. && node.totalDemerits > MAX_DEMERITS) {
  476. //log.debug(" XXX lines = " + node.line + " demerits = " + node.totalDemerits);
  477. removeNode(i, node);
  478. } else {
  479. //log.debug(" ok lines = " + node.line + " demerits = " + node.totalDemerits);
  480. }
  481. }
  482. }
  483. } else {
  484. // leave only the active node with fewest total demerits
  485. for (int i = startLine; i < endLine; i++) {
  486. for (KnuthNode node = getNode(i); node != null; node = node.next) {
  487. bestActiveNode = compareNodes(bestActiveNode, node);
  488. if (node != bestActiveNode) {
  489. removeNode(i, node);
  490. }
  491. }
  492. }
  493. }
  494. return bestActiveNode.line;
  495. }
  496. }
  497. private int constantLineHeight = 12000;
  498. /**
  499. * Create a new Line Layout Manager.
  500. * This is used by the block layout manager to create
  501. * line managers for handling inline areas flowing into line areas.
  502. * @param block the block formatting object
  503. * @param lh the default line height
  504. * @param l the default lead, from top to baseline
  505. * @param f the default follow, from baseline to bottom
  506. */
  507. public LineLayoutManager(Block block, Length lh, int l, int f) {
  508. super(block);
  509. fobj = block;
  510. // the child FObj are owned by the parent BlockLM
  511. // this LM has all its childLMs preloaded
  512. fobjIter = null;
  513. lineHeight = lh;
  514. lead = l;
  515. follow = f;
  516. }
  517. /** @see org.apache.fop.layoutmgr.LayoutManager */
  518. public LinkedList getNextKnuthElements(LayoutContext context, int alignment) {
  519. Font fs = fobj.getCommonFont().getFontState(fobj.getFOEventHandler().getFontInfo(), this);
  520. alignmentContext
  521. = new AlignmentContext(fs, lineHeight.getValue(this), context.getWritingMode());
  522. context.setAlignmentContext(alignmentContext);
  523. // Get a break from currently active child LM
  524. // Set up constraints for inline level managers
  525. // IPD remaining in line
  526. MinOptMax availIPD = context.getStackLimit();
  527. clearPrevIPD();
  528. //PHASE 1: Create Knuth elements
  529. if (knuthParagraphs == null) {
  530. // it's the first time this method is called
  531. knuthParagraphs = new ArrayList();
  532. // here starts Knuth's algorithm
  533. collectInlineKnuthElements(context);
  534. } else {
  535. // this method has been called before
  536. // all line breaks are already calculated
  537. }
  538. // return finished when there's no content
  539. if (knuthParagraphs.size() == 0) {
  540. setFinished(true);
  541. return null;
  542. }
  543. //PHASE 2: Create line breaks
  544. return createLineBreaks(context.getBPAlignment(), context);
  545. /*
  546. LineBreakPosition lbp = null;
  547. if (breakpoints == null) {
  548. // find the optimal line breaking points for each paragraph
  549. breakpoints = new ArrayList();
  550. ListIterator paragraphsIterator
  551. = knuthParagraphs.listIterator(knuthParagraphs.size());
  552. Paragraph currPar = null;
  553. while (paragraphsIterator.hasPrevious()) {
  554. currPar = (Paragraph) paragraphsIterator.previous();
  555. findBreakingPoints(currPar, context.getStackLimit().opt);
  556. }
  557. }*/
  558. //PHASE 3: Return lines
  559. /*
  560. // get a break point from the list
  561. lbp = (LineBreakPosition) breakpoints.get(iReturnedLBP ++);
  562. if (iReturnedLBP == breakpoints.size()) {
  563. setFinished(true);
  564. }
  565. BreakPoss curLineBP = new BreakPoss(lbp);
  566. curLineBP.setFlag(BreakPoss.ISLAST, isFinished());
  567. curLineBP.setStackingSize(new MinOptMax(lbp.lineHeight));
  568. return curLineBP;
  569. */
  570. }
  571. /**
  572. * Phase 1 of Knuth algorithm: Collect all inline Knuth elements before determining line breaks.
  573. * @param context the LayoutContext
  574. * @param availIPD available IPD for line (should be removed!)
  575. */
  576. private void collectInlineKnuthElements(LayoutContext context) {
  577. LayoutContext inlineLC = new LayoutContext(context);
  578. InlineLevelLayoutManager curLM;
  579. LinkedList returnedList = null;
  580. iLineWidth = context.getStackLimit().opt;
  581. // convert all the text in a sequence of paragraphs made
  582. // of KnuthBox, KnuthGlue and KnuthPenalty objects
  583. boolean bPrevWasKnuthBox = false;
  584. StringBuffer trace = new StringBuffer("LineLM:");
  585. Paragraph lastPar = null;
  586. while ((curLM = (InlineLevelLayoutManager) getChildLM()) != null) {
  587. returnedList = curLM.getNextKnuthElements(inlineLC, effectiveAlignment);
  588. if (returnedList == null) {
  589. // curLM returned null; this can happen
  590. // if it has nothing more to layout,
  591. // so just iterate once more to see
  592. // if there are other children
  593. continue;
  594. }
  595. if (returnedList.size() == 0) {
  596. continue;
  597. }
  598. if (lastPar != null) {
  599. KnuthSequence firstSeq = (KnuthSequence) returnedList.getFirst();
  600. // finish last paragraph before a new block sequence
  601. if (!firstSeq.isInlineSequence()) {
  602. lastPar.endParagraph();
  603. ElementListObserver.observe(lastPar, "line", null);
  604. lastPar = null;
  605. if (log.isTraceEnabled()) {
  606. trace.append(" ]");
  607. }
  608. bPrevWasKnuthBox = false;
  609. }
  610. // does the first element of the first paragraph add to an existing word?
  611. if (lastPar != null) {
  612. KnuthElement thisElement;
  613. thisElement = (KnuthElement) firstSeq.get(0);
  614. if (thisElement.isBox() && !thisElement.isAuxiliary()
  615. && bPrevWasKnuthBox) {
  616. lastPar.addALetterSpace();
  617. }
  618. }
  619. }
  620. // loop over the KnuthSequences (and single KnuthElements) in returnedList
  621. ListIterator iter = returnedList.listIterator();
  622. while (iter.hasNext()) {
  623. KnuthSequence sequence = (KnuthSequence) iter.next();
  624. // the sequence contains inline Knuth elements
  625. if (sequence.isInlineSequence()) {
  626. // look at the last element
  627. ListElement lastElement = sequence.getLast();
  628. if (lastElement == null) {
  629. throw new NullPointerException(
  630. "Sequence was empty! lastElement is null");
  631. }
  632. bPrevWasKnuthBox = lastElement.isBox()
  633. && !((KnuthElement) lastElement).isAuxiliary()
  634. && ((KnuthElement) lastElement).getW() != 0;
  635. // if last paragraph is open, add the new elements to the paragraph
  636. // else this is the last paragraph
  637. if (lastPar == null) {
  638. lastPar = new Paragraph(this,
  639. textAlignment, textAlignmentLast,
  640. textIndent.getValue(this),
  641. lastLineEndIndent.getValue(this));
  642. lastPar.startParagraph();
  643. if (log.isTraceEnabled()) {
  644. trace.append(" [");
  645. }
  646. } else {
  647. if (log.isTraceEnabled()) {
  648. trace.append(" +");
  649. }
  650. }
  651. lastPar.addAll(sequence);
  652. if (log.isTraceEnabled()) {
  653. trace.append(" I");
  654. }
  655. // finish last paragraph if it was closed with a linefeed
  656. if (lastElement.isPenalty()
  657. && ((KnuthPenalty) lastElement).getP()
  658. == -KnuthPenalty.INFINITE) {
  659. // a penalty item whose value is -inf
  660. // represents a preserved linefeed,
  661. // which forces a line break
  662. lastPar.removeLast();
  663. if (!lastPar.containsBox()) {
  664. //only a forced linefeed on this line
  665. //-> compensate with an auxiliary glue
  666. lastPar.add(new KnuthGlue(iLineWidth, 0, iLineWidth, null, true));
  667. }
  668. lastPar.endParagraph();
  669. ElementListObserver.observe(lastPar, "line", null);
  670. lastPar = null;
  671. if (log.isTraceEnabled()) {
  672. trace.append(" ]");
  673. }
  674. bPrevWasKnuthBox = false;
  675. }
  676. } else { // the sequence is a block sequence
  677. // the positions will be wrapped with this LM in postProcessLineBreaks
  678. knuthParagraphs.add(sequence);
  679. if (log.isTraceEnabled()) {
  680. trace.append(" B");
  681. }
  682. }
  683. } // end of loop over returnedList
  684. }
  685. if (lastPar != null) {
  686. lastPar.endParagraph();
  687. ElementListObserver.observe(lastPar, "line", fobj.getId());
  688. if (log.isTraceEnabled()) {
  689. trace.append(" ]");
  690. }
  691. }
  692. log.trace(trace);
  693. }
  694. /**
  695. * Find a set of breaking points.
  696. * This method is called only once by getNextBreakPoss, and it
  697. * subsequently calls the other findBreakingPoints() method with
  698. * different parameters, until a set of breaking points is found.
  699. *
  700. * @param par the list of elements that must be parted
  701. * into lines
  702. * @param lineWidth the desired length ot the lines
  703. */
  704. /*
  705. private void findBreakingPoints(Paragraph par, int lineWidth) {
  706. // maximum adjustment ratio permitted
  707. float maxAdjustment = 1;
  708. // first try
  709. if (!findBreakingPoints(par, lineWidth, maxAdjustment, false)) {
  710. // the first try failed, now try something different
  711. log.debug("No set of breaking points found with maxAdjustment = " + maxAdjustment);
  712. if (hyphenationProperties.hyphenate == Constants.EN_TRUE) {
  713. // consider every hyphenation point as a legal break
  714. findHyphenationPoints(par);
  715. } else {
  716. // try with a higher threshold
  717. maxAdjustment = 5;
  718. }
  719. if (!findBreakingPoints(par, lineWidth, maxAdjustment, false)) {
  720. // the second try failed too, try with a huge threshold;
  721. // if this fails too, use a different algorithm
  722. log.debug("No set of breaking points found with maxAdjustment = " + maxAdjustment
  723. + (hyphenationProperties.hyphenate == Constants.EN_TRUE ? " and hyphenation" : ""));
  724. maxAdjustment = 20;
  725. if (!findBreakingPoints(par, lineWidth, maxAdjustment, true)) {
  726. log.debug("No set of breaking points found, using first-fit algorithm");
  727. }
  728. }
  729. }
  730. }
  731. private boolean findBreakingPoints(Paragraph par, int lineWidth,
  732. double threshold, boolean force) {
  733. KnuthParagraph knuthPara = new KnuthParagraph(par);
  734. int lines = knuthPara.findBreakPoints(lineWidth, threshold, force);
  735. if (lines == 0) {
  736. return false;
  737. }
  738. for (int i = lines-1; i >= 0; i--) {
  739. int line = i+1;
  740. if (log.isTraceEnabled()) {
  741. log.trace("Making line from " + knuthPara.getStart(i) + " to " +
  742. knuthPara.getEnd(i));
  743. }
  744. // compute indent and adjustment ratio, according to
  745. // the value of text-align and text-align-last
  746. int difference = knuthPara.getDifference(i);
  747. if (line == lines) {
  748. difference += par.lineFillerWidth;
  749. }
  750. int textAlign = (line < lines)
  751. ? textAlignment : textAlignmentLast;
  752. int indent = (textAlign == EN_CENTER)
  753. ? difference / 2
  754. : (textAlign == EN_END) ? difference : 0;
  755. indent += (line == 1 && knuthParagraphs.indexOf(par) == 0)
  756. ? textIndent.getValue(this) : 0;
  757. double ratio = (textAlign == EN_JUSTIFY)
  758. ? knuthPara.getAdjustRatio(i) : 0;
  759. int start = knuthPara.getStart(i);
  760. int end = knuthPara.getEnd(i);
  761. makeLineBreakPosition(par, start, end, 0, ratio, indent);
  762. }
  763. return true;
  764. }
  765. private void makeLineBreakPosition(Paragraph par,
  766. int firstElementIndex, int lastElementIndex,
  767. int insertIndex, double ratio, int indent) {
  768. // line height calculation
  769. int halfLeading = (lineHeight - lead - follow) / 2;
  770. // height above the main baseline
  771. int lineLead = lead + halfLeading;
  772. // maximum size of top and bottom alignment
  773. int lineFollow = follow + halfLeading;
  774. ListIterator inlineIterator
  775. = par.listIterator(firstElementIndex);
  776. for (int j = firstElementIndex;
  777. j <= lastElementIndex;
  778. j++) {
  779. KnuthElement element = (KnuthElement) inlineIterator.next();
  780. if (element.isBox()) {
  781. KnuthInlineBox box = (KnuthInlineBox)element;
  782. if (box.getLead() > lineLead) {
  783. lineLead = box.getLead();
  784. }
  785. if (box.getTotal() > lineFollow) {
  786. lineFollow = box.getTotal();
  787. }
  788. if (box.getMiddle() > lineLead + middleShift) {
  789. lineLead += box.getMiddle()
  790. - lineLead - middleShift;
  791. }
  792. if (box.getMiddle() > middlefollow - middleShift) {
  793. middlefollow += box.getMiddle()
  794. - middlefollow + middleShift;
  795. }
  796. }
  797. }
  798. if (lineFollow - lineLead > middlefollow) {
  799. middlefollow = lineFollow - lineLead;
  800. }
  801. breakpoints.add(insertIndex,
  802. new LineBreakPosition(this,
  803. knuthParagraphs.indexOf(par),
  804. lastElementIndex ,
  805. ratio, 0, indent,
  806. lineLead + middlefollow,
  807. lineLead));
  808. }*/
  809. /**
  810. * Phase 2 of Knuth algorithm: find optimal break points.
  811. * @param alignment alignment in BP direction of the paragraph
  812. * @param context the layout context
  813. * @return a list of Knuth elements representing broken lines
  814. */
  815. private LinkedList createLineBreaks(int alignment, LayoutContext context) {
  816. // find the optimal line breaking points for each paragraph
  817. ListIterator paragraphsIterator
  818. = knuthParagraphs.listIterator(knuthParagraphs.size());
  819. lineLayoutsList = new ArrayList(knuthParagraphs.size());
  820. LineLayoutPossibilities llPoss;
  821. while (paragraphsIterator.hasPrevious()) {
  822. KnuthSequence seq = (KnuthSequence) paragraphsIterator.previous();
  823. if (!seq.isInlineSequence()) {
  824. // This set of line layout possibilities does not matter;
  825. // we only need an entry in lineLayoutsList.
  826. llPoss = new LineLayoutPossibilities();
  827. } else {
  828. llPoss = findOptimalBreakingPoints(alignment, (Paragraph) seq);
  829. }
  830. lineLayoutsList.add(0, llPoss);
  831. }
  832. setFinished(true);
  833. //Post-process the line breaks found
  834. return postProcessLineBreaks(alignment, context);
  835. }
  836. /**
  837. * Fint the optimal linebreaks for a paragraph
  838. * @param alignment alignment of the paragraph
  839. * @param currPar the Paragraph for which the linebreaks are found
  840. * @return the line layout possibilities for the paragraph
  841. */
  842. private LineLayoutPossibilities findOptimalBreakingPoints(int alignment, Paragraph currPar) {
  843. // use the member lineLayouts, which is read by LineBreakingAlgorithm.updateData1 and 2
  844. lineLayouts = new LineLayoutPossibilities();
  845. double maxAdjustment = 1;
  846. int iBPcount = 0;
  847. LineBreakingAlgorithm alg = new LineBreakingAlgorithm(alignment,
  848. textAlignment, textAlignmentLast,
  849. textIndent.getValue(this), currPar.lineFiller.opt,
  850. lineHeight.getValue(this), lead, follow,
  851. (knuthParagraphs.indexOf(currPar) == 0),
  852. hyphenationLadderCount.getEnum() == EN_NO_LIMIT
  853. ? 0 : hyphenationLadderCount.getValue(),
  854. this);
  855. if (hyphenationProperties.hyphenate == EN_TRUE
  856. && fobj.getWrapOption() != EN_NO_WRAP) {
  857. findHyphenationPoints(currPar);
  858. }
  859. // first try
  860. int allowedBreaks;
  861. if (wrapOption == EN_NO_WRAP) {
  862. allowedBreaks = BreakingAlgorithm.ONLY_FORCED_BREAKS;
  863. } else {
  864. allowedBreaks = BreakingAlgorithm.NO_FLAGGED_PENALTIES;
  865. }
  866. alg.setConstantLineWidth(iLineWidth);
  867. iBPcount = alg.findBreakingPoints(currPar,
  868. maxAdjustment, false, allowedBreaks);
  869. if (iBPcount == 0 || alignment == EN_JUSTIFY) {
  870. // if the first try found a set of breaking points, save them
  871. if (iBPcount > 0) {
  872. alg.resetAlgorithm();
  873. lineLayouts.savePossibilities(false);
  874. } else {
  875. // the first try failed
  876. log.debug("No set of breaking points found with maxAdjustment = " + maxAdjustment);
  877. }
  878. // now try something different
  879. log.debug("Hyphenation possible? " + (hyphenationProperties.hyphenate == EN_TRUE));
  880. if (hyphenationProperties.hyphenate == EN_TRUE
  881. && !(allowedBreaks == BreakingAlgorithm.ONLY_FORCED_BREAKS)) {
  882. // consider every hyphenation point as a legal break
  883. allowedBreaks = BreakingAlgorithm.ALL_BREAKS;
  884. } else {
  885. // try with a higher threshold
  886. maxAdjustment = 5;
  887. }
  888. if ((iBPcount
  889. = alg.findBreakingPoints(currPar,
  890. maxAdjustment, false, allowedBreaks)) == 0) {
  891. // the second try failed too, try with a huge threshold
  892. // and force the algorithm to find
  893. // a set of breaking points
  894. log.debug("No set of breaking points found with maxAdjustment = "
  895. + maxAdjustment
  896. + (hyphenationProperties.hyphenate == EN_TRUE
  897. ? " and hyphenation" : ""));
  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. * @see org.apache.fop.layoutmgr.BlockLevelLayoutManager#mustKeepTogether
  1158. */
  1159. public boolean mustKeepTogether() {
  1160. return ((BlockLevelLayoutManager) getParent()).mustKeepTogether();
  1161. }
  1162. /**
  1163. * @see org.apache.fop.layoutmgr.BlockLevelLayoutManager#mustKeepWithPrevious
  1164. */
  1165. public boolean mustKeepWithPrevious() {
  1166. return false;
  1167. }
  1168. /**
  1169. * @see org.apache.fop.layoutmgr.BlockLevelLayoutManager#mustKeepWithNext
  1170. */
  1171. public boolean mustKeepWithNext() {
  1172. return false;
  1173. }
  1174. /**
  1175. * @see org.apache.fop.layoutmgr.BlockLevelLayoutManager#negotiateBPDAdjustment(int, org.apache.fop.layoutmgr.KnuthElement)
  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. * @see org.apache.fop.layoutmgr.BlockLevelLayoutManager#discardSpace(KnuthGlue)
  1194. */
  1195. public void discardSpace(KnuthGlue spaceGlue) {
  1196. }
  1197. /**
  1198. * @see org.apache.fop.layoutmgr.LayoutManager#getChangedKnuthElements(List, int)
  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. log.trace(" Word to hyphenate: " + sbChars.toString());
  1307. // find hyphenation points
  1308. HyphContext hc = getHyphenContext(sbChars);
  1309. // ask each LM to hyphenate its word fragment
  1310. if (hc != null) {
  1311. KnuthElement element = null;
  1312. for (int i = 0; i < (boxCount + auxCount); i++) {
  1313. currParIterator.previous();
  1314. }
  1315. for (int i = 0; i < (boxCount + auxCount); i++) {
  1316. element = (KnuthElement) currParIterator.next();
  1317. if (element.isBox() && !element.isAuxiliary()) {
  1318. ((InlineLevelLayoutManager)
  1319. element.getLayoutManager()).hyphenate(element.getPosition(), hc);
  1320. } else {
  1321. // nothing to do, element is an auxiliary KnuthElement
  1322. }
  1323. }
  1324. }
  1325. }
  1326. }
  1327. // create iterator for the updateList
  1328. ListIterator updateListIterator = updateList.listIterator();
  1329. Update currUpdate = null;
  1330. //int iPreservedElements = 0;
  1331. int iAddedElements = 0;
  1332. //int iRemovedElements = 0;
  1333. while (updateListIterator.hasNext()) {
  1334. // ask the LMs to apply the changes and return
  1335. // the new KnuthElements to replace the old ones
  1336. currUpdate = (Update) updateListIterator.next();
  1337. int fromIndex = currUpdate.iFirstIndex;
  1338. int toIndex;
  1339. if (updateListIterator.hasNext()) {
  1340. Update nextUpdate = (Update) updateListIterator.next();
  1341. toIndex = nextUpdate.iFirstIndex;
  1342. updateListIterator.previous();
  1343. } else {
  1344. // maybe this is not always correct!
  1345. toIndex = currPar.size() - currPar.ignoreAtEnd
  1346. - iAddedElements;
  1347. }
  1348. // applyChanges() returns true if the LM modifies its data,
  1349. // so it must return new KnuthElements to replace the old ones
  1350. if (((InlineLevelLayoutManager) currUpdate.inlineLM)
  1351. .applyChanges(currPar.subList(fromIndex + iAddedElements,
  1352. toIndex + iAddedElements))) {
  1353. // insert the new KnuthElements
  1354. LinkedList newElements = null;
  1355. newElements
  1356. = currUpdate.inlineLM.getChangedKnuthElements
  1357. (currPar.subList(fromIndex + iAddedElements,
  1358. toIndex + iAddedElements),
  1359. /*flaggedPenalty,*/ effectiveAlignment);
  1360. // remove the old elements
  1361. currPar.subList(fromIndex + iAddedElements,
  1362. toIndex + iAddedElements).clear();
  1363. // insert the new elements
  1364. currPar.addAll(fromIndex + iAddedElements, newElements);
  1365. iAddedElements += newElements.size() - (toIndex - fromIndex);
  1366. }
  1367. }
  1368. updateListIterator = null;
  1369. updateList.clear();
  1370. }
  1371. /**
  1372. * Line area is always considered to act as a fence.
  1373. * @param isNotFirst ignored
  1374. * @return always true
  1375. */
  1376. protected boolean hasLeadingFence(boolean isNotFirst) {
  1377. return true;
  1378. }
  1379. /**
  1380. * Line area is always considered to act as a fence.
  1381. * @param isNotLast ignored
  1382. * @return always true
  1383. */
  1384. protected boolean hasTrailingFence(boolean isNotLast) {
  1385. return true;
  1386. }
  1387. private HyphContext getHyphenContext(StringBuffer sbChars) {
  1388. // Find all hyphenation points in this word
  1389. // (get in an array of offsets)
  1390. // hyphenationProperties are from the block level?.
  1391. // Note that according to the spec,
  1392. // they also "apply to" fo:character.
  1393. // I don't know what that means, since
  1394. // if we change language in the middle of a "word",
  1395. // the effect would seem quite strange!
  1396. // Or perhaps in that case, we say that it's several words.
  1397. // We probably should bring the hyphenation props up from the actual
  1398. // TextLM which generate the hyphenation buffer,
  1399. // since these properties inherit and could be specified
  1400. // on an inline or wrapper below the block level.
  1401. Hyphenation hyph
  1402. = Hyphenator.hyphenate(hyphenationProperties.language,
  1403. hyphenationProperties.country,
  1404. getFObj().getUserAgent().getFactory().getHyphenationTreeResolver(),
  1405. sbChars.toString(),
  1406. hyphenationProperties.hyphenationRemainCharacterCount,
  1407. hyphenationProperties.hyphenationPushCharacterCount);
  1408. // They hyph structure contains the information we need
  1409. // Now start from prev: reset to that position, ask that LM to get
  1410. // a Position for the first hyphenation offset. If the offset isn't in
  1411. // its characters, it returns null,
  1412. // but must tell how many chars it had.
  1413. // Keep looking at currentBP using next hyphenation point until the
  1414. // returned size is greater than the available size
  1415. // or no more hyphenation points remain. Choose the best break.
  1416. if (hyph != null) {
  1417. return new HyphContext(hyph.getHyphenationPoints());
  1418. } else {
  1419. return null;
  1420. }
  1421. }
  1422. /**
  1423. * Reset the positions to the given position.
  1424. *
  1425. * @param resetPos the position to reset to
  1426. */
  1427. public void resetPosition(Position resetPos) {
  1428. if (resetPos == null) {
  1429. setFinished(false);
  1430. iReturnedLBP = 0;
  1431. } else {
  1432. if (isFinished()) {
  1433. // if isFinished is true, iReturned LBP == breakpoints.size()
  1434. // and breakpoints.get(iReturnedLBP) would generate
  1435. // an IndexOutOfBoundException
  1436. setFinished(false);
  1437. iReturnedLBP--;
  1438. }
  1439. // It is not clear that the member lineLayouts has the correct value;
  1440. // because the method is not called, this cannot be checked.
  1441. while ((LineBreakPosition) lineLayouts.getChosenPosition(iReturnedLBP)
  1442. != (LineBreakPosition) resetPos) {
  1443. iReturnedLBP--;
  1444. }
  1445. iReturnedLBP++;
  1446. }
  1447. }
  1448. /**
  1449. * Add the areas with the break points.
  1450. *
  1451. * @param parentIter the iterator of break positions
  1452. * @param context the context for adding areas
  1453. */
  1454. public void addAreas(PositionIterator parentIter,
  1455. LayoutContext context) {
  1456. while (parentIter.hasNext()) {
  1457. Position pos = (Position) parentIter.next();
  1458. boolean isLastPosition = !parentIter.hasNext();
  1459. if (pos instanceof LineBreakPosition) {
  1460. addInlineArea(context, pos, isLastPosition);
  1461. } else if ((pos instanceof NonLeafPosition) && pos.generatesAreas()) {
  1462. addBlockArea(context, pos, isLastPosition);
  1463. } else {
  1464. /*
  1465. * pos was the Position inside a penalty item, nothing to do;
  1466. * or Pos does not generate an area,
  1467. * i.e. it stand for spaces, borders and padding.
  1468. */
  1469. }
  1470. }
  1471. setCurrentArea(null); // ?? necessary
  1472. }
  1473. /**
  1474. * Add a line with inline content
  1475. * @param context the context for adding areas
  1476. * @param pos the position for which the line is generated
  1477. * @param isLastPosition true if this is the last position of this LM
  1478. */
  1479. private void addInlineArea(LayoutContext context, Position pos, boolean isLastPosition) {
  1480. ListIterator seqIterator = null;
  1481. KnuthElement tempElement = null;
  1482. // the TLM which created the last KnuthElement in this line
  1483. LayoutManager lastLM = null;
  1484. LineBreakPosition lbp = (LineBreakPosition) pos;
  1485. int iCurrParIndex;
  1486. iCurrParIndex = lbp.iParIndex;
  1487. KnuthSequence seq = (KnuthSequence) knuthParagraphs.get(iCurrParIndex);
  1488. int iStartElement = lbp.iStartIndex;
  1489. int iEndElement = lbp.getLeafPos();
  1490. LineArea lineArea
  1491. = new LineArea((lbp.getLeafPos() < seq.size() - 1
  1492. ? textAlignment : textAlignmentLast),
  1493. lbp.difference, lbp.availableStretch, lbp.availableShrink);
  1494. if (lbp.startIndent != 0) {
  1495. lineArea.addTrait(Trait.START_INDENT, new Integer(lbp.startIndent));
  1496. }
  1497. lineArea.setBPD(lbp.lineHeight);
  1498. lineArea.setIPD(lbp.lineWidth);
  1499. lineArea.addTrait(Trait.SPACE_BEFORE, new Integer(lbp.spaceBefore));
  1500. lineArea.addTrait(Trait.SPACE_AFTER, new Integer(lbp.spaceAfter));
  1501. alignmentContext.resizeLine(lbp.lineHeight, lbp.baseline);
  1502. if (seq instanceof Paragraph) {
  1503. Paragraph currPar = (Paragraph) seq;
  1504. // ignore the first elements added by the LineLayoutManager
  1505. iStartElement += (iStartElement == 0) ? currPar.ignoreAtStart : 0;
  1506. // if this is the last line area that for this paragraph,
  1507. // ignore the last elements added by the LineLayoutManager and
  1508. // subtract the last-line-end-indent from the area ipd
  1509. if (iEndElement == (currPar.size() - 1)) {
  1510. iEndElement -= currPar.ignoreAtEnd;
  1511. lineArea.setIPD(lineArea.getIPD() - lastLineEndIndent.getValue(this));
  1512. }
  1513. }
  1514. // Remove trailing spaces if allowed so
  1515. if (whiteSpaceTreament == EN_IGNORE_IF_SURROUNDING_LINEFEED
  1516. || whiteSpaceTreament == EN_IGNORE
  1517. || whiteSpaceTreament == EN_IGNORE_IF_BEFORE_LINEFEED) {
  1518. // ignore the last element in the line if it is a KnuthGlue object
  1519. seqIterator = seq.listIterator(iEndElement);
  1520. tempElement = (KnuthElement) seqIterator.next();
  1521. if (tempElement.isGlue()) {
  1522. iEndElement--;
  1523. // this returns the same KnuthElement
  1524. seqIterator.previous();
  1525. if (seqIterator.hasPrevious()) {
  1526. tempElement = (KnuthElement) seqIterator.previous();
  1527. } else {
  1528. tempElement = null;
  1529. }
  1530. }
  1531. if (tempElement != null) {
  1532. lastLM = tempElement.getLayoutManager();
  1533. }
  1534. }
  1535. // Remove leading spaces if allowed so
  1536. if (whiteSpaceTreament == EN_IGNORE_IF_SURROUNDING_LINEFEED
  1537. || whiteSpaceTreament == EN_IGNORE
  1538. || whiteSpaceTreament == EN_IGNORE_IF_AFTER_LINEFEED) {
  1539. // ignore KnuthGlue and KnuthPenalty objects
  1540. // at the beginning of the line
  1541. seqIterator = seq.listIterator(iStartElement);
  1542. tempElement = (KnuthElement) seqIterator.next();
  1543. while (!tempElement.isBox() && seqIterator.hasNext()) {
  1544. tempElement = (KnuthElement) seqIterator.next();
  1545. iStartElement++;
  1546. }
  1547. }
  1548. // Add the inline areas to lineArea
  1549. PositionIterator inlinePosIter
  1550. = new KnuthPossPosIter(seq, iStartElement, iEndElement + 1);
  1551. iStartElement = lbp.getLeafPos() + 1;
  1552. if (iStartElement == seq.size()) {
  1553. // advance to next paragraph
  1554. iStartElement = 0;
  1555. }
  1556. LayoutContext lc = new LayoutContext(0);
  1557. lc.setAlignmentContext(alignmentContext);
  1558. lc.setSpaceAdjust(lbp.dAdjust);
  1559. lc.setIPDAdjust(lbp.ipdAdjust);
  1560. lc.setLeadingSpace(new SpaceSpecifier(true));
  1561. lc.setTrailingSpace(new SpaceSpecifier(false));
  1562. lc.setFlags(LayoutContext.RESOLVE_LEADING_SPACE, true);
  1563. /*
  1564. * extension (not in the XSL FO recommendation): if the left and right margins
  1565. * have been optimized, recompute indents and / or adjust ratio, according
  1566. * to the paragraph horizontal alignment
  1567. */
  1568. if (false && textAlignment == EN_JUSTIFY) {
  1569. // re-compute space adjust ratio
  1570. int updatedDifference = context.getStackLimit().opt
  1571. - lbp.lineWidth + lbp.difference;
  1572. double updatedRatio = 0.0;
  1573. if (updatedDifference > 0) {
  1574. updatedRatio = (float) updatedDifference / lbp.availableStretch;
  1575. } else if (updatedDifference < 0) {
  1576. updatedRatio = (float) updatedDifference / lbp.availableShrink;
  1577. }
  1578. lc.setIPDAdjust(updatedRatio);
  1579. //log.debug("LLM.addAreas> old difference = " + lbp.difference + " new difference = " + updatedDifference);
  1580. //log.debug(" old ratio = " + lbp.ipdAdjust + " new ratio = " + updatedRatio);
  1581. } else if (false && textAlignment == EN_CENTER) {
  1582. // re-compute indent
  1583. int updatedIndent = lbp.startIndent
  1584. + (context.getStackLimit().opt - lbp.lineWidth) / 2;
  1585. lineArea.addTrait(Trait.START_INDENT, new Integer(updatedIndent));
  1586. } else if (false && textAlignment == EN_END) {
  1587. // re-compute indent
  1588. int updatedIndent = lbp.startIndent
  1589. + (context.getStackLimit().opt - lbp.lineWidth);
  1590. lineArea.addTrait(Trait.START_INDENT, new Integer(updatedIndent));
  1591. }
  1592. setCurrentArea(lineArea);
  1593. setChildContext(lc);
  1594. LayoutManager childLM;
  1595. while ((childLM = inlinePosIter.getNextChildLM()) != null) {
  1596. lc.setFlags(LayoutContext.LAST_AREA, (childLM == lastLM));
  1597. childLM.addAreas(inlinePosIter, lc);
  1598. lc.setLeadingSpace(lc.getTrailingSpace());
  1599. lc.setTrailingSpace(new SpaceSpecifier(false));
  1600. }
  1601. // when can this be null?
  1602. // if display-align is distribute, add space after
  1603. if (context.getSpaceAfter() > 0
  1604. && (!context.isLastArea() || !isLastPosition)) {
  1605. lineArea.setBPD(lineArea.getBPD() + context.getSpaceAfter());
  1606. }
  1607. lineArea.finalise();
  1608. parentLM.addChildArea(lineArea);
  1609. }
  1610. /**
  1611. * Add a line with block content
  1612. * @param context the context for adding areas
  1613. * @param pos the position for which the line is generated
  1614. * @param isLastPosition true if this is the last position of this LM
  1615. */
  1616. private void addBlockArea(LayoutContext context, Position pos, boolean isLastPosition) {
  1617. /* Nested block-level content;
  1618. * go down the LM stack again;
  1619. * "unwrap" the positions and put the child positions in a new list.
  1620. * The positionList must contain one area-generating position,
  1621. * which creates one line area.
  1622. */
  1623. List positionList = new ArrayList(1);
  1624. Position innerPosition;
  1625. innerPosition = ((NonLeafPosition) pos).getPosition();
  1626. positionList.add(innerPosition);
  1627. // do we have the last LM?
  1628. LayoutManager lastLM = null;
  1629. if (isLastPosition) {
  1630. lastLM = innerPosition.getLM();
  1631. }
  1632. LineArea lineArea = new LineArea();
  1633. setCurrentArea(lineArea);
  1634. LayoutContext lc = new LayoutContext(0);
  1635. lc.setAlignmentContext(alignmentContext);
  1636. setChildContext(lc);
  1637. PositionIterator childPosIter = new StackingIter(positionList.listIterator());
  1638. LayoutContext blocklc = new LayoutContext(0);
  1639. blocklc.setLeadingSpace(new SpaceSpecifier(true));
  1640. blocklc.setTrailingSpace(new SpaceSpecifier(false));
  1641. blocklc.setFlags(LayoutContext.RESOLVE_LEADING_SPACE, true);
  1642. LayoutManager childLM;
  1643. while ((childLM = childPosIter.getNextChildLM()) != null) {
  1644. // set last area flag
  1645. blocklc.setFlags(LayoutContext.LAST_AREA,
  1646. (context.isLastArea() && childLM == lastLM));
  1647. blocklc.setStackLimit(context.getStackLimit());
  1648. // Add the line areas to Area
  1649. childLM.addAreas(childPosIter, blocklc);
  1650. blocklc.setLeadingSpace(blocklc.getTrailingSpace());
  1651. blocklc.setTrailingSpace(new SpaceSpecifier(false));
  1652. }
  1653. lineArea.updateExtentsFromChildren();
  1654. parentLM.addChildArea(lineArea);
  1655. }
  1656. /**
  1657. * @see org.apache.fop.layoutmgr.LayoutManager#addChildArea(Area)
  1658. */
  1659. public void addChildArea(Area childArea) {
  1660. // Make sure childArea is inline area
  1661. if (childArea instanceof InlineArea) {
  1662. Area parent = getCurrentArea();
  1663. if (getContext().resolveLeadingSpace()) {
  1664. addSpace(parent,
  1665. getContext().getLeadingSpace().resolve(false),
  1666. getContext().getSpaceAdjust());
  1667. }
  1668. parent.addChildArea(childArea);
  1669. }
  1670. }
  1671. // --------- Property Resolution related functions --------- //
  1672. /**
  1673. * @see org.apache.fop.layoutmgr.LayoutManager#getGeneratesBlockArea
  1674. */
  1675. public boolean getGeneratesBlockArea() {
  1676. return true;
  1677. }
  1678. /**
  1679. * @see org.apache.fop.layoutmgr.LayoutManager#getGeneratesLineArea
  1680. */
  1681. public boolean getGeneratesLineArea() {
  1682. return true;
  1683. }
  1684. }