KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > awt > font > LineBreakMeasurer


1 /*
2  * @(#)LineBreakMeasurer.java 1.23 03/12/19
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 /*
9  * (C) Copyright Taligent, Inc. 1996 - 1997, All Rights Reserved
10  * (C) Copyright IBM Corp. 1996 - 1998, All Rights Reserved
11  *
12  * The original version of this source code and documentation is
13  * copyrighted and owned by Taligent, Inc., a wholly-owned subsidiary
14  * of IBM. These materials are provided under terms of a License
15  * Agreement between Taligent and Sun. This technology is protected
16  * by multiple US and International patents.
17  *
18  * This notice and attribution to Taligent may not be removed.
19  * Taligent is a registered trademark of Taligent, Inc.
20  *
21  */

22
23 package java.awt.font;
24
25 import java.text.BreakIterator JavaDoc;
26 import java.text.CharacterIterator JavaDoc;
27 import java.text.AttributedCharacterIterator JavaDoc;
28 import java.awt.font.FontRenderContext JavaDoc;
29
30 /**
31  * The <code>LineBreakMeasurer</code> class allows styled text to be
32  * broken into lines (or segments) that fit within a particular visual
33  * advance. This is useful for clients who wish to display a paragraph of
34  * text that fits within a specific width, called the <b>wrapping
35  * width</b>.
36  * <p>
37  * <code>LineBreakMeasurer</code> is constructed with an iterator over
38  * styled text. The iterator's range should be a single paragraph in the
39  * text.
40  * <code>LineBreakMeasurer</code> maintains a position in the text for the
41  * start of the next text segment. Initially, this position is the
42  * start of text. Paragraphs are assigned an overall direction (either
43  * left-to-right or right-to-left) according to the bidirectional
44  * formatting rules. All segments obtained from a paragraph have the
45  * same direction as the paragraph.
46  * <p>
47  * Segments of text are obtained by calling the method
48  * <code>nextLayout</code>, which returns a {@link TextLayout}
49  * representing the text that fits within the wrapping width.
50  * The <code>nextLayout</code> method moves the current position
51  * to the end of the layout returned from <code>nextLayout</code>.
52  * <p>
53  * <code>LineBreakMeasurer</code> implements the most commonly used
54  * line-breaking policy: Every word that fits within the wrapping
55  * width is placed on the line. If the first word does not fit, then all
56  * of the characters that fit within the wrapping width are placed on the
57  * line. At least one character is placed on each line.
58  * <p>
59  * The <code>TextLayout</code> instances returned by
60  * <code>LineBreakMeasurer</code> treat tabs like 0-width spaces. Clients
61  * who wish to obtain tab-delimited segments for positioning should use
62  * the overload of <code>nextLayout</code> which takes a limiting offset
63  * in the text.
64  * The limiting offset should be the first character after the tab.
65  * The <code>TextLayout</code> objects returned from this method end
66  * at the limit provided (or before, if the text between the current
67  * position and the limit won't fit entirely within the wrapping
68  * width).
69  * <p>
70  * Clients who are laying out tab-delimited text need a slightly
71  * different line-breaking policy after the first segment has been
72  * placed on a line. Instead of fitting partial words in the
73  * remaining space, they should place words which don't fit in the
74  * remaining space entirely on the next line. This change of policy
75  * can be requested in the overload of <code>nextLayout</code> which
76  * takes a <code>boolean</code> parameter. If this parameter is
77  * <code>true</code>, <code>nextLayout</code> returns
78  * <code>null</code> if the first word won't fit in
79  * the given space. See the tab sample below.
80  * <p>
81  * In general, if the text used to construct the
82  * <code>LineBreakMeasurer</code> changes, a new
83  * <code>LineBreakMeasurer</code> must be constructed to reflect
84  * the change. (The old <code>LineBreakMeasurer</code> continues to
85  * function properly, but it won't be aware of the text change.)
86  * Nevertheless, if the text change is the insertion or deletion of a
87  * single character, an existing <code>LineBreakMeasurer</code> can be
88  * 'updated' by calling <code>insertChar</code> or
89  * <code>deleteChar</code>. Updating an existing
90  * <code>LineBreakMeasurer</code> is much faster than creating a new one.
91  * Clients who modify text based on user typing should take advantage
92  * of these methods.
93  * <p>
94  * <strong>Examples</strong>:<p>
95  * Rendering a paragraph in a component
96  * <blockquote>
97  * <pre>
98  * public void paint(Graphics graphics) {
99  *
100  * Point2D pen = new Point2D(10, 20);
101  * Graphics2D g2d = (Graphics2D)graphics;
102  * FontRenderContext frc = g2d.getFontRenderContext();
103  *
104  * // let styledText be an AttributedCharacterIterator containing at least
105  * // one character
106  *
107  * LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);
108  * float wrappingWidth = getSize().width - 15;
109  *
110  * while (measurer.getPosition() < fStyledText.length()) {
111  *
112  * TextLayout layout = measurer.nextLayout(wrappingWidth);
113  *
114  * pen.y += (layout.getAscent());
115  * float dx = layout.isLeftToRight() ?
116  * 0 : (wrappingWidth - layout.getAdvance());
117  *
118  * layout.draw(graphics, pen.x + dx, pen.y);
119  * pen.y += layout.getDescent() + layout.getLeading();
120  * }
121  * }
122  * </pre>
123  * </blockquote>
124  * <p>
125  * Rendering text with tabs. For simplicity, the overall text
126  * direction is assumed to be left-to-right
127  * <blockquote>
128  * <pre>
129  * public void paint(Graphics graphics) {
130  *
131  * float leftMargin = 10, rightMargin = 310;
132  * float[] tabStops = { 100, 250 };
133  *
134  * // assume styledText is an AttributedCharacterIterator, and the number
135  * // of tabs in styledText is tabCount
136  *
137  * int[] tabLocations = new int[tabCount+1];
138  *
139  * int i = 0;
140  * for (char c = styledText.first(); c != styledText.DONE; c = styledText.next()) {
141  * if (c == '\t') {
142  * tabLocations[i++] = styledText.getIndex();
143  * }
144  * }
145  * tabLocations[tabCount] = styledText.getEndIndex() - 1;
146  *
147  * // Now tabLocations has an entry for every tab's offset in
148  * // the text. For convenience, the last entry is tabLocations
149  * // is the offset of the last character in the text.
150  *
151  * LineBreakMeasurer measurer = new LineBreakMeasurer(styledText);
152  * int currentTab = 0;
153  * float verticalPos = 20;
154  *
155  * while (measurer.getPosition() < styledText.getEndIndex()) {
156  *
157  * // Lay out and draw each line. All segments on a line
158  * // must be computed before any drawing can occur, since
159  * // we must know the largest ascent on the line.
160  * // TextLayouts are computed and stored in a Vector;
161  * // their horizontal positions are stored in a parallel
162  * // Vector.
163  *
164  * // lineContainsText is true after first segment is drawn
165  * boolean lineContainsText = false;
166  * boolean lineComplete = false;
167  * float maxAscent = 0, maxDescent = 0;
168  * float horizontalPos = leftMargin;
169  * Vector layouts = new Vector(1);
170  * Vector penPositions = new Vector(1);
171  *
172  * while (!lineComplete) {
173  * float wrappingWidth = rightMargin - horizontalPos;
174  * TextLayout layout =
175  * measurer.nextLayout(wrappingWidth,
176  * tabLocations[currentTab]+1,
177  * lineContainsText);
178  *
179  * // layout can be null if lineContainsText is true
180  * if (layout != null) {
181  * layouts.addElement(layout);
182  * penPositions.addElement(new Float(horizontalPos));
183  * horizontalPos += layout.getAdvance();
184  * maxAscent = Math.max(maxAscent, layout.getAscent());
185  * maxDescent = Math.max(maxDescent,
186  * layout.getDescent() + layout.getLeading());
187  * } else {
188  * lineComplete = true;
189  * }
190  *
191  * lineContainsText = true;
192  *
193  * if (measurer.getPosition() == tabLocations[currentTab]+1) {
194  * currentTab++;
195  * }
196  *
197  * if (measurer.getPosition() == styledText.getEndIndex())
198  * lineComplete = true;
199  * else if (horizontalPos >= tabStops[tabStops.length-1])
200  * lineComplete = true;
201  *
202  * if (!lineComplete) {
203  * // move to next tab stop
204  * int j;
205  * for (j=0; horizontalPos >= tabStops[j]; j++) {}
206  * horizontalPos = tabStops[j];
207  * }
208  * }
209  *
210  * verticalPos += maxAscent;
211  *
212  * Enumeration layoutEnum = layouts.elements();
213  * Enumeration positionEnum = penPositions.elements();
214  *
215  * // now iterate through layouts and draw them
216  * while (layoutEnum.hasMoreElements()) {
217  * TextLayout nextLayout = (TextLayout) layoutEnum.nextElement();
218  * Float nextPosition = (Float) positionEnum.nextElement();
219  * nextLayout.draw(graphics, nextPosition.floatValue(), verticalPos);
220  * }
221  *
222  * verticalPos += maxDescent;
223  * }
224  * }
225  * </pre>
226  * </blockquote>
227  * @see TextLayout
228  */

229
230 public final class LineBreakMeasurer {
231     
232     private BreakIterator JavaDoc breakIter;
233     private int start;
234     private int pos;
235     private int limit;
236     private TextMeasurer JavaDoc measurer;
237     private CharArrayIterator JavaDoc charIter;
238
239     /**
240      * Constructs a <code>LineBreakMeasurer</code> for the specified text.
241      *
242      * @param text the text for which this <code>LineBreakMeasurer</code>
243      * produces <code>TextLayout</code> objects; the text must contain
244      * at least one character; if the text available through
245      * <code>iter</code> changes, further calls to this
246      * <code>LineBreakMeasurer</code> instance are undefined (except,
247      * in some cases, when <code>insertChar</code> or
248      * <code>deleteChar</code> are invoked afterward - see below)
249      * @param frc contains information about a graphics device which is
250      * needed to measure the text correctly;
251      * text measurements can vary slightly depending on the
252      * device resolution, and attributes such as antialiasing; this
253      * parameter does not specify a translation between the
254      * <code>LineBreakMeasurer</code> and user space
255      * @see LineBreakMeasurer#insertChar
256      * @see LineBreakMeasurer#deleteChar
257      */

258     public LineBreakMeasurer(AttributedCharacterIterator JavaDoc text, FontRenderContext JavaDoc frc) {
259         this(text, BreakIterator.getLineInstance(), frc);
260     }
261
262     /**
263      * Constructs a <code>LineBreakMeasurer</code> for the specified text.
264      *
265      * @param text the text for which this <code>LineBreakMeasurer</code>
266      * produces <code>TextLayout</code> objects; the text must contain
267      * at least one character; if the text available through
268      * <code>iter</code> changes, further calls to this
269      * <code>LineBreakMeasurer</code> instance are undefined (except,
270      * in some cases, when <code>insertChar</code> or
271      * <code>deleteChar</code> are invoked afterward - see below)
272      * @param breakIter the {@link BreakIterator} which defines line
273      * breaks
274      * @param frc contains information about a graphics device which is
275      * needed to measure the text correctly;
276      * text measurements can vary slightly depending on the
277      * device resolution, and attributes such as antialiasing; this
278      * parameter does not specify a translation between the
279      * <code>LineBreakMeasurer</code> and user space
280      * @throws IllegalArgumentException if the text has less than one character
281      * @see LineBreakMeasurer#insertChar
282      * @see LineBreakMeasurer#deleteChar
283      */

284     public LineBreakMeasurer(AttributedCharacterIterator JavaDoc text,
285                              BreakIterator JavaDoc breakIter,
286                              FontRenderContext JavaDoc frc) {
287         if (text.getEndIndex() - text.getBeginIndex() < 1) {
288         throw new IllegalArgumentException JavaDoc("Text must contain at least one character.");
289     }
290
291         this.breakIter = breakIter;
292         this.measurer = new TextMeasurer JavaDoc(text, frc);
293         this.limit = text.getEndIndex();
294         this.pos = this.start = text.getBeginIndex();
295         
296         charIter = new CharArrayIterator JavaDoc(measurer.getChars(), this.start);
297         this.breakIter.setText(charIter);
298     }
299
300     /**
301      * Returns the position at the end of the next layout. Does NOT
302      * update the current position of this <code>LineBreakMeasurer</code>.
303      *
304      * @param wrappingWidth the maximum visible advance permitted for
305      * the text in the next layout
306      * @return an offset in the text representing the limit of the
307      * next <code>TextLayout</code>.
308      */

309     public int nextOffset(float wrappingWidth) {
310         return nextOffset(wrappingWidth, limit, false);
311     }
312
313     /**
314      * Returns the position at the end of the next layout. Does NOT
315      * update the current position of this <code>LineBreakMeasurer</code>.
316      *
317      * @param wrappingWidth the maximum visible advance permitted for
318      * the text in the next layout
319      * @param offsetLimit the first character that can not be included
320      * in the next layout, even if the text after the limit would fit
321      * within the wrapping width; <code>offsetLimit</code> must be
322      * greater than the current position
323      * @param requireNextWord if <code>true</code>, the current position
324      * that is returned if the entire next word does not fit within
325      * <code>wrappingWidth</code>; if <code>false</code>, the offset
326      * returned is at least one greater than the current position
327      * @return an offset in the text representing the limit of the
328      * next <code>TextLayout</code>
329      */

330     public int nextOffset(float wrappingWidth, int offsetLimit,
331                           boolean requireNextWord) {
332
333         int nextOffset = pos;
334
335         if (pos < limit) {
336             if (offsetLimit <= pos) {
337                     throw new IllegalArgumentException JavaDoc("offsetLimit must be after current position");
338             }
339
340             int charAtMaxAdvance =
341                             measurer.getLineBreakIndex(pos, wrappingWidth);
342
343             if (charAtMaxAdvance == limit) {
344                 nextOffset = limit;
345             }
346             else if (Character.isWhitespace(measurer.getChars()[charAtMaxAdvance-start])) {
347                 nextOffset = breakIter.following(charAtMaxAdvance);
348             }
349             else {
350             // Break is in a word; back up to previous break.
351

352                 // NOTE: I think that breakIter.preceding(limit) should be
353
// equivalent to breakIter.last(), breakIter.previous() but
354
// the authors of BreakIterator thought otherwise...
355
// If they were equivalent then the first branch would be
356
// unnecessary.
357
int testPos = charAtMaxAdvance + 1;
358                 if (testPos == limit) {
359                     breakIter.last();
360                     nextOffset = breakIter.previous();
361                 }
362                 else {
363                     nextOffset = breakIter.preceding(testPos);
364                 }
365
366                 if (nextOffset <= pos) {
367                     // first word doesn't fit on line
368
if (requireNextWord) {
369                         nextOffset = pos;
370                     }
371                     else {
372                         nextOffset = Math.max(pos+1, charAtMaxAdvance);
373                     }
374                 }
375             }
376         }
377
378         if (nextOffset > offsetLimit) {
379             nextOffset = offsetLimit;
380         }
381
382         return nextOffset;
383     }
384
385     /**
386      * Returns the next layout, and updates the current position.
387      *
388      * @param wrappingWidth the maximum visible advance permitted for
389      * the text in the next layout
390      * @return a <code>TextLayout</code>, beginning at the current
391      * position, which represents the next line fitting within
392      * <code>wrappingWidth</code>
393      */

394     public TextLayout JavaDoc nextLayout(float wrappingWidth) {
395         return nextLayout(wrappingWidth, limit, false);
396     }
397
398     /**
399      * Returns the next layout, and updates the current position.
400      *
401      * @param wrappingWidth the maximum visible advance permitted
402      * for the text in the next layout
403      * @param offsetLimit the first character that can not be
404      * included in the next layout, even if the text after the limit
405      * would fit within the wrapping width; <code>offsetLimit</code>
406      * must be greater than the current position
407      * @param requireNextWord if <code>true</code>, and if the entire word
408      * at the current position does not fit within the wrapping width,
409      * <code>null</code> is returned. If <code>false</code>, a valid
410      * layout is returned that includes at least the character at the
411      * current position
412      * @return a <code>TextLayout</code>, beginning at the current
413      * position, that represents the next line fitting within
414      * <code>wrappingWidth</code>. If the current position is at the end
415      * of the text used by this <code>LineBreakMeasurer</code>,
416      * <code>null</code> is returned
417      */

418     public TextLayout JavaDoc nextLayout(float wrappingWidth, int offsetLimit,
419                                  boolean requireNextWord) {
420
421         if (pos < limit) {
422             int layoutLimit = nextOffset(wrappingWidth, offsetLimit, requireNextWord);
423             if (layoutLimit == pos) {
424                 return null;
425             }
426
427             TextLayout JavaDoc result = measurer.getLayout(pos, layoutLimit);
428             pos = layoutLimit;
429
430             return result;
431         } else {
432             return null;
433         }
434     }
435
436     /**
437      * Returns the current position of this <code>LineBreakMeasurer</code>.
438      *
439      * @return the current position of this <code>LineBreakMeasurer</code>
440      * @see #setPosition
441      */

442     public int getPosition() {
443         return pos;
444     }
445
446     /**
447      * Sets the current position of this <code>LineBreakMeasurer</code>.
448      *
449      * @param newPosition the current position of this
450      * <code>LineBreakMeasurer</code>; the position should be within the
451      * text used to construct this <code>LineBreakMeasurer</code> (or in
452      * the text most recently passed to <code>insertChar</code>
453      * or <code>deleteChar</code>
454      * @see #getPosition
455      */

456     public void setPosition(int newPosition) {
457         if (newPosition < start || newPosition > limit) {
458             throw new IllegalArgumentException JavaDoc("position is out of range");
459         }
460         pos = newPosition;
461     }
462
463     /**
464      * Updates this <code>LineBreakMeasurer</code> after a single
465      * character is inserted into the text, and sets the current
466      * position to the beginning of the paragraph.
467      *
468      * @param newParagraph the text after the insertion
469      * @param insertPos the position in the text at which the character
470      * is inserted
471      * @throws IndexOutOfBoundsException if <code>insertPos</code> is less
472      * than the start of <code>newParagraph</code> or greater than
473      * or equal to the end of <code>newParagraph</code>
474      * @throws NullPointerException if <code>newParagraph</code> is
475      * <code>null</code>
476      * @see #deleteChar
477      */

478     public void insertChar(AttributedCharacterIterator JavaDoc newParagraph,
479                            int insertPos) {
480
481         measurer.insertChar(newParagraph, insertPos);
482
483         limit = newParagraph.getEndIndex();
484         pos = start = newParagraph.getBeginIndex();
485
486         charIter.reset(measurer.getChars(), newParagraph.getBeginIndex());
487         breakIter.setText(charIter);
488     }
489
490     /**
491      * Updates this <code>LineBreakMeasurer</code> after a single
492      * character is deleted from the text, and sets the current
493      * position to the beginning of the paragraph.
494      * @param newParagraph the text after the deletion
495      * @param deletePos the position in the text at which the character
496      * is deleted
497      * @throws IndexOutOfBoundsException if <code>deletePos</code> is
498      * less than the start of <code>newParagraph</code> or greater
499      * than the end of <code>newParagraph</code>
500      * @throws NullPointerException if <code>newParagraph</code> is
501      * <code>null</code>
502      * @see #insertChar
503      */

504     public void deleteChar(AttributedCharacterIterator JavaDoc newParagraph,
505                            int deletePos) {
506
507         measurer.deleteChar(newParagraph, deletePos);
508
509         limit = newParagraph.getEndIndex();
510         pos = start = newParagraph.getBeginIndex();
511
512         charIter.reset(measurer.getChars(), start);
513         breakIter.setText(charIter);
514     }
515 }
516
517
Popular Tags