Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

block_bug39414.xml 83KB

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