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

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