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.

TextLayoutManager.java 63KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  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.Arrays;
  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.Trait;
  27. import org.apache.fop.area.inline.TextArea;
  28. import org.apache.fop.fo.Constants;
  29. import org.apache.fop.fo.FOText;
  30. import org.apache.fop.fonts.Font;
  31. import org.apache.fop.fonts.FontSelector;
  32. import org.apache.fop.fonts.GlyphMapping;
  33. import org.apache.fop.layoutmgr.InlineKnuthSequence;
  34. import org.apache.fop.layoutmgr.KnuthBox;
  35. import org.apache.fop.layoutmgr.KnuthElement;
  36. import org.apache.fop.layoutmgr.KnuthGlue;
  37. import org.apache.fop.layoutmgr.KnuthPenalty;
  38. import org.apache.fop.layoutmgr.KnuthSequence;
  39. import org.apache.fop.layoutmgr.LayoutContext;
  40. import org.apache.fop.layoutmgr.LeafPosition;
  41. import org.apache.fop.layoutmgr.Position;
  42. import org.apache.fop.layoutmgr.PositionIterator;
  43. import org.apache.fop.layoutmgr.TraitSetter;
  44. import org.apache.fop.text.linebreak.LineBreakStatus;
  45. import org.apache.fop.traits.MinOptMax;
  46. import org.apache.fop.traits.SpaceVal;
  47. import org.apache.fop.util.CharUtilities;
  48. import org.apache.fop.util.ListUtil;
  49. /**
  50. * LayoutManager for text (a sequence of characters) which generates one
  51. * or more inline areas.
  52. */
  53. public class TextLayoutManager extends LeafNodeLayoutManager {
  54. //TODO: remove all final modifiers at local variables
  55. // static final int SOFT_HYPHEN_PENALTY = KnuthPenalty.FLAGGED_PENALTY / 10;
  56. private static final int SOFT_HYPHEN_PENALTY = 1;
  57. /**
  58. * this class stores information about changes in vecAreaInfo which are not yet applied
  59. */
  60. private final class PendingChange {
  61. private final GlyphMapping mapping;
  62. private final int index;
  63. private PendingChange(final GlyphMapping mapping, final int index) {
  64. this.mapping = mapping;
  65. this.index = index;
  66. }
  67. }
  68. /**
  69. * logging instance
  70. */
  71. private static final Log LOG = LogFactory.getLog(TextLayoutManager.class);
  72. // Hold all possible breaks for the text in this LM's FO.
  73. private final List<GlyphMapping> mappings;
  74. /** Non-space characters on which we can end a line. */
  75. private static final String BREAK_CHARS = "-/";
  76. private final FOText foText;
  77. /**
  78. * Contains an array of widths to adjust for kerning. The first entry can
  79. * be used to influence the start position of the first letter. The entry i+1 defines the
  80. * cursor advancement after the character i. A null entry means no special advancement.
  81. */
  82. private final MinOptMax[] letterSpaceAdjustArray; //size = textArray.length + 1
  83. /** Font used for the space between words. */
  84. private Font spaceFont = null;
  85. /** Start index of next TextArea */
  86. private int nextStart = 0;
  87. /** size of a space character (U+0020) glyph in current font */
  88. private int spaceCharIPD;
  89. private MinOptMax wordSpaceIPD;
  90. private MinOptMax letterSpaceIPD;
  91. /** size of the hyphen character glyph in current font */
  92. private int hyphIPD;
  93. private boolean hasChanged = false;
  94. private int[] returnedIndices = {0, 0};
  95. private int changeOffset = 0;
  96. private int thisStart = 0;
  97. private int tempStart = 0;
  98. private List changeList = new LinkedList();
  99. private AlignmentContext alignmentContext = null;
  100. /**
  101. * The width to be reserved for border and padding at the start of the line.
  102. */
  103. private int lineStartBAP = 0;
  104. /**
  105. * The width to be reserved for border and padding at the end of the line.
  106. */
  107. private int lineEndBAP = 0;
  108. private boolean keepTogether;
  109. private final Position auxiliaryPosition = new LeafPosition(this, -1);
  110. /**
  111. * Create a Text layout manager.
  112. *
  113. * @param node The FOText object to be rendered
  114. */
  115. public TextLayoutManager(FOText node) {
  116. foText = node;
  117. letterSpaceAdjustArray = new MinOptMax[node.length() + 1];
  118. mappings = new ArrayList<GlyphMapping>();
  119. }
  120. private KnuthPenalty makeZeroWidthPenalty(int penaltyValue) {
  121. return new KnuthPenalty(0, penaltyValue, false, auxiliaryPosition, true);
  122. }
  123. private KnuthBox makeAuxiliaryZeroWidthBox() {
  124. return new KnuthInlineBox(0, null, notifyPos(new LeafPosition(this, -1)), true);
  125. }
  126. /** {@inheritDoc} */
  127. public void initialize() {
  128. foText.resetBuffer();
  129. spaceFont = FontSelector.selectFontForCharacterInText(' ', foText, this);
  130. // With CID fonts, space isn't necessary currentFontState.width(32)
  131. spaceCharIPD = spaceFont.getCharWidth(' ');
  132. // Use hyphenationChar property
  133. // TODO: Use hyphen based on actual font used!
  134. hyphIPD = foText.getCommonHyphenation().getHyphIPD(spaceFont);
  135. SpaceVal letterSpacing = SpaceVal.makeLetterSpacing(foText.getLetterSpacing());
  136. SpaceVal wordSpacing = SpaceVal.makeWordSpacing(foText.getWordSpacing(), letterSpacing,
  137. spaceFont);
  138. // letter space applies only to consecutive non-space characters,
  139. // while word space applies to space characters;
  140. // i.e. the spaces in the string "A SIMPLE TEST" are:
  141. // A<<ws>>S<ls>I<ls>M<ls>P<ls>L<ls>E<<ws>>T<ls>E<ls>S<ls>T
  142. // there is no letter space after the last character of a word,
  143. // nor after a space character
  144. // NOTE: The above is not quite correct. Read on in XSL 1.0, 7.16.2, letter-spacing
  145. // set letter space and word space dimension;
  146. // the default value "normal" was converted into a MinOptMax value
  147. // in the SpaceVal.makeWordSpacing() method
  148. letterSpaceIPD = letterSpacing.getSpace();
  149. wordSpaceIPD = MinOptMax.getInstance(spaceCharIPD).plus(wordSpacing.getSpace());
  150. keepTogether = foText.getKeepTogether().getWithinLine().getEnum() == Constants.EN_ALWAYS;
  151. }
  152. /**
  153. * Generate and add areas to parent area.
  154. * This can either generate an area for each TextArea and each space, or
  155. * an area containing all text with a parameter controlling the size of
  156. * the word space. The latter is most efficient for PDF generation.
  157. * Set size of each area.
  158. * @param posIter Iterator over Position information returned
  159. * by this LayoutManager.
  160. * @param context LayoutContext for adjustments
  161. */
  162. public void addAreas(final PositionIterator posIter, final LayoutContext context) {
  163. // Add word areas
  164. GlyphMapping mapping;
  165. int wordSpaceCount = 0;
  166. int letterSpaceCount = 0;
  167. int firstMappingIndex = -1;
  168. int lastMappingIndex = 0;
  169. MinOptMax realWidth = MinOptMax.ZERO;
  170. /* On first area created, add any leading space.
  171. * Calculate word-space stretch value.
  172. */
  173. GlyphMapping lastMapping = null;
  174. while (posIter.hasNext()) {
  175. final LeafPosition tbpNext = (LeafPosition) posIter.next();
  176. if (tbpNext == null) {
  177. continue; //Ignore elements without Positions
  178. }
  179. if (tbpNext.getLeafPos() != -1) {
  180. mapping = mappings.get(tbpNext.getLeafPos());
  181. if (lastMapping == null
  182. || (mapping.font != lastMapping.font)
  183. || (mapping.level != lastMapping.level)) {
  184. if (lastMapping != null) {
  185. addMappingAreas(lastMapping, wordSpaceCount,
  186. letterSpaceCount, firstMappingIndex,
  187. lastMappingIndex, realWidth, context);
  188. }
  189. firstMappingIndex = tbpNext.getLeafPos();
  190. wordSpaceCount = 0;
  191. letterSpaceCount = 0;
  192. realWidth = MinOptMax.ZERO;
  193. }
  194. wordSpaceCount += mapping.wordSpaceCount;
  195. letterSpaceCount += mapping.letterSpaceCount;
  196. realWidth = realWidth.plus(mapping.areaIPD);
  197. lastMappingIndex = tbpNext.getLeafPos();
  198. lastMapping = mapping;
  199. }
  200. }
  201. if (lastMapping != null) {
  202. addMappingAreas(lastMapping, wordSpaceCount, letterSpaceCount, firstMappingIndex,
  203. lastMappingIndex, realWidth, context);
  204. }
  205. }
  206. private void addMappingAreas(GlyphMapping mapping, int wordSpaceCount, int letterSpaceCount,
  207. int firstMappingIndex, int lastMappingIndex,
  208. MinOptMax realWidth, LayoutContext context) {
  209. // TODO: These two statements (if, for) were like this before my recent
  210. // changes. However, it seems as if they should use the GlyphMapping from
  211. // firstMappingIndex.. lastMappingIndex rather than just the last mapping.
  212. // This needs to be checked.
  213. int textLength = mapping.getWordLength();
  214. if (mapping.letterSpaceCount == textLength && !mapping.isHyphenated
  215. && context.isLastArea()) {
  216. // the line ends at a character like "/" or "-";
  217. // remove the letter space after the last character
  218. realWidth = realWidth.minus(letterSpaceIPD);
  219. letterSpaceCount--;
  220. }
  221. for (int i = mapping.startIndex; i < mapping.endIndex; i++) {
  222. MinOptMax letterSpaceAdjustment = letterSpaceAdjustArray[i + 1];
  223. if (letterSpaceAdjustment != null && letterSpaceAdjustment.isElastic()) {
  224. letterSpaceCount++;
  225. }
  226. }
  227. // add hyphenation character if the last word is hyphenated
  228. if (context.isLastArea() && mapping.isHyphenated) {
  229. realWidth = realWidth.plus(hyphIPD);
  230. }
  231. /* Calculate adjustments */
  232. double ipdAdjust = context.getIPDAdjust();
  233. // calculate total difference between real and available width
  234. int difference;
  235. if (ipdAdjust > 0.0) {
  236. difference = (int) (realWidth.getStretch() * ipdAdjust);
  237. } else {
  238. difference = (int) (realWidth.getShrink() * ipdAdjust);
  239. }
  240. // set letter space adjustment
  241. int letterSpaceDim = letterSpaceIPD.getOpt();
  242. if (ipdAdjust > 0.0) {
  243. letterSpaceDim += (int) (letterSpaceIPD.getStretch() * ipdAdjust);
  244. } else {
  245. letterSpaceDim += (int) (letterSpaceIPD.getShrink() * ipdAdjust);
  246. }
  247. int totalAdjust = (letterSpaceDim - letterSpaceIPD.getOpt()) * letterSpaceCount;
  248. // set word space adjustment
  249. int wordSpaceDim = wordSpaceIPD.getOpt();
  250. if (wordSpaceCount > 0) {
  251. wordSpaceDim += (difference - totalAdjust) / wordSpaceCount;
  252. }
  253. totalAdjust += (wordSpaceDim - wordSpaceIPD.getOpt()) * wordSpaceCount;
  254. if (totalAdjust != difference) {
  255. // the applied adjustment is greater or smaller than the needed one
  256. TextLayoutManager.LOG
  257. .trace("TextLM.addAreas: error in word / letter space adjustment = "
  258. + (totalAdjust - difference));
  259. // set totalAdjust = difference, so that the width of the TextArea
  260. // will counterbalance the error and the other inline areas will be
  261. // placed correctly
  262. totalAdjust = difference;
  263. }
  264. TextArea textArea = new TextAreaBuilder(realWidth, totalAdjust, context, firstMappingIndex,
  265. lastMappingIndex, context.isLastArea(), mapping.font).build();
  266. // wordSpaceDim is computed in relation to wordSpaceIPD.opt
  267. // but the renderer needs to know the adjustment in relation
  268. // to the size of the space character in the current font;
  269. // moreover, the pdf renderer adds the character spacing even to
  270. // the last character of a word and to space characters: in order
  271. // to avoid this, we must subtract the letter space width twice;
  272. // the renderer will compute the space width as:
  273. // space width =
  274. // = "normal" space width + letterSpaceAdjust + wordSpaceAdjust
  275. // = spaceCharIPD + letterSpaceAdjust +
  276. // + (wordSpaceDim - spaceCharIPD - 2 * letterSpaceAdjust)
  277. // = wordSpaceDim - letterSpaceAdjust
  278. textArea.setTextLetterSpaceAdjust(letterSpaceDim);
  279. textArea.setTextWordSpaceAdjust(wordSpaceDim - spaceCharIPD
  280. - 2 * textArea.getTextLetterSpaceAdjust());
  281. if (context.getIPDAdjust() != 0) {
  282. // add information about space width
  283. textArea.setSpaceDifference(wordSpaceIPD.getOpt() - spaceCharIPD
  284. - 2 * textArea.getTextLetterSpaceAdjust());
  285. }
  286. parentLayoutManager.addChildArea(textArea);
  287. }
  288. private final class TextAreaBuilder {
  289. // constructor initialized state
  290. private final MinOptMax width; // content ipd
  291. private final int adjust; // content ipd adjustment
  292. private final LayoutContext context; // layout context
  293. private final int firstIndex; // index of first GlyphMapping
  294. private final int lastIndex; // index of last GlyphMapping
  295. private final boolean isLastArea; // true if last inline area in line area
  296. private final Font font; // applicable font
  297. // other, non-constructor state
  298. private TextArea textArea; // text area being constructed
  299. private int blockProgressionDimension; // calculated bpd
  300. private GlyphMapping mapping; // current mapping when iterating over words
  301. private StringBuffer wordChars; // current word's character buffer
  302. private int[] letterSpaceAdjust; // current word's letter space adjustments
  303. private int letterSpaceAdjustIndex; // last written letter space adjustment index
  304. private int[] wordLevels; // current word's bidi levels
  305. private int wordLevelsIndex; // last written bidi level index
  306. private int wordIPD; // accumulated ipd of current word
  307. private int[][] gposAdjustments; // current word's glyph position adjustments
  308. private int gposAdjustmentsIndex; // last written glyph position adjustment index
  309. /**
  310. * Creates a new <code>TextAreaBuilder</code> which itself builds an inline word area. This
  311. * creates a TextArea and sets up the various attributes.
  312. *
  313. * @param width the MinOptMax width of the content
  314. * @param adjust the total ipd adjustment with respect to the optimal width
  315. * @param context the layout context
  316. * @param firstIndex the index of the first GlyphMapping used for the TextArea
  317. * @param lastIndex the index of the last GlyphMapping used for the TextArea
  318. * @param isLastArea is this TextArea the last in a line?
  319. * @param font Font to be used in this particular TextArea
  320. */
  321. private TextAreaBuilder(MinOptMax width, int adjust, LayoutContext context,
  322. int firstIndex, int lastIndex, boolean isLastArea, Font font) {
  323. this.width = width;
  324. this.adjust = adjust;
  325. this.context = context;
  326. this.firstIndex = firstIndex;
  327. this.lastIndex = lastIndex;
  328. this.isLastArea = isLastArea;
  329. this.font = font;
  330. }
  331. private TextArea build() {
  332. createTextArea();
  333. setInlineProgressionDimension();
  334. calcBlockProgressionDimension();
  335. setBlockProgressionDimension();
  336. setBaselineOffset();
  337. setBlockProgressionOffset();
  338. setText();
  339. TraitSetter.addFontTraits(textArea, font);
  340. textArea.addTrait(Trait.COLOR, foText.getColor());
  341. TraitSetter.addTextDecoration(textArea, foText.getTextDecoration());
  342. if (!context.treatAsArtifact()) {
  343. TraitSetter.addStructureTreeElement(textArea, foText.getStructureTreeElement());
  344. }
  345. return textArea;
  346. }
  347. /**
  348. * Creates an plain <code>TextArea</code> or a justified <code>TextArea</code> with
  349. * additional information.
  350. */
  351. private void createTextArea() {
  352. if (context.getIPDAdjust() == 0.0) {
  353. textArea = new TextArea();
  354. } else {
  355. textArea = new TextArea(width.getStretch(), width.getShrink(),
  356. adjust);
  357. }
  358. }
  359. private void setInlineProgressionDimension() {
  360. textArea.setIPD(width.getOpt() + adjust);
  361. }
  362. private void calcBlockProgressionDimension() {
  363. blockProgressionDimension = font.getAscender() - font.getDescender();
  364. }
  365. private void setBlockProgressionDimension() {
  366. textArea.setBPD(blockProgressionDimension);
  367. }
  368. private void setBaselineOffset() {
  369. textArea.setBaselineOffset(font.getAscender());
  370. }
  371. private void setBlockProgressionOffset() {
  372. if (blockProgressionDimension == alignmentContext.getHeight()) {
  373. textArea.setBlockProgressionOffset(0);
  374. } else {
  375. textArea.setBlockProgressionOffset(alignmentContext.getOffset());
  376. }
  377. }
  378. /**
  379. * Sets the text of the TextArea, split into words and spaces.
  380. */
  381. private void setText() {
  382. int mappingIndex = -1;
  383. int wordCharLength = 0;
  384. for (int wordIndex = firstIndex; wordIndex <= lastIndex; wordIndex++) {
  385. mapping = getGlyphMapping(wordIndex);
  386. if (mapping.isSpace) {
  387. addSpaces();
  388. } else {
  389. // mapping stores information about a word fragment
  390. if (mappingIndex == -1) {
  391. // here starts a new word
  392. mappingIndex = wordIndex;
  393. wordCharLength = 0;
  394. }
  395. wordCharLength += mapping.getWordLength();
  396. if (isWordEnd(wordIndex)) {
  397. addWord(mappingIndex, wordIndex, wordCharLength);
  398. mappingIndex = -1;
  399. }
  400. }
  401. }
  402. }
  403. private boolean isWordEnd(int mappingIndex) {
  404. return mappingIndex == lastIndex || getGlyphMapping(mappingIndex + 1).isSpace;
  405. }
  406. /**
  407. * Add word with fragments from STARTINDEX to ENDINDEX, where
  408. * total length of (possibly mapped) word is CHARLENGTH.
  409. * A word is composed from one or more word fragments, where each
  410. * fragment corresponds to distinct instance in a sequence of
  411. * area info instances starting at STARTINDEX continuing through (and
  412. * including) ENDINDEX.
  413. * @param startIndex index of first area info of word to add
  414. * @param endIndex index of last area info of word to add
  415. * @param wordLength number of (mapped) characters in word
  416. */
  417. private void addWord(int startIndex, int endIndex, int wordLength) {
  418. int blockProgressionOffset = 0;
  419. boolean gposAdjusted = false;
  420. if (isHyphenated(endIndex)) {
  421. // TODO may be problematic in some I18N contexts [GA]
  422. wordLength++;
  423. }
  424. initWord(wordLength);
  425. // iterate over word's fragments, adding word chars (with bidi
  426. // levels), letter space adjustments, and glyph position adjustments
  427. for (int i = startIndex; i <= endIndex; i++) {
  428. GlyphMapping wordMapping = getGlyphMapping(i);
  429. addWordChars(wordMapping);
  430. addLetterAdjust(wordMapping);
  431. if (addGlyphPositionAdjustments(wordMapping)) {
  432. gposAdjusted = true;
  433. }
  434. }
  435. if (isHyphenated(endIndex)) {
  436. // TODO may be problematic in some I18N contexts [GA]
  437. addHyphenationChar();
  438. }
  439. if (!gposAdjusted) {
  440. gposAdjustments = null;
  441. }
  442. textArea.addWord(wordChars.toString(), wordIPD, letterSpaceAdjust,
  443. getNonEmptyLevels(), gposAdjustments, blockProgressionOffset);
  444. }
  445. private int[] getNonEmptyLevels() {
  446. if (wordLevels != null) {
  447. assert wordLevelsIndex <= wordLevels.length;
  448. boolean empty = true;
  449. for (int i = 0, n = wordLevelsIndex; i < n; i++) {
  450. if (wordLevels [ i ] >= 0) {
  451. empty = false;
  452. break;
  453. }
  454. }
  455. return empty ? null : wordLevels;
  456. } else {
  457. return null;
  458. }
  459. }
  460. /**
  461. * Fully allocate word character buffer, letter space adjustments
  462. * array, bidi levels array, and glyph position adjustments array.
  463. * based on full word length, including all (possibly mapped) fragments.
  464. * @param wordLength length of word including all (possibly mapped) fragments
  465. */
  466. private void initWord(int wordLength) {
  467. wordChars = new StringBuffer(wordLength);
  468. letterSpaceAdjust = new int[wordLength];
  469. letterSpaceAdjustIndex = 0;
  470. wordLevels = new int[wordLength];
  471. wordLevelsIndex = 0;
  472. Arrays.fill(wordLevels, -1);
  473. gposAdjustments = new int[wordLength][4];
  474. gposAdjustmentsIndex = 0;
  475. wordIPD = 0;
  476. }
  477. private boolean isHyphenated(int endIndex) {
  478. return isLastArea && endIndex == lastIndex && mapping.isHyphenated;
  479. }
  480. private void addHyphenationChar() {
  481. wordChars.append(foText.getCommonHyphenation().getHyphChar(font));
  482. // [TBD] expand bidi word levels, letter space adjusts, gpos adjusts
  483. // [TBD] [GA] problematic in bidi context... what is level of hyphen?
  484. textArea.setHyphenated();
  485. }
  486. /**
  487. * Given a word area info associated with a word fragment,
  488. * (1) concatenate (possibly mapped) word characters to word character buffer;
  489. * (2) concatenante (possibly mapped) word bidi levels to levels buffer;
  490. * (3) update word's IPD with optimal IPD of fragment.
  491. * @param wordMapping fragment info
  492. */
  493. private void addWordChars(GlyphMapping wordMapping) {
  494. int s = wordMapping.startIndex;
  495. int e = wordMapping.endIndex;
  496. if (wordMapping.mapping != null) {
  497. wordChars.append(wordMapping.mapping);
  498. addWordLevels(getMappingBidiLevels(wordMapping));
  499. } else {
  500. for (int i = s; i < e; i++) {
  501. wordChars.append(foText.charAt(i));
  502. }
  503. addWordLevels(foText.getBidiLevels(s, e));
  504. }
  505. wordIPD += wordMapping.areaIPD.getOpt();
  506. }
  507. /**
  508. * Obtain bidirectional levels of mapping of characters over specific interval.
  509. * @param start index in character buffer
  510. * @param end index in character buffer
  511. * @return a (possibly empty) array of bidi levels or null
  512. * in case no bidi levels have been assigned
  513. */
  514. private int[] getMappingBidiLevels(GlyphMapping mapping) {
  515. if (mapping.mapping != null) {
  516. int nc = mapping.endIndex - mapping.startIndex;
  517. int nm = mapping.mapping.length();
  518. int[] la = foText.getBidiLevels(mapping.startIndex, mapping.endIndex);
  519. if (la == null) {
  520. return null;
  521. } else if (nm == nc) { // mapping is same length as mapped range
  522. return la;
  523. } else if (nm > nc) { // mapping is longer than mapped range
  524. int[] ma = new int[nm];
  525. System.arraycopy(la, 0, ma, 0, la.length);
  526. for (int i = la.length, n = ma.length, l = (i > 0) ? la[i - 1] : 0; i < n; i++) {
  527. ma[i] = l;
  528. }
  529. return ma;
  530. } else { // mapping is shorter than mapped range
  531. int[] ma = new int[nm];
  532. System.arraycopy(la, 0, ma, 0, ma.length);
  533. return ma;
  534. }
  535. } else {
  536. return foText.getBidiLevels(mapping.startIndex, mapping.endIndex);
  537. }
  538. }
  539. /**
  540. * Given a (possibly null) bidi levels array associated with a word fragment,
  541. * concatenante (possibly mapped) word bidi levels to levels buffer.
  542. * @param levels bidi levels array or null
  543. */
  544. private void addWordLevels(int[] levels) {
  545. int numLevels = (levels != null) ? levels.length : 0;
  546. if (numLevels > 0) {
  547. int need = wordLevelsIndex + numLevels;
  548. if (need <= wordLevels.length) {
  549. System.arraycopy(levels, 0, wordLevels, wordLevelsIndex, numLevels);
  550. } else {
  551. throw new IllegalStateException(
  552. "word levels array too short: expect at least "
  553. + need + " entries, but has only " + wordLevels.length + " entries");
  554. }
  555. }
  556. wordLevelsIndex += numLevels;
  557. }
  558. /**
  559. * Given a word area info associated with a word fragment,
  560. * concatenate letter space adjustments for each (possibly mapped) character.
  561. * @param wordMapping fragment info
  562. */
  563. private void addLetterAdjust(GlyphMapping wordMapping) {
  564. int letterSpaceCount = wordMapping.letterSpaceCount;
  565. int wordLength = wordMapping.getWordLength();
  566. int taAdjust = textArea.getTextLetterSpaceAdjust();
  567. for (int i = 0, n = wordLength; i < n; i++) {
  568. int j = letterSpaceAdjustIndex + i;
  569. if (j > 0) {
  570. int k = wordMapping.startIndex + i;
  571. MinOptMax adj = (k < letterSpaceAdjustArray.length)
  572. ? letterSpaceAdjustArray [ k ] : null;
  573. letterSpaceAdjust [ j ] = (adj == null) ? 0 : adj.getOpt();
  574. }
  575. if (letterSpaceCount > 0) {
  576. letterSpaceAdjust [ j ] += taAdjust;
  577. letterSpaceCount--;
  578. }
  579. }
  580. letterSpaceAdjustIndex += wordLength;
  581. }
  582. /**
  583. * Given a word area info associated with a word fragment,
  584. * concatenate glyph position adjustments for each (possibly mapped) character.
  585. * @param wordMapping fragment info
  586. * @return true if an adjustment was non-zero
  587. */
  588. private boolean addGlyphPositionAdjustments(GlyphMapping wordMapping) {
  589. boolean adjusted = false;
  590. int[][] gpa = wordMapping.gposAdjustments;
  591. int numAdjusts = (gpa != null) ? gpa.length : 0;
  592. int wordLength = wordMapping.getWordLength();
  593. if (numAdjusts > 0) {
  594. int need = gposAdjustmentsIndex + numAdjusts;
  595. if (need <= gposAdjustments.length) {
  596. for (int i = 0, n = wordLength, j = 0; i < n; i++) {
  597. if (i < numAdjusts) {
  598. int[] wpa1 = gposAdjustments [ gposAdjustmentsIndex + i ];
  599. int[] wpa2 = gpa [ j++ ];
  600. for (int k = 0; k < 4; k++) {
  601. int a = wpa2 [ k ];
  602. if (a != 0) {
  603. wpa1 [ k ] += a;
  604. adjusted = true;
  605. }
  606. }
  607. }
  608. }
  609. } else {
  610. throw new IllegalStateException(
  611. "gpos adjustments array too short: expect at least "
  612. + need + " entries, but has only " + gposAdjustments.length
  613. + " entries");
  614. }
  615. }
  616. gposAdjustmentsIndex += wordLength;
  617. return adjusted;
  618. }
  619. /**
  620. * The <code>GlyphMapping</code> stores information about spaces.
  621. * <p/>
  622. * Add the spaces - except zero-width spaces - to the TextArea.
  623. */
  624. private void addSpaces() {
  625. int blockProgressionOffset = 0;
  626. // [TBD] need to better handling of spaceIPD assignment, for now,
  627. // divide the area info's allocated IPD evenly among the
  628. // non-zero-width space characters
  629. int numZeroWidthSpaces = 0;
  630. for (int i = mapping.startIndex; i < mapping.endIndex; i++) {
  631. char spaceChar = foText.charAt(i);
  632. if (CharUtilities.isZeroWidthSpace(spaceChar)) {
  633. numZeroWidthSpaces++;
  634. }
  635. }
  636. int numSpaces = mapping.endIndex - mapping.startIndex - numZeroWidthSpaces;
  637. int spaceIPD = mapping.areaIPD.getOpt() / ((numSpaces > 0) ? numSpaces : 1);
  638. // add space area children, one for each non-zero-width space character
  639. for (int i = mapping.startIndex; i < mapping.endIndex; i++) {
  640. char spaceChar = foText.charAt(i);
  641. int level = foText.bidiLevelAt(i);
  642. if (!CharUtilities.isZeroWidthSpace(spaceChar)) {
  643. textArea.addSpace(
  644. spaceChar, spaceIPD,
  645. CharUtilities.isAdjustableSpace(spaceChar),
  646. blockProgressionOffset, level);
  647. }
  648. }
  649. }
  650. }
  651. private void addGlyphMapping(GlyphMapping mapping) {
  652. addGlyphMapping(mappings.size(), mapping);
  653. }
  654. private void addGlyphMapping(int index, GlyphMapping mapping) {
  655. mappings.add(index, mapping);
  656. }
  657. private void removeGlyphMapping(int index) {
  658. mappings.remove(index);
  659. }
  660. private GlyphMapping getGlyphMapping(int index) {
  661. return mappings.get(index);
  662. }
  663. /** {@inheritDoc} */
  664. public List getNextKnuthElements(final LayoutContext context, final int alignment) {
  665. lineStartBAP = context.getLineStartBorderAndPaddingWidth();
  666. lineEndBAP = context.getLineEndBorderAndPaddingWidth();
  667. alignmentContext = context.getAlignmentContext();
  668. final List returnList = new LinkedList();
  669. KnuthSequence sequence = new InlineKnuthSequence();
  670. GlyphMapping mapping = null;
  671. GlyphMapping prevMapping = null;
  672. returnList.add(sequence);
  673. if (LOG.isDebugEnabled()) {
  674. LOG.debug("GK: [" + nextStart + "," + foText.length() + "]");
  675. }
  676. LineBreakStatus lineBreakStatus = new LineBreakStatus();
  677. thisStart = nextStart;
  678. boolean inWord = false;
  679. boolean inWhitespace = false;
  680. char ch = 0;
  681. int level = -1;
  682. int prevLevel = -1;
  683. while (nextStart < foText.length()) {
  684. ch = foText.charAt(nextStart);
  685. level = foText.bidiLevelAt(nextStart);
  686. boolean breakOpportunity = false;
  687. byte breakAction = keepTogether
  688. ? LineBreakStatus.PROHIBITED_BREAK
  689. : lineBreakStatus.nextChar(ch);
  690. switch (breakAction) {
  691. case LineBreakStatus.COMBINING_PROHIBITED_BREAK:
  692. case LineBreakStatus.PROHIBITED_BREAK:
  693. break;
  694. case LineBreakStatus.EXPLICIT_BREAK:
  695. break;
  696. case LineBreakStatus.COMBINING_INDIRECT_BREAK:
  697. case LineBreakStatus.DIRECT_BREAK:
  698. case LineBreakStatus.INDIRECT_BREAK:
  699. breakOpportunity = true;
  700. break;
  701. default:
  702. TextLayoutManager.LOG.error("Unexpected breakAction: " + breakAction);
  703. }
  704. if (LOG.isDebugEnabled()) {
  705. LOG.debug("GK: {"
  706. + " index = " + nextStart
  707. + ", char = " + CharUtilities.charToNCRef(ch)
  708. + ", level = " + level
  709. + ", levelPrev = " + prevLevel
  710. + ", inWord = " + inWord
  711. + ", inSpace = " + inWhitespace
  712. + "}");
  713. }
  714. if (inWord) {
  715. if (breakOpportunity
  716. || GlyphMapping.isSpace(ch)
  717. || CharUtilities.isExplicitBreak(ch)
  718. || ((prevLevel != -1) && (level != prevLevel))) {
  719. // this.foText.charAt(lastIndex) == CharUtilities.SOFT_HYPHEN
  720. prevMapping = processWord(alignment, sequence, prevMapping, ch,
  721. breakOpportunity, true, prevLevel);
  722. }
  723. } else if (inWhitespace) {
  724. if (ch != CharUtilities.SPACE || breakOpportunity) {
  725. prevMapping = processWhitespace(alignment, sequence,
  726. breakOpportunity, prevLevel);
  727. }
  728. } else {
  729. if (mapping != null) {
  730. prevMapping = mapping;
  731. processLeftoverGlyphMapping(alignment, sequence, mapping,
  732. ch == CharUtilities.SPACE || breakOpportunity);
  733. mapping = null;
  734. }
  735. if (breakAction == LineBreakStatus.EXPLICIT_BREAK) {
  736. sequence = processLinebreak(returnList, sequence);
  737. }
  738. }
  739. if (ch == CharUtilities.SPACE
  740. && foText.getWhitespaceTreatment() == Constants.EN_PRESERVE
  741. || ch == CharUtilities.NBSPACE) {
  742. final Font font = FontSelector.selectFontForCharacterInText(ch,
  743. this.foText, this);
  744. font.mapChar(ch);
  745. // preserved space or non-breaking space:
  746. // create the GlyphMapping object
  747. mapping = new GlyphMapping(nextStart, nextStart + 1, 1, 0, wordSpaceIPD, false, true,
  748. breakOpportunity, spaceFont, level, null);
  749. thisStart = nextStart + 1;
  750. } else if (CharUtilities.isFixedWidthSpace(ch) || CharUtilities.isZeroWidthSpace(ch)) {
  751. // create the GlyphMapping object
  752. Font font = FontSelector.selectFontForCharacterInText(ch, foText, this);
  753. MinOptMax ipd = MinOptMax.getInstance(font.getCharWidth(ch));
  754. mapping = new GlyphMapping(nextStart, nextStart + 1, 0, 0, ipd, false, true,
  755. breakOpportunity, font, level, null);
  756. thisStart = nextStart + 1;
  757. } else if (CharUtilities.isExplicitBreak(ch)) {
  758. //mandatory break-character: only advance index
  759. thisStart = nextStart + 1;
  760. }
  761. inWord = !GlyphMapping.isSpace(ch) && !CharUtilities.isExplicitBreak(ch);
  762. inWhitespace = ch == CharUtilities.SPACE
  763. && foText.getWhitespaceTreatment() != Constants.EN_PRESERVE;
  764. prevLevel = level;
  765. nextStart++;
  766. }
  767. // Process any last elements
  768. if (inWord) {
  769. processWord(alignment, sequence, prevMapping, ch, false, false, prevLevel);
  770. } else if (inWhitespace) {
  771. processWhitespace(alignment, sequence, !keepTogether, prevLevel);
  772. } else if (mapping != null) {
  773. processLeftoverGlyphMapping(alignment, sequence, mapping,
  774. ch == CharUtilities.ZERO_WIDTH_SPACE);
  775. } else if (CharUtilities.isExplicitBreak(ch)) {
  776. this.processLinebreak(returnList, sequence);
  777. }
  778. if (((List) ListUtil.getLast(returnList)).isEmpty()) {
  779. //Remove an empty sequence because of a trailing newline
  780. ListUtil.removeLast(returnList);
  781. }
  782. setFinished(true);
  783. if (returnList.isEmpty()) {
  784. return null;
  785. } else {
  786. return returnList;
  787. }
  788. }
  789. private KnuthSequence processLinebreak(List returnList, KnuthSequence sequence) {
  790. if (lineEndBAP != 0) {
  791. sequence.add(new KnuthGlue(lineEndBAP, 0, 0, auxiliaryPosition, true));
  792. }
  793. sequence.endSequence();
  794. sequence = new InlineKnuthSequence();
  795. returnList.add(sequence);
  796. return sequence;
  797. }
  798. private void processLeftoverGlyphMapping(int alignment, KnuthSequence sequence,
  799. GlyphMapping mapping, boolean breakOpportunityAfter) {
  800. addGlyphMapping(mapping);
  801. mapping.breakOppAfter = breakOpportunityAfter;
  802. addElementsForASpace(sequence, alignment, mapping, mappings.size() - 1);
  803. }
  804. private GlyphMapping processWhitespace(final int alignment,
  805. final KnuthSequence sequence, final boolean breakOpportunity, int level) {
  806. if (LOG.isDebugEnabled()) {
  807. LOG.debug("PS: [" + thisStart + "," + nextStart + "]");
  808. }
  809. // End of whitespace
  810. // create the GlyphMapping object
  811. assert nextStart >= thisStart;
  812. GlyphMapping mapping = new GlyphMapping(
  813. thisStart, nextStart, nextStart - thisStart, 0,
  814. wordSpaceIPD.mult(nextStart - thisStart),
  815. false, true, breakOpportunity, spaceFont, level, null);
  816. addGlyphMapping(mapping);
  817. // create the elements
  818. addElementsForASpace(sequence, alignment, mapping, mappings.size() - 1);
  819. thisStart = nextStart;
  820. return mapping;
  821. }
  822. private GlyphMapping processWord(final int alignment, final KnuthSequence sequence,
  823. GlyphMapping prevMapping, final char ch, final boolean breakOpportunity,
  824. final boolean checkEndsWithHyphen, int level) {
  825. //Word boundary found, process widths and kerning
  826. int lastIndex = nextStart;
  827. while (lastIndex > 0 && foText.charAt(lastIndex - 1) == CharUtilities.SOFT_HYPHEN) {
  828. lastIndex--;
  829. }
  830. final boolean endsWithHyphen = checkEndsWithHyphen
  831. && foText.charAt(lastIndex) == CharUtilities.SOFT_HYPHEN;
  832. Font font = FontSelector.selectFontForCharactersInText(
  833. foText, thisStart, lastIndex, foText, this);
  834. char breakOpportunityChar = breakOpportunity ? ch : 0;
  835. char precedingChar = prevMapping != null && !prevMapping.isSpace
  836. && prevMapping.endIndex > 0 ? foText.charAt(prevMapping.endIndex - 1) : 0;
  837. GlyphMapping mapping = GlyphMapping.doGlyphMapping(foText, thisStart, lastIndex, font,
  838. letterSpaceIPD, letterSpaceAdjustArray, precedingChar, breakOpportunityChar, endsWithHyphen, level);
  839. prevMapping = mapping;
  840. addGlyphMapping(mapping);
  841. tempStart = nextStart;
  842. //add the elements
  843. addElementsForAWordFragment(sequence, alignment, mapping, mappings.size() - 1);
  844. thisStart = nextStart;
  845. return prevMapping;
  846. }
  847. /** {@inheritDoc} */
  848. public List addALetterSpaceTo(List oldList) {
  849. return addALetterSpaceTo(oldList, 0);
  850. }
  851. /** {@inheritDoc} */
  852. public List addALetterSpaceTo(final List oldList, int depth) {
  853. // old list contains only a box, or the sequence: box penalty glue box;
  854. // look at the Position stored in the first element in oldList
  855. // which is always a box
  856. ListIterator oldListIterator = oldList.listIterator();
  857. KnuthElement knuthElement = (KnuthElement) oldListIterator.next();
  858. Position pos = knuthElement.getPosition();
  859. LeafPosition leafPos = (LeafPosition) pos.getPosition(depth);
  860. int index = leafPos.getLeafPos();
  861. //element could refer to '-1' position, for non-collapsed spaces (?)
  862. if (index > -1) {
  863. GlyphMapping mapping = getGlyphMapping(index);
  864. mapping.letterSpaceCount++;
  865. mapping.addToAreaIPD(letterSpaceIPD);
  866. if (TextLayoutManager.BREAK_CHARS.indexOf(foText.charAt(tempStart - 1)) >= 0) {
  867. // the last character could be used as a line break
  868. // append new elements to oldList
  869. oldListIterator = oldList.listIterator(oldList.size());
  870. oldListIterator.add(new KnuthPenalty(0, KnuthPenalty.FLAGGED_PENALTY, true,
  871. auxiliaryPosition, false));
  872. oldListIterator.add(new KnuthGlue(letterSpaceIPD, auxiliaryPosition, false));
  873. } else if (letterSpaceIPD.isStiff()) {
  874. // constant letter space: replace the box
  875. // give it the unwrapped position of the replaced element
  876. oldListIterator.set(new KnuthInlineBox(mapping.areaIPD.getOpt(),
  877. alignmentContext, pos, false));
  878. } else {
  879. // adjustable letter space: replace the glue
  880. oldListIterator.next(); // this would return the penalty element
  881. oldListIterator.next(); // this would return the glue element
  882. oldListIterator.set(new KnuthGlue(letterSpaceIPD.mult(mapping.letterSpaceCount),
  883. auxiliaryPosition, true));
  884. }
  885. }
  886. return oldList;
  887. }
  888. /** {@inheritDoc} */
  889. public void hyphenate(Position pos, HyphContext hyphContext) {
  890. GlyphMapping mapping = getGlyphMapping(((LeafPosition) pos).getLeafPos() + changeOffset);
  891. int startIndex = mapping.startIndex;
  892. int stopIndex;
  893. boolean nothingChanged = true;
  894. Font font = mapping.font;
  895. while (startIndex < mapping.endIndex) {
  896. MinOptMax newIPD = MinOptMax.ZERO;
  897. boolean hyphenFollows;
  898. stopIndex = startIndex + hyphContext.getNextHyphPoint();
  899. if (hyphContext.hasMoreHyphPoints() && stopIndex <= mapping.endIndex) {
  900. // stopIndex is the index of the first character
  901. // after a hyphenation point
  902. hyphenFollows = true;
  903. } else {
  904. // there are no more hyphenation points,
  905. // or the next one is after mapping.breakIndex
  906. hyphenFollows = false;
  907. stopIndex = mapping.endIndex;
  908. }
  909. hyphContext.updateOffset(stopIndex - startIndex);
  910. //log.info("Word: " + new String(textArray, startIndex, stopIndex - startIndex));
  911. for (int i = startIndex; i < stopIndex; i++) {
  912. char ch = foText.charAt(i);
  913. newIPD = newIPD.plus(font.getCharWidth(ch));
  914. //if (i > startIndex) {
  915. if (i < stopIndex) {
  916. MinOptMax letterSpaceAdjust = letterSpaceAdjustArray[i + 1];
  917. if (i == stopIndex - 1 && hyphenFollows) {
  918. //the letter adjust here needs to be handled further down during
  919. //element generation because it depends on hyph/no-hyph condition
  920. letterSpaceAdjust = null;
  921. }
  922. if (letterSpaceAdjust != null) {
  923. newIPD = newIPD.plus(letterSpaceAdjust);
  924. }
  925. }
  926. }
  927. // add letter spaces
  928. boolean isWordEnd
  929. = (stopIndex == mapping.endIndex)
  930. && (mapping.letterSpaceCount < mapping.getWordLength());
  931. int letterSpaceCount = isWordEnd ? stopIndex - startIndex - 1 : stopIndex - startIndex;
  932. assert letterSpaceCount >= 0;
  933. newIPD = newIPD.plus(letterSpaceIPD.mult(letterSpaceCount));
  934. if (!(nothingChanged && stopIndex == mapping.endIndex && !hyphenFollows)) {
  935. // the new GlyphMapping object is not equal to the old one
  936. changeList.add(
  937. new PendingChange(
  938. new GlyphMapping(startIndex, stopIndex, 0,
  939. letterSpaceCount, newIPD, hyphenFollows,
  940. false, false, font, -1, null),
  941. ((LeafPosition) pos).getLeafPos() + changeOffset));
  942. nothingChanged = false;
  943. }
  944. startIndex = stopIndex;
  945. }
  946. hasChanged |= !nothingChanged;
  947. }
  948. /** {@inheritDoc} */
  949. public boolean applyChanges(final List oldList) {
  950. return applyChanges(oldList, 0);
  951. }
  952. /** {@inheritDoc} */
  953. public boolean applyChanges(final List oldList, int depth) {
  954. // make sure the LM appears unfinished in between this call
  955. // and the next call to getChangedKnuthElements()
  956. setFinished(false);
  957. if (oldList.isEmpty()) {
  958. return false;
  959. }
  960. // Find the first and last positions in oldList that point to a GlyphMapping
  961. // (i.e. getLeafPos() != -1)
  962. LeafPosition startPos = null;
  963. LeafPosition endPos = null;
  964. ListIterator oldListIter;
  965. for (oldListIter = oldList.listIterator(); oldListIter.hasNext();) {
  966. Position pos = ((KnuthElement) oldListIter.next()).getPosition();
  967. startPos = (LeafPosition) pos.getPosition(depth);
  968. if (startPos != null && startPos.getLeafPos() != -1) {
  969. break;
  970. }
  971. }
  972. for (oldListIter = oldList.listIterator(oldList.size()); oldListIter.hasPrevious();) {
  973. Position pos = ((KnuthElement) oldListIter.previous()).getPosition();
  974. endPos = (LeafPosition) pos.getPosition(depth);
  975. if (endPos != null && endPos.getLeafPos() != -1) {
  976. break;
  977. }
  978. }
  979. // set start/end index, taking into account any offset due to
  980. // changes applied to previous paragraphs
  981. returnedIndices[0] = (startPos != null ? startPos.getLeafPos() : -1) + changeOffset;
  982. returnedIndices[1] = (endPos != null ? endPos.getLeafPos() : -1) + changeOffset;
  983. int mappingsAdded = 0;
  984. int mappingsRemoved = 0;
  985. if (!changeList.isEmpty()) {
  986. int oldIndex = -1;
  987. int changeIndex;
  988. PendingChange currChange;
  989. ListIterator changeListIterator = changeList.listIterator();
  990. while (changeListIterator.hasNext()) {
  991. currChange = (PendingChange) changeListIterator.next();
  992. if (currChange.index == oldIndex) {
  993. mappingsAdded++;
  994. changeIndex = currChange.index + mappingsAdded - mappingsRemoved;
  995. } else {
  996. mappingsRemoved++;
  997. mappingsAdded++;
  998. oldIndex = currChange.index;
  999. changeIndex = currChange.index + mappingsAdded - mappingsRemoved;
  1000. removeGlyphMapping(changeIndex);
  1001. }
  1002. addGlyphMapping(changeIndex, currChange.mapping);
  1003. }
  1004. changeList.clear();
  1005. }
  1006. // increase the end index for getChangedKnuthElements()
  1007. returnedIndices[1] += (mappingsAdded - mappingsRemoved);
  1008. // increase offset to use for subsequent paragraphs
  1009. changeOffset += (mappingsAdded - mappingsRemoved);
  1010. return hasChanged;
  1011. }
  1012. /** {@inheritDoc} */
  1013. public List getChangedKnuthElements(final List oldList, final int alignment) {
  1014. if (isFinished()) {
  1015. return null;
  1016. }
  1017. final LinkedList returnList = new LinkedList();
  1018. for (; returnedIndices[0] <= returnedIndices[1]; returnedIndices[0]++) {
  1019. GlyphMapping mapping = getGlyphMapping(returnedIndices[0]);
  1020. if (mapping.wordSpaceCount == 0) {
  1021. // mapping refers either to a word or a word fragment
  1022. addElementsForAWordFragment(returnList, alignment, mapping, returnedIndices[0]);
  1023. } else {
  1024. // mapping refers to a space
  1025. addElementsForASpace(returnList, alignment, mapping, returnedIndices[0]);
  1026. }
  1027. }
  1028. setFinished(returnedIndices[0] == mappings.size() - 1);
  1029. //ElementListObserver.observe(returnList, "text-changed", null);
  1030. return returnList;
  1031. }
  1032. /** {@inheritDoc} */
  1033. public String getWordChars(Position pos) {
  1034. int leafValue = ((LeafPosition) pos).getLeafPos() + changeOffset;
  1035. if (leafValue != -1) {
  1036. GlyphMapping mapping = getGlyphMapping(leafValue);
  1037. StringBuffer buffer = new StringBuffer(mapping.getWordLength());
  1038. for (int i = mapping.startIndex; i < mapping.endIndex; i++) {
  1039. buffer.append(foText.charAt(i));
  1040. }
  1041. return buffer.toString();
  1042. } else {
  1043. return "";
  1044. }
  1045. }
  1046. private void addElementsForASpace(List baseList, int alignment, GlyphMapping mapping,
  1047. int leafValue) {
  1048. LeafPosition mainPosition = new LeafPosition(this, leafValue);
  1049. if (!mapping.breakOppAfter) {
  1050. // a non-breaking space
  1051. if (alignment == Constants.EN_JUSTIFY) {
  1052. // the space can stretch and shrink, and must be preserved
  1053. // when starting a line
  1054. baseList.add(makeAuxiliaryZeroWidthBox());
  1055. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1056. baseList.add(new KnuthGlue(mapping.areaIPD, mainPosition, false));
  1057. } else {
  1058. // the space does not need to stretch or shrink, and must be
  1059. // preserved when starting a line
  1060. baseList.add(new KnuthInlineBox(mapping.areaIPD.getOpt(), null, mainPosition,
  1061. true));
  1062. }
  1063. } else {
  1064. if (foText.charAt(mapping.startIndex) != CharUtilities.SPACE
  1065. || foText.getWhitespaceTreatment() == Constants.EN_PRESERVE) {
  1066. // a breaking space that needs to be preserved
  1067. baseList.addAll(getElementsForBreakingSpace(alignment, mapping, auxiliaryPosition, 0,
  1068. mainPosition, mapping.areaIPD.getOpt(), true));
  1069. } else {
  1070. // a (possible block) of breaking spaces
  1071. baseList.addAll(getElementsForBreakingSpace(alignment, mapping, mainPosition,
  1072. mapping.areaIPD.getOpt(), auxiliaryPosition, 0, false));
  1073. }
  1074. }
  1075. }
  1076. private List getElementsForBreakingSpace(int alignment, GlyphMapping mapping, Position pos2,
  1077. int p2WidthOffset, Position pos3,
  1078. int p3WidthOffset, boolean skipZeroCheck) {
  1079. List elements = new ArrayList();
  1080. switch (alignment) {
  1081. case EN_CENTER:
  1082. // centered text:
  1083. // if the second element is chosen as a line break these elements
  1084. // add a constant amount of stretch at the end of a line and at the
  1085. // beginning of the next one, otherwise they don't add any stretch
  1086. elements.add(new KnuthGlue(lineEndBAP, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1087. auxiliaryPosition, false));
  1088. elements.add(makeZeroWidthPenalty(0));
  1089. elements.add(new KnuthGlue(p2WidthOffset - (lineStartBAP + lineEndBAP), -6
  1090. * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos2, false));
  1091. elements.add(makeAuxiliaryZeroWidthBox());
  1092. elements.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1093. elements.add(new KnuthGlue(lineStartBAP + p3WidthOffset,
  1094. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos3, false));
  1095. break;
  1096. case EN_START: // fall through
  1097. case EN_END:
  1098. // left- or right-aligned text:
  1099. // if the second element is chosen as a line break these elements
  1100. // add a constant amount of stretch at the end of a line, otherwise
  1101. // they don't add any stretch
  1102. KnuthGlue g;
  1103. if (skipZeroCheck || lineStartBAP != 0 || lineEndBAP != 0) {
  1104. g = new KnuthGlue(
  1105. lineEndBAP,
  1106. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, auxiliaryPosition, false);
  1107. elements.add(g);
  1108. elements.add(makeZeroWidthPenalty(0));
  1109. g = new KnuthGlue(
  1110. p2WidthOffset - (lineStartBAP + lineEndBAP),
  1111. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos2, false);
  1112. elements.add(g);
  1113. elements.add(makeAuxiliaryZeroWidthBox());
  1114. elements.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1115. g = new KnuthGlue(lineStartBAP + p3WidthOffset, 0, 0, pos3, false);
  1116. elements.add(g);
  1117. } else {
  1118. g = new KnuthGlue(
  1119. 0,
  1120. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, auxiliaryPosition, false);
  1121. elements.add(g);
  1122. elements.add(makeZeroWidthPenalty(0));
  1123. g = new KnuthGlue(
  1124. mapping.areaIPD.getOpt(),
  1125. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos2, false);
  1126. elements.add(g);
  1127. }
  1128. break;
  1129. case EN_JUSTIFY:
  1130. // justified text:
  1131. // the stretch and shrink depends on the space width
  1132. elements.addAll(getElementsForJustifiedText(mapping, pos2, p2WidthOffset, pos3,
  1133. p3WidthOffset, skipZeroCheck, mapping.areaIPD.getShrink()));
  1134. break;
  1135. default:
  1136. // last line justified, the other lines unjustified:
  1137. // use only the space stretch
  1138. elements.addAll(getElementsForJustifiedText(mapping, pos2, p2WidthOffset, pos3,
  1139. p3WidthOffset, skipZeroCheck, 0));
  1140. }
  1141. return elements;
  1142. }
  1143. private List getElementsForJustifiedText(GlyphMapping mapping, Position pos2, int p2WidthOffset,
  1144. Position pos3, int p3WidthOffset, boolean skipZeroCheck,
  1145. int shrinkability) {
  1146. int stretchability = mapping.areaIPD.getStretch();
  1147. List elements = new ArrayList();
  1148. if (skipZeroCheck || lineStartBAP != 0 || lineEndBAP != 0) {
  1149. elements.add(new KnuthGlue(lineEndBAP, 0, 0, auxiliaryPosition, false));
  1150. elements.add(makeZeroWidthPenalty(0));
  1151. elements.add(new KnuthGlue(p2WidthOffset - (lineStartBAP + lineEndBAP),
  1152. stretchability, shrinkability, pos2, false));
  1153. elements.add(makeAuxiliaryZeroWidthBox());
  1154. elements.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1155. elements.add(new KnuthGlue(lineStartBAP + p3WidthOffset, 0, 0, pos3, false));
  1156. } else {
  1157. elements.add(new KnuthGlue(mapping.areaIPD.getOpt(), stretchability, shrinkability,
  1158. pos2, false));
  1159. }
  1160. return elements;
  1161. }
  1162. private void addElementsForAWordFragment(List baseList, int alignment, GlyphMapping mapping,
  1163. int leafValue) {
  1164. LeafPosition mainPosition = new LeafPosition(this, leafValue);
  1165. // if the last character of the word fragment is '-' or '/',
  1166. // the fragment could end a line; in this case, it loses one
  1167. // of its letter spaces;
  1168. boolean suppressibleLetterSpace = mapping.breakOppAfter && !mapping.isHyphenated;
  1169. if (letterSpaceIPD.isStiff()) {
  1170. // constant letter spacing
  1171. baseList.add(new KnuthInlineBox(suppressibleLetterSpace
  1172. ? mapping.areaIPD.getOpt() - letterSpaceIPD.getOpt()
  1173. : mapping.areaIPD.getOpt(),
  1174. alignmentContext, notifyPos(mainPosition), false));
  1175. } else {
  1176. // adjustable letter spacing
  1177. int unsuppressibleLetterSpaces = suppressibleLetterSpace
  1178. ? mapping.letterSpaceCount - 1
  1179. : mapping.letterSpaceCount;
  1180. baseList.add(new KnuthInlineBox(mapping.areaIPD.getOpt()
  1181. - mapping.letterSpaceCount * letterSpaceIPD.getOpt(),
  1182. alignmentContext, notifyPos(mainPosition), false));
  1183. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1184. baseList.add(new KnuthGlue(letterSpaceIPD.mult(unsuppressibleLetterSpaces),
  1185. auxiliaryPosition, true));
  1186. baseList.add(makeAuxiliaryZeroWidthBox());
  1187. }
  1188. // extra-elements if the word fragment is the end of a syllable,
  1189. // or it ends with a character that can be used as a line break
  1190. if (mapping.isHyphenated) {
  1191. MinOptMax widthIfNoBreakOccurs = null;
  1192. if (mapping.endIndex < foText.length()) {
  1193. //Add in kerning in no-break condition
  1194. widthIfNoBreakOccurs = letterSpaceAdjustArray[mapping.endIndex];
  1195. }
  1196. //if (mapping.breakIndex)
  1197. // the word fragment ends at the end of a syllable:
  1198. // if a break occurs the content width increases,
  1199. // otherwise nothing happens
  1200. addElementsForAHyphen(baseList, alignment, hyphIPD, widthIfNoBreakOccurs,
  1201. mapping.breakOppAfter && mapping.isHyphenated);
  1202. } else if (suppressibleLetterSpace) {
  1203. // the word fragment ends with a character that acts as a hyphen
  1204. // if a break occurs the width does not increase,
  1205. // otherwise there is one more letter space
  1206. addElementsForAHyphen(baseList, alignment, 0, letterSpaceIPD, true);
  1207. }
  1208. }
  1209. private void addElementsForAHyphen(List baseList, int alignment, int widthIfBreakOccurs,
  1210. MinOptMax widthIfNoBreakOccurs, boolean unflagged) {
  1211. if (widthIfNoBreakOccurs == null) {
  1212. widthIfNoBreakOccurs = MinOptMax.ZERO;
  1213. }
  1214. switch (alignment) {
  1215. case EN_CENTER:
  1216. // centered text:
  1217. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1218. baseList.add(new KnuthGlue(lineEndBAP, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1219. auxiliaryPosition, true));
  1220. baseList.add(new KnuthPenalty(hyphIPD, unflagged
  1221. ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1222. : KnuthPenalty.FLAGGED_PENALTY, !unflagged, auxiliaryPosition, false));
  1223. baseList.add(new KnuthGlue(-(lineEndBAP + lineStartBAP),
  1224. -6 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1225. auxiliaryPosition, false));
  1226. baseList.add(makeAuxiliaryZeroWidthBox());
  1227. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1228. baseList.add(new KnuthGlue(lineStartBAP, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH,
  1229. 0, auxiliaryPosition, true));
  1230. break;
  1231. case EN_START: // fall through
  1232. case EN_END:
  1233. // left- or right-aligned text:
  1234. if (lineStartBAP != 0 || lineEndBAP != 0) {
  1235. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1236. baseList.add(new KnuthGlue(lineEndBAP,
  1237. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1238. auxiliaryPosition, false));
  1239. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1240. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1241. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1242. auxiliaryPosition, false));
  1243. baseList.add(new KnuthGlue(widthIfNoBreakOccurs.getOpt()
  1244. - (lineStartBAP + lineEndBAP),
  1245. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1246. auxiliaryPosition, false));
  1247. baseList.add(makeAuxiliaryZeroWidthBox());
  1248. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1249. baseList.add(new KnuthGlue(lineStartBAP, 0, 0, auxiliaryPosition, false));
  1250. } else {
  1251. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1252. baseList.add(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1253. auxiliaryPosition, false));
  1254. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1255. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1256. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1257. auxiliaryPosition, false));
  1258. baseList.add(new KnuthGlue(widthIfNoBreakOccurs.getOpt(),
  1259. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1260. auxiliaryPosition, false));
  1261. }
  1262. break;
  1263. default:
  1264. // justified text, or last line justified:
  1265. // just a flagged penalty
  1266. if (lineStartBAP != 0 || lineEndBAP != 0) {
  1267. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1268. baseList.add(new KnuthGlue(lineEndBAP, 0, 0, auxiliaryPosition, false));
  1269. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1270. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1271. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1272. auxiliaryPosition, false));
  1273. // extra elements representing a letter space that is suppressed
  1274. // if a break occurs
  1275. if (widthIfNoBreakOccurs.isNonZero()) {
  1276. baseList.add(new KnuthGlue(widthIfNoBreakOccurs.getOpt()
  1277. - (lineStartBAP + lineEndBAP),
  1278. widthIfNoBreakOccurs.getStretch(),
  1279. widthIfNoBreakOccurs.getShrink(),
  1280. auxiliaryPosition, false));
  1281. } else {
  1282. baseList.add(new KnuthGlue(-(lineStartBAP + lineEndBAP), 0, 0,
  1283. auxiliaryPosition, false));
  1284. }
  1285. baseList.add(makeAuxiliaryZeroWidthBox());
  1286. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1287. baseList.add(new KnuthGlue(lineStartBAP, 0, 0,
  1288. auxiliaryPosition, false));
  1289. } else {
  1290. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1291. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1292. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1293. auxiliaryPosition, false));
  1294. // extra elements representing a letter space that is suppressed
  1295. // if a break occurs
  1296. if (widthIfNoBreakOccurs.isNonZero()) {
  1297. baseList.add(new KnuthGlue(widthIfNoBreakOccurs, auxiliaryPosition, false));
  1298. }
  1299. }
  1300. }
  1301. }
  1302. /** {@inheritDoc} */
  1303. public String toString() {
  1304. return super.toString() + "{"
  1305. + "chars = \'"
  1306. + CharUtilities.toNCRefs(foText.getCharSequence().toString())
  1307. + "\'"
  1308. + ", len = " + foText.length()
  1309. + "}";
  1310. }
  1311. }