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

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