1. /*
  2. * @(#)LineBreakMeasurer.java 1.13 01/11/29
  3. *
  4. * Copyright 2002 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. *
  98. * // let styledText be an AttributedCharacterIterator containing at least
  99. * // one character
  100. *
  101. * LineBreakMeasurer measurer = new LineBreakMeasurer(styledText);
  102. * float wrappingWidth = getSize().width - 15;
  103. *
  104. * while (measurer.getPosition() < fStyledText.length()) {
  105. *
  106. * TextLayout layout = measurer.nextLayout(wrappingWidth);
  107. *
  108. * pen.y += (layout.getAscent());
  109. * float dx = layout.isLeftToRight() ?
  110. * 0 : (wrappingWidth - layout.getAdvance());
  111. *
  112. * layout.draw(graphics, pen.x + dx, pen.y);
  113. * pen.y += layout.getDescent() + layout.getLeading();
  114. * }
  115. * }
  116. * </pre>
  117. * </blockquote>
  118. * <p>
  119. * Rendering text with tabs. For simplicity, the overall text
  120. * direction is assumed to be left-to-right
  121. * <blockquote>
  122. * <pre>
  123. * public void paint(Graphics graphics) {
  124. *
  125. * float leftMargin = 10, rightMargin = 310;
  126. * float[] tabStops = { 100, 250 };
  127. *
  128. * // assume styledText is an AttributedCharacterIterator, and the number
  129. * // of tabs in styledText is tabCount
  130. *
  131. * int[] tabLocations = new int[tabCount+1];
  132. *
  133. * int i = 0;
  134. * for (char c = styledText.first(); c != styledText.DONE; c = styledText.next()) {
  135. * if (c == '\t') {
  136. * tabLocations[i++] = styledText.getIndex();
  137. * }
  138. * }
  139. * tabLocations[tabCount] = styledText.getEndIndex() - 1;
  140. *
  141. * // Now tabLocations has an entry for every tab's offset in
  142. * // the text. For convenience, the last entry is tabLocations
  143. * // is the offset of the last character in the text.
  144. *
  145. * LineBreakMeasurer measurer = new LineBreakMeasurer(styledText);
  146. * int currentTab = 0;
  147. * float verticalPos = 20;
  148. *
  149. * while (measurer.getPosition() < styledText.getEndIndex()) {
  150. *
  151. * // Lay out and draw each line. All segments on a line
  152. * // must be computed before any drawing can occur, since
  153. * // we must know the largest ascent on the line.
  154. * // TextLayouts are computed and stored in a Vector;
  155. * // their horizontal positions are stored in a parallel
  156. * // Vector.
  157. *
  158. * // lineContainsText is true after first segment is drawn
  159. * boolean lineContainsText = false;
  160. * boolean lineComplete = false;
  161. * float maxAscent = 0, maxDescent = 0;
  162. * float horizontalPos = leftMargin;
  163. * Vector layouts = new Vector(1);
  164. * Vector penPositions = new Vector(1);
  165. *
  166. * while (!lineComplete) {
  167. * float wrappingWidth = rightMargin - horizontalPos;
  168. * TextLayout layout =
  169. * measurer.nextLayout(wrappingWidth,
  170. * tabLocations[currentTab]+1,
  171. * lineContainsText);
  172. *
  173. * // layout can be null if lineContainsText is true
  174. * if (layout != null) {
  175. * layouts.addElement(layout);
  176. * penPositions.addElement(new Float(horizontalPos));
  177. * horizontalPos += layout.getAdvance();
  178. * maxAscent = Math.max(maxAscent, layout.getAscent());
  179. * maxDescent = Math.max(maxDescent,
  180. * layout.getDescent() + layout.getLeading());
  181. * } else {
  182. * lineComplete = true;
  183. * }
  184. *
  185. * lineContainsText = true;
  186. *
  187. * if (measurer.getPosition() == tabLocations[currentTab]+1) {
  188. * currentTab++;
  189. * }
  190. *
  191. * if (measurer.getPosition() == styledText.getEndIndex())
  192. * lineComplete = true;
  193. * else if (horizontalPos >= tabStops[tabStops.length-1])
  194. * lineComplete = true;
  195. *
  196. * if (!lineComplete) {
  197. * // move to next tab stop
  198. * int j;
  199. * for (j=0; horizontalPos >= tabStops[j]; j++) {}
  200. * horizontalPos = tabStops[j];
  201. * }
  202. * }
  203. *
  204. * verticalPos += maxAscent;
  205. *
  206. * Enumeration layoutEnum = layouts.elements();
  207. * Enumeration positionEnum = penPositions.elements();
  208. *
  209. * // now iterate through layouts and draw them
  210. * while (layoutEnum.hasMoreElements()) {
  211. * TextLayout nextLayout = (TextLayout) layoutEnum.nextElement();
  212. * Float nextPosition = (Float) positionEnum.nextElement();
  213. * nextLayout.draw(graphics, nextPosition.floatValue(), verticalPos);
  214. * }
  215. *
  216. * verticalPos += maxDescent;
  217. * }
  218. * }
  219. * </pre>
  220. * </blockquote>
  221. * @see TextLayout
  222. */
  223. public final class LineBreakMeasurer {
  224. private AttributedCharacterIterator text;
  225. private BreakIterator breakIter;
  226. private int pos;
  227. private int limit;
  228. private TextMeasurer measurer;
  229. /**
  230. * Constructs a <code>LineBreakMeasurer</code> for the specified text.
  231. * @param text the text for which this <code>LineBreakMeasurer</code>
  232. * produces <code>TextLayout</code> objects. The text must contain at
  233. * least one character. If the text available through
  234. * <code>iter</code> changes, further calls to this
  235. * <code>LineBreakMeasurer</code> instance are undefined (except,
  236. * in some cases, when <code>insertChar</code> or
  237. * <code>deleteChar</code> are invoked afterward - see below).
  238. * @param frc the {@link FontRenderContext} in which the text is
  239. * measured
  240. * @see LineBreakMeasurer#insertChar
  241. * @see LineBreakMeasurer#deleteChar
  242. */
  243. public LineBreakMeasurer(AttributedCharacterIterator text, FontRenderContext frc) {
  244. this(text, BreakIterator.getLineInstance(), frc);
  245. }
  246. /**
  247. * Constructs a <code>LineBreakMeasurer</code> for the specified text.
  248. * @param text the text for which this <code>LineBreakMeasurer</code>
  249. * produces <code>TextLayout</code> objects. The text must contain at
  250. * least one character. If the text available through
  251. * <code>iter</code> changes, further calls to this
  252. * <code>LineBreakMeasurer</code> instance are undefined (except,
  253. * in some cases, when <code>insertChar</code> or
  254. * <code>deleteChar</code> are invoked afterward - see below).
  255. * @param breakIter the {@link BreakIterator} which defines line
  256. * breaks
  257. * @param frc the <code>FontRenderContext</code> in which the text is
  258. * measured
  259. * @see LineBreakMeasurer#insertChar
  260. * @see LineBreakMeasurer#deleteChar
  261. */
  262. public LineBreakMeasurer(AttributedCharacterIterator text,
  263. BreakIterator breakIter,
  264. FontRenderContext frc) {
  265. this.text = text;
  266. this.breakIter = breakIter;
  267. this.breakIter.setText((CharacterIterator)text.clone());
  268. this.measurer = new TextMeasurer(text, frc);
  269. this.limit = text.getEndIndex();
  270. this.pos = text.getBeginIndex();
  271. text.setIndex(pos);
  272. }
  273. /**
  274. * Returns the position at the end of the next layout. Does NOT
  275. * update the current position of this <code>LineBreakMeasurer</code>.
  276. * @param maxAdvance the maximum visible advance permitted for
  277. * the text in the next layout
  278. * @return an offset in the text representing the limit of the
  279. * next <code>TextLayout</code>.
  280. */
  281. public int nextOffset(float maxAdvance) {
  282. return nextOffset(maxAdvance, limit, false);
  283. }
  284. /**
  285. * Returns the position at the end of the next layout. Does NOT
  286. * update the current position of this <code>LineBreakMeasurer</code>.
  287. * @param wrappingWidth the maximum visible advance permitted for
  288. * the text in the next layout
  289. * @param offsetLimit the first character that can not be included
  290. * in the next layout, even if the text after the limit would fit
  291. * within the wrapping width. <code>offsetLimit</code> must be
  292. * greater than the current position.
  293. * @param requireNextWord if <code>true</code>, the current position
  294. * that is returned if the entire next word does not fit within
  295. * <code>wrappingWidth</code>. If <code>false</code>, the offset
  296. * returned is at least one greater than the current position.
  297. * @return an offset in the text representing the limit of the
  298. * next <code>TextLayout</code>.
  299. */
  300. public int nextOffset(float wrappingWidth, int offsetLimit,
  301. boolean requireNextWord) {
  302. int nextOffset = pos;
  303. if (pos < limit) {
  304. if (offsetLimit <= pos) {
  305. throw new IllegalArgumentException("offsetLimit must be after current position");
  306. }
  307. int charAtMaxAdvance =
  308. measurer.getLineBreakIndex(pos, wrappingWidth);
  309. text.setIndex(charAtMaxAdvance);
  310. if (charAtMaxAdvance == limit) {
  311. nextOffset = limit;
  312. }
  313. else if (Character.isWhitespace(text.current())) {
  314. nextOffset = breakIter.following(charAtMaxAdvance);
  315. }
  316. else {
  317. // Break is in a word; back up to previous break.
  318. breakIter.following(charAtMaxAdvance);
  319. nextOffset = breakIter.previous();
  320. if (nextOffset <= pos) {
  321. // first word doesn't fit on line
  322. if (requireNextWord) {
  323. nextOffset = pos;
  324. }
  325. else {
  326. nextOffset = Math.max(pos+1, charAtMaxAdvance);
  327. }
  328. }
  329. }
  330. }
  331. if (nextOffset > offsetLimit) {
  332. nextOffset = offsetLimit;
  333. }
  334. return nextOffset;
  335. }
  336. /**
  337. * Returns the next layout, and updates the current position.
  338. * @param maxAdvance the maximum visible advance permitted for
  339. * the text in the next layout
  340. * @return a <code>TextLayout</code>, beginning at the current
  341. * position, which represents the next line fitting within
  342. * <code>maxAdvance</code>.
  343. */
  344. public TextLayout nextLayout(float maxAdvance) {
  345. return nextLayout(maxAdvance, limit, false);
  346. }
  347. /**
  348. * Returns the next layout, and updates the current position.
  349. * @param wrappingWidth the maximum visible advance permitted
  350. * for the text in the next layout
  351. * @param offsetLimit the first character that can not be
  352. * included in the next layout, even if the text after the limit
  353. * would fit within the wrapping width. <code>offsetLimit</code>
  354. * must be greater than the current position.
  355. * @param requireNextWord if <code>true</code>, and if the entire word
  356. * at the current position does not fit within the wrapping width,
  357. * <code>null</code> is returned. If <code>false</code>, a valid
  358. * layout is returned that includes at least the character at the
  359. * current position.
  360. * @return a <code>TextLayout</code>, beginning at the current
  361. * position, that represents the next line fitting within
  362. * <code>maxAdvance</code>. If the current position is at the end of
  363. * the text used by this <code>LineBreakMeasurer</code>,
  364. * <code>null</code> is returned.
  365. */
  366. public TextLayout nextLayout(float wrappingWidth, int offsetLimit,
  367. boolean requireNextWord) {
  368. if (pos < text.getEndIndex()) {
  369. int layoutLimit = nextOffset(wrappingWidth, offsetLimit, requireNextWord);
  370. if (layoutLimit == pos) {
  371. return null;
  372. }
  373. TextLayout result = measurer.getLayout(pos, layoutLimit);
  374. pos = layoutLimit;
  375. return result;
  376. } else {
  377. return null;
  378. }
  379. }
  380. /**
  381. * Returns the current position of this
  382. * <code>LineBreakMeasurer</code>.
  383. * @return the current position of this
  384. * <code>LineBreakMeasurer</code>.
  385. * @see #setPosition
  386. */
  387. public int getPosition() {
  388. return pos;
  389. }
  390. /**
  391. * Sets the current position of this <code>LineBreakMeasurer</code>.
  392. * @param newPosition the current position of this
  393. * <code>LineBreakMeasurer</code>. The position should be within the
  394. * text used to construct this <code>LineBreakMeasurer</code> (or in
  395. * the text most recently passed to <code>insertChar</code>
  396. * or <code>deleteChar</code>.
  397. * @see #getPosition
  398. */
  399. public void setPosition(int newPosition) {
  400. if (newPosition < text.getBeginIndex() || newPosition > limit) {
  401. throw new IllegalArgumentException("position is out of range");
  402. }
  403. pos = newPosition;
  404. }
  405. /**
  406. * Updates this <code>LineBreakMeasurer</code> after a single
  407. * character is inserted into the text.
  408. * @param newParagraph the text after the insertion
  409. * @param insertPos the position in the text at which the character
  410. * is inserted
  411. * @see #deleteChar
  412. */
  413. public void insertChar(AttributedCharacterIterator newParagraph,
  414. int insertPos) {
  415. text = newParagraph;
  416. breakIter.setText((CharacterIterator)text.clone());
  417. limit = text.getEndIndex();
  418. pos = text.getBeginIndex();
  419. measurer.insertChar(newParagraph, insertPos);
  420. }
  421. /**
  422. * Updates this <code>LineBreakMeasurer</code> after a single
  423. * character is deleted from the text.
  424. * @param newParagraph the text after the deletion
  425. * @param deletePos the position in the text at which the character
  426. * is deleted
  427. * @see #insertChar
  428. */
  429. public void deleteChar(AttributedCharacterIterator newParagraph,
  430. int deletePos) {
  431. text = newParagraph;
  432. breakIter.setText((CharacterIterator)text.clone());
  433. limit = text.getEndIndex();
  434. pos = text.getBeginIndex();
  435. measurer.deleteChar(newParagraph, deletePos);
  436. }
  437. }