1. /*
  2. * @(#)LineBreakMeasurer.java 1.22 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. /*
  8. * (C) Copyright Taligent, Inc. 1996 - 1997, All Rights Reserved
  9. * (C) Copyright IBM Corp. 1996 - 1998, All Rights Reserved
  10. *
  11. * The original version of this source code and documentation is
  12. * copyrighted and owned by Taligent, Inc., a wholly-owned subsidiary
  13. * of IBM. These materials are provided under terms of a License
  14. * Agreement between Taligent and Sun. This technology is protected
  15. * by multiple US and International patents.
  16. *
  17. * This notice and attribution to Taligent may not be removed.
  18. * Taligent is a registered trademark of Taligent, Inc.
  19. *
  20. */
  21. package java.awt.font;
  22. import java.text.BreakIterator;
  23. import java.text.CharacterIterator;
  24. import java.text.AttributedCharacterIterator;
  25. import java.awt.font.FontRenderContext;
  26. /**
  27. * The <code>LineBreakMeasurer</code> class allows styled text to be
  28. * broken into lines (or segments) that fit within a particular visual
  29. * advance. This is useful for clients who wish to display a paragraph of
  30. * text that fits within a specific width, called the <b>wrapping
  31. * width</b>.
  32. * <p>
  33. * <code>LineBreakMeasurer</code> is constructed with an iterator over
  34. * styled text. The iterator's range should be a single paragraph in the
  35. * text.
  36. * <code>LineBreakMeasurer</code> maintains a position in the text for the
  37. * start of the next text segment. Initially, this position is the
  38. * start of text. Paragraphs are assigned an overall direction (either
  39. * left-to-right or right-to-left) according to the bidirectional
  40. * formatting rules. All segments obtained from a paragraph have the
  41. * same direction as the paragraph.
  42. * <p>
  43. * Segments of text are obtained by calling the method
  44. * <code>nextLayout</code>, which returns a {@link TextLayout}
  45. * representing the text that fits within the wrapping width.
  46. * The <code>nextLayout</code> method moves the current position
  47. * to the end of the layout returned from <code>nextLayout</code>.
  48. * <p>
  49. * <code>LineBreakMeasurer</code> implements the most commonly used
  50. * line-breaking policy: Every word that fits within the wrapping
  51. * width is placed on the line. If the first word does not fit, then all
  52. * of the characters that fit within the wrapping width are placed on the
  53. * line. At least one character is placed on each line.
  54. * <p>
  55. * The <code>TextLayout</code> instances returned by
  56. * <code>LineBreakMeasurer</code> treat tabs like 0-width spaces. Clients
  57. * who wish to obtain tab-delimited segments for positioning should use
  58. * the overload of <code>nextLayout</code> which takes a limiting offset
  59. * in the text.
  60. * The limiting offset should be the first character after the tab.
  61. * The <code>TextLayout</code> objects returned from this method end
  62. * at the limit provided (or before, if the text between the current
  63. * position and the limit won't fit entirely within the wrapping
  64. * width).
  65. * <p>
  66. * Clients who are laying out tab-delimited text need a slightly
  67. * different line-breaking policy after the first segment has been
  68. * placed on a line. Instead of fitting partial words in the
  69. * remaining space, they should place words which don't fit in the
  70. * remaining space entirely on the next line. This change of policy
  71. * can be requested in the overload of <code>nextLayout</code> which
  72. * takes a <code>boolean</code> parameter. If this parameter is
  73. * <code>true</code>, <code>nextLayout</code> returns
  74. * <code>null</code> if the first word won't fit in
  75. * the given space. See the tab sample below.
  76. * <p>
  77. * In general, if the text used to construct the
  78. * <code>LineBreakMeasurer</code> changes, a new
  79. * <code>LineBreakMeasurer</code> must be constructed to reflect
  80. * the change. (The old <code>LineBreakMeasurer</code> continues to
  81. * function properly, but it won't be aware of the text change.)
  82. * Nevertheless, if the text change is the insertion or deletion of a
  83. * single character, an existing <code>LineBreakMeasurer</code> can be
  84. * 'updated' by calling <code>insertChar</code> or
  85. * <code>deleteChar</code>. Updating an existing
  86. * <code>LineBreakMeasurer</code> is much faster than creating a new one.
  87. * Clients who modify text based on user typing should take advantage
  88. * of these methods.
  89. * <p>
  90. * <strong>Examples</strong>:<p>
  91. * Rendering a paragraph in a component
  92. * <blockquote>
  93. * <pre>
  94. * public void paint(Graphics graphics) {
  95. *
  96. * Point2D pen = new Point2D(10, 20);
  97. * Graphics2D g2d = (Graphics2D)graphics;
  98. * FontRenderContext frc = g2d.getFontRenderContext();
  99. *
  100. * // let styledText be an AttributedCharacterIterator containing at least
  101. * // one character
  102. *
  103. * LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);
  104. * float wrappingWidth = getSize().width - 15;
  105. *
  106. * while (measurer.getPosition() < fStyledText.length()) {
  107. *
  108. * TextLayout layout = measurer.nextLayout(wrappingWidth);
  109. *
  110. * pen.y += (layout.getAscent());
  111. * float dx = layout.isLeftToRight() ?
  112. * 0 : (wrappingWidth - layout.getAdvance());
  113. *
  114. * layout.draw(graphics, pen.x + dx, pen.y);
  115. * pen.y += layout.getDescent() + layout.getLeading();
  116. * }
  117. * }
  118. * </pre>
  119. * </blockquote>
  120. * <p>
  121. * Rendering text with tabs. For simplicity, the overall text
  122. * direction is assumed to be left-to-right
  123. * <blockquote>
  124. * <pre>
  125. * public void paint(Graphics graphics) {
  126. *
  127. * float leftMargin = 10, rightMargin = 310;
  128. * float[] tabStops = { 100, 250 };
  129. *
  130. * // assume styledText is an AttributedCharacterIterator, and the number
  131. * // of tabs in styledText is tabCount
  132. *
  133. * int[] tabLocations = new int[tabCount+1];
  134. *
  135. * int i = 0;
  136. * for (char c = styledText.first(); c != styledText.DONE; c = styledText.next()) {
  137. * if (c == '\t') {
  138. * tabLocations[i++] = styledText.getIndex();
  139. * }
  140. * }
  141. * tabLocations[tabCount] = styledText.getEndIndex() - 1;
  142. *
  143. * // Now tabLocations has an entry for every tab's offset in
  144. * // the text. For convenience, the last entry is tabLocations
  145. * // is the offset of the last character in the text.
  146. *
  147. * LineBreakMeasurer measurer = new LineBreakMeasurer(styledText);
  148. * int currentTab = 0;
  149. * float verticalPos = 20;
  150. *
  151. * while (measurer.getPosition() < styledText.getEndIndex()) {
  152. *
  153. * // Lay out and draw each line. All segments on a line
  154. * // must be computed before any drawing can occur, since
  155. * // we must know the largest ascent on the line.
  156. * // TextLayouts are computed and stored in a Vector;
  157. * // their horizontal positions are stored in a parallel
  158. * // Vector.
  159. *
  160. * // lineContainsText is true after first segment is drawn
  161. * boolean lineContainsText = false;
  162. * boolean lineComplete = false;
  163. * float maxAscent = 0, maxDescent = 0;
  164. * float horizontalPos = leftMargin;
  165. * Vector layouts = new Vector(1);
  166. * Vector penPositions = new Vector(1);
  167. *
  168. * while (!lineComplete) {
  169. * float wrappingWidth = rightMargin - horizontalPos;
  170. * TextLayout layout =
  171. * measurer.nextLayout(wrappingWidth,
  172. * tabLocations[currentTab]+1,
  173. * lineContainsText);
  174. *
  175. * // layout can be null if lineContainsText is true
  176. * if (layout != null) {
  177. * layouts.addElement(layout);
  178. * penPositions.addElement(new Float(horizontalPos));
  179. * horizontalPos += layout.getAdvance();
  180. * maxAscent = Math.max(maxAscent, layout.getAscent());
  181. * maxDescent = Math.max(maxDescent,
  182. * layout.getDescent() + layout.getLeading());
  183. * } else {
  184. * lineComplete = true;
  185. * }
  186. *
  187. * lineContainsText = true;
  188. *
  189. * if (measurer.getPosition() == tabLocations[currentTab]+1) {
  190. * currentTab++;
  191. * }
  192. *
  193. * if (measurer.getPosition() == styledText.getEndIndex())
  194. * lineComplete = true;
  195. * else if (horizontalPos >= tabStops[tabStops.length-1])
  196. * lineComplete = true;
  197. *
  198. * if (!lineComplete) {
  199. * // move to next tab stop
  200. * int j;
  201. * for (j=0; horizontalPos >= tabStops[j]; j++) {}
  202. * horizontalPos = tabStops[j];
  203. * }
  204. * }
  205. *
  206. * verticalPos += maxAscent;
  207. *
  208. * Enumeration layoutEnum = layouts.elements();
  209. * Enumeration positionEnum = penPositions.elements();
  210. *
  211. * // now iterate through layouts and draw them
  212. * while (layoutEnum.hasMoreElements()) {
  213. * TextLayout nextLayout = (TextLayout) layoutEnum.nextElement();
  214. * Float nextPosition = (Float) positionEnum.nextElement();
  215. * nextLayout.draw(graphics, nextPosition.floatValue(), verticalPos);
  216. * }
  217. *
  218. * verticalPos += maxDescent;
  219. * }
  220. * }
  221. * </pre>
  222. * </blockquote>
  223. * @see TextLayout
  224. */
  225. public final class LineBreakMeasurer {
  226. private BreakIterator breakIter;
  227. private int start;
  228. private int pos;
  229. private int limit;
  230. private TextMeasurer measurer;
  231. private CharArrayIterator charIter;
  232. /**
  233. * Constructs a <code>LineBreakMeasurer</code> for the specified text.
  234. *
  235. * @param text the text for which this <code>LineBreakMeasurer</code>
  236. * produces <code>TextLayout</code> objects; the text must contain
  237. * at least one character; if the text available through
  238. * <code>iter</code> changes, further calls to this
  239. * <code>LineBreakMeasurer</code> instance are undefined (except,
  240. * in some cases, when <code>insertChar</code> or
  241. * <code>deleteChar</code> are invoked afterward - see below)
  242. * @param frc contains information about a graphics device which is
  243. * needed to measure the text correctly;
  244. * text measurements can vary slightly depending on the
  245. * device resolution, and attributes such as antialiasing; this
  246. * parameter does not specify a translation between the
  247. * <code>LineBreakMeasurer</code> and user space
  248. * @see LineBreakMeasurer#insertChar
  249. * @see LineBreakMeasurer#deleteChar
  250. */
  251. public LineBreakMeasurer(AttributedCharacterIterator text, FontRenderContext frc) {
  252. this(text, BreakIterator.getLineInstance(), frc);
  253. }
  254. /**
  255. * Constructs a <code>LineBreakMeasurer</code> for the specified text.
  256. *
  257. * @param text the text for which this <code>LineBreakMeasurer</code>
  258. * produces <code>TextLayout</code> objects; the text must contain
  259. * at least one character; if the text available through
  260. * <code>iter</code> changes, further calls to this
  261. * <code>LineBreakMeasurer</code> instance are undefined (except,
  262. * in some cases, when <code>insertChar</code> or
  263. * <code>deleteChar</code> are invoked afterward - see below)
  264. * @param breakIter the {@link BreakIterator} which defines line
  265. * breaks
  266. * @param frc contains information about a graphics device which is
  267. * needed to measure the text correctly;
  268. * text measurements can vary slightly depending on the
  269. * device resolution, and attributes such as antialiasing; this
  270. * parameter does not specify a translation between the
  271. * <code>LineBreakMeasurer</code> and user space
  272. * @throws IllegalArgumentException if the text has less than one character
  273. * @see LineBreakMeasurer#insertChar
  274. * @see LineBreakMeasurer#deleteChar
  275. */
  276. public LineBreakMeasurer(AttributedCharacterIterator text,
  277. BreakIterator breakIter,
  278. FontRenderContext frc) {
  279. if (text.getEndIndex() - text.getBeginIndex() < 1) {
  280. throw new IllegalArgumentException("Text must contain at least one character.");
  281. }
  282. this.breakIter = breakIter;
  283. this.measurer = new TextMeasurer(text, frc);
  284. this.limit = text.getEndIndex();
  285. this.pos = this.start = text.getBeginIndex();
  286. charIter = new CharArrayIterator(measurer.getChars(), this.start);
  287. this.breakIter.setText(charIter);
  288. }
  289. /**
  290. * Returns the position at the end of the next layout. Does NOT
  291. * update the current position of this <code>LineBreakMeasurer</code>.
  292. *
  293. * @param wrappingWidth the maximum visible advance permitted for
  294. * the text in the next layout
  295. * @return an offset in the text representing the limit of the
  296. * next <code>TextLayout</code>.
  297. */
  298. public int nextOffset(float wrappingWidth) {
  299. return nextOffset(wrappingWidth, limit, false);
  300. }
  301. /**
  302. * Returns the position at the end of the next layout. Does NOT
  303. * update the current position of this <code>LineBreakMeasurer</code>.
  304. *
  305. * @param wrappingWidth the maximum visible advance permitted for
  306. * the text in the next layout
  307. * @param offsetLimit the first character that can not be included
  308. * in the next layout, even if the text after the limit would fit
  309. * within the wrapping width; <code>offsetLimit</code> must be
  310. * greater than the current position
  311. * @param requireNextWord if <code>true</code>, the current position
  312. * that is returned if the entire next word does not fit within
  313. * <code>wrappingWidth</code> if <code>false</code>, the offset
  314. * returned is at least one greater than the current position
  315. * @return an offset in the text representing the limit of the
  316. * next <code>TextLayout</code>
  317. */
  318. public int nextOffset(float wrappingWidth, int offsetLimit,
  319. boolean requireNextWord) {
  320. int nextOffset = pos;
  321. if (pos < limit) {
  322. if (offsetLimit <= pos) {
  323. throw new IllegalArgumentException("offsetLimit must be after current position");
  324. }
  325. int charAtMaxAdvance =
  326. measurer.getLineBreakIndex(pos, wrappingWidth);
  327. if (charAtMaxAdvance == limit) {
  328. nextOffset = limit;
  329. }
  330. else if (Character.isWhitespace(measurer.getChars()[charAtMaxAdvance-start])) {
  331. nextOffset = breakIter.following(charAtMaxAdvance);
  332. }
  333. else {
  334. // Break is in a word; back up to previous break.
  335. // NOTE: I think that breakIter.preceding(limit) should be
  336. // equivalent to breakIter.last(), breakIter.previous() but
  337. // the authors of BreakIterator thought otherwise...
  338. // If they were equivalent then the first branch would be
  339. // unnecessary.
  340. int testPos = charAtMaxAdvance + 1;
  341. if (testPos == limit) {
  342. breakIter.last();
  343. nextOffset = breakIter.previous();
  344. }
  345. else {
  346. nextOffset = breakIter.preceding(testPos);
  347. }
  348. if (nextOffset <= pos) {
  349. // first word doesn't fit on line
  350. if (requireNextWord) {
  351. nextOffset = pos;
  352. }
  353. else {
  354. nextOffset = Math.max(pos+1, charAtMaxAdvance);
  355. }
  356. }
  357. }
  358. }
  359. if (nextOffset > offsetLimit) {
  360. nextOffset = offsetLimit;
  361. }
  362. return nextOffset;
  363. }
  364. /**
  365. * Returns the next layout, and updates the current position.
  366. *
  367. * @param wrappingWidth the maximum visible advance permitted for
  368. * the text in the next layout
  369. * @return a <code>TextLayout</code>, beginning at the current
  370. * position, which represents the next line fitting within
  371. * <code>wrappingWidth</code>
  372. */
  373. public TextLayout nextLayout(float wrappingWidth) {
  374. return nextLayout(wrappingWidth, limit, false);
  375. }
  376. /**
  377. * Returns the next layout, and updates the current position.
  378. *
  379. * @param wrappingWidth the maximum visible advance permitted
  380. * for the text in the next layout
  381. * @param offsetLimit the first character that can not be
  382. * included in the next layout, even if the text after the limit
  383. * would fit within the wrapping width; <code>offsetLimit</code>
  384. * must be greater than the current position
  385. * @param requireNextWord if <code>true</code>, and if the entire word
  386. * at the current position does not fit within the wrapping width,
  387. * <code>null</code> is returned. If <code>false</code>, a valid
  388. * layout is returned that includes at least the character at the
  389. * current position
  390. * @return a <code>TextLayout</code>, beginning at the current
  391. * position, that represents the next line fitting within
  392. * <code>wrappingWidth</code>. If the current position is at the end
  393. * of the text used by this <code>LineBreakMeasurer</code>,
  394. * <code>null</code> is returned
  395. */
  396. public TextLayout nextLayout(float wrappingWidth, int offsetLimit,
  397. boolean requireNextWord) {
  398. if (pos < limit) {
  399. int layoutLimit = nextOffset(wrappingWidth, offsetLimit, requireNextWord);
  400. if (layoutLimit == pos) {
  401. return null;
  402. }
  403. TextLayout result = measurer.getLayout(pos, layoutLimit);
  404. pos = layoutLimit;
  405. return result;
  406. } else {
  407. return null;
  408. }
  409. }
  410. /**
  411. * Returns the current position of this <code>LineBreakMeasurer</code>.
  412. *
  413. * @return the current position of this <code>LineBreakMeasurer</code>
  414. * @see #setPosition
  415. */
  416. public int getPosition() {
  417. return pos;
  418. }
  419. /**
  420. * Sets the current position of this <code>LineBreakMeasurer</code>.
  421. *
  422. * @param newPosition the current position of this
  423. * <code>LineBreakMeasurer</code> the position should be within the
  424. * text used to construct this <code>LineBreakMeasurer</code> (or in
  425. * the text most recently passed to <code>insertChar</code>
  426. * or <code>deleteChar</code>
  427. * @see #getPosition
  428. */
  429. public void setPosition(int newPosition) {
  430. if (newPosition < start || newPosition > limit) {
  431. throw new IllegalArgumentException("position is out of range");
  432. }
  433. pos = newPosition;
  434. }
  435. /**
  436. * Updates this <code>LineBreakMeasurer</code> after a single
  437. * character is inserted into the text, and sets the current
  438. * position to the beginning of the paragraph.
  439. *
  440. * @param newParagraph the text after the insertion
  441. * @param insertPos the position in the text at which the character
  442. * is inserted
  443. * @throws IndexOutOfBoundsException if <code>insertPos</code> is less
  444. * than the start of <code>newParagraph</code> or greater than
  445. * or equal to the end of <code>newParagraph</code>
  446. * @throws NullPointerException if <code>newParagraph</code> is
  447. * <code>null</code>
  448. * @see #deleteChar
  449. */
  450. public void insertChar(AttributedCharacterIterator newParagraph,
  451. int insertPos) {
  452. measurer.insertChar(newParagraph, insertPos);
  453. limit = newParagraph.getEndIndex();
  454. pos = start = newParagraph.getBeginIndex();
  455. charIter.reset(measurer.getChars(), newParagraph.getBeginIndex());
  456. breakIter.setText(charIter);
  457. }
  458. /**
  459. * Updates this <code>LineBreakMeasurer</code> after a single
  460. * character is deleted from the text, and sets the current
  461. * position to the beginning of the paragraph.
  462. * @param newParagraph the text after the deletion
  463. * @param deletePos the position in the text at which the character
  464. * is deleted
  465. * @throws IndexOutOfBoundsException if <code>deletePos</code> is
  466. * less than the start of <code>newParagraph</code> or greater
  467. * than the end of <code>newParagraph</code>
  468. * @throws NullPointerException if <code>newParagraph</code> is
  469. * <code>null</code>
  470. * @see #insertChar
  471. */
  472. public void deleteChar(AttributedCharacterIterator newParagraph,
  473. int deletePos) {
  474. measurer.deleteChar(newParagraph, deletePos);
  475. limit = newParagraph.getEndIndex();
  476. pos = start = newParagraph.getBeginIndex();
  477. charIter.reset(measurer.getChars(), start);
  478. breakIter.setText(charIter);
  479. }
  480. }