001    /* TextMeasurer.java
002       Copyright (C) 2006 Free Software Foundation, Inc.
003    
004    This file is part of GNU Classpath.
005    
006    GNU Classpath is free software; you can redistribute it and/or modify
007    it under the terms of the GNU General Public License as published by
008    the Free Software Foundation; either version 2, or (at your option)
009    any later version.
010    
011    GNU Classpath is distributed in the hope that it will be useful, but
012    WITHOUT ANY WARRANTY; without even the implied warranty of
013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014    General Public License for more details.
015    
016    You should have received a copy of the GNU General Public License
017    along with GNU Classpath; see the file COPYING.  If not, write to the
018    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
019    02110-1301 USA.
020    
021    Linking this library statically or dynamically with other modules is
022    making a combined work based on this library.  Thus, the terms and
023    conditions of the GNU General Public License cover the whole
024    combination.
025    
026    As a special exception, the copyright holders of this library give you
027    permission to link this library with independent modules to produce an
028    executable, regardless of the license terms of these independent
029    modules, and to copy and distribute the resulting executable under
030    terms of your choice, provided that you also meet, for each linked
031    independent module, the terms and conditions of the license of that
032    module.  An independent module is a module which is not derived from
033    or based on this library.  If you modify this library, you may extend
034    this exception to your version of the library, but you are not
035    obligated to do so.  If you do not wish to do so, delete this
036    exception statement from your version. */
037    
038    
039    package java.awt.font;
040    
041    import java.text.AttributedCharacterIterator;
042    import java.awt.Shape;
043    
044    /**
045     * TextMeasurer is a small utility class for measuring the length of laid-out
046     * text objects. 
047     *
048     * @author Sven de Marothy
049     * @since 1.3
050     */
051    public final class TextMeasurer implements Cloneable
052    {
053      private AttributedCharacterIterator text;
054      private FontRenderContext frc;
055      private TextLayout totalLayout;
056      private int numChars;
057    
058      /**
059       * Creates a TextMeasurer from a given text in the form of an
060       * <code>AttributedCharacterIterator</code> and a 
061       * <code>FontRenderContext</code>.
062       */  
063      public TextMeasurer (AttributedCharacterIterator text, FontRenderContext frc)
064      {
065        this.text = text;
066        this.frc = frc;
067        totalLayout = new TextLayout( text, frc );
068        numChars = totalLayout.getCharacterCount();
069      }
070    
071      /**
072       * Clones the TextMeasurer object
073       */
074      protected Object clone ()
075      {
076        return new TextMeasurer( text, frc );
077      }
078    
079      /**
080       * Update the text if a character is deleted at the position deletePos
081       * @param newParagraph - the updated paragraph.
082       * @param deletePos - the deletion position
083       */
084      public void deleteChar (AttributedCharacterIterator newParagraph,
085                              int deletePos)
086      {
087        totalLayout = new TextLayout(newParagraph, frc);
088        if( deletePos < 0 || deletePos > totalLayout.getCharacterCount() )
089          throw new NullPointerException("Invalid deletePos:"+deletePos);
090        numChars = totalLayout.getCharacterCount();
091        text = newParagraph;
092      }
093    
094      /**
095       * Update the text if a character is inserted at the position insertPos
096       * @param newParagraph - the updated paragraph.
097       * @param insertPos - the insertion position
098       */
099      public void insertChar (AttributedCharacterIterator newParagraph,
100                              int insertPos)
101      {
102        totalLayout = new TextLayout(newParagraph, frc);
103        if( insertPos < 0 || insertPos > totalLayout.getCharacterCount() )
104          throw new NullPointerException("Invalid insertPos:"+insertPos);
105        numChars = totalLayout.getCharacterCount();
106        text = newParagraph;
107      }
108    
109      /***
110       * Returns the total advance between two positions in the paragraph.
111       * Characters from start to limit-1 (inclusive) are included in this count.
112       *
113       * @param start - the starting character index.
114       * @param limit - the limiting index.
115       */
116      public float getAdvanceBetween (int start, int limit)
117      {
118        Shape s = totalLayout.getLogicalHighlightShape( start, limit );
119        return (float)s.getBounds2D().getWidth();
120      }
121    
122      /**
123       * Returns a <code>TextLayout</code> object corresponding to the characters
124       * from text to limit.
125       * @param start - the starting character index.
126       * @param limit - the limiting index.
127       */
128      public TextLayout getLayout (int start, int limit)
129      {
130        if( start >= limit )
131          throw new IllegalArgumentException("Start position must be < limit.");
132        return new TextLayout( totalLayout, start, limit );
133      }
134    
135      /**
136       * Returns the line-break index from a given starting index and a maximum
137       * advance. The index returned is the first character outside the given
138       * advance (or the limit of the string, if all remaining characters fit.)
139       *
140       * @param start - the starting index.
141       * @param maxAdvance - the maximum advance allowed.
142       * @return the index of the first character beyond maxAdvance, or the 
143       * index of the last character + 1.
144       */
145      public int getLineBreakIndex (int start, float maxAdvance)
146      {   
147        if( start < 0 )
148          throw new IllegalArgumentException("Start parameter must be > 0.");
149    
150        double remainingLength = getAdvanceBetween( start, numChars );
151        
152        int guessOffset = (int)( ( (double)maxAdvance / (double)remainingLength)
153                                 * ( (double)numChars - (double)start ) );
154        guessOffset += start;
155        if( guessOffset > numChars )
156          guessOffset = numChars;
157        
158        double guessLength = getAdvanceBetween( start, guessOffset );
159        boolean makeSmaller = ( guessLength > maxAdvance );
160        int inc = makeSmaller ? -1 : 1;
161        boolean keepGoing = true;
162    
163        do
164          {
165            guessOffset = guessOffset + inc;
166            if( guessOffset <= start || guessOffset > numChars )
167              {
168                keepGoing = false;
169              }
170            else
171              {
172                guessLength = getAdvanceBetween( start, guessOffset );
173                if( makeSmaller && ( guessLength <= maxAdvance) )          
174                  keepGoing = false;
175                if( !makeSmaller && ( guessLength >= maxAdvance) )
176                  keepGoing = false;
177              }
178          }
179        while( keepGoing );
180    
181        // Return first index that doesn't fit.
182        if( !makeSmaller )
183          guessOffset--;
184    
185        if( guessOffset > numChars )
186          return numChars;
187    
188        return guessOffset;
189      }
190    }