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

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