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

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