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

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