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