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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  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. while (nextStart < foText.length()) {
  703. ch = foText.charAt(nextStart);
  704. level = foText.bidiLevelAt(nextStart);
  705. boolean breakOpportunity = false;
  706. byte breakAction = keepTogether
  707. ? LineBreakStatus.PROHIBITED_BREAK
  708. : lineBreakStatus.nextChar(ch);
  709. switch (breakAction) {
  710. case LineBreakStatus.COMBINING_PROHIBITED_BREAK:
  711. case LineBreakStatus.PROHIBITED_BREAK:
  712. break;
  713. case LineBreakStatus.EXPLICIT_BREAK:
  714. break;
  715. case LineBreakStatus.COMBINING_INDIRECT_BREAK:
  716. case LineBreakStatus.DIRECT_BREAK:
  717. case LineBreakStatus.INDIRECT_BREAK:
  718. breakOpportunity = true;
  719. break;
  720. default:
  721. TextLayoutManager.LOG.error("Unexpected breakAction: " + breakAction);
  722. }
  723. if (LOG.isDebugEnabled()) {
  724. LOG.debug("GK: {"
  725. + " index = " + nextStart
  726. + ", char = " + CharUtilities.charToNCRef(ch)
  727. + ", level = " + level
  728. + ", levelPrev = " + prevLevel
  729. + ", inWord = " + inWord
  730. + ", inSpace = " + inWhitespace
  731. + "}");
  732. }
  733. if (inWord) {
  734. if (breakOpportunity
  735. || GlyphMapping.isSpace(ch)
  736. || CharUtilities.isExplicitBreak(ch)
  737. || ((prevLevel != -1) && (level != prevLevel))) {
  738. // this.foText.charAt(lastIndex) == CharUtilities.SOFT_HYPHEN
  739. prevMapping = processWord(alignment, sequence, prevMapping, ch,
  740. breakOpportunity, true, prevLevel, retainControls);
  741. }
  742. } else if (inWhitespace) {
  743. if (ch != CharUtilities.SPACE || breakOpportunity) {
  744. prevMapping = processWhitespace(alignment, sequence,
  745. breakOpportunity, prevLevel);
  746. }
  747. } else {
  748. if (mapping != null) {
  749. prevMapping = mapping;
  750. processLeftoverGlyphMapping(alignment, sequence, mapping,
  751. ch == CharUtilities.SPACE || breakOpportunity);
  752. mapping = null;
  753. }
  754. if (breakAction == LineBreakStatus.EXPLICIT_BREAK) {
  755. sequence = processLinebreak(returnList, sequence);
  756. }
  757. }
  758. if (ch == CharUtilities.SPACE
  759. && foText.getWhitespaceTreatment() == Constants.EN_PRESERVE
  760. || ch == CharUtilities.NBSPACE) {
  761. final Font font = FontSelector.selectFontForCharacterInText(ch,
  762. this.foText, this);
  763. font.mapChar(ch);
  764. // preserved space or non-breaking space:
  765. // create the GlyphMapping object
  766. MinOptMax areaIPD;
  767. if (prevMapping != null && prevMapping.isSpace) {
  768. areaIPD = wordSpaceIPD.minus(letterSpaceIPD);
  769. } else {
  770. areaIPD = wordSpaceIPD;
  771. }
  772. mapping = new GlyphMapping(nextStart, nextStart + 1, 1, 0, areaIPD, false, true,
  773. breakOpportunity, spaceFont, level, null);
  774. thisStart = nextStart + 1;
  775. } else if (CharUtilities.isFixedWidthSpace(ch) || CharUtilities.isZeroWidthSpace(ch)) {
  776. // create the GlyphMapping object
  777. Font font = FontSelector.selectFontForCharacterInText(ch, foText, this);
  778. MinOptMax ipd = MinOptMax.getInstance(font.getCharWidth(ch));
  779. mapping = new GlyphMapping(nextStart, nextStart + 1, 0, 0, ipd, false, true,
  780. breakOpportunity, font, level, null);
  781. thisStart = nextStart + 1;
  782. } else if (CharUtilities.isExplicitBreak(ch)) {
  783. //mandatory break-character: only advance index
  784. thisStart = nextStart + 1;
  785. }
  786. inWord = !GlyphMapping.isSpace(ch) && !CharUtilities.isExplicitBreak(ch);
  787. inWhitespace = ch == CharUtilities.SPACE
  788. && foText.getWhitespaceTreatment() != Constants.EN_PRESERVE;
  789. prevLevel = level;
  790. nextStart++;
  791. }
  792. // Process any last elements
  793. if (inWord) {
  794. processWord(alignment, sequence, prevMapping, ch, false, false, prevLevel, retainControls);
  795. } else if (inWhitespace) {
  796. processWhitespace(alignment, sequence, !keepTogether, prevLevel);
  797. } else if (mapping != null) {
  798. processLeftoverGlyphMapping(alignment, sequence, mapping,
  799. ch == CharUtilities.ZERO_WIDTH_SPACE);
  800. } else if (CharUtilities.isExplicitBreak(ch)) {
  801. this.processLinebreak(returnList, sequence);
  802. }
  803. if (((List) ListUtil.getLast(returnList)).isEmpty()) {
  804. //Remove an empty sequence because of a trailing newline
  805. ListUtil.removeLast(returnList);
  806. }
  807. setFinished(true);
  808. if (returnList.isEmpty()) {
  809. return null;
  810. } else {
  811. return returnList;
  812. }
  813. }
  814. private KnuthSequence processLinebreak(List returnList, KnuthSequence sequence) {
  815. if (lineEndBAP != 0) {
  816. sequence.add(new KnuthGlue(lineEndBAP, 0, 0, auxiliaryPosition, true));
  817. }
  818. sequence.endSequence();
  819. sequence = new InlineKnuthSequence();
  820. returnList.add(sequence);
  821. return sequence;
  822. }
  823. private void processLeftoverGlyphMapping(int alignment, KnuthSequence sequence,
  824. GlyphMapping mapping, boolean breakOpportunityAfter) {
  825. addGlyphMapping(mapping);
  826. mapping.breakOppAfter = breakOpportunityAfter;
  827. addElementsForASpace(sequence, alignment, mapping, mappings.size() - 1);
  828. }
  829. private GlyphMapping processWhitespace(final int alignment,
  830. final KnuthSequence sequence, final boolean breakOpportunity, int level) {
  831. if (LOG.isDebugEnabled()) {
  832. LOG.debug("PS: [" + thisStart + "," + nextStart + "]");
  833. }
  834. // End of whitespace
  835. // create the GlyphMapping object
  836. assert nextStart >= thisStart;
  837. GlyphMapping mapping = new GlyphMapping(
  838. thisStart, nextStart, nextStart - thisStart, 0,
  839. wordSpaceIPD.mult(nextStart - thisStart),
  840. false, true, breakOpportunity, spaceFont, level, null);
  841. addGlyphMapping(mapping);
  842. // create the elements
  843. addElementsForASpace(sequence, alignment, mapping, mappings.size() - 1);
  844. thisStart = nextStart;
  845. return mapping;
  846. }
  847. private GlyphMapping processWord(final int alignment, final KnuthSequence sequence,
  848. GlyphMapping prevMapping, final char ch, final boolean breakOpportunity,
  849. final boolean checkEndsWithHyphen, int level, boolean retainControls) {
  850. //Word boundary found, process widths and kerning
  851. int lastIndex = nextStart;
  852. while (lastIndex > 0 && foText.charAt(lastIndex - 1) == CharUtilities.SOFT_HYPHEN) {
  853. lastIndex--;
  854. }
  855. final boolean endsWithHyphen = checkEndsWithHyphen
  856. && foText.charAt(lastIndex) == CharUtilities.SOFT_HYPHEN;
  857. Font font = FontSelector.selectFontForCharactersInText(
  858. foText, thisStart, lastIndex, foText, this);
  859. char breakOpportunityChar = breakOpportunity ? ch : 0;
  860. char precedingChar = prevMapping != null && !prevMapping.isSpace
  861. && prevMapping.endIndex > 0 ? foText.charAt(prevMapping.endIndex - 1) : 0;
  862. GlyphMapping mapping = GlyphMapping.doGlyphMapping(foText, thisStart, lastIndex, font,
  863. letterSpaceIPD, letterSpaceAdjustArray, precedingChar, breakOpportunityChar,
  864. endsWithHyphen, level, false, false, retainControls);
  865. prevMapping = mapping;
  866. addGlyphMapping(mapping);
  867. tempStart = nextStart;
  868. //add the elements
  869. addElementsForAWordFragment(sequence, alignment, mapping, mappings.size() - 1);
  870. thisStart = nextStart;
  871. return prevMapping;
  872. }
  873. /** {@inheritDoc} */
  874. public List addALetterSpaceTo(List oldList) {
  875. return addALetterSpaceTo(oldList, 0);
  876. }
  877. /** {@inheritDoc} */
  878. public List addALetterSpaceTo(final List oldList, int depth) {
  879. // old list contains only a box, or the sequence: box penalty glue box;
  880. // look at the Position stored in the first element in oldList
  881. // which is always a box
  882. ListIterator oldListIterator = oldList.listIterator();
  883. KnuthElement knuthElement = (KnuthElement) oldListIterator.next();
  884. Position pos = knuthElement.getPosition();
  885. Position innerPosition = pos.getPosition(depth);
  886. assert (innerPosition instanceof LeafPosition);
  887. LeafPosition leafPos = (LeafPosition) innerPosition;
  888. int index = leafPos.getLeafPos();
  889. //element could refer to '-1' position, for non-collapsed spaces (?)
  890. if (index > -1) {
  891. GlyphMapping mapping = getGlyphMapping(index);
  892. mapping.letterSpaceCount++;
  893. mapping.addToAreaIPD(letterSpaceIPD);
  894. if (TextLayoutManager.BREAK_CHARS.indexOf(foText.charAt(tempStart - 1)) >= 0) {
  895. // the last character could be used as a line break
  896. // append new elements to oldList
  897. oldListIterator = oldList.listIterator(oldList.size());
  898. oldListIterator.add(new KnuthPenalty(0, KnuthPenalty.FLAGGED_PENALTY, true,
  899. auxiliaryPosition, false));
  900. oldListIterator.add(new KnuthGlue(letterSpaceIPD, auxiliaryPosition, false));
  901. } else if (letterSpaceIPD.isStiff()) {
  902. // constant letter space: replace the box
  903. // give it the unwrapped position of the replaced element
  904. oldListIterator.set(new KnuthInlineBox(mapping.areaIPD.getOpt(),
  905. alignmentContext, pos, false));
  906. } else {
  907. // adjustable letter space: replace the glue
  908. oldListIterator.next(); // this would return the penalty element
  909. oldListIterator.next(); // this would return the glue element
  910. oldListIterator.set(new KnuthGlue(letterSpaceIPD.mult(mapping.letterSpaceCount),
  911. auxiliaryPosition, true));
  912. }
  913. }
  914. return oldList;
  915. }
  916. /** {@inheritDoc} */
  917. public void hyphenate(Position pos, HyphContext hyphContext) {
  918. int glyphIndex = ((LeafPosition) pos).getLeafPos() + changeOffset;
  919. GlyphMapping mapping = getGlyphMapping(glyphIndex);
  920. int startIndex = mapping.startIndex;
  921. int stopIndex;
  922. boolean nothingChanged = true;
  923. Font font = mapping.font;
  924. // skip hyphenation if previously hyphenated using soft hyphen
  925. if (mapping.isHyphenated || (glyphIndex > 0 && getGlyphMapping(glyphIndex - 1).isHyphenated)) {
  926. stopIndex = mapping.endIndex;
  927. hyphContext.updateOffset(stopIndex - startIndex);
  928. startIndex = stopIndex;
  929. }
  930. while (startIndex < mapping.endIndex) {
  931. MinOptMax newIPD = MinOptMax.ZERO;
  932. boolean hyphenFollows;
  933. stopIndex = startIndex + hyphContext.getNextHyphPoint();
  934. if (hyphContext.hasMoreHyphPoints() && stopIndex <= mapping.endIndex) {
  935. // stopIndex is the index of the first character
  936. // after a hyphenation point
  937. hyphenFollows = true;
  938. } else {
  939. // there are no more hyphenation points,
  940. // or the next one is after mapping.breakIndex
  941. hyphenFollows = false;
  942. stopIndex = mapping.endIndex;
  943. }
  944. hyphContext.updateOffset(stopIndex - startIndex);
  945. //log.info("Word: " + new String(textArray, startIndex, stopIndex - startIndex));
  946. for (int i = startIndex; i < stopIndex; i++) {
  947. int cp = Character.codePointAt(foText, i);
  948. i += Character.charCount(cp) - 1;
  949. newIPD = newIPD.plus(font.getCharWidth(cp));
  950. //if (i > startIndex) {
  951. if (i < stopIndex) {
  952. MinOptMax letterSpaceAdjust = letterSpaceAdjustArray[i + 1];
  953. if (i == stopIndex - 1 && hyphenFollows) {
  954. //the letter adjust here needs to be handled further down during
  955. //element generation because it depends on hyph/no-hyph condition
  956. letterSpaceAdjust = null;
  957. }
  958. if (letterSpaceAdjust != null) {
  959. newIPD = newIPD.plus(letterSpaceAdjust);
  960. }
  961. }
  962. }
  963. // add letter spaces
  964. boolean isWordEnd
  965. = (stopIndex == mapping.endIndex)
  966. && (mapping.letterSpaceCount < mapping.getWordLength());
  967. int letterSpaceCount = isWordEnd ? stopIndex - startIndex - 1 : stopIndex - startIndex;
  968. assert letterSpaceCount >= 0;
  969. newIPD = newIPD.plus(letterSpaceIPD.mult(letterSpaceCount));
  970. if (!(nothingChanged && stopIndex == mapping.endIndex && !hyphenFollows)) {
  971. // the new GlyphMapping object is not equal to the old one
  972. changeList.add(
  973. new PendingChange(
  974. new GlyphMapping(startIndex, stopIndex, 0,
  975. letterSpaceCount, newIPD, hyphenFollows,
  976. false, false, font, -1, null),
  977. glyphIndex));
  978. nothingChanged = false;
  979. }
  980. startIndex = stopIndex;
  981. }
  982. hasChanged |= !nothingChanged;
  983. }
  984. /** {@inheritDoc} */
  985. public boolean applyChanges(final List oldList) {
  986. return applyChanges(oldList, 0);
  987. }
  988. /** {@inheritDoc} */
  989. public boolean applyChanges(final List oldList, int depth) {
  990. // make sure the LM appears unfinished in between this call
  991. // and the next call to getChangedKnuthElements()
  992. setFinished(false);
  993. if (oldList.isEmpty()) {
  994. return false;
  995. }
  996. // Find the first and last positions in oldList that point to a GlyphMapping
  997. // (i.e. getLeafPos() != -1)
  998. LeafPosition startPos = null;
  999. LeafPosition endPos = null;
  1000. ListIterator oldListIter;
  1001. for (oldListIter = oldList.listIterator(); oldListIter.hasNext();) {
  1002. Position pos = ((KnuthElement) oldListIter.next()).getPosition();
  1003. Position innerPosition = pos.getPosition(depth);
  1004. assert (innerPosition == null || innerPosition instanceof LeafPosition);
  1005. startPos = (LeafPosition) innerPosition;
  1006. if (startPos != null && startPos.getLeafPos() != -1) {
  1007. break;
  1008. }
  1009. }
  1010. for (oldListIter = oldList.listIterator(oldList.size()); oldListIter.hasPrevious();) {
  1011. Position pos = ((KnuthElement) oldListIter.previous()).getPosition();
  1012. Position innerPosition = pos.getPosition(depth);
  1013. assert (innerPosition instanceof LeafPosition);
  1014. endPos = (LeafPosition) innerPosition;
  1015. if (endPos != null && endPos.getLeafPos() != -1) {
  1016. break;
  1017. }
  1018. }
  1019. // set start/end index, taking into account any offset due to
  1020. // changes applied to previous paragraphs
  1021. returnedIndices[0] = (startPos != null ? startPos.getLeafPos() : -1) + changeOffset;
  1022. returnedIndices[1] = (endPos != null ? endPos.getLeafPos() : -1) + changeOffset;
  1023. int mappingsAdded = 0;
  1024. int mappingsRemoved = 0;
  1025. if (!changeList.isEmpty()) {
  1026. int oldIndex = -1;
  1027. int changeIndex;
  1028. PendingChange currChange;
  1029. for (Object aChangeList : changeList) {
  1030. currChange = (PendingChange) aChangeList;
  1031. if (currChange.index == oldIndex) {
  1032. mappingsAdded++;
  1033. changeIndex = currChange.index + mappingsAdded - mappingsRemoved;
  1034. } else {
  1035. mappingsRemoved++;
  1036. mappingsAdded++;
  1037. oldIndex = currChange.index;
  1038. changeIndex = currChange.index + mappingsAdded - mappingsRemoved;
  1039. removeGlyphMapping(changeIndex);
  1040. }
  1041. addGlyphMapping(changeIndex, currChange.mapping);
  1042. }
  1043. changeList.clear();
  1044. }
  1045. // increase the end index for getChangedKnuthElements()
  1046. returnedIndices[1] += (mappingsAdded - mappingsRemoved);
  1047. // increase offset to use for subsequent paragraphs
  1048. changeOffset += (mappingsAdded - mappingsRemoved);
  1049. return hasChanged;
  1050. }
  1051. /** {@inheritDoc} */
  1052. public List getChangedKnuthElements(final List oldList, final int alignment) {
  1053. if (isFinished()) {
  1054. return null;
  1055. }
  1056. final LinkedList returnList = new LinkedList();
  1057. for (; returnedIndices[0] <= returnedIndices[1]; returnedIndices[0]++) {
  1058. GlyphMapping mapping = getGlyphMapping(returnedIndices[0]);
  1059. if (mapping.wordSpaceCount == 0) {
  1060. // mapping refers either to a word or a word fragment
  1061. addElementsForAWordFragment(returnList, alignment, mapping, returnedIndices[0]);
  1062. } else {
  1063. // mapping refers to a space
  1064. addElementsForASpace(returnList, alignment, mapping, returnedIndices[0]);
  1065. }
  1066. }
  1067. setFinished(returnedIndices[0] == mappings.size() - 1);
  1068. //ElementListObserver.observe(returnList, "text-changed", null);
  1069. return returnList;
  1070. }
  1071. /** {@inheritDoc} */
  1072. public String getWordChars(Position pos) {
  1073. int leafValue = ((LeafPosition) pos).getLeafPos() + changeOffset;
  1074. if (leafValue != -1) {
  1075. GlyphMapping mapping = getGlyphMapping(leafValue);
  1076. StringBuffer buffer = new StringBuffer(mapping.getWordLength());
  1077. for (int i = mapping.startIndex; i < mapping.endIndex; i++) {
  1078. buffer.append(foText.charAt(i));
  1079. }
  1080. return buffer.toString();
  1081. } else {
  1082. return "";
  1083. }
  1084. }
  1085. private void addElementsForASpace(List baseList, int alignment, GlyphMapping mapping,
  1086. int leafValue) {
  1087. LeafPosition mainPosition = new LeafPosition(this, leafValue);
  1088. if (!mapping.breakOppAfter) {
  1089. // a non-breaking space
  1090. if (alignment == Constants.EN_JUSTIFY) {
  1091. // the space can stretch and shrink, and must be preserved
  1092. // when starting a line
  1093. baseList.add(makeAuxiliaryZeroWidthBox());
  1094. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1095. baseList.add(new KnuthGlue(mapping.areaIPD, mainPosition, false));
  1096. } else {
  1097. // the space does not need to stretch or shrink, and must be
  1098. // preserved when starting a line
  1099. baseList.add(new KnuthInlineBox(mapping.areaIPD.getOpt(), null, mainPosition,
  1100. true));
  1101. }
  1102. } else {
  1103. if (foText.charAt(mapping.startIndex) != CharUtilities.SPACE
  1104. || foText.getWhitespaceTreatment() == Constants.EN_PRESERVE) {
  1105. // a breaking space that needs to be preserved
  1106. baseList.addAll(getElementsForBreakingSpace(alignment, mapping, auxiliaryPosition, 0,
  1107. mainPosition, mapping.areaIPD.getOpt(), true));
  1108. } else {
  1109. // a (possible block) of breaking spaces
  1110. baseList.addAll(getElementsForBreakingSpace(alignment, mapping, mainPosition,
  1111. mapping.areaIPD.getOpt(), auxiliaryPosition, 0, false));
  1112. }
  1113. }
  1114. }
  1115. private List getElementsForBreakingSpace(int alignment, GlyphMapping mapping, Position pos2,
  1116. int p2WidthOffset, Position pos3,
  1117. int p3WidthOffset, boolean skipZeroCheck) {
  1118. List elements = new ArrayList();
  1119. switch (alignment) {
  1120. case EN_CENTER:
  1121. // centered text:
  1122. // if the second element is chosen as a line break these elements
  1123. // add a constant amount of stretch at the end of a line and at the
  1124. // beginning of the next one, otherwise they don't add any stretch
  1125. elements.add(new KnuthGlue(lineEndBAP, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1126. auxiliaryPosition, false));
  1127. elements.add(makeZeroWidthPenalty(0));
  1128. elements.add(new KnuthGlue(p2WidthOffset - (lineStartBAP + lineEndBAP), -6
  1129. * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos2, false));
  1130. elements.add(makeAuxiliaryZeroWidthBox());
  1131. elements.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1132. elements.add(new KnuthGlue(lineStartBAP + p3WidthOffset,
  1133. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos3, false));
  1134. break;
  1135. case EN_START: // fall through
  1136. case EN_END:
  1137. // left- or right-aligned text:
  1138. // if the second element is chosen as a line break these elements
  1139. // add a constant amount of stretch at the end of a line, otherwise
  1140. // they don't add any stretch
  1141. KnuthGlue g;
  1142. if (skipZeroCheck || lineStartBAP != 0 || lineEndBAP != 0) {
  1143. g = new KnuthGlue(
  1144. lineEndBAP,
  1145. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, auxiliaryPosition, false);
  1146. elements.add(g);
  1147. elements.add(makeZeroWidthPenalty(0));
  1148. g = new KnuthGlue(
  1149. p2WidthOffset - (lineStartBAP + lineEndBAP),
  1150. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos2, false);
  1151. elements.add(g);
  1152. elements.add(makeAuxiliaryZeroWidthBox());
  1153. elements.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1154. g = new KnuthGlue(lineStartBAP + p3WidthOffset, 0, 0, pos3, false);
  1155. elements.add(g);
  1156. } else {
  1157. g = new KnuthGlue(
  1158. 0,
  1159. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, auxiliaryPosition, false);
  1160. elements.add(g);
  1161. elements.add(makeZeroWidthPenalty(0));
  1162. g = new KnuthGlue(
  1163. mapping.areaIPD.getOpt(),
  1164. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0, pos2, false);
  1165. elements.add(g);
  1166. }
  1167. break;
  1168. case EN_JUSTIFY:
  1169. // justified text:
  1170. // the stretch and shrink depends on the space width
  1171. elements.addAll(getElementsForJustifiedText(mapping, pos2, p2WidthOffset, pos3,
  1172. p3WidthOffset, skipZeroCheck, mapping.areaIPD.getShrink()));
  1173. break;
  1174. default:
  1175. // last line justified, the other lines unjustified:
  1176. // use only the space stretch
  1177. elements.addAll(getElementsForJustifiedText(mapping, pos2, p2WidthOffset, pos3,
  1178. p3WidthOffset, skipZeroCheck, 0));
  1179. }
  1180. return elements;
  1181. }
  1182. private List getElementsForJustifiedText(GlyphMapping mapping, Position pos2, int p2WidthOffset,
  1183. Position pos3, int p3WidthOffset, boolean skipZeroCheck,
  1184. int shrinkability) {
  1185. int stretchability = mapping.areaIPD.getStretch();
  1186. List elements = new ArrayList();
  1187. if (skipZeroCheck || lineStartBAP != 0 || lineEndBAP != 0) {
  1188. elements.add(new KnuthGlue(lineEndBAP, 0, 0, auxiliaryPosition, false));
  1189. elements.add(makeZeroWidthPenalty(0));
  1190. elements.add(new KnuthGlue(p2WidthOffset - (lineStartBAP + lineEndBAP),
  1191. stretchability, shrinkability, pos2, false));
  1192. elements.add(makeAuxiliaryZeroWidthBox());
  1193. elements.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1194. elements.add(new KnuthGlue(lineStartBAP + p3WidthOffset, 0, 0, pos3, false));
  1195. } else {
  1196. elements.add(new KnuthGlue(mapping.areaIPD.getOpt(), stretchability, shrinkability,
  1197. pos2, false));
  1198. }
  1199. return elements;
  1200. }
  1201. private void addElementsForAWordFragment(List baseList, int alignment, GlyphMapping mapping,
  1202. int leafValue) {
  1203. LeafPosition mainPosition = new LeafPosition(this, leafValue);
  1204. // if the last character of the word fragment is '-' or '/',
  1205. // the fragment could end a line; in this case, it loses one
  1206. // of its letter spaces;
  1207. boolean suppressibleLetterSpace = mapping.breakOppAfter && !mapping.isHyphenated;
  1208. if (letterSpaceIPD.isStiff()) {
  1209. // constant letter spacing
  1210. baseList.add(new KnuthInlineBox(suppressibleLetterSpace
  1211. ? mapping.areaIPD.getOpt() - letterSpaceIPD.getOpt()
  1212. : mapping.areaIPD.getOpt(),
  1213. alignmentContext, notifyPos(mainPosition), false));
  1214. } else {
  1215. // adjustable letter spacing
  1216. int unsuppressibleLetterSpaces = suppressibleLetterSpace
  1217. ? mapping.letterSpaceCount - 1
  1218. : mapping.letterSpaceCount;
  1219. baseList.add(new KnuthInlineBox(mapping.areaIPD.getOpt()
  1220. - mapping.letterSpaceCount * letterSpaceIPD.getOpt(),
  1221. alignmentContext, notifyPos(mainPosition), false));
  1222. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1223. baseList.add(new KnuthGlue(letterSpaceIPD.mult(unsuppressibleLetterSpaces),
  1224. auxiliaryPosition, true));
  1225. baseList.add(makeAuxiliaryZeroWidthBox());
  1226. }
  1227. // extra-elements if the word fragment is the end of a syllable,
  1228. // or it ends with a character that can be used as a line break
  1229. if (mapping.isHyphenated) {
  1230. MinOptMax widthIfNoBreakOccurs = null;
  1231. if (mapping.endIndex < foText.length()) {
  1232. //Add in kerning in no-break condition
  1233. widthIfNoBreakOccurs = letterSpaceAdjustArray[mapping.endIndex];
  1234. }
  1235. //if (mapping.breakIndex)
  1236. // the word fragment ends at the end of a syllable:
  1237. // if a break occurs the content width increases,
  1238. // otherwise nothing happens
  1239. addElementsForAHyphen(baseList, alignment, hyphIPD, widthIfNoBreakOccurs,
  1240. mapping.breakOppAfter);
  1241. } else if (suppressibleLetterSpace) {
  1242. // the word fragment ends with a character that acts as a hyphen
  1243. // if a break occurs the width does not increase,
  1244. // otherwise there is one more letter space
  1245. addElementsForAHyphen(baseList, alignment, 0, letterSpaceIPD, true);
  1246. }
  1247. }
  1248. private void addElementsForAHyphen(List baseList, int alignment, int widthIfBreakOccurs,
  1249. MinOptMax widthIfNoBreakOccurs, boolean unflagged) {
  1250. if (widthIfNoBreakOccurs == null) {
  1251. widthIfNoBreakOccurs = MinOptMax.ZERO;
  1252. }
  1253. switch (alignment) {
  1254. case EN_CENTER:
  1255. // centered text:
  1256. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1257. baseList.add(new KnuthGlue(lineEndBAP, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1258. auxiliaryPosition, true));
  1259. baseList.add(new KnuthPenalty(hyphIPD, unflagged
  1260. ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1261. : KnuthPenalty.FLAGGED_PENALTY, !unflagged, auxiliaryPosition, false));
  1262. baseList.add(new KnuthGlue(-(lineEndBAP + lineStartBAP),
  1263. -6 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1264. auxiliaryPosition, false));
  1265. baseList.add(makeAuxiliaryZeroWidthBox());
  1266. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1267. baseList.add(new KnuthGlue(lineStartBAP, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH,
  1268. 0, auxiliaryPosition, true));
  1269. break;
  1270. case EN_START: // fall through
  1271. case EN_END:
  1272. // left- or right-aligned text:
  1273. if (lineStartBAP != 0 || lineEndBAP != 0) {
  1274. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1275. baseList.add(new KnuthGlue(lineEndBAP,
  1276. 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1277. auxiliaryPosition, false));
  1278. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1279. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1280. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1281. auxiliaryPosition, false));
  1282. baseList.add(new KnuthGlue(widthIfNoBreakOccurs.getOpt()
  1283. - (lineStartBAP + lineEndBAP),
  1284. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1285. auxiliaryPosition, false));
  1286. baseList.add(makeAuxiliaryZeroWidthBox());
  1287. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1288. baseList.add(new KnuthGlue(lineStartBAP, 0, 0, auxiliaryPosition, false));
  1289. } else {
  1290. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1291. baseList.add(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1292. auxiliaryPosition, false));
  1293. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1294. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1295. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1296. auxiliaryPosition, false));
  1297. baseList.add(new KnuthGlue(widthIfNoBreakOccurs.getOpt(),
  1298. -3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
  1299. auxiliaryPosition, false));
  1300. }
  1301. break;
  1302. default:
  1303. // justified text, or last line justified:
  1304. // just a flagged penalty
  1305. if (lineStartBAP != 0 || lineEndBAP != 0) {
  1306. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1307. baseList.add(new KnuthGlue(lineEndBAP, 0, 0, auxiliaryPosition, false));
  1308. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1309. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1310. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1311. auxiliaryPosition, false));
  1312. // extra elements representing a letter space that is suppressed
  1313. // if a break occurs
  1314. if (widthIfNoBreakOccurs.isNonZero()) {
  1315. baseList.add(new KnuthGlue(widthIfNoBreakOccurs.getOpt()
  1316. - (lineStartBAP + lineEndBAP),
  1317. widthIfNoBreakOccurs.getStretch(),
  1318. widthIfNoBreakOccurs.getShrink(),
  1319. auxiliaryPosition, false));
  1320. } else {
  1321. baseList.add(new KnuthGlue(-(lineStartBAP + lineEndBAP), 0, 0,
  1322. auxiliaryPosition, false));
  1323. }
  1324. baseList.add(makeAuxiliaryZeroWidthBox());
  1325. baseList.add(makeZeroWidthPenalty(KnuthElement.INFINITE));
  1326. baseList.add(new KnuthGlue(lineStartBAP, 0, 0,
  1327. auxiliaryPosition, false));
  1328. } else {
  1329. baseList.add(new KnuthPenalty(widthIfBreakOccurs,
  1330. unflagged ? TextLayoutManager.SOFT_HYPHEN_PENALTY
  1331. : KnuthPenalty.FLAGGED_PENALTY, !unflagged,
  1332. auxiliaryPosition, false));
  1333. // extra elements representing a letter space that is suppressed
  1334. // if a break occurs
  1335. if (widthIfNoBreakOccurs.isNonZero()) {
  1336. baseList.add(new KnuthGlue(widthIfNoBreakOccurs, auxiliaryPosition, false));
  1337. }
  1338. }
  1339. }
  1340. }
  1341. @Override
  1342. public List<ChangeBar> getChangeBarList() {
  1343. if (foText == null) {
  1344. return null;
  1345. } else {
  1346. return foText.getChangeBarList();
  1347. }
  1348. }
  1349. /** {@inheritDoc} */
  1350. public String toString() {
  1351. return super.toString() + "{"
  1352. + "chars = \'"
  1353. + CharUtilities.toNCRefs(foText.getCharSequence().toString())
  1354. + "\'"
  1355. + ", len = " + foText.length()
  1356. + "}";
  1357. }
  1358. }