home *** CD-ROM | disk | FTP | other *** search
Java Source | 1998-03-20 | 16.4 KB | 442 lines |
- /*
- * @(#)LineBreakMeasurer.java 1.4 98/03/18
- *
- * Copyright 1998 by Sun Microsystems, Inc.,
- * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
- * All rights reserved.
- *
- * This software is the confidential and proprietary information
- * of Sun Microsystems, Inc. ("Confidential Information"). You
- * shall not disclose such Confidential Information and shall use
- * it only in accordance with the terms of the license agreement
- * you entered into with Sun.
- */
-
- /*
- * (C) Copyright Taligent, Inc. 1996 - 1997, All Rights Reserved
- * (C) Copyright IBM Corp. 1996 - 1998, All Rights Reserved
- *
- * The original version of this source code and documentation is
- * copyrighted and owned by Taligent, Inc., a wholly-owned subsidiary
- * of IBM. These materials are provided under terms of a License
- * Agreement between Taligent and Sun. This technology is protected
- * by multiple US and International patents.
- *
- * This notice and attribution to Taligent may not be removed.
- * Taligent is a registered trademark of Taligent, Inc.
- *
- */
-
- package java.awt.font;
-
- import java.text.BreakIterator;
- import java.text.CharacterIterator;
- import java.text.AttributedCharacterIterator;
-
- /**
- * LineBreakMeasurer allows styled text to be broken into lines (or
- * segments) which fit within a given visual advance. This is useful
- * for clients who wish to display a paragraph of text which fits
- * within a specific width, called the <b>wrapping width</b>.
- * <p>
- * LineBreakMeasurer is constructed with an iterator over styled text.
- * The iterator's range should be a single paragraph in the text.
- * LineBreakMeasurer maintains a position in the text for the start of
- * of the next text segment; initially, this position is the start of
- * text. Paragraphs are assigned an overall direction (either
- * left-to-right or right-to-left) according to the bidirectional
- * formatting rules. All segments obtained from a paragraph have the
- * same direction as the paragraph.
- * <p>
- * Segments of text are obtained by calling the method nextLayout(),
- * which will return a TextLayout representing the text that fits
- * within the wrapping width. nextLayout() moves the current position
- * to the end of the layout returned from nextLayout().
- * <p>
- * LineBreakMeasurer implements the most commonly used line-breaking
- * policy: Every word which will fit within the wrapping width is
- * placed on the line. If the first word will not fit, then all of the
- * characters which fit within the wrapping width are placed on the
- * line. At least one character is placed on each line.
- * <p>
- * The TextLayout instances returned by LineBreakMeasurer treat tabs
- * ('\t') like 0-width spaces. Clients who wish to obtain
- * tab-delimited segments for positioning should use the overload of
- * nextLayout() which takes a limiting offset in the text.
- * The limiting offset should be the first character after the tab.
- * The TextLayouts returned from this method will end at the limit
- * provided (or before, if the text between the current position and
- * the limit won't fit entirely within the given wrapping width).
- * <p>
- * Clients who are laying out tab-delimited text need a slightly
- * different line-breaking policy after the first segment has been
- * placed on a line. Instead of fitting partial words in the
- * remaining space, they should place words which don't fit in the
- * remaining space entirely on the next line. This change of policy
- * can be requested in the overload of nextLayout() which takes a
- * boolean parameter. If this parameter is <code>true</code>,
- * nextLayout() will return null if the first word won't fit in
- * the given space. See the tab sample below.
- * <p>
- * In general, if the text used to construct the LineBreakMeasurer
- * changes, a new LineBreakMeasurer must be constructed to reflect
- * the change. (The old LineBreakMeasurer will continue to function
- * properly, but it won't be aware of the text change.) However, if
- * the text change is the insertion or deletion of a single
- * character, an existing LineBreakMeasurer may be 'updated' by
- * calling insertChar() or deleteChar(). Updating an existing
- * LineBreakMeasurer is much faster than creating a new one. Clients
- * that modify text based on user typing will want to take advantage
- * of these methods.
- * <p>
- * <strong>Examples</strong>:<p>
- * Drawing a paragraph in a component
- * <blockquote>
- * <pre>
- * public void paint(Graphics graphics) {
- *
- * Point2D pen = new Point2D(10, 20);
- *
- * // let styledText be a StyledString containing at least one
- * // character
- *
- * LineBreakMeasurer measurer =
- * new LineBreakMeasurer(new StyledStringIterator(styledText));
- * float wrappingWidth = getSize().width - 15;
- *
- * while (measurer.getPosition() < fStyledText.length()) {
- *
- * TextLayout layout = measurer.nextLayout(wrappingWidth);
- *
- * pen.y += (layout.getAscent());
- * float dx = layout.isLeftToRight() ?
- * 0 : (wrappingWidth - layout.getAdvance());
- *
- * layout.draw(graphics, pen.x + dx, pen.y);
- * pen.y += layout.getDescent() + layout.getLeading();
- * }
- * }
- * </pre>
- * </blockquote>
- * <p>
- * Drawing text with tabs. For simplicity, the overall text
- * direction is assumed to be left-to-right
- * <blockquote>
- * <pre>
- * public void paint(Graphics graphics) {
- *
- * float leftMargin = 10, rightMargin = 310;
- * float[] tabStops = { 100, 250 };
- *
- * // assume fStyledText is a StyledString, and the number
- * // of tabs in fStyledText is fTabCount
- *
- * int[] tabLocations = new int[fTabCount+1];
- *
- * AttributedCharacterIterator iter =
- * new StyledStringIterator(fStyledText);
- * int i=0;
- * for (char c = iter.first(); c != iter.DONE; c = iter.next()) {
- * if (c == '\t') {
- * tabLocations[i++] = iter.getIndex();
- * }
- * }
- * tabLocations[fTabCount] = iter.getEndIndex() - 1;
- *
- * // Now tabLocations has an entry for every tab's offset in
- * // the text. For convenience, the last entry is tabLocations
- * // is the offset of the last character in the text.
- *
- * LineBreakMeasurer measurer = new LineBreakMeasurer(iter);
- * int currentTab = 0;
- * float verticalPos = 20;
- *
- * while (measurer.getPosition() < iter.getEndIndex()) {
- *
- * // Lay out and draw each line. All segments on a line
- * // must be computed before any drawing can occur, since
- * // we must know the largest ascent on the line.
- * // TextLayouts are computed and stored in a Vector;
- * // their horizontal positions are stored in a parallel
- * // Vector.
- *
- * // lineContainsText is true after first segment is drawn
- * boolean lineContainsText = false;
- * boolean lineComplete = false;
- * float maxAscent = 0, maxDescent = 0;
- * float horizontalPos = leftMargin;
- * Vector layouts = new Vector(1);
- * Vector penPositions = new Vector(1);
- *
- * while (!lineComplete) {
- * float wrappingWidth = rightMargin - horizontalPos;
- * TextLayout layout =
- * measurer.nextLayout(wrappingWidth,
- * tabLocations[currentTab]+1,
- * lineContainsText);
- *
- * // layout can be null if lineContainsText is true
- * if (layout != null) {
- * layouts.addElement(layout);
- * penPositions.addElement(new Float(horizontalPos));
- * horizontalPos += layout.getAdvance();
- * maxAscent = Math.max(maxAscent, layout.getAscent());
- * maxDescent = Math.max(maxDescent,
- * layout.getDescent() + layout.getLeading());
- * } else {
- * lineComplete = true;
- * }
- *
- * lineContainsText = true;
- *
- * if (measurer.getPosition() == tabLocations[currentTab]+1) {
- * currentTab++;
- * }
- *
- * if (measurer.getPosition() == iter.getEndIndex())
- * lineComplete = true;
- * else if (horizontalPos >= tabStops[tabStops.length-1])
- * lineComplete = true;
- *
- * if (!lineComplete) {
- * // move to next tab stop
- * int j;
- * for (j=0; horizontalPos >= tabStops[j]; j++) {}
- * horizontalPos = tabStops[j];
- * }
- * }
- *
- * verticalPos += maxAscent;
- *
- * Enumeration layoutEnum = layouts.elements();
- * Enumeration positionEnum = penPositions.elements();
- *
- * // now iterate through layouts and draw them
- * while (layoutEnum.hasMoreElements()) {
- * TextLayout nextLayout = (TextLayout) layoutEnum.nextElement();
- * Float nextPosition = (Float) positionEnum.nextElement();
- * nextLayout.draw(graphics, nextPosition.floatValue(), verticalPos);
- * }
- *
- * verticalPos += maxDescent;
- * }
- * }
- * </pre>
- * </blockquote>
- * @see TextLayout
- */
-
- public final class LineBreakMeasurer {
- private AttributedCharacterIterator text;
- private BreakIterator breakIter;
- private int pos;
- private int limit;
- private TextMeasurer measurer;
-
- /**
- * Construct a LineBreakMeasurer for the given text.
- * @param text the text for which the LineBreakMeasurer will
- * produce TextLayouts. Must contain at least one character.
- * @see LineBreakMeasurer#insertChar
- * @see LineBreakMeasurer#deleteChar
- */
- public LineBreakMeasurer(AttributedCharacterIterator text) {
- this(text, BreakIterator.getLineInstance());
- }
-
- public LineBreakMeasurer(AttributedCharacterIterator text,
- BreakIterator breakIter) {
- this.text = text;
- this.breakIter = breakIter;
- this.breakIter.setText((CharacterIterator)text.clone());
- this.measurer = new TextMeasurer(text);
- this.limit = text.getEndIndex();
- this.pos = text.getBeginIndex();
- text.setIndex(pos);
- }
-
- /**
- * Return the position at the end of the next layout. Does NOT
- * update the current position of the LineBreakMeasurer.
- * @param maxAdvance the maximum visible advance permitted for
- * the text in the next layout.
- * @return an offset in the text representing the limit of the
- * next TextLayout
- */
- public int nextOffset(float maxAdvance) {
- return nextOffset(maxAdvance, limit, false);
- }
-
- /**
- * Return the position at the end of the next layout. Does NOT
- * update the current position of the LineBreakMeasurer.
- * @param wrappingWidth the maximum visible advance permitted for
- * the text in the next layout.
- * @param offsetLimit the first character which may not be included
- * in the next layout, even if the text after the limit would fit
- * within the wrapping width. Must be greater than the current
- * position.
- * @param requireNextWord if true, the current position will be
- * returned if the entire next word will not fit within
- * wrappingWidth. If false, the offset returned will be at least
- * one greater than the current position.
- * @return an offset in the text representing the limit of the
- * next TextLayout
- */
- public int nextOffset(float wrappingWidth, int offsetLimit,
- boolean requireNextWord) {
-
- int nextOffset = pos;
-
- if (pos < limit) {
- if (offsetLimit <= pos) {
- throw new IllegalArgumentException("offsetLimit must be after current position");
- }
-
- int charAtMaxAdvance =
- measurer.getLineBreakIndex(pos, wrappingWidth);
- text.setIndex(charAtMaxAdvance);
-
- if (charAtMaxAdvance == limit) {
- nextOffset = limit;
- }
- else if (Character.isWhitespace(text.current())) {
- nextOffset = breakIter.following(charAtMaxAdvance);
- }
- else {
- // Break is in a word; back up to previous break.
-
- breakIter.following(charAtMaxAdvance);
- nextOffset = breakIter.previous();
-
- if (nextOffset <= pos) {
- // first word doesn't fit on line
- if (requireNextWord) {
- nextOffset = pos;
- }
- else {
- nextOffset = Math.max(pos+1, charAtMaxAdvance);
- }
- }
- }
- }
-
- if (nextOffset > offsetLimit) {
- nextOffset = offsetLimit;
- }
-
- return nextOffset;
- }
-
- /**
- * Return the next layout, and update the current position.
- * @param maxAdvance the maximum visible advance permitted for
- * the text in the next layout.
- * @return a TextLayout, beginning at the current position,
- * which represents the next line fitting within maxAdvance.
- */
- public TextLayout nextLayout(float maxAdvance) {
- return nextLayout(maxAdvance, limit, false);
- }
-
- /**
- * Return the next layout, and update the current position.
- * @param wrappingWidth the maximum visible advance permitted
- * for the text in the next layout.
- * @param offsetLimit the first character which may not be
- * included in the next layout, even if the text after the limit
- * would fit within the wrapping width. Must be greater than the
- * current position.
- * @param requireNextWord if true, and if the entire word at the
- * current position won't fit within wrapping width, null will be
- * returned. If false, a valid layout will be returned
- * that includes at least the character at the current position.
- * @return a TextLayout, beginning at the current position, that
- * represents the next line fitting within maxAdvance. If the
- * current position is at the end of the text used by the
- * LineBreakMeasurer, null is returned.
- */
- public TextLayout nextLayout(float wrappingWidth, int offsetLimit,
- boolean requireNextWord) {
-
- if (pos < text.getEndIndex()) {
- int layoutLimit = nextOffset(wrappingWidth, offsetLimit, requireNextWord);
- if (layoutLimit == pos) {
- return null;
- }
-
- TextLayout result = measurer.getLayout(pos, layoutLimit);
- pos = layoutLimit;
-
- return result;
- } else {
- return null;
- }
- }
-
- /**
- * Return the current position of the LineBreakMeasurer.
- * @return the current position of the LineBreakMeasurer
- * @see #setPosition
- */
- public int getPosition() {
- return pos;
- }
-
- /**
- * Set the current position of the LineBreakMeasurer.
- * @param newPosition the current position of the LineBreakMeasurer.
- * The position should be within the text used to construct the
- * LineBreakMeasurer (or in the text most recently passed to
- * insertChar or deleteChar).
- * @see #getPosition
- */
- public void setPosition(int newPosition) {
- if (newPosition < text.getBeginIndex() || newPosition > limit) {
- throw new IllegalArgumentException("position is out of range");
- }
- pos = newPosition;
- }
-
- /**
- * Update the LineBreakMeasurer after a single character was inserted
- * into the text.
- * @param newParagraph the text after the insertion
- * @param insertPos the position in the text at which the character
- * was inserted
- * @see #deleteChar
- */
- public void insertChar(AttributedCharacterIterator newParagraph,
- int insertPos) {
-
- text = newParagraph;
- breakIter.setText((CharacterIterator)text.clone());
-
- limit = text.getEndIndex();
- pos = text.getBeginIndex();
-
- measurer.insertChar(newParagraph, insertPos);
- }
-
- /**
- * Update the LineBreakMeasurer after a single character was deleted
- * from the text.
- * @param newParagraph the text after the deletion
- * @param deletePos the position in the text at which the character
- * was deleted
- * @see #insertChar
- */
- public void deleteChar(AttributedCharacterIterator newParagraph,
- int deletePos) {
-
- text = newParagraph;
- breakIter.setText((CharacterIterator)text.clone());
-
- limit = text.getEndIndex();
- pos = text.getBeginIndex();
-
- measurer.deleteChar(newParagraph, deletePos);
- }
- }
-
-