Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TextLayoutManager.java 63KB

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