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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  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;
  85. /** Start index of next TextArea */
  86. private int nextStart;
  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;
  94. private int[] returnedIndices = {0, 0};
  95. private int changeOffset;
  96. private int thisStart;
  97. private int tempStart;
  98. private List changeList = new LinkedList();
  99. private AlignmentContext alignmentContext;
  100. /**
  101. * The width to be reserved for border and padding at the start of the line.
  102. */
  103. private int lineStartBAP;
  104. /**
  105. * The width to be reserved for border and padding at the end of the line.
  106. */
  107. private int lineEndBAP;
  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. textArea.updateLevel(mapping.level);
  387. if (mapping.isSpace) {
  388. addSpaces();
  389. } else {
  390. // mapping stores information about a word fragment
  391. if (mappingIndex == -1) {
  392. // here starts a new word
  393. mappingIndex = wordIndex;
  394. wordCharLength = 0;
  395. }
  396. wordCharLength += mapping.getWordLength();
  397. if (isWordEnd(wordIndex)) {
  398. addWord(mappingIndex, wordIndex, wordCharLength);
  399. mappingIndex = -1;
  400. }
  401. }
  402. }
  403. }
  404. private boolean isWordEnd(int mappingIndex) {
  405. return mappingIndex == lastIndex || getGlyphMapping(mappingIndex + 1).isSpace;
  406. }
  407. /**
  408. * Add word with fragments from STARTINDEX to ENDINDEX, where
  409. * total length of (possibly mapped) word is CHARLENGTH.
  410. * A word is composed from one or more word fragments, where each
  411. * fragment corresponds to distinct instance in a sequence of
  412. * area info instances starting at STARTINDEX continuing through (and
  413. * including) ENDINDEX.
  414. * @param startIndex index of first area info of word to add
  415. * @param endIndex index of last area info of word to add
  416. * @param wordLength number of (mapped) characters in word
  417. */
  418. private void addWord(int startIndex, int endIndex, int wordLength) {
  419. int blockProgressionOffset = 0;
  420. boolean gposAdjusted = false;
  421. if (isHyphenated(endIndex)) {
  422. // TODO may be problematic in some I18N contexts [GA]
  423. wordLength++;
  424. }
  425. initWord(wordLength);
  426. // iterate over word's fragments, adding word chars (with bidi
  427. // levels), letter space adjustments, and glyph position adjustments
  428. for (int i = startIndex; i <= endIndex; i++) {
  429. GlyphMapping wordMapping = getGlyphMapping(i);
  430. addWordChars(wordMapping);
  431. addLetterAdjust(wordMapping);
  432. if (addGlyphPositionAdjustments(wordMapping)) {
  433. gposAdjusted = true;
  434. }
  435. }
  436. if (isHyphenated(endIndex)) {
  437. // TODO may be problematic in some I18N contexts [GA]
  438. addHyphenationChar();
  439. }
  440. if (!gposAdjusted) {
  441. gposAdjustments = null;
  442. }
  443. textArea.addWord(wordChars.toString(), wordIPD, letterSpaceAdjust,
  444. getNonEmptyLevels(), gposAdjustments, blockProgressionOffset);
  445. }
  446. private int[] getNonEmptyLevels() {
  447. if (wordLevels != null) {
  448. assert wordLevelsIndex <= wordLevels.length;
  449. boolean empty = true;
  450. for (int i = 0, n = wordLevelsIndex; i < n; i++) {
  451. if (wordLevels [ i ] >= 0) {
  452. empty = false;
  453. break;
  454. }
  455. }
  456. return empty ? null : wordLevels;
  457. } else {
  458. return null;
  459. }
  460. }
  461. /**
  462. * Fully allocate word character buffer, letter space adjustments
  463. * array, bidi levels array, and glyph position adjustments array.
  464. * based on full word length, including all (possibly mapped) fragments.
  465. * @param wordLength length of word including all (possibly mapped) fragments
  466. */
  467. private void initWord(int wordLength) {
  468. wordChars = new StringBuffer(wordLength);
  469. letterSpaceAdjust = new int[wordLength];
  470. letterSpaceAdjustIndex = 0;
  471. wordLevels = new int[wordLength];
  472. wordLevelsIndex = 0;
  473. Arrays.fill(wordLevels, -1);
  474. gposAdjustments = new int[wordLength][4];
  475. gposAdjustmentsIndex = 0;
  476. wordIPD = 0;
  477. }
  478. private boolean isHyphenated(int endIndex) {
  479. return isLastArea && endIndex == lastIndex && mapping.isHyphenated;
  480. }
  481. private void addHyphenationChar() {
  482. wordChars.append(foText.getCommonHyphenation().getHyphChar(font));
  483. // [TBD] expand bidi word levels, letter space adjusts, gpos adjusts
  484. // [TBD] [GA] problematic in bidi context... what is level of hyphen?
  485. textArea.setHyphenated();
  486. }
  487. /**
  488. * Given a word area info associated with a word fragment,
  489. * (1) concatenate (possibly mapped) word characters to word character buffer;
  490. * (2) concatenante (possibly mapped) word bidi levels to levels buffer;
  491. * (3) update word's IPD with optimal IPD of fragment.
  492. * @param wordMapping fragment info
  493. */
  494. private void addWordChars(GlyphMapping wordMapping) {
  495. int s = wordMapping.startIndex;
  496. int e = wordMapping.endIndex;
  497. if (wordMapping.mapping != null) {
  498. wordChars.append(wordMapping.mapping);
  499. addWordLevels(getMappingBidiLevels(wordMapping));
  500. } else {
  501. for (int i = s; i < e; i++) {
  502. wordChars.append(foText.charAt(i));
  503. }
  504. addWordLevels(foText.getBidiLevels(s, e));
  505. }
  506. wordIPD += wordMapping.areaIPD.getOpt();
  507. }
  508. /**
  509. * Obtain bidirectional levels of mapping of characters over specific interval.
  510. * @param start index in character buffer
  511. * @param end index in character buffer
  512. * @return a (possibly empty) array of bidi levels or null
  513. * in case no bidi levels have been assigned
  514. */
  515. private int[] getMappingBidiLevels(GlyphMapping mapping) {
  516. if (mapping.mapping != null) {
  517. int nc = mapping.endIndex - mapping.startIndex;
  518. int nm = mapping.mapping.length();
  519. int[] la = foText.getBidiLevels(mapping.startIndex, mapping.endIndex);
  520. if (la == null) {
  521. return null;
  522. } else if (nm == nc) { // mapping is same length as mapped range
  523. return la;
  524. } else if (nm > nc) { // mapping is longer than mapped range
  525. int[] ma = new int[nm];
  526. System.arraycopy(la, 0, ma, 0, la.length);
  527. for (int i = la.length, n = ma.length, l = (i > 0) ? la[i - 1] : 0; i < n; i++) {
  528. ma[i] = l;
  529. }
  530. return ma;
  531. } else { // mapping is shorter than mapped range
  532. int[] ma = new int[nm];
  533. System.arraycopy(la, 0, ma, 0, ma.length);
  534. return ma;
  535. }
  536. } else {
  537. return foText.getBidiLevels(mapping.startIndex, mapping.endIndex);
  538. }
  539. }
  540. /**
  541. * Given a (possibly null) bidi levels array associated with a word fragment,
  542. * concatenante (possibly mapped) word bidi levels to levels buffer.
  543. * @param levels bidi levels array or null
  544. */
  545. private void addWordLevels(int[] levels) {
  546. int numLevels = (levels != null) ? levels.length : 0;
  547. if (numLevels > 0) {
  548. int need = wordLevelsIndex + numLevels;
  549. if (need <= wordLevels.length) {
  550. System.arraycopy(levels, 0, wordLevels, wordLevelsIndex, numLevels);
  551. } else {
  552. throw new IllegalStateException(
  553. "word levels array too short: expect at least "
  554. + need + " entries, but has only " + wordLevels.length + " entries");
  555. }
  556. }
  557. wordLevelsIndex += numLevels;
  558. }
  559. /**
  560. * Given a word area info associated with a word fragment,
  561. * concatenate letter space adjustments for each (possibly mapped) character.
  562. * @param wordMapping fragment info
  563. */
  564. private void addLetterAdjust(GlyphMapping wordMapping) {
  565. int letterSpaceCount = wordMapping.letterSpaceCount;
  566. int wordLength = wordMapping.getWordLength();
  567. int taAdjust = textArea.getTextLetterSpaceAdjust();
  568. for (int i = 0, n = wordLength; i < n; i++) {
  569. int j = letterSpaceAdjustIndex + i;
  570. if (j > 0) {
  571. int k = wordMapping.startIndex + i;
  572. MinOptMax adj = (k < letterSpaceAdjustArray.length)
  573. ? letterSpaceAdjustArray [ k ] : null;
  574. letterSpaceAdjust [ j ] = (adj == null) ? 0 : adj.getOpt();
  575. }
  576. if (letterSpaceCount > 0) {
  577. letterSpaceAdjust [ j ] += taAdjust;
  578. letterSpaceCount--;
  579. }
  580. }
  581. letterSpaceAdjustIndex += wordLength;
  582. }
  583. /**
  584. * Given a word area info associated with a word fragment,
  585. * concatenate glyph position adjustments for each (possibly mapped) character.
  586. * @param wordMapping fragment info
  587. * @return true if an adjustment was non-zero
  588. */
  589. private boolean addGlyphPositionAdjustments(GlyphMapping wordMapping) {
  590. boolean adjusted = false;
  591. int[][] gpa = wordMapping.gposAdjustments;
  592. int numAdjusts = (gpa != null) ? gpa.length : 0;
  593. int wordLength = wordMapping.getWordLength();
  594. if (numAdjusts > 0) {
  595. int need = gposAdjustmentsIndex + numAdjusts;
  596. if (need <= gposAdjustments.length) {
  597. for (int i = 0, n = wordLength, j = 0; i < n; i++) {
  598. if (i < numAdjusts) {
  599. int[] wpa1 = gposAdjustments [ gposAdjustmentsIndex + i ];
  600. int[] wpa2 = gpa [ j++ ];
  601. for (int k = 0; k < 4; k++) {
  602. int a = wpa2 [ k ];
  603. if (a != 0) {
  604. wpa1 [ k ] += a;
  605. adjusted = true;
  606. }
  607. }
  608. }
  609. }
  610. } else {
  611. throw new IllegalStateException(
  612. "gpos adjustments array too short: expect at least "
  613. + need + " entries, but has only " + gposAdjustments.length
  614. + " entries");
  615. }
  616. }
  617. gposAdjustmentsIndex += wordLength;
  618. return adjusted;
  619. }
  620. /**
  621. * The <code>GlyphMapping</code> stores information about spaces.
  622. * <p/>
  623. * Add the spaces - except zero-width spaces - to the TextArea.
  624. */
  625. private void addSpaces() {
  626. int blockProgressionOffset = 0;
  627. // [TBD] need to better handling of spaceIPD assignment, for now,
  628. // divide the area info's allocated IPD evenly among the
  629. // non-zero-width space characters
  630. int numZeroWidthSpaces = 0;
  631. for (int i = mapping.startIndex; i < mapping.endIndex; i++) {
  632. char spaceChar = foText.charAt(i);
  633. if (CharUtilities.isZeroWidthSpace(spaceChar)) {
  634. numZeroWidthSpaces++;
  635. }
  636. }
  637. int numSpaces = mapping.endIndex - mapping.startIndex - numZeroWidthSpaces;
  638. int spaceIPD = mapping.areaIPD.getOpt() / ((numSpaces > 0) ? numSpaces : 1);
  639. // add space area children, one for each non-zero-width space character
  640. for (int i = mapping.startIndex; i < mapping.endIndex; i++) {
  641. char spaceChar = foText.charAt(i);
  642. int level = foText.bidiLevelAt(i);
  643. if (!CharUtilities.isZeroWidthSpace(spaceChar)) {
  644. textArea.addSpace(
  645. spaceChar, spaceIPD,
  646. CharUtilities.isAdjustableSpace(spaceChar),
  647. blockProgressionOffset, level);
  648. }
  649. }
  650. }
  651. }
  652. private void addGlyphMapping(GlyphMapping mapping) {
  653. addGlyphMapping(mappings.size(), mapping);
  654. }
  655. private void addGlyphMapping(int index, GlyphMapping mapping) {
  656. mappings.add(index, mapping);
  657. }
  658. private void removeGlyphMapping(int index) {
  659. mappings.remove(index);
  660. }
  661. private GlyphMapping getGlyphMapping(int index) {
  662. return mappings.get(index);
  663. }
  664. /** {@inheritDoc} */
  665. public List getNextKnuthElements(final LayoutContext context, final int alignment) {
  666. lineStartBAP = context.getLineStartBorderAndPaddingWidth();
  667. lineEndBAP = context.getLineEndBorderAndPaddingWidth();
  668. alignmentContext = context.getAlignmentContext();
  669. final List returnList = new LinkedList();
  670. KnuthSequence sequence = new InlineKnuthSequence();
  671. GlyphMapping mapping = null;
  672. GlyphMapping prevMapping = null;
  673. returnList.add(sequence);
  674. if (LOG.isDebugEnabled()) {
  675. LOG.debug("GK: [" + nextStart + "," + foText.length() + "]");
  676. }
  677. LineBreakStatus lineBreakStatus = new LineBreakStatus();
  678. thisStart = nextStart;
  679. boolean inWord = false;
  680. boolean inWhitespace = false;
  681. char ch = 0;
  682. int level = -1;
  683. int prevLevel = -1;
  684. boolean retainControls = false;
  685. while (nextStart < foText.length()) {
  686. ch = foText.charAt(nextStart);
  687. level = foText.bidiLevelAt(nextStart);
  688. boolean breakOpportunity = false;
  689. byte breakAction = keepTogether
  690. ? LineBreakStatus.PROHIBITED_BREAK
  691. : lineBreakStatus.nextChar(ch);
  692. switch (breakAction) {
  693. case LineBreakStatus.COMBINING_PROHIBITED_BREAK:
  694. case LineBreakStatus.PROHIBITED_BREAK:
  695. break;
  696. case LineBreakStatus.EXPLICIT_BREAK:
  697. break;
  698. case LineBreakStatus.COMBINING_INDIRECT_BREAK:
  699. case LineBreakStatus.DIRECT_BREAK:
  700. case LineBreakStatus.INDIRECT_BREAK:
  701. breakOpportunity = true;
  702. break;
  703. default:
  704. TextLayoutManager.LOG.error("Unexpected breakAction: " + breakAction);
  705. }
  706. if (LOG.isDebugEnabled()) {
  707. LOG.debug("GK: {"
  708. + " index = " + nextStart
  709. + ", char = " + CharUtilities.charToNCRef(ch)
  710. + ", level = " + level
  711. + ", levelPrev = " + prevLevel
  712. + ", inWord = " + inWord
  713. + ", inSpace = " + inWhitespace
  714. + "}");
  715. }
  716. if (inWord) {
  717. if (breakOpportunity
  718. || GlyphMapping.isSpace(ch)
  719. || CharUtilities.isExplicitBreak(ch)
  720. || ((prevLevel != -1) && (level != prevLevel))) {
  721. // this.foText.charAt(lastIndex) == CharUtilities.SOFT_HYPHEN
  722. prevMapping = processWord(alignment, sequence, prevMapping, ch,
  723. breakOpportunity, true, prevLevel, retainControls);
  724. }
  725. } else if (inWhitespace) {
  726. if (ch != CharUtilities.SPACE || breakOpportunity) {
  727. prevMapping = processWhitespace(alignment, sequence,
  728. breakOpportunity, prevLevel);
  729. }
  730. } else {
  731. if (mapping != null) {
  732. prevMapping = mapping;
  733. processLeftoverGlyphMapping(alignment, sequence, mapping,
  734. ch == CharUtilities.SPACE || breakOpportunity);
  735. mapping = null;
  736. }
  737. if (breakAction == LineBreakStatus.EXPLICIT_BREAK) {
  738. sequence = processLinebreak(returnList, sequence);
  739. }
  740. }
  741. if (ch == CharUtilities.SPACE
  742. && foText.getWhitespaceTreatment() == Constants.EN_PRESERVE
  743. || ch == CharUtilities.NBSPACE) {
  744. final Font font = FontSelector.selectFontForCharacterInText(ch,
  745. this.foText, this);
  746. font.mapChar(ch);
  747. // preserved space or non-breaking space:
  748. // create the GlyphMapping object
  749. mapping = new GlyphMapping(nextStart, nextStart + 1, 1, 0, wordSpaceIPD, false, true,
  750. breakOpportunity, spaceFont, level, null);
  751. thisStart = nextStart + 1;
  752. } else if (CharUtilities.isFixedWidthSpace(ch) || CharUtilities.isZeroWidthSpace(ch)) {
  753. // create the GlyphMapping object
  754. Font font = FontSelector.selectFontForCharacterInText(ch, foText, this);
  755. MinOptMax ipd = MinOptMax.getInstance(font.getCharWidth(ch));
  756. mapping = new GlyphMapping(nextStart, nextStart + 1, 0, 0, ipd, false, true,
  757. breakOpportunity, font, level, null);
  758. thisStart = nextStart + 1;
  759. } else if (CharUtilities.isExplicitBreak(ch)) {
  760. //mandatory break-character: only advance index
  761. thisStart = nextStart + 1;
  762. }
  763. inWord = !GlyphMapping.isSpace(ch) && !CharUtilities.isExplicitBreak(ch);
  764. inWhitespace = ch == CharUtilities.SPACE
  765. && foText.getWhitespaceTreatment() != Constants.EN_PRESERVE;
  766. prevLevel = level;
  767. nextStart++;
  768. }
  769. // Process any last elements
  770. if (inWord) {
  771. processWord(alignment, sequence, prevMapping, ch, false, false, prevLevel, retainControls);
  772. } else if (inWhitespace) {
  773. processWhitespace(alignment, sequence, !keepTogether, prevLevel);
  774. } else if (mapping != null) {
  775. processLeftoverGlyphMapping(alignment, sequence, mapping,
  776. ch == CharUtilities.ZERO_WIDTH_SPACE);
  777. } else if (CharUtilities.isExplicitBreak(ch)) {
  778. this.processLinebreak(returnList, sequence);
  779. }
  780. if (((List) ListUtil.getLast(returnList)).isEmpty()) {
  781. //Remove an empty sequence because of a trailing newline
  782. ListUtil.removeLast(returnList);
  783. }
  784. setFinished(true);
  785. if (returnList.isEmpty()) {
  786. return null;
  787. } else {
  788. return returnList;
  789. }
  790. }
  791. private KnuthSequence processLinebreak(List returnList, KnuthSequence sequence) {
  792. if (lineEndBAP != 0) {
  793. sequence.add(new KnuthGlue(lineEndBAP, 0, 0, auxiliaryPosition, true));
  794. }
  795. sequence.endSequence();
  796. sequence = new InlineKnuthSequence();
  797. returnList.add(sequence);
  798. return sequence;
  799. }
  800. private void processLeftoverGlyphMapping(int alignment, KnuthSequence sequence,
  801. GlyphMapping mapping, boolean breakOpportunityAfter) {
  802. addGlyphMapping(mapping);
  803. mapping.breakOppAfter = breakOpportunityAfter;
  804. addElementsForASpace(sequence, alignment, mapping, mappings.size() - 1);
  805. }
  806. private GlyphMapping processWhitespace(final int alignment,
  807. final KnuthSequence sequence, final boolean breakOpportunity, int level) {
  808. if (LOG.isDebugEnabled()) {
  809. LOG.debug("PS: [" + thisStart + "," + nextStart + "]");
  810. }
  811. // End of whitespace
  812. // create the GlyphMapping object
  813. assert nextStart >= thisStart;
  814. GlyphMapping mapping = new GlyphMapping(
  815. thisStart, nextStart, nextStart - thisStart, 0,
  816. wordSpaceIPD.mult(nextStart - thisStart),
  817. false, true, breakOpportunity, spaceFont, level, null);
  818. addGlyphMapping(mapping);
  819. // create the elements
  820. addElementsForASpace(sequence, alignment, mapping, mappings.size() - 1);
  821. thisStart = nextStart;
  822. return mapping;
  823. }
  824. private GlyphMapping processWord(final int alignment, final KnuthSequence sequence,
  825. GlyphMapping prevMapping, final char ch, final boolean breakOpportunity,
  826. final boolean checkEndsWithHyphen, int level, boolean retainControls) {
  827. //Word boundary found, process widths and kerning
  828. int lastIndex = nextStart;
  829. while (lastIndex > 0 && foText.charAt(lastIndex - 1) == CharUtilities.SOFT_HYPHEN) {
  830. lastIndex--;
  831. }
  832. final boolean endsWithHyphen = checkEndsWithHyphen
  833. && foText.charAt(lastIndex) == CharUtilities.SOFT_HYPHEN;
  834. Font font = FontSelector.selectFontForCharactersInText(
  835. foText, thisStart, lastIndex, foText, this);
  836. char breakOpportunityChar = breakOpportunity ? ch : 0;
  837. char precedingChar = prevMapping != null && !prevMapping.isSpace
  838. && prevMapping.endIndex > 0 ? foText.charAt(prevMapping.endIndex - 1) : 0;
  839. GlyphMapping mapping = GlyphMapping.doGlyphMapping(foText, thisStart, lastIndex, font,
  840. letterSpaceIPD, letterSpaceAdjustArray, precedingChar, breakOpportunityChar,
  841. endsWithHyphen, level, false, false, retainControls);
  842. prevMapping = mapping;
  843. addGlyphMapping(mapping);
  844. tempStart = nextStart;
  845. //add the elements
  846. addElementsForAWordFragment(sequence, alignment, mapping, mappings.size() - 1);
  847. thisStart = nextStart;
  848. return prevMapping;
  849. }
  850. /** {@inheritDoc} */
  851. public List addALetterSpaceTo(List oldList) {
  852. return addALetterSpaceTo(oldList, 0);
  853. }
  854. /** {@inheritDoc} */
  855. public List addALetterSpaceTo(final List oldList, int depth) {
  856. // old list contains only a box, or the sequence: box penalty glue box;
  857. // look at the Position stored in the first element in oldList
  858. // which is always a box
  859. ListIterator oldListIterator = oldList.listIterator();
  860. KnuthElement knuthElement = (KnuthElement) oldListIterator.next();
  861. Position pos = knuthElement.getPosition();
  862. LeafPosition leafPos = (LeafPosition) pos.getPosition(depth);
  863. int index = leafPos.getLeafPos();
  864. //element could refer to '-1' position, for non-collapsed spaces (?)
  865. if (index > -1) {
  866. GlyphMapping mapping = getGlyphMapping(index);
  867. mapping.letterSpaceCount++;
  868. mapping.addToAreaIPD(letterSpaceIPD);
  869. if (TextLayoutManager.BREAK_CHARS.indexOf(foText.charAt(tempStart - 1)) >= 0) {
  870. // the last character could be used as a line break
  871. // append new elements to oldList
  872. oldListIterator = oldList.listIterator(oldList.size());
  873. oldListIterator.add(new KnuthPenalty(0, KnuthPenalty.FLAGGED_PENALTY, true,
  874. auxiliaryPosition, false));
  875. oldListIterator.add(new KnuthGlue(letterSpaceIPD, auxiliaryPosition, false));
  876. } else if (letterSpaceIPD.isStiff()) {
  877. // constant letter space: replace the box
  878. // give it the unwrapped position of the replaced element
  879. oldListIterator.set(new KnuthInlineBox(mapping.areaIPD.getOpt(),
  880. alignmentContext, pos, false));
  881. } else {
  882. // adjustable letter space: replace the glue
  883. oldListIterator.next(); // this would return the penalty element
  884. oldListIterator.next(); // this would return the glue element
  885. oldListIterator.set(new KnuthGlue(letterSpaceIPD.mult(mapping.letterSpaceCount),
  886. auxiliaryPosition, true));
  887. }
  888. }
  889. return oldList;
  890. }
  891. /** {@inheritDoc} */
  892. public void hyphenate(Position pos, HyphContext hyphContext) {
  893. GlyphMapping mapping = getGlyphMapping(((LeafPosition) pos).getLeafPos() + changeOffset);
  894. int startIndex = mapping.startIndex;
  895. int stopIndex;
  896. boolean nothingChanged = true;
  897. Font font = mapping.font;
  898. while (startIndex < mapping.endIndex) {
  899. MinOptMax newIPD = MinOptMax.ZERO;
  900. boolean hyphenFollows;
  901. stopIndex = startIndex + hyphContext.getNextHyphPoint();
  902. if (hyphContext.hasMoreHyphPoints() && stopIndex <= mapping.endIndex) {
  903. // stopIndex is the index of the first character
  904. // after a hyphenation point
  905. hyphenFollows = true;
  906. } else {
  907. // there are no more hyphenation points,
  908. // or the next one is after mapping.breakIndex
  909. hyphenFollows = false;
  910. stopIndex = mapping.endIndex;
  911. }
  912. hyphContext.updateOffset(stopIndex - startIndex);
  913. //log.info("Word: " + new String(textArray, startIndex, stopIndex - startIndex));
  914. for (int i = startIndex; i < stopIndex; i++) {
  915. char ch = foText.charAt(i);
  916. newIPD = newIPD.plus(font.getCharWidth(ch));
  917. //if (i > startIndex) {
  918. if (i < stopIndex) {
  919. MinOptMax letterSpaceAdjust = letterSpaceAdjustArray[i + 1];
  920. if (i == stopIndex - 1 && hyphenFollows) {
  921. //the letter adjust here needs to be handled further down during
  922. //element generation because it depends on hyph/no-hyph condition
  923. letterSpaceAdjust = null;
  924. }
  925. if (letterSpaceAdjust != null) {
  926. newIPD = newIPD.plus(letterSpaceAdjust);
  927. }
  928. }
  929. }
  930. // add letter spaces
  931. boolean isWordEnd
  932. = (stopIndex == mapping.endIndex)
  933. && (mapping.letterSpaceCount < mapping.getWordLength());
  934. int letterSpaceCount = isWordEnd ? stopIndex - startIndex - 1 : stopIndex - startIndex;
  935. assert letterSpaceCount >= 0;
  936. newIPD = newIPD.plus(letterSpaceIPD.mult(letterSpaceCount));
  937. if (!(nothingChanged && stopIndex == mapping.endIndex && !hyphenFollows)) {
  938. // the new GlyphMapping object is not equal to the old one
  939. changeList.add(
  940. new PendingChange(
  941. new GlyphMapping(startIndex, stopIndex, 0,
  942. letterSpaceCount, newIPD, hyphenFollows,
  943. false, false, font, -1, null),
  944. ((LeafPosition) pos).getLeafPos() + changeOffset));
  945. nothingChanged = false;
  946. }
  947. startIndex = stopIndex;
  948. }
  949. hasChanged |= !nothingChanged;
  950. }
  951. /** {@inheritDoc} */
  952. public boolean applyChanges(final List oldList) {
  953. return applyChanges(oldList, 0);
  954. }
  955. /** {@inheritDoc} */
  956. public boolean applyChanges(final List oldList, int depth) {
  957. // make sure the LM appears unfinished in between this call
  958. // and the next call to getChangedKnuthElements()
  959. setFinished(false);
  960. if (oldList.isEmpty()) {
  961. return false;
  962. }
  963. // Find the first and last positions in oldList that point to a GlyphMapping
  964. // (i.e. getLeafPos() != -1)
  965. LeafPosition startPos = null;
  966. LeafPosition endPos = null;
  967. ListIterator oldListIter;
  968. for (oldListIter = oldList.listIterator(); oldListIter.hasNext();) {
  969. Position pos = ((KnuthElement) oldListIter.next()).getPosition();
  970. startPos = (LeafPosition) pos.getPosition(depth);
  971. if (startPos != null && startPos.getLeafPos() != -1) {
  972. break;
  973. }
  974. }
  975. for (oldListIter = oldList.listIterator(oldList.size()); oldListIter.hasPrevious();) {
  976. Position pos = ((KnuthElement) oldListIter.previous()).getPosition();
  977. endPos = (LeafPosition) pos.getPosition(depth);
  978. if (endPos != null && endPos.getLeafPos() != -1) {
  979. break;
  980. }
  981. }
  982. // set start/end index, taking into account any offset due to
  983. // changes applied to previous paragraphs
  984. returnedIndices[0] = (startPos != null ? startPos.getLeafPos() : -1) + changeOffset;
  985. returnedIndices[1] = (endPos != null ? endPos.getLeafPos() : -1) + changeOffset;
  986. int mappingsAdded = 0;
  987. int mappingsRemoved = 0;
  988. if (!changeList.isEmpty()) {
  989. int oldIndex = -1;
  990. int changeIndex;
  991. PendingChange currChange;
  992. ListIterator changeListIterator = changeList.listIterator();
  993. while (changeListIterator.hasNext()) {
  994. currChange = (PendingChange) changeListIterator.next();
  995. if (currChange.index == oldIndex) {
  996. mappingsAdded++;
  997. changeIndex = currChange.index + mappingsAdded - mappingsRemoved;
  998. } else {
  999. mappingsRemoved++;
  1000. mappingsAdded++;
  1001. oldIndex = currChange.index;
  1002. changeIndex = currChange.index + mappingsAdded - mappingsRemoved;
  1003. removeGlyphMapping(changeIndex);
  1004. }
  1005. addGlyphMapping(changeIndex, currChange.mapping);
  1006. }
  1007. changeList.clear();
  1008. }
  1009. // increase the end index for getChangedKnuthElements()
  1010. returnedIndices[1] += (mappingsAdded - mappingsRemoved);
  1011. // increase offset to use for subsequent paragraphs
  1012. changeOffset += (mappingsAdded - mappingsRemoved);
  1013. return hasChanged;
  1014. }
  1015. /** {@inheritDoc} */
  1016. public List getChangedKnuthElements(final List oldList, final int alignment) {
  1017. if (isFinished()) {
  1018. return null;
  1019. }
  1020. final LinkedList returnList = new LinkedList();
  1021. for (; returnedIndices[0] <= returnedIndices[1]; returnedIndices[0]++) {
  1022. GlyphMapping mapping = getGlyphMapping(returnedIndices[0]);
  1023. if (mapping.wordSpaceCount == 0) {
  1024. // mapping refers either to a word or a word fragment
  1025. addElementsForAWordFragment(returnList, alignment, mapping, returnedIndices[0]);
  1026. } else {
  1027. // mapping refers to a space
  1028. addElementsForASpace(returnList, alignment, mapping, returnedIndices[0]);
  1029. }
  1030. }
  1031. setFinished(returnedIndices[0] == mappings.size() - 1);
  1032. //ElementListObserver.observe(returnList, "text-changed", null);
  1033. return returnList;
  1034. }
  1035. /** {@inheritDoc} */
  1036. public String getWordChars(Position pos) {
  1037. int leafValue = ((LeafPosition) pos).getLeafPos() + changeOffset;
  1038. if (leafValue != -1) {
  1039. GlyphMapping mapping = getGlyphMapping(leafValue);
  1040. StringBuffer buffer = new StringBuffer(mapping.getWordLength());
  1041. for (int i = mapping.startIndex; i < mapping.endIndex; i++) {
  1042. buffer.append(foText.charAt(i));
  1043. }
  1044. return buffer.toString();
  1045. } else {
  1046. return "";
  1047. }
  1048. }
  1049. private void addElementsForASpace(List baseList, int alignment, GlyphMapping mapping,
  1050. int leafValue) {
  1051. LeafPosition mainPosition = new LeafPosition(this, leafValue);
  1052. if (!mapping.breakOppAfter) {
  1053. // a non-breaking space
  1054. if (alignment == Constants.EN_JUSTIFY) {
  1055. // the space can stretch and shrink, and must be preserved
  1056. // when starting a line
  1057. baseList.add(makeAuxiliaryZeroWidthBox());
  1058. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1059. baseList.add(new KnuthGlue(mapping.areaIPD, mainPosition, false));
  1060. } else {
  1061. // the space does not need to stretch or shrink, and must be
  1062. // preserved when starting a line
  1063. baseList.add(new KnuthInlineBox(mapping.areaIPD.getOpt(), null, mainPosition,
  1064. true));
  1065. }
  1066. } else {
  1067. if (foText.charAt(mapping.startIndex) != CharUtilities.SPACE
  1068. || foText.getWhitespaceTreatment() == Constants.EN_PRESERVE) {
  1069. // a breaking space that needs to be preserved
  1070. baseList.addAll(getElementsForBreakingSpace(alignment, mapping, auxiliaryPosition, 0,
  1071. mainPosition, mapping.areaIPD.getOpt(), true));
  1072. } else {
  1073. // a (possible block) of breaking spaces
  1074. baseList.addAll(getElementsForBreakingSpace(alignment, mapping, mainPosition,
  1075. mapping.areaIPD.getOpt(), auxiliaryPosition, 0, false));
  1076. }
  1077. }
  1078. }
  1079. private List getElementsForBreakingSpace(int alignment, GlyphMapping mapping, Position pos2,
  1080. int p2WidthOffset, Position pos3,
  1081. int p3WidthOffset, boolean skipZeroCheck) {
  1082. List elements = new ArrayList();
  1083. switch (alignment) {
  1084. case EN_CENTER:
  1085. // centered text:
  1086. // if the second element is chosen as a line break these elements
  1087. // add a constant amount of stretch at the end of a line and at the
  1088. // beginning of the next one, otherwise they don't add any stretch
  1089. elements.add(new KnuthGlue(lineEndBAP, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1090. auxiliaryPosition, false));
  1091. elements.add(makeZeroWidthPenalty(0));
  1092. elements.add(new KnuthGlue(p2WidthOffset - (lineStartBAP + lineEndBAP), -6
  1093. * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos2, false));
  1094. elements.add(makeAuxiliaryZeroWidthBox());
  1095. elements.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1096. elements.add(new KnuthGlue(lineStartBAP + p3WidthOffset,
  1097. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos3, false));
  1098. break;
  1099. case EN_START: // fall through
  1100. case EN_END:
  1101. // left- or right-aligned text:
  1102. // if the second element is chosen as a line break these elements
  1103. // add a constant amount of stretch at the end of a line, otherwise
  1104. // they don't add any stretch
  1105. KnuthGlue g;
  1106. if (skipZeroCheck || lineStartBAP != 0 || lineEndBAP != 0) {
  1107. g = new KnuthGlue(
  1108. lineEndBAP,
  1109. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, auxiliaryPosition, false);
  1110. elements.add(g);
  1111. elements.add(makeZeroWidthPenalty(0));
  1112. g = new KnuthGlue(
  1113. p2WidthOffset - (lineStartBAP + lineEndBAP),
  1114. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos2, false);
  1115. elements.add(g);
  1116. elements.add(makeAuxiliaryZeroWidthBox());
  1117. elements.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1118. g = new KnuthGlue(lineStartBAP + p3WidthOffset, 0, 0, pos3, false);
  1119. elements.add(g);
  1120. } else {
  1121. g = new KnuthGlue(
  1122. 0,
  1123. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, auxiliaryPosition, false);
  1124. elements.add(g);
  1125. elements.add(makeZeroWidthPenalty(0));
  1126. g = new KnuthGlue(
  1127. mapping.areaIPD.getOpt(),
  1128. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos2, false);
  1129. elements.add(g);
  1130. }
  1131. break;
  1132. case EN_JUSTIFY:
  1133. // justified text:
  1134. // the stretch and shrink depends on the space width
  1135. elements.addAll(getElementsForJustifiedText(mapping, pos2, p2WidthOffset, pos3,
  1136. p3WidthOffset, skipZeroCheck, mapping.areaIPD.getShrink()));
  1137. break;
  1138. default:
  1139. // last line justified, the other lines unjustified:
  1140. // use only the space stretch
  1141. elements.addAll(getElementsForJustifiedText(mapping, pos2, p2WidthOffset, pos3,
  1142. p3WidthOffset, skipZeroCheck, 0));
  1143. }
  1144. return elements;
  1145. }
  1146. private List getElementsForJustifiedText(GlyphMapping mapping, Position pos2, int p2WidthOffset,
  1147. Position pos3, int p3WidthOffset, boolean skipZeroCheck,
  1148. int shrinkability) {
  1149. int stretchability = mapping.areaIPD.getStretch();
  1150. List elements = new ArrayList();
  1151. if (skipZeroCheck || lineStartBAP != 0 || lineEndBAP != 0) {
  1152. elements.add(new KnuthGlue(lineEndBAP, 0, 0, auxiliaryPosition, false));
  1153. elements.add(makeZeroWidthPenalty(0));
  1154. elements.add(new KnuthGlue(p2WidthOffset - (lineStartBAP + lineEndBAP),
  1155. stretchability, shrinkability, pos2, false));
  1156. elements.add(makeAuxiliaryZeroWidthBox());
  1157. elements.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1158. elements.add(new KnuthGlue(lineStartBAP + p3WidthOffset, 0, 0, pos3, false));
  1159. } else {
  1160. elements.add(new KnuthGlue(mapping.areaIPD.getOpt(), stretchability, shrinkability,
  1161. pos2, false));
  1162. }
  1163. return elements;
  1164. }
  1165. private void addElementsForAWordFragment(List baseList, int alignment, GlyphMapping mapping,
  1166. int leafValue) {
  1167. LeafPosition mainPosition = new LeafPosition(this, leafValue);
  1168. // if the last character of the word fragment is '-' or '/',
  1169. // the fragment could end a line; in this case, it loses one
  1170. // of its letter spaces;
  1171. boolean suppressibleLetterSpace = mapping.breakOppAfter && !mapping.isHyphenated;
  1172. if (letterSpaceIPD.isStiff()) {
  1173. // constant letter spacing
  1174. baseList.add(new KnuthInlineBox(suppressibleLetterSpace
  1175. ? mapping.areaIPD.getOpt() - letterSpaceIPD.getOpt()
  1176. : mapping.areaIPD.getOpt(),
  1177. alignmentContext, notifyPos(mainPosition), false));
  1178. } else {
  1179. // adjustable letter spacing
  1180. int unsuppressibleLetterSpaces = suppressibleLetterSpace
  1181. ? mapping.letterSpaceCount - 1
  1182. : mapping.letterSpaceCount;
  1183. baseList.add(new KnuthInlineBox(mapping.areaIPD.getOpt()
  1184. - mapping.letterSpaceCount * letterSpaceIPD.getOpt(),
  1185. alignmentContext, notifyPos(mainPosition), false));
  1186. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1187. baseList.add(new KnuthGlue(letterSpaceIPD.mult(unsuppressibleLetterSpaces),
  1188. auxiliaryPosition, true));
  1189. baseList.add(makeAuxiliaryZeroWidthBox());
  1190. }
  1191. // extra-elements if the word fragment is the end of a syllable,
  1192. // or it ends with a character that can be used as a line break
  1193. if (mapping.isHyphenated) {
  1194. MinOptMax widthIfNoBreakOccurs = null;
  1195. if (mapping.endIndex < foText.length()) {
  1196. //Add in kerning in no-break condition
  1197. widthIfNoBreakOccurs = letterSpaceAdjustArray[mapping.endIndex];
  1198. }
  1199. //if (mapping.breakIndex)
  1200. // the word fragment ends at the end of a syllable:
  1201. // if a break occurs the content width increases,
  1202. // otherwise nothing happens
  1203. addElementsForAHyphen(baseList, alignment, hyphIPD, widthIfNoBreakOccurs,
  1204. mapping.breakOppAfter && mapping.isHyphenated);
  1205. } else if (suppressibleLetterSpace) {
  1206. // the word fragment ends with a character that acts as a hyphen
  1207. // if a break occurs the width does not increase,
  1208. // otherwise there is one more letter space
  1209. addElementsForAHyphen(baseList, alignment, 0, letterSpaceIPD, true);
  1210. }
  1211. }
  1212. private void addElementsForAHyphen(List baseList, int alignment, int widthIfBreakOccurs,
  1213. MinOptMax widthIfNoBreakOccurs, boolean unflagged) {
  1214. if (widthIfNoBreakOccurs == null) {
  1215. widthIfNoBreakOccurs = MinOptMax.ZERO;
  1216. }
  1217. switch (alignment) {
  1218. case EN_CENTER:
  1219. // centered text:
  1220. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1221. baseList.add(new KnuthGlue(lineEndBAP, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1222. auxiliaryPosition, true));
  1223. baseList.add(new KnuthPenalty(hyphIPD, unflagged
  1224. ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1225. : KnuthPenalty.FLAGGED_PENALTY, !unflagged, auxiliaryPosition, false));
  1226. baseList.add(new KnuthGlue(-(lineEndBAP + lineStartBAP),
  1227. -6 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1228. auxiliaryPosition, false));
  1229. baseList.add(makeAuxiliaryZeroWidthBox());
  1230. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1231. baseList.add(new KnuthGlue(lineStartBAP, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH,
  1232. 0, auxiliaryPosition, true));
  1233. break;
  1234. case EN_START: // fall through
  1235. case EN_END:
  1236. // left- or right-aligned text:
  1237. if (lineStartBAP != 0 || lineEndBAP != 0) {
  1238. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1239. baseList.add(new KnuthGlue(lineEndBAP,
  1240. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1241. auxiliaryPosition, false));
  1242. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1243. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1244. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1245. auxiliaryPosition, false));
  1246. baseList.add(new KnuthGlue(widthIfNoBreakOccurs.getOpt()
  1247. - (lineStartBAP + lineEndBAP),
  1248. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1249. auxiliaryPosition, false));
  1250. baseList.add(makeAuxiliaryZeroWidthBox());
  1251. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1252. baseList.add(new KnuthGlue(lineStartBAP, 0, 0, auxiliaryPosition, false));
  1253. } else {
  1254. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1255. baseList.add(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1256. auxiliaryPosition, false));
  1257. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1258. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1259. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1260. auxiliaryPosition, false));
  1261. baseList.add(new KnuthGlue(widthIfNoBreakOccurs.getOpt(),
  1262. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1263. auxiliaryPosition, false));
  1264. }
  1265. break;
  1266. default:
  1267. // justified text, or last line justified:
  1268. // just a flagged penalty
  1269. if (lineStartBAP != 0 || lineEndBAP != 0) {
  1270. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1271. baseList.add(new KnuthGlue(lineEndBAP, 0, 0, auxiliaryPosition, false));
  1272. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1273. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1274. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1275. auxiliaryPosition, false));
  1276. // extra elements representing a letter space that is suppressed
  1277. // if a break occurs
  1278. if (widthIfNoBreakOccurs.isNonZero()) {
  1279. baseList.add(new KnuthGlue(widthIfNoBreakOccurs.getOpt()
  1280. - (lineStartBAP + lineEndBAP),
  1281. widthIfNoBreakOccurs.getStretch(),
  1282. widthIfNoBreakOccurs.getShrink(),
  1283. auxiliaryPosition, false));
  1284. } else {
  1285. baseList.add(new KnuthGlue(-(lineStartBAP + lineEndBAP), 0, 0,
  1286. auxiliaryPosition, false));
  1287. }
  1288. baseList.add(makeAuxiliaryZeroWidthBox());
  1289. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1290. baseList.add(new KnuthGlue(lineStartBAP, 0, 0,
  1291. auxiliaryPosition, false));
  1292. } else {
  1293. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1294. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1295. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1296. auxiliaryPosition, false));
  1297. // extra elements representing a letter space that is suppressed
  1298. // if a break occurs
  1299. if (widthIfNoBreakOccurs.isNonZero()) {
  1300. baseList.add(new KnuthGlue(widthIfNoBreakOccurs, auxiliaryPosition, false));
  1301. }
  1302. }
  1303. }
  1304. }
  1305. /** {@inheritDoc} */
  1306. public String toString() {
  1307. return super.toString() + "{"
  1308. + "chars = \'"
  1309. + CharUtilities.toNCRefs(foText.getCharSequence().toString())
  1310. + "\'"
  1311. + ", len = " + foText.length()
  1312. + "}";
  1313. }
  1314. }