home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Java 1.2 How-To
/
JavaHowTo.iso
/
3rdParty
/
jbuilder
/
unsupported
/
JDK1.2beta3
/
SOURCE
/
SRC.ZIP
/
java
/
awt
/
font
/
TextLayout.java
< prev
next >
Encoding:
Amiga
Atari
Commodore
DOS
FM Towns/JPY
Macintosh
Macintosh JP
NeXTSTEP
RISC OS/Acorn
UTF-8
Wrap
Java Source
|
1998-03-20
|
121.2 KB
|
3,450 lines
/*
* @(#)TextLayout.java 1.38 98/03/18
*
* Copyright 1997, 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.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.AttributedCharacterIterator;
import java.text.AttributeSet;
/**
* TextLayout is an immutable graphical representation of styled character data.
* <p>
* It provides the following capabilities:<ul>
* <li>implicit bidirectional analysis and reordering,
* <li>cursor positioning and movement, including split cursors for
* mixed directional text,
* <li>highlighting, including both logical and visual highlighting
* for mixed directional text,
* <li>multiple baselines (roman, hanging, and centered),
* <li>hit testing,
* <li>justification,
* <li>default font substitution,
* <li>metric information such as ascent, descent, and advance, and
* <li>rendering
* </ul>
* <p>
* TextLayout can be rendered by calling Graphics2D.drawString passing
* an instance of TextLayout and a position as the arguments.
* <p>
* TextLayout can be constructed either directly or through use of a
* LineBreakMeasurer. When constructed directly, the source text represents
* a single paragraph. LineBreakMeasurer provides support for line breaking
* to support wrapped text, see its documentation for more information.
* <p>
* TextLayout construction logically proceeds as follows:<ul>
* <li>paragraph attributes are extracted and examined,
* <li>text is analyzed for bidirectional reordering, and reordering
* information is computed if needed,
* <li>text is segmented into style runs
* <li>fonts are chosen for style runs, first by using a font if the
* attribute TextAttributeSet.FONT is present, otherwise by computing
* a default font using the attributes that have been defined
* <li>if a default font was computed, the style runs are further
* broken into subruns renderable by the font, so that font substitution
* appropriate to the text can be performed,
* <li>if text is on multiple baselines, the runs or subruns are further
* broken into subruns sharing a common baseline,
* <li>glyphsets are generated for each run using the chosen font,
* <li>final bidirectional reordering is performed on the glyphsets
* </ul>
* <p>
* All graphical information returned from TextLayout's methods is relative
* to the origin of the TextLayout, which is the intersection of the
* TextLayout's baseline with its left edge. Also, coordinates passed
* into TextLayout's methods are assumed to be relative to the TextLayout's
* origin. Clients will usually need to translate between TextLayout's
* coordinate system and the coordinate system in another object (such as
* a Graphics).
* <p>
* TextLayouts are constructed from styled text, but they do not retain a
* reference to their source text. Thus, changes in the text previously used
* to generate a TextLayout do not affect the TextLayout.
* <p>
* Three methods on TextLayout (<code>getNextRightHit</code>,
* <code>getNextLeftHit</code>, and <code>hitTestChar</code>) return instances
* of <code>TextHitInfo</code>. The offsets contained in these TextHitInfo's
* are relative to the start of the TextLayout, <b>not</b> to the text used to
* create the TextLayout. Similarly, TextLayout methods which accept
* TextHitInfo instances as parameters expect the TextHitInfo's offsets to be
* relative to the TextLayout, not to any underlying text storage model.
* <p>
* <strong>Examples</strong>:<p>
* Constructing and drawing a TextLayout and its bounding rectangle:
* <blockquote><pre>
* Graphics2D g = ...;
* Point2D loc = ...;
* Font font = Font.getFont("Helvetica-bold-italic");
* TextLayout layout = new TextLayout("This is a string", font);
* g.drawString(layout, loc.getX(), loc.getY());
*
* Rectangle2D bounds = layout.getBounds();
* bounds.setRect(bounds.getX()+loc.getX(),
* bounds.getY()+loc.getY(),
* bounds.getWidth(),
* bounds.getHeight())
* g.draw(bounds);
* </pre>
* </blockquote>
* <p>
* Hit-testing a TextLayout (determining which character is at
* a particular graphical location):
* <blockquote><pre>
* Point2D click = ...;
* TextHitInfo hit = layout.hitTestChar(
* (float) (click.getX() - loc.getX()),
* (float) (click.getY() - loc.getY()));
* </pre>
* </blockquote>
* <p>
* Displaying every caret position in a layout. Also, this demonstrates
* how to correctly right-arrow from one TextHitInfo to another:
* <blockquoute><pre>
* // translate graphics to origin of layout on screen
* g.translate(loc.getX(), loc.getY());
* TextHitInfo hit = layout.isLeftToRight()?
* TextHitInfo.trailing(-1) :
* TextHitInfo.leading(layout.getCharacterCount());
* for (; hit != null; hit = layout.getNextRightHit(hit.getInsertionOffset())) {
* Shape[] carets = layout.getCaretShapes(hit.getInsertionOffset());
* Shape caret = carets[0] == null? carets[1] : carets[0];
* g.draw(caret);
* }
* </pre></blockquote>
* <p>
* Drawing a selection range corresponding to a substring in the source text.
* The selected area may not be visually contiguous:
* <blockquoute><pre>
* // selStart, selLimit should be relative to the layout,
* // not to the source text
*
* int selStart = ..., selLimit = ...;
* Color selectionColor = ...;
* Shape selection = layout.getLogicalHighlight(selStart, selLimit);
* // selection may consist of disjoint areas
* // graphics is assumed to be tranlated to origin of layout
* g.setColor(selectionColor);
* g.fill(selection);
* </pre></blockquote>
* <p>
* Drawing a visually contiguous selection range. The selection range may
* correspond to more than one substring in the source text. The ranges of
* the corresponding source text substrings can be obtained with
* <code>getLogicalRangesForVisualSelection()</code>:
* <blockquoute><pre>
* TextOffset selStart = ..., selLimit = ...;
* Shape selection = layout.getVisualHighlightSelection(selStart, selLimit);
* g.setColor(selectionColor);
* g.fill(selection);
* int[] ranges = getLogicalRangesForVisualSelection(selStart, selLimit);
* // ranges[0], ranges[1] is the first selection range,
* // ranges[2], ranges[3] is the second selection range, etc.
* </pre></blockquote>
* <p>
* @see LineBreakMeasurer
* @see TextAttributeSet
* @see TextHitInfo
*/
public final class TextLayout implements Cloneable {
private TextLayoutComponent[] glyphs;
private int[] glyphsOrder;
private byte baseline;
private float[] baselineOffsets;
private boolean isDirectionLTR;
private boolean isVerticalLine;
// cached values computed from GlyphSets and set info:
// all are recomputed from scratch in buildCache()
private float visibleAdvance;
private float advance;
private float ascent;
private float descent;
private float leading;
private int characterCount;
private int hashCodeCache;
// This value is obtained from an attribute, and constrained to the
// interval [0,1]. If 0, the layout cannot be justified.
private float justifyRatio;
// If a layout is produced by justification, then that layout
// cannot be justified. To enforce this constraint the
// justifyRatio of the justified layout is set to this value.
private static final float ALREADY_JUSTIFIED = -53.9f;
// dx and dy specify the distance between the TextLayout's origin
// and the origin of the leftmost GlyphSet (TextLayoutComponent,
// actually). They were used for hanging punctuation support,
// which is no longer implemented. Currently they are both always 0,
// and TextLayout is not guaranteed to work with non-zero dx, dy
// values right now. They were left in as an aide and reminder to
// anyone who implements hanging punctuation or other similar stuff.
// They are static now so they don't take up space in TextLayout
// instances.
private static float dx;
private static float dy;
/*
* TextLayouts are supposedly immutable. If you mutate a TextLayout under
* the covers (like the justification code does) you'll need to set this
* back to null.
*/
private GlyphIterator protoIterator = null;
/*
* Natural bounds is used internally. It is built on demand in
* getNaturalBounds.
*/
private Rectangle2D naturalBounds = null;
/*
* boundsRect encloses all of the bits this TextLayout can draw. It
* is build on demand in getBounds.
*/
private Rectangle2D boundsRect = null;
/*
* flag to supress/allow carets inside of ligatures when hit testing or
* arrow-keying
*/
private boolean caretsInLigaturesAreAllowed = false;
/**
* This class contains one method, getStrongCaret, which is used to
* specify the policy which determines the strong caret in dual-caret
* text. The strong caret is used to move the caret to the left or
* right. Instances of this class can be passed to getCarets,
* getNextLeftHit and getNextRightHit to customize strong caret
* selection.
*
* To specify alternate caret policies, subclass CaretPolicy and
* override getStrongCaret. getStrongCaret should inspect the two
* TextHitInfo arguments and choose one of them as the strong caret.
*
* Most clients clients do not need to use this class.
*/
public static class CaretPolicy {
/**
* Choose one of the given TextHitInfo instances as a strong
* caret in the given TextLayout.
* @param hit1 A valid hit in <code>layout</code>
* @param hit2 A valid hit in <code>layout</code>
* @param layout The TextLayout in which <code>hit1</code>
* and <code>hit2</code> are used
* @return either <code>hit1</code> or <code>hit2</code>
* (or an equivalent TextHitInfo), indicating the
* strong caret
*/
public TextHitInfo getStrongCaret(TextHitInfo hit1,
TextHitInfo hit2,
TextLayout layout) {
// default implmentation just calls private method on layout
return layout.getStrongHit(hit1, hit2);
}
}
/**
* This CaretPolicy is used when a policy is not specified by the
* client. With this policy, a hit on a character whose direction
* is the same as the line direction is strong than a hit on a
* counterdirectional character. If the character's direcitons are
* the same, a hit on the leading edge of a character is stronger
* than a hit on the trailing edge of a character.
*/
public static final CaretPolicy DEFAULT_CARET_POLICY = new CaretPolicy();
/**
* Construct a layout from a string and a font.
*
* All the text is styled using the provided font.
*
* The string must specify a single paragraph of text, as an
* entire paragraph is required for the bidirectional
* algorithm.
*
* @param str the text to display.
* @param font a font used to style the text.
*/
public TextLayout(String string, Font font) {
if (font == null) {
throw new IllegalArgumentException("Null font passed to TextLayout constructor.");
}
if (string == null) {
throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
}
if (string.length() == 0) {
throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
}
char[] text = string.toCharArray();
if (font.sameBaselineUpTo(text, 0, text.length) == text.length) {
fastInit(text, 0, text.length, font, null);
} else {
StyledString ss = new StyledString(string, font);
standardInit(new StyledStringIterator(ss));
}
}
/**
* Construct a layout from a string and an attribute set.
* <p>
* All the text is styled using the provided attributes.
* <p>
* The string must specify a single paragraph of text, as an
* entire paragraph is required for the bidirectional
* algorithm.
*
* @param str the text to display.
* @param attributes the attributes used to style the text.
*/
public TextLayout(String string, AttributeSet attributes) {
if (string == null) {
throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
}
if (attributes == null) {
throw new IllegalArgumentException("Null attribute set passed to TextLayout constructor.");
}
if (string.length() == 0) {
throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
}
char[] text = string.toCharArray();
Font font = singleFont(text, 0, text.length, attributes);
if (font != null) {
fastInit(text, 0, text.length, font, attributes);
} else {
standardInit(new StyledStringIterator(string, attributes));
}
}
/*
* Determine a font for the attributes, and if a single font can render all
* the text on one baseline, return it, otherwise null. If the attributes
* specify a font, assume it can display all the text without checking.
*
* If the AttributeSet contains an embedded graphic, return null.
*/
private static Font singleFont(char[] text,
int start,
int limit,
AttributeSet attributes) {
if (attributes.get(TextAttributeSet.EMBEDDED_GRAPHIC) != null) {
return null;
}
Font font = (Font)attributes.get(TextAttributeSet.FONT);
if (font == null) {
font = Font.getFont(attributes); // uses static cache in Font;
if (font.canDisplayUpTo(text, start, limit) != limit) {
return null;
}
}
if (font.sameBaselineUpTo(text, start, limit) != limit) {
return null;
}
return font;
}
/**
* Construct a layout from a styled string.
* <p>
* The text must specify a single paragraph of text, as an
* entire paragraph is required for the bidirectional
* algorithm.
*
* @param text the styled text to display.
*/
public TextLayout(StyledString text) {
if (text == null) {
throw new IllegalArgumentException("Null styled string passed to TextLayout constructor.");
}
if (text.length() == 0) {
throw new IllegalArgumentException("Zero length styled string passed to TextLayout constructor.");
}
// direct access to StyledString internal data!!!
if (text.attrs.length == 1) {
AttributeSet attrs = text.attrs[0];
Font font = singleFont(text.chars, 0, text.chars.length, attrs);
if (font != null) {
fastInit(text.chars, 0, text.chars.length, font, attrs);
return;
}
}
standardInit(new StyledStringIterator(text));
}
/**
* Construct a layout from an iterator over styled text.
* <p>
* The iterator must specify a single paragraph of text, as an
* entire paragraph is required for the bidirectional
* algorithm.
*
* @param text the styled text to display.
*/
public TextLayout(AttributedCharacterIterator text) {
if (text == null) {
throw new IllegalArgumentException("Null iterator passed to TextLayout constructor.");
}
int start = text.getBeginIndex();
int limit = text.getEndIndex();
if (start == limit) {
throw new IllegalArgumentException("Zero length iterator passed to TextLayout constructor.");
}
text.first();
if (text.getRunLimit() == limit) {
int len = limit - start;
char[] chars = new char[len];
// text.getChars(start, limit, chars, 0);
int n = 0;
for (char c = text.first(); c != text.DONE; c = text.next()) {
chars[n++] = c;
}
text.first();
AttributeSet attributes = text.getAttributes();
Font font = singleFont(chars, 0, len, attributes);
if (font != null) {
fastInit(chars, 0, len, font, attributes);
return;
}
}
standardInit(text);
}
/**
* Initialize the paragraph-specific data.
*/
private void paragraphInit(byte aBaseline, float[] aBaselineOffsets, AttributeSet attrs) {
// Object vf = attrs.get(TextAttributeSet.ORIENTATION);
// isVerticalLine = TextAttributeSet.ORIENTATION_VERTICAL.equals(vf);
isVerticalLine = false;
/*
* if paragraph features define a baseline, use it, otherwise use
* the baseline for the first char.
*/
Byte baselineLF = (Byte)attrs.get(TextAttributeSet.BASELINE);
if (baselineLF == null) {
baseline = aBaseline;
} else {
baseline = baselineLF.byteValue();
}
/*
* if paragraph features define the baselines, use them, otherwise
* use the baselines for the first font that can display the initial
* text.
*/
baselineOffsets = (float[])attrs.get(TextAttributeSet.BASELINE_OFFSETS);
if (baselineOffsets == null) {
baselineOffsets = aBaselineOffsets;
}
// normalize to current baseline
if (baselineOffsets[baseline] != 0) {
float base = baselineOffsets[baseline];
float[] temp = new float[baselineOffsets.length];
for (int i = 0; i < temp.length; i++)
temp[i] = baselineOffsets[i] - base;
baselineOffsets = temp;
}
/*
* if justification is defined, use it (forcing to valid range)
* otherwise set to 1.0
*/
Float justifyLF = (Float) attrs.get(TextAttributeSet.JUSTIFICATION);
if (justifyLF == null) {
justifyRatio = 1;
} else {
justifyRatio = justifyLF.floatValue();
if (justifyRatio < 0) {
justifyRatio = 0;
} else if (justifyRatio > 1) {
justifyRatio = 1;
}
}
}
/*
* the fast init generates a single glyph set. This requires:
* all one style
* all renderable by one font (ie no embedded graphics)
* all on one baseline
*/
private void fastInit(char[] text, int start, int limit, Font font, AttributeSet attrs) {
// Object vf = attrs.get(TextAttributeSet.ORIENTATION);
// isVerticalLine = TextAttributeSet.ORIENTATION_VERTICAL.equals(vf);
isVerticalLine = false;
char c = text[start];
byte glyphBaseline = font.getBaselineFor(c);
if (attrs == null) {
baseline = glyphBaseline;
baselineOffsets = font.getBaselineOffsetsFor(c);
justifyRatio = 1.0f;
} else {
char ch = text[start];
paragraphInit(font.getBaselineFor(ch), font.getBaselineOffsetsFor(ch), attrs);
}
byte[] levels = null;
int[] inverse = null;
IncrementalBidi bidi = IncrementalBidi.createBidi(text, start, limit, attrs);
if (bidi != null) {
isDirectionLTR = bidi.isDirectionLTR();
levels = bidi.getLevels();
inverse = bidi.createLogicalToVisualMap();
} else {
isDirectionLTR = true;
}
glyphs = new TextLayoutComponent[1];
GlyphSet gs = font.getGlyphSet(text, start, limit, glyphBaseline, inverse, levels);
glyphs[0] = new GlyphSetComponent(gs);
}
/*
* the standard init generates multiple glyph sets based on style,
* renderable, and baseline runs.
*/
private void standardInit(AttributedCharacterIterator text) {
// set paragraph attributes
{
// If there's an embedded graphic at the start of the
// paragraph, look for the first non-graphic character
// and use it and its font to initialize the paragraph.
// If not, use the first graphic to initialize.
char firstChar = text.first();
AttributeSet paragraphAttrs = text.getAttributes();
AttributeSet fontAttrs = paragraphAttrs;
GraphicAttribute firstGraphic = (GraphicAttribute)
paragraphAttrs.get(TextAttributeSet.EMBEDDED_GRAPHIC);
boolean useFirstGraphic = false;
if (firstGraphic != null) {
useFirstGraphic = true;
for (firstChar = text.setIndex(text.getRunLimit());
firstChar != text.DONE;
firstChar = text.setIndex(text.getRunLimit())) {
fontAttrs = text.getAttributes();
if (fontAttrs.get(TextAttributeSet.EMBEDDED_GRAPHIC) == null) {
useFirstGraphic = false;
break;
}
}
if (useFirstGraphic) {
firstChar = text.first();
}
}
if (useFirstGraphic) {
// hmmm what to do here? Just try to supply reasonable
// values I guess.
byte defaultBaseline =
TextLayoutGraphic.getBaselineFromGraphic(firstGraphic);
float[] defaultOffsets =
Font.DEFAULT.getBaselineOffsetsFor(firstChar);
paragraphInit(defaultBaseline, defaultOffsets, paragraphAttrs);
}
else {
Font defaultFont = (Font)fontAttrs.get(TextAttributeSet.FONT);
if (defaultFont == null) {
defaultFont = Font.getBestFontFor(text, text.getIndex(), text.getEndIndex());
}
paragraphInit(defaultFont.getBaselineFor(firstChar),
defaultFont.getBaselineOffsetsFor(firstChar), paragraphAttrs);
}
}
isDirectionLTR = true;
byte[] levels = null;
int[] inverse = null;
IncrementalBidi bidi = IncrementalBidi.createBidi(text);
if (bidi != null) {
isDirectionLTR = bidi.isDirectionLTR();
levels = bidi.getLevels();
inverse = bidi.createLogicalToVisualMap();
}
int textStart = text.getBeginIndex();
int textLimit = text.getEndIndex();
characterCount = textLimit - textStart;
/*
* create a vector to temporarily hold glyph sets. We don't create the
* array yet because we don't know how long it should be. Some style
* runs may be broken up into several different glyph sets because a
* font can't display the entire run or because it is visually
* discontiguous.
*/
java.util.Vector glyphVector = new java.util.Vector();
/*
* text may be inside some larger text, be sure to adjust before
* accessing arrays, which map zero to the start of the text.
*/
int pos = textStart;
do {
text.setIndex(pos);
int runLimit = text.getRunLimit(); // <= textLimit
AttributeSet attributes = text.getAttributes();
GraphicAttribute graphicAttribute = (GraphicAttribute)
attributes.get(TextAttributeSet.EMBEDDED_GRAPHIC);
if (graphicAttribute != null) {
do {
int chunkLimit =
textStart + firstVisualChunk(inverse, levels,
pos - textStart, runLimit - textStart);
TextLayoutGraphic graphic = new TextLayoutGraphic(
text.getBeginIndex(), graphicAttribute,
pos, chunkLimit, inverse, levels);
glyphVector.addElement(graphic);
pos = chunkLimit;
} while(pos < runLimit);
}
else {
do {
/*
* If the client has indicated a font, they're responsible for
* ensuring that it can display all the text to which it is
* applied. We won't do anything to handle it.
*/
int displayLimit = runLimit; // default
Font font = (Font) attributes.get(TextAttributeSet.FONT);
if (font == null) {
font = Font.getBestFontFor(text, pos, runLimit);
displayLimit = font.canDisplayUpTo(text, pos, runLimit);
}
do {
int chunkLimit = textStart + firstVisualChunk(inverse,
levels, pos - textStart,
displayLimit - textStart); // <= displayLimit
do {
char c = text.setIndex(pos);
byte baseline = font.getBaselineFor(c);
if (!font.isUniformBaseline()) {
do {
c = text.next();
} while (text.getIndex() < chunkLimit &&
font.getBaselineFor(c) == baseline);
} else {
text.setIndex(chunkLimit);
}
GlyphSet glyphSet = font.getGlyphSet(text,
pos, text.getIndex(), baseline, inverse, levels);
glyphVector.addElement(new GlyphSetComponent(glyphSet));
pos = text.getIndex();
} while (pos < chunkLimit);
} while (pos < displayLimit);
} while (pos < runLimit);
}
} while (pos < textLimit);
glyphs = new TextLayoutComponent[glyphVector.size()];
for (int i = 0; i < glyphs.length; i++) {
glyphs[i] = (TextLayoutComponent) glyphVector.elementAt(i);
}
/*
* Create a visual ordering for the glyph sets. The important thing
* here is that the values have the proper rank with respect to
* each other, not the exact values. For example, the first glyph
* set that appears visually should have the lowest value. The last
* should have the highest value. The values are then normalized
* to map 1-1 with positions in glyphs. This is exactly analogous to
* the way glyphs are maintained in a glyphset.
*
* This leaves the array null if the order is canonical.
*/
if (inverse != null && glyphs.length > 1) {
glyphsOrder = new int[glyphs.length];
int start = 0;
for (int i = 0; i < glyphs.length; i++) {
glyphsOrder[i] = inverse[start];
start += glyphs[i].getNumGlyphs();
}
glyphsOrder = GlyphSet.getContiguousOrder(glyphsOrder);
glyphsOrder = GlyphSet.getInverseOrder(glyphsOrder);
}
}
/*
* A utility to get a range of text that is both logically and visually
* contiguous.
* If the entire range is ok, return limit, otherwise return the first
* directional change after start. We could do better than this, but
* it doesn't seem worth it at the moment.
*/
private static int firstVisualChunk(int order[], byte direction[],
int start, int limit)
{
if (order != null) {
int min = order[start];
int max = order[start];
int count = limit - start;
for (int i = start + 1; i < limit; i++) {
min = Math.min(min, order[i]);
max = Math.max(max, order[i]);
if (max - min >= count) {
if (direction != null) {
byte baseLevel = direction[start];
for (int j = start + 1; j < i; j++) {
if (direction[j] != baseLevel) {
return j;
}
}
}
return i;
}
}
}
return limit;
}
/*
* A utility to rebuild the ascent/descent/leading/advance cache.
* You'll need to call this if you clone and mutate (like justification,
* editing methods do)
*/
private void ensureCache() {
if (protoIterator == null) {
buildCache();
}
}
/**
* This method is here to keep the Symantec JIT happy. The code
* was in buildCache and the JIT didn't like it for some reason.
*/
private void computeAscent() {
TextLayoutComponent gs;
for (int i = 0; i < glyphs.length; i++) {
gs = glyphs[i];
float baselineOffset = baselineOffsets[gs.getBaseline()];
ascent = Math.max(ascent, -baselineOffset + gs.getAscent());
}
}
private void buildCache() {
TextLayoutComponent gs;
ascent = 0;
descent = 0;
leading = 0;
advance = -dx;
// {jbr} have to do two passes now; one for ascent and one for descent
computeAscent();
for (int i = 0; i < glyphs.length; i++) {
gs = glyphs[i];
float baselineOffset = baselineOffsets[gs.getBaseline()];
float gd = baselineOffset + gs.getDescent(ascent+baselineOffset);
descent = Math.max(descent, gd);
leading = Math.max(leading, gd + gs.getLeading());
}
leading -= descent;
GlyphIterator iter = createGlyphIterator();
characterCount = iter.limit();
advance += iter.totalAdvance();
// compute visibleAdvance
visibleAdvance = advance;
if (isDirectionLTR) {
iter.lastVisualGlyph();
while (iter.isValid() && iter.isWhitespace()) {
visibleAdvance -= iter.distanceToNextGlyph();
iter.previousVisualGlyph();
}
} else {
// by default, iter is set to first visual glyph when created
while (iter.isValid() && iter.isWhitespace()) {
visibleAdvance -= iter.distanceToNextGlyph();
iter.nextVisualGlyph();
}
}
// naturalBounds, boundsRect will be generated on demand
naturalBounds = null;
boundsRect = null;
// hashCode will be regenerated on demand
hashCodeCache = 0;
}
private Rectangle2D getNaturalBounds() {
ensureCache();
if (naturalBounds == null) {
TextLayoutComponent gs;
gs = glyphsOrder==null? glyphs[0] : glyphs[glyphsOrder[0]];
float angle = gs.getItalicAngle();
float leftOrTop = isVerticalLine? -dy : -dx;
if (angle < 0) {
leftOrTop -= angle*gs.getAscent();
}
else if (angle > 0) {
leftOrTop -= angle*gs.getDescent(ascent);
}
gs = glyphsOrder==null? glyphs[glyphs.length-1] :
glyphs[glyphsOrder[glyphs.length-1]];
angle = gs.getItalicAngle();
float rightOrBottom = advance;
if (angle < 0) {
rightOrBottom += angle*gs.getDescent(ascent);
}
else {
rightOrBottom += angle*gs.getAscent();
}
float lineDim = rightOrBottom - leftOrTop;
if (isVerticalLine) {
naturalBounds = new Rectangle2D.Float(
-descent, leftOrTop, ascent + descent, lineDim);
}
else {
naturalBounds = new Rectangle2D.Float(
leftOrTop, -ascent, lineDim, ascent + descent);
}
}
return naturalBounds;
}
/**
* Create a copy of this layout.
*/
protected Object clone() {
/*
* !!! I think this is safe. Once created, nothing mutates the
* glyphsets or arrays. But we need to make sure.
* {jbr} actually, that's not quite true. The justification code
* mutates after cloning. It doesn't actually change the glyphsets
* (that's impossible) but it replaces them with justified sets. This
* is a problem for GlyphIterator creation, since new GlyphIterators
* are created by cloning a prototype. If the prototype has outdated
* glyphsets, so will the new ones. A partial solution is to set the
* prototypical GlyphIterator to null when the glyphsets change. If
* you forget this one time, you're hosed.
*/
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
/*
* Utility to throw an expection if an invalid TextHitInfo is passed
* as a parameter. Avoids code duplication.
*/
private void checkTextHit(TextHitInfo hit) {
if (hit == null) {
throw new IllegalArgumentException("TextHitInfo is null.");
}
if (hit.getInsertionIndex() < 0 ||
hit.getInsertionIndex() > characterCount) {
throw new IllegalArgumentException("TextHitInfo is out of range");
}
}
/**
* Create a copy of this layout justified to the given width.
* <p>
* If this layout has already been justified, an exception is thrown.
* If this layout's justification ratio is zero, a layout identical to this
* one is returned.
*
* @param justificationWidth the width to use when justifying the line.
* For best results, it should not be too different from the current
* advance of the line.
* @return a layout justified to the given width.
* @exception Error if this layout has already been justified, an Error is
* thrown.
*/
public TextLayout getJustifiedLayout(float justificationWidth) {
if (justificationWidth <= 0) {
throw new IllegalArgumentException("justificationWidth <= 0 passed to TextLayout.getJustifiedLayout()");
}
if (justifyRatio == ALREADY_JUSTIFIED) {
throw new Error("Can't justify again.");
}
TextLayout result = (TextLayout)clone();
if (justifyRatio > 0) {
result.handleJustify(justificationWidth);
}
result.justifyRatio = ALREADY_JUSTIFIED;
return result;
}
/**
* Justify this layout. Overridden by subclassers to control justification.
*
* The layout will only justify if the paragraph attributes (from the
* source text, possibly defaulted by the layout attributes) indicate a
* non-zero justification ratio. The text will be justified to the
* indicated width. The current implementation also adjusts hanging
* punctuation and trailing whitespace to overhang the justification width.
* Once justified, the layout may not be rejustified.
* <p>
* Some code may rely on immutablity of layouts. Subclassers should not
* call this directly, but instead should call getJustifiedLayout, which
* will call this method on a clone of this layout, preserving
* the original.
*
* @param justificationWidth the width to use when justifying the line.
* For best results, it should not be too different from the current
* advance of the line.
* @see #getJustifiedLayout
*/
protected void handleJustify(float justificationWidth) {
if (justifyRatio > 0 && justificationWidth > 0) {
newJustify(justificationWidth);
}
}
// !!! this could be in the justifier object, if we decided to have one.
private void newJustify(float justificationWidth) {
/*
* calculate visual limits of text needing justification
* this excludes leading and trailing overhanging punctuation and
* trailing whitespace leave limit at last char, we won't add
* justification space after it, but do need to count its advance.
*/
TextLayoutComponent[] newglyphs = new TextLayoutComponent[glyphs.length];
float leftHang = 0;
float adv = 0;
float justifyDelta = 0;
boolean rejustify = false;
do {
GlyphIterator iter = createGlyphIterator();
adv = iter.totalAdvance();
// System.out.println("advance: " + adv);
float ignoredLeftAdvance = 0;
float ignoredRightAdvance = 0;
/*
* ??? if we're a tabbed segment on a line, perhaps we don't hang
* punctuation on one or both sides?
* ??? Do we really want to hang punctuation? I guess we do want
* to hang whitespace, so we still need some of this code.
*/
// {jbr} not hanging punctuation now
boolean hangLeftPunctuation = false;
boolean hangRightPunctuation = false;
iter.firstVisualGlyph();
if (!isDirectionLTR) {
while (iter.isValid() && iter.isWhitespace()) {
ignoredLeftAdvance += iter.distanceToNextGlyph();
iter.nextVisualGlyph();
}
}
if (hangLeftPunctuation) {
while (iter.isValid() && iter.isHangingPunctuation()) {
ignoredLeftAdvance += iter.distanceToNextGlyph();
iter.nextVisualGlyph();
}
}
int start;
// Do we really want to adjust for bearings???
// Remind: {jbr} I don't think so. Bearings are not a design
// metric; they're a physical, bit-bounds metric.
// Disabled for now.
if (iter.isValid()) { // visual for first character in segment
//ignoredLeftAdvance += iter.getLSB();
start = iter.visualIndex();
}
else {
start = characterCount;
}
leftHang = ignoredLeftAdvance;
iter.lastVisualGlyph();
if (isDirectionLTR) {
// System.out.print("s: " + start + ", l: " + iter.limit + ", (" + iter.visualIndex() + "," + iter.logicalIndex() + ")");
while (iter.isValid() && iter.visualIndex() > start &&
iter.isWhitespace()) {
ignoredRightAdvance += iter.distanceToNextGlyph();
iter.previousVisualGlyph();
// System.out.print(", (" + iter.visualIndex() + "," + iter.logicalIndex() + ")");
}
// System.out.println();
}
if (hangRightPunctuation) {
while (iter.isValid() && iter.visualIndex() > start &&
iter.isHangingPunctuation()) {
ignoredRightAdvance += iter.distanceToNextGlyph();
iter.previousVisualGlyph();
}
}
// Do we really want to adjust for bearings???
// Remind {jbr} No - see above.
if (iter.isValid()) {// visual adjust for last character in segment
//ignoredRightAdvance += iter.getRSB();
}
int end = iter.visualIndex();
/*
* get the advance of the text that has to fit the justification
* width
*/
float justifyAdvance =
adv - ignoredLeftAdvance - ignoredRightAdvance;
// get the actual justification delta
justifyDelta = (justificationWidth - justifyAdvance) * justifyRatio;
/*
* generate an array of GlyphJustificationInfo records to pass to
* the justifier
*/
int glyphCount = 0;
for (int i = 0; i < glyphs.length; i++) {
glyphCount += glyphs[i].getNumGlyphs();
}
GlyphJustificationInfo[] info =
new GlyphJustificationInfo[glyphCount];
if (start < characterCount) {
iter.setVisualGlyph(start);
while (iter.isValid() && iter.visualIndex() <= end) {
boolean glyphIsLTR = iter.glyphIsLTR();
GlyphJustificationInfo[] gi = iter.glyphJustificationInfos();
for (int i=0; i < gi.length; i++) {
int off = glyphIsLTR? i : gi.length - i - 1;
info[iter.visualIndex() + off] = gi[i];
}
iter.nextVisualGlyph();
}
}
// invoke justifier on the records
// ignore left of start and right of end
TextJustifier justifier = new TextJustifier(info, start, end + 1);
float[] deltas = justifier.justify(justifyDelta);
/*
* ??? How do you position hanging punctuation when you've
* justified a line? Should you not hang it when the line has to
* stretch too much? If you compress the line, should you also
* compress the punctuation to match the compression that would
* have been applied had it not been hanging?
* go through glyphsets in visual order, applying justification
* flags is a hack reference param for java on entry, true if can
* substitute glyphset that requires rejustification on return,
* true if rejustification is required
*/
boolean canRejustify = rejustify == false;
boolean wantRejustify = false;
boolean[] flags = new boolean[1];
int index = 0;
for (int vi = 0; vi < glyphs.length; vi++) {
int i = (glyphsOrder == null) ? vi : glyphsOrder[vi];
int numGlyphs = glyphs[i].getNumGlyphs();
flags[0] = canRejustify;
//System.out.println(vi + "/" + i + " dl: " + deltas.length + ", i: " + index + ", gn: " + numGlyphs);
newglyphs[i] = glyphs[i].applyJustification(deltas, index, flags);
if (flags[0]) {
glyphs[i] = newglyphs[i]; // need to process new codes
}
wantRejustify |= flags[0];
index += numGlyphs * 2;
}
rejustify = wantRejustify && !rejustify; // only make two passes
protoIterator = null; // force iterator to reflect new glyphsets
} while (rejustify);
// {jbr} No hanging characters anymore.
//if (isVerticalLine) {
// dy = leftHang;
//} else {
// dx = leftHang;
//}
glyphs = newglyphs;
advance = adv + justifyDelta;
}
/**
* Return the baseline for this layout.
*
* The baseline is one of the values defined in Font (roman, centered,
* hanging). Ascent and descent are relative to this baseline. The
* baselineOffsets are also relative to this baseline.
*
* @see #getBaselineOffsets
* @see Font
*/
public byte getBaseline() {
return baseline;
}
/**
* Return the offsets array for the baselines used for this layout.
* <p>
* The array is indexed by one of the values defined in Font (roman,
* centered, hanging). The values are relative to this layout's baseline,
* so that getBaselineOffsets[getBaseline()] == 0. Offsets
* are added to the position of the layout's baseline to get the position
* for the new baseline.
*
* @see #getBaseline
* @see Font
*/
public float[] getBaselineOffsets() {
float[] offsets = new float[baselineOffsets.length];
System.arraycopy(baselineOffsets, 0, offsets, 0, offsets.length);
return offsets;
}
/**
* Return the advance of the layout.
*
* The advance is the distance from the origin to the advance of the
* rightmost (bottommost) character measuring in the line direction.
*/
public float getAdvance() {
ensureCache();
return advance;
}
/**
* Return the advance of the layout, minus trailing whitespace.
*
* @see #getAdvance
*/
public float getVisibleAdvance() {
ensureCache();
return visibleAdvance;
}
/**
* Return the ascent of the layout.
*
* The ascent is the distance from the top (right) of the layout to the
* baseline. It is always positive or zero. The ascent is sufficient to
* accomodate superscripted text and is the maximum of the sum of the the
* ascent, offset, and baseline of each glyph.
*/
public float getAscent() {
ensureCache();
return ascent;
}
/**
* Return the descent of the layout.
*
* The descent is the distance from the baseline to the bottom (left) of
* the layout. It is always positive or zero. The descent is sufficient
* to accomodate subscripted text and is maximum of the sum of the descent,
* offset, and baseline of each glyph.
*/
public float getDescent() {
ensureCache();
return descent;
}
/**
* Return the leading of the layout.
*
* The leading is the suggested interline spacing for this layout.
* <p>
* The leading is computed from the leading, descent, and baseline
* of all glyphsets in the layout. The algorithm is roughly as follows:
* <blockquote><pre>
* maxD = 0;
* maxDL = 0;
* for (GlyphSet g in all glyphsets) {
* maxD = max(maxD, g.getDescent() + offsets[g.getBaseline()]);
* maxDL = max(maxDL, g.getDescent() + g.getLeading() +
* offsets[g.getBaseline()]);
* }
* return maxDL - maxD;
* </pre></blockquote>
*/
public float getLeading() {
ensureCache();
return leading;
}
/**
* Return the bounds of the layout.
*
* This contains all of the pixels the layout can draw. It may not
* coincide exactly with the ascent, descent, origin or advance of
* the layout.
*/
public Rectangle2D getBounds() {
ensureCache();
if (boundsRect == null) {
float gsAdvance = isVerticalLine? -dy : -dx;
float left = Float.MAX_VALUE, right = Float.MIN_VALUE;
float top = Float.MAX_VALUE, bottom = Float.MIN_VALUE;
for (int i=0; i < glyphs.length; i++) {
TextLayoutComponent gs;
gs = glyphsOrder==null? glyphs[i] : glyphs[glyphsOrder[i]];
Rectangle2D gsBounds = gs.getBounds(this);
left = Math.min(left, (float) gsBounds.getLeft() + gsAdvance);
right = Math.max(right, (float) gsBounds.getRight() + gsAdvance);
gsAdvance += gs.getAdvance();
float shift = baselineOffsets[gs.getBaseline()];
top = Math.min(top, (float) gsBounds.getTop()+shift);
bottom = Math.max(bottom, (float) gsBounds.getBottom()+shift);
}
boundsRect = new Rectangle2D.Float(left, top, right-left, bottom-top);
}
Rectangle2D bounds = new Rectangle2D.Float();
bounds.setRect(boundsRect);
// remind!! hack!!
boundsRect = null;
return bounds;
}
/**
* Return true if the layout is left-to-right.
*
* The layout has a base direction of either left-to-right (LTR) or
* right-to-left (RTL). This is independent of the actual direction of
* text on the line, which may be either or mixed. Left-to-right layouts
* by default should position flush left, and if on a tabbed line, the
* tabs run left to right, so that logically successive layouts position
* left to right. The opposite is true for RTL layouts. By default they
* should position flush left, and tabs run right-to-left.
*
* On vertical lines all text runs top-to-bottom, and is treated as LTR.
*/
public boolean isLeftToRight() {
return isDirectionLTR;
}
/**
* Return true if the layout is vertical.
*/
public boolean isVertical() {
return isVerticalLine;
}
/**
* Return the number of characters represented by this layout.
*/
public int getCharacterCount() {
ensureCache();
return characterCount;
}
/*
* carets and hit testing
*
* Positions on a text line are represented by instances of TextHitInfo.
* Any TextHitInfo with characterOffset between 0 and characterCount-1,
* inclusive, represents a valid position on the line. Additionally,
* [-1, trailing] and [characterCount, leading] are valid positions, and
* represent positions at the logical start and end of the line,
* respectively.
*
* The characterOffsets in TextHitInfo's used and returned by TextLayout
* are relative to the beginning of the text layout, not necessarily to
* the beginning of the text storage the client is using.
*
*
* Every valid TextHitInfo has either one or two carets associated with it.
* A caret is a visual location in the TextLayout indicating where text at
* the TextHitInfo will be displayed on screen. If a TextHitInfo
* represents a location on a directional boundary, then there are two
* possible visible positions for newly inserted text. Consider the
* following example, in which capital letters indicate right-to-left text,
* and the overall line direction is left-to-right:
*
* Text Storage: [ a, b, C, D, E, f ]
* Display: a b E D C f
*
* The text hit info (1, t) represents the trailing side of 'b'. If 'q',
* a left-to-right character is inserted into the text storage at this
* location, it will be displayed between the 'b' and the 'E':
*
* Text Storage: [ a, b, q, C, D, E, f ]
* Display: a b q E D C f
*
* However, if a 'W', which is right-to-left, is inserted into the storage
* after 'b', the storage and display will be:
*
* Text Storage: [ a, b, W, C, D, E, f ]
* Display: a b E D C W f
*
* So, for the original text storage, two carets should be displayed for
* location (1, t): one visually between 'b' and 'E' and one visually
* between 'C' and 'f'.
*
*
* When two carets are displayed for a TextHitInfo, one caret is the
* 'strong' caret and the other is the 'weak' caret. The strong caret
* indicates where an inserted character will be displayed when that
* character's direction is the same as the direction of the TextLayout.
* The weak caret shows where an character inserted character will be
* displayed when the character's direction is opposite that of the
* TextLayout.
*
*
* Clients should not be overly concerned with the details of correct
* caret display. TextLayout.getCarets(TextHitInfo) will return an
* array of two paths representing where carets should be displayed.
* The first path in the array is the strong caret; the second element,
* if non-null, is the weak caret. If the second element is null,
* then there is no weak caret for the given TextHitInfo.
*
*
* Since text can be visually reordered, logically consecutive
* TextHitInfo's may not be visually consecutive. One implication of this
* is that a client cannot tell from inspecting a TextHitInfo whether the
* hit represents the first (or last) caret in the layout. Clients
* can call getVisualOtherHit(); if the visual companion is
* (-1, TRAILING) or (characterCount, LEADING), then the hit is at the
* first (last) caret position in the layout.
*/
private float[] getCaretInfo(int caret, Rectangle2D bounds) {
float top1X, top2X;
float bottom1X, bottom2X;
GlyphIterator iter = createGlyphIterator();
if (caret == 0 || caret == characterCount) {
float pos;
if (caret == characterCount) {
iter.setVisualGlyph(characterCount-1);
pos = iter.glyphLinePosition() + iter.glyphAdvance();
}
else {
pos = iter.glyphLinePosition();
}
float angle = iter.glyphAngle();
top1X = top2X = pos + angle*iter.glyphAscent();
bottom1X = bottom2X = pos - angle*iter.glyphDescent();
}
else {
{
iter.setVisualGlyph(caret-1);
float angle1 = iter.glyphAngle();
float pos1 = iter.glyphLinePosition() + iter.glyphAdvance();
top1X = pos1 + angle1*iter.glyphAscent();
bottom1X = pos1 - angle1*iter.glyphDescent();
}
{
iter.nextVisualGlyph();
float angle2 = iter.glyphAngle();
float pos2 = iter.glyphLinePosition();
top2X = pos2 + angle2*iter.glyphAscent();
bottom2X = pos2 - angle2*iter.glyphDescent();
}
}
float topX = (top1X + top2X) / 2;
float bottomX = (bottom1X + bottom2X) / 2;
float[] info = new float[2];
if (isVerticalLine) {
info[1] = (float) ((topX - bottomX) / bounds.getWidth());
info[0] = (float) (topX + (info[1]*bounds.getLeft()));
}
else {
info[1] = (float) ((topX - bottomX) / bounds.getHeight());
info[0] = (float) (bottomX + (info[1]*bounds.getBottom()));
}
return info;
}
/**
* Return an array of two floats describing the caret.
*
* result[0] is offset along advance on the baseline,
* result[1] is run/rise
*
* The caret at the start of the line has the position and angle of the
* first glyph at the base. The caret at the end of the line has the
* start + advance and angle of the last glyph at the base.
* Intermediate carets average the values for the left and right glyphs.
*
* Clients who wish to compute their own carets can access the base
* information used by the default caret code. The caret position is
* also required to support arrow-key navigation from line to line.
*
* @param caret the caret index
*/
private float[] oldGetCaretInfo(int caret, Rectangle2D bounds) {
float x;
float y;
float a;
GlyphIterator iter = createGlyphIterator();
if (caret == 0) {
iter.setVisualGlyph(0);
x = iter.glyphXPosition();
y = iter.glyphYPosition();
a = iter.glyphAngle();
} else if (caret == characterCount) {
iter.setVisualGlyph(characterCount - 1);
x = iter.glyphXPosition();
y = iter.glyphYPosition();
a = iter.glyphAngle();
float adv = iter.glyphAdvance();
if (isVerticalLine) {
y += adv;
} else {
x += adv;
}
} else {
iter.setVisualGlyph(caret);
float xr = iter.glyphXPosition();
float yr = iter.glyphYPosition();
float ar = iter.glyphAngle();
iter.previousVisualGlyph();
float xl = iter.glyphXPosition();
float yl = iter.glyphYPosition();
float al = iter.glyphAngle();
float adv = iter.glyphAdvance();
if (isVerticalLine) {
yl += adv;
} else {
xl += adv;
}
x = (xr + xl) / 2;
y = (yr + yl) / 2;
a = (ar + al) / 2; // not really the half angle, but it will do
}
// System.out.println("caret: " + caret + ", x: " + x + ", y: " + y + ", a: " + a);
float[] result = new float[2];
if (isVerticalLine) {
result[0] = y + x*a;
} else {
result[0] = x + y*a;
}
result[1] = a;
return result;
}
/**
* Return information about the caret corresponding to hit.
*
* The first element of the array is the intersection of the caret with
* the baseline. The second element of the array is the slope (run/rise)
* of the caret.
* <p>
* This method is meant for informational use. To display carets, it
* is better to use <code>getCarets</code>.
*
* @param hit a hit on a character in this layout
* @param bounds the bounds to which the caret info is constructed
* @return a two-element array containing the position and slope of
* the caret
*
* @see #getCarets
*/
public float[] getCaretInfo(TextHitInfo hit, Rectangle2D bounds) {
ensureCache();
checkTextHit(hit);
return getCaretInfo(hitToCaret(hit), bounds);
}
/**
* A convenience overload using the natural bounds of this layout.
*/
public float[] getCaretInfo(TextHitInfo hit) {
return getCaretInfo(hit, getNaturalBounds());
}
/**
* Return a caret index corresponding to the hit.
*
* Carets are numbered from left to right (top to bottom) starting from
* zero. This always places carets next to the character hit, on the
* indicated side of the character.
*/
private int hitToCaret(TextHitInfo hit) {
if (hit.getCharIndex() < 0) {
return isDirectionLTR ? 0 : characterCount;
} else if (hit.getCharIndex() >= characterCount) {
return isDirectionLTR ? characterCount : 0;
}
GlyphIterator iter = createGlyphIterator();
// {jbr} changed slightly. Doesn't try to skip ligatures / combining chars.
iter.setLogicalGlyph(hit.getCharIndex());
if (hit.isLeadingEdge() != iter.glyphIsLTR()) {
// ie if hit is on right side of glyph
iter.nextVisualGlyph();
}
int caret;
if (iter.isValid()) {
caret = iter.visualIndex();
} else {
caret = characterCount;
}
return caret;
}
/**
* Given a caret index, return a hit whose caret is at the index.
* The hit is NOT guaranteed to be strong!!!
*
* @param caret a caret index.
* @return a hit on this layout whose strong caret is at the requested
* index.
*/
private TextHitInfo caretToHit(int caret) {
if (caret == 0 || caret == characterCount) {
if ((caret == characterCount) == isDirectionLTR) {
return TextHitInfo.leading(characterCount);
}
else {
return TextHitInfo.trailing(-1);
}
}
else {
GlyphIterator iter = createGlyphIterator();
iter.setVisualGlyph(caret);
int charIndex = iter.logicalIndex();
boolean leading = iter.glyphIsLTR();
return leading? TextHitInfo.leading(charIndex)
: TextHitInfo.trailing(charIndex);
}
}
private boolean iterIsAtValidCaret(GlyphIterator iter) {
if (!iter.isValid() || iter.isStandard() || iter.isLigature() || iter.logicalIndex()==0) {
return true;
}
if (iter.isCombining()) {
return false;
}
if (iter.isFiller()) {
return caretsInLigaturesAreAllowed;
} else {
throw new Error("Unanticipated iterator state in iterIsAtValidCaret().");
}
}
/**
* Return the hit for the next caret to the right (bottom); if no
* such hit, return null.
*
* If the hit character index is out of bounds, an IllegalArgumentException
* is thrown.
*
* @param hit a hit on a character in this layout.
* @return a hit whose caret appears at the next position to the
* right (bottom) of the caret of the provided hit, or null.
*/
public TextHitInfo getNextRightHit(TextHitInfo hit) {
ensureCache();
checkTextHit(hit);
int caret = hitToCaret(hit);
if (caret == getCharacterCount()) {
return null;
}
GlyphIterator iter = createGlyphIterator();
iter.setVisualGlyph(caret);
do {
iter.nextVisualGlyph();
} while (!iterIsAtValidCaret(iter));
caret = iter.isValid()? iter.visualIndex() : characterCount;
hit = caretToHit(caret);
return hit;
}
/**
* Return the hit for the next caret to the right (bottom); if no
* such hit, return null. The hit is to the right of the strong
* caret at the given offset, as determined by the given caret
* policy.
* The returned hit is the stronger of the two possible
* hits, as determined by the given caret policy.
*
* @param offset An insertion offset in this layout. Cannot be
* less than 0 or greater than the layout's character count.
* @param policy The policy used to select the strong caret.
* @return a hit whose caret appears at the next position to the
* right (bottom) of the caret of the provided hit, or null.
*/
public TextHitInfo getNextRightHit(int offset, CaretPolicy policy) {
if (offset < 0 || offset > characterCount) {
throw new IllegalArgumentException("Offset out of bounds in TextLayout.getNextRightHit()");
}
if (policy == null) {
throw new IllegalArgumentException("Null CaretPolicy passed to TextLayout.getCarets()");
}
TextHitInfo hit1 = TextHitInfo.afterOffset(offset);
TextHitInfo hit2 = hit1.getOtherHit();
TextHitInfo nextHit = getNextRightHit(policy.getStrongCaret(hit1, hit2, this));
TextHitInfo otherHit = getVisualOtherHit(nextHit);
return policy.getStrongCaret(otherHit, nextHit, this);
}
/**
* Return the hit for the next caret to the right (bottom); if no
* such hit, return null. The hit is to the right of the strong
* caret at the given offset, as determined by the default caret
* policy.
* The returned hit is the stronger of the two possible
* hits, as determined by the default caret policy.
*
* @param offset An insertion offset in this layout. Cannot be
* less than 0 or greater than the layout's character count.
* @return a hit whose caret appears at the next position to the
* right (bottom) of the caret of the provided hit, or null.
*/
public TextHitInfo getNextRightHit(int offset) {
return getNextRightHit(offset, DEFAULT_CARET_POLICY);
}
/**
* Return the hit for the next caret to the left (top); if no such
* hit, return null.
*
* If the hit character index is out of bounds, an IllegalArgumentException
* is thrown.
*
* @param hit a hit on a character in this layout.
* @return a hit whose caret appears at the next position to the
* left (top) of the caret of the provided hit, or null.
*/
public TextHitInfo getNextLeftHit(TextHitInfo hit) {
ensureCache();
checkTextHit(hit);
int caret = hitToCaret(hit);
if (caret == 0) {
return null;
}
GlyphIterator iter = createGlyphIterator();
iter.setVisualGlyph(caret-1);
while (!iterIsAtValidCaret(iter)) {
iter.previousVisualGlyph();
}
caret = iter.isValid()? iter.visualIndex() : 0;
hit = caretToHit(caret);
return hit;
}
/**
* Return the hit for the next caret to the left (top); if no
* such hit, return null. The hit is to the left of the strong
* caret at the given offset, as determined by the given caret
* policy.
* The returned hit is the stronger of the two possible
* hits, as determined by the given caret policy.
*
* @param offset An insertion offset in this layout. Cannot be
* less than 0 or greater than the layout's character count.
* @param policy The policy used to select the strong caret.
* @return a hit whose caret appears at the next position to the
* left (top) of the caret of the provided hit, or null.
*/
public TextHitInfo getNextLeftHit(int offset, CaretPolicy policy) {
if (policy == null) {
throw new IllegalArgumentException("Null CaretPolicy passed to TextLayout.getNextLeftHit()");
}
if (offset < 0 || offset > characterCount) {
throw new IllegalArgumentException("Offset out of bounds in TextLayout.getNextLeftHit()");
}
TextHitInfo hit1 = TextHitInfo.afterOffset(offset);
TextHitInfo hit2 = hit1.getOtherHit();
TextHitInfo nextHit = getNextLeftHit(policy.getStrongCaret(hit1, hit2, this));
TextHitInfo otherHit = getVisualOtherHit(nextHit);
return policy.getStrongCaret(otherHit, nextHit, this);
}
/**
* Return the hit for the next caret to the left (top); if no
* such hit, return null. The hit is to the left of the strong
* caret at the given offset, as determined by the default caret
* policy.
* The returned hit is the stronger of the two possible
* hits, as determined by the default caret policy.
*
* @param offset An insertion offset in this layout. Cannot be
* less than 0 or greater than the layout's character count.
* @return a hit whose caret appears at the next position to the
* left (top) of the caret of the provided hit, or null.
*/
public TextHitInfo getNextLeftHit(int offset) {
return getNextLeftHit(offset, DEFAULT_CARET_POLICY);
}
/**
* Return the hit on the opposite side of this hit's caret.
*/
public TextHitInfo getVisualOtherHit(TextHitInfo hit) {
ensureCache();
checkTextHit(hit);
GlyphIterator iter = createGlyphIterator();
int hitCharIndex = hit.getCharIndex();
int charIndex;
boolean leading;
if (hitCharIndex == -1 || hitCharIndex == characterCount) {
if (isDirectionLTR == (hitCharIndex == -1)) {
iter.firstVisualGlyph();
}
else {
iter.lastVisualGlyph();
}
charIndex = iter.logicalIndex();
if (isDirectionLTR == (hitCharIndex == -1)) {
// at left end
leading = iter.glyphIsLTR();
}
else {
// at right end
leading = !iter.glyphIsLTR();
}
}
else {
iter.setLogicalGlyph(hitCharIndex);
boolean movedToRight;
if (iter.glyphIsLTR() == hit.isLeadingEdge()) {
iter.previousVisualGlyph();
movedToRight = false;
}
else {
iter.nextVisualGlyph();
movedToRight = true;
}
if (iter.isValid()) {
charIndex = iter.logicalIndex();
leading = movedToRight == iter.glyphIsLTR();
}
else {
charIndex =
(movedToRight == isDirectionLTR)? characterCount : -1;
leading = charIndex == characterCount;
}
}
return leading? TextHitInfo.leading(charIndex) :
TextHitInfo.trailing(charIndex);
}
/**
* Return an array of four floats corresponding the endpoints of the caret
* x0, y0, x1, y1.
*
* This creates a line along the slope of the caret intersecting the
* baseline at the caret
* position, and extending from ascent above the baseline to descent below
* it.
*/
private double[] getCaretPath(int caret, Rectangle2D bounds,
boolean clipToBounds) {
float[] info = getCaretInfo(caret, bounds);
double pos = info[0];
double slope = info[1];
double x0, y0, x1, y1;
double x2 = -3141.59, y2 = -2.7; // values are there to make compiler happy
double left = bounds.getX();
double right = left + bounds.getWidth();
double top = bounds.getY();
double bottom = top + bounds.getHeight();
boolean threePoints = false;
if (isVerticalLine) {
if (slope >= 0) {
x0 = left;
x1 = right;
y0 = pos + x0 * slope;
y1 = pos + x1 * slope;
}
else {
x1 = left;
x0 = right;
y1 = pos + x1 * slope;
y0 = pos + x0 * slope;
}
// y0 <= y1, always
if (clipToBounds) {
if (y0 < top) {
if (slope == 0 || y1 <= top) {
y0 = y1 = top;
}
else {
threePoints = true;
y2 = top;
x2 = x0 + (top-y0)/slope;
y0 = top;
if (y1 > bottom)
y1 = bottom;
}
}
else if (y1 > bottom) {
if (slope == 0 || y0 >= bottom) {
y0 = y1 = bottom;
}
else {
threePoints = true;
y2 = bottom;
x2 = x1 - (y1-bottom)/slope;
y1 = bottom;
}
}
}
}
else {
if (slope >= 0) {
y0 = bottom;
y1 = top;
x0 = pos - y0 * slope;
x1 = pos - y1 * slope;
}
else {
y1 = bottom;
y0 = top;
x1 = pos - y0 * slope;
x0 = pos - y1 * slope;
}
// x0 <= x1, always
if (clipToBounds) {
if (x0 < left) {
if (slope == 0 || x1 <= left) {
x0 = x1 = left;
}
else {
threePoints = true;
x2 = left;
y2 = y0 - (left-x0)/slope;
x0 = left;
if (x1 > right)
x1 = right;
}
}
else if (x1 > right) {
if (slope == 0 || x0 >= right) {
x0 = x1 = right;
}
else {
threePoints = true;
x2 = right;
y2 = y1 + (x1-right)/slope;
x1 = right;
}
}
}
}
return threePoints?
new double[] { x0, y0, x2, y2, x1, y1 } :
new double[] { x0, y0, x1, y1 };
}
private static GeneralPath pathToShape(double[] path, boolean close) {
GeneralPath result = new GeneralPath(GeneralPath.EVEN_ODD, path.length);
result.moveTo((float)path[0], (float)path[1]);
for (int i = 2; i < path.length; i += 2) {
result.lineTo((float)path[i], (float)path[i+1]);
}
if (close) {
result.closePath();
}
return result;
}
public Shape getCaretShape(TextHitInfo hit, Rectangle2D bounds) {
checkTextHit(hit);
if (bounds == null) {
throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCaret()");
}
int hitCaret = hitToCaret(hit);
GeneralPath hitShape =
pathToShape(getCaretPath(hitCaret, bounds, false), false);
//return new Highlight(hitShape, true);
return hitShape;
}
public Shape getCaretShape(TextHitInfo hit) {
return getCaretShape(hit, getNaturalBounds());
}
/**
* Return the "stronger" of the TextHitInfos. The TextHitInfos
* should be logical or visual counterparts. They are not
* checked for validity.
*/
private final TextHitInfo getStrongHit(TextHitInfo hit1, TextHitInfo hit2) {
// right now we're using the following rule for strong hits:
// A hit on a character whose direction matches the line direction
// is stronger than one on a character running opposite the
// line direction.
// If this rule ties, the hit on the leading edge of a character wins.
// If THIS rule ties, hit1 wins. Both rules shouldn't tie, unless the
// infos aren't counterparts of some sort.
boolean hit1Ltr, hit2Ltr;
GlyphIterator iter = null;
if (hit1.getCharIndex() == characterCount || hit1.getCharIndex() == -1) {
hit1Ltr = isDirectionLTR;
}
else {
if (iter == null) {
iter = createGlyphIterator();
}
iter.setLogicalGlyph(hit1.getCharIndex());
hit1Ltr = (iter.glyphLevel() & 0x1) == 0;
}
if (hit1Ltr == isDirectionLTR && hit1.isLeadingEdge()) {
return hit1;
}
if (hit2.getCharIndex() == characterCount || hit2.getCharIndex() == -1) {
hit2Ltr = isDirectionLTR;
}
else {
if (iter == null) {
iter = createGlyphIterator();
}
iter.setLogicalGlyph(hit2.getCharIndex());
hit2Ltr = (iter.glyphLevel() & 0x1) == 0;
}
if (hit1Ltr == hit2Ltr) {
if (!hit2.isLeadingEdge()) {
return hit1;
}
else {
return (hit1.isLeadingEdge())? hit1 : hit2;
}
}
else {
if (hit1Ltr == isDirectionLTR) {
return hit1;
}
else {
return hit2;
}
}
}
/**
* Return the level of the character at index. Indices -1 and
* characterCount are assigned the base level of the layout.
*/
public byte getCharacterLevel(int index) {
// hmm, allow indices at endpoints? For now, yes.
if (index == -1 || index == characterCount) {
return (byte) (isDirectionLTR? 0 : 1);
}
if (index < 0 || index >= characterCount) {
throw new IllegalArgumentException("Index is out of range in getCharacterLevel.");
}
GlyphIterator iter = createGlyphIterator();
iter.setLogicalGlyph(index);
return iter.glyphLevel();
}
/**
* Return two paths corresponding to the strong and weak caret.
*
* @param offset an offset in the layout
* @param bounds the bounds to which to extend the carets
* @return an array of two paths. Element zero is the strong caret
* (if any) or null. Element one is the weak caret (if any) or null.
* Element 0 and element 1 are never both null.
*/
public Shape[] getCaretShapes(int offset, Rectangle2D bounds, CaretPolicy policy) {
ensureCache();
if (offset < 0 || offset > characterCount) {
throw new IllegalArgumentException("Offset out of bounds in TextLayout.getCarets()");
}
if (bounds == null) {
throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getCarets()");
}
if (policy == null) {
throw new IllegalArgumentException("Null CaretPolicy passed to TextLayout.getCarets()");
}
Shape[] result = new Shape[2];
TextHitInfo hit = TextHitInfo.afterOffset(offset);
int hitCaret = hitToCaret(hit);
Shape hitShape =
pathToShape(getCaretPath(hitCaret, bounds, false), false);
TextHitInfo otherHit = hit.getOtherHit();
int otherCaret = hitToCaret(otherHit);
if (hitCaret == otherCaret) {
result[0] = hitShape;
}
else { // more than one caret
Shape otherShape =
pathToShape(getCaretPath(otherCaret, bounds, false), false);
TextHitInfo strongHit = policy.getStrongCaret(hit, otherHit, this);
boolean hitIsStrong = strongHit.equals(hit);
if (hitIsStrong) {// then other is weak
result[0] = hitShape;
result[1] = otherShape;
}
else {
result[0] = otherShape;
result[1] = hitShape;
}
}
return result;
}
/**
* A convenience overload that uses the default caret policy.
*/
public Shape[] getCaretShapes(int offset, Rectangle2D bounds) {
// {sfb} parameter checking is done in overloaded version
return getCaretShapes(offset, bounds, DEFAULT_CARET_POLICY);
}
/**
* A convenience overload that uses the natural bounds of the layout as
* the bounds, and the default caret policy.
*/
public Shape[] getCaretShapes(int offset) {
// {sfb} parameter checking is done in overloaded version
return getCaretShapes(offset, getNaturalBounds(), DEFAULT_CARET_POLICY);
}
// A utility to return a path enclosing the given path
// Path0 must be left or top of path1
// {jbr} no assumptions about size of path0, path1 anymore.
private static GeneralPath boundingShape(double[] path0, double[] path1) {
GeneralPath result = pathToShape(path0, false);
for (int i = path1.length-2; i >=0; i -= 2) {
result.lineTo((float)path1[i], (float)path1[i+1]);
}
result.closePath();
return result;
}
// A utility to convert a pair of carets into a bounding path
// {jbr} Shape is never outside of bounds.
private GeneralPath caretBoundingShape(int caret0,
int caret1,
Rectangle2D bounds) {
if (caret0 > caret1) {
int temp = caret0;
caret0 = caret1;
caret1 = temp;
}
return boundingShape(getCaretPath(caret0, bounds, true),
getCaretPath(caret1, bounds, true));
}
/*
* A utility to return the path bounding the area to the left (top) of the
* layout.
* Shape is never outside of bounds.
*/
private GeneralPath leftShape(Rectangle2D bounds) {
double[] path0;
if (isVerticalLine) {
path0 = new double[] { bounds.getX(), bounds.getY(),
bounds.getX() + bounds.getWidth(),
bounds.getY() };
} else {
path0 = new double[] { bounds.getX(),
bounds.getY() + bounds.getHeight(),
bounds.getX(), bounds.getY() };
}
double[] path1 = getCaretPath(0, bounds, true);
return boundingShape(path0, path1);
}
/*
* A utility to return the path bounding the area to the right (bottom) of
* the layout.
*/
private GeneralPath rightShape(Rectangle2D bounds) {
double[] path1;
if (isVerticalLine) {
path1 = new double[] {
bounds.getX(),
bounds.getY() + bounds.getHeight(),
bounds.getX() + bounds.getWidth(),
bounds.getY() + bounds.getHeight()
};
} else {
path1 = new double[] {
bounds.getX() + bounds.getWidth(),
bounds.getY() + bounds.getHeight(),
bounds.getX() + bounds.getWidth(),
bounds.getY()
};
}
double[] path0 = getCaretPath(characterCount, bounds, true);
return boundingShape(path0, path1);
}
/**
* Return the logical ranges of text corresponding to a visual selection.
*
* @param firstEndpoint an endpoint of the visual range.
* @param secondEndpoint the other enpoint of the visual range. Can be less than
* <code>firstEndpoint</code>.
* @return an array of integers representing start/limit pairs for the
* selected ranges
*
* @see #getVisualHighlight
*/
public int[] getLogicalRangesForVisualSelection(TextHitInfo firstEndpoint,
TextHitInfo secondEndpoint) {
ensureCache();
checkTextHit(firstEndpoint);
checkTextHit(secondEndpoint);
// !!! probably want to optimize for all LTR text
boolean[] included = new boolean[characterCount];
GlyphIterator iter = createGlyphIterator();
int startIndex = hitToCaret(firstEndpoint);
int limitIndex = hitToCaret(secondEndpoint);
if (startIndex > limitIndex) {
int t = startIndex;
startIndex = limitIndex;
limitIndex = t;
}
/*
* now we have the visual indexes of the glyphs at the start and limit
* of the selection range walk through runs marking characters that
* were included in the visual range there is probably a more efficient
* way to do this, but this ought to work, so hey
*/
if (startIndex < limitIndex) {
iter.setVisualGlyph(startIndex);
while (iter.isValid() && iter.visualIndex() < limitIndex) {
included[iter.logicalIndex()] = true;
iter.nextVisualGlyph();
}
}
/*
* count how many runs we have, ought to be one or two, but perhaps
* things are especially weird
*/
int count = 0;
boolean inrun = false;
for (int i = 0; i < characterCount; i++) {
if (included[i] != inrun) {
inrun = !inrun;
if (inrun) {
count++;
}
}
}
int[] ranges = new int[count * 2];
count = 0;
inrun = false;
for (int i = 0; i < characterCount; i++) {
if (included[i] != inrun) {
ranges[count++] = i;
inrun = !inrun;
}
}
if (inrun) {
ranges[count++] = characterCount;
}
return ranges;
}
/**
* Return a path enclosing the visual selection in the given range,
* extended to bounds.
* <p>
* If the selection includes the leftmost (topmost) position, the selection
* is extended to the left (top) of the bounds. If the selection includes
* the rightmost (bottommost) position, the selection is extended to the
* right (bottom) of the bounds. The height (width on vertical lines) of
* the selection is always extended to bounds.
* <p>
* Although the selection is always contiguous, the logically selected
* text can be discontiguous on lines with mixed-direction text. The
* logical ranges of text selected can be retrieved using
* getLogicalRangesForVisualSelection. For example, consider the text
* 'ABCdef' where capital letters indicate right-to-left text, rendered
* on a right-to-left line, with a visual selection from 0L (the leading
* edge of 'A') to 3T (the trailing edge of 'd'). The text appears as
* follows, with bold underlined areas representing the selection:
* <br><pre>
* d<u><b>efCBA </b></u>
* </pre>
* The logical selection ranges are 0-3, 4-6 (ABC, ef) because the
* visually contiguous text is logically discontiguous. Also note that
* since the rightmost position on the layout (to the right of 'A') is
* selected, the selection is extended to the right of the bounds.
*
* @param firstEndpoint one end of the visual selection
* @param secondEndpoint the other end of the visual selection
* @param bounds the bounding rectangle to which to extend the selection
* @return an area enclosing the selection
*
* @see #getLogicalRangesForVisualSelection
* @see #getLogicalHighlight
*/
public Shape getVisualHighlightShape(TextHitInfo firstEndpoint,
TextHitInfo secondEndpoint,
Rectangle2D bounds)
{
ensureCache();
checkTextHit(firstEndpoint);
checkTextHit(secondEndpoint);
if(bounds == null) {
throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getVisualHighlight()");
}
GeneralPath result = new GeneralPath(GeneralPath.EVEN_ODD);
int firstCaret = hitToCaret(firstEndpoint);
int secondCaret = hitToCaret(secondEndpoint);
result.append(caretBoundingShape(firstCaret, secondCaret, bounds),
false);
if (firstCaret == 0 || secondCaret == 0) {
result.append(leftShape(bounds), false);
}
if (firstCaret == characterCount || secondCaret == characterCount) {
result.append(rightShape(bounds), false);
}
//return new Highlight(result, false);
return result;
}
/**
* A convenience overload which uses the natural bounds of the layout.
*/
public Shape getVisualHighlightShape(TextHitInfo firstEndpoint,
TextHitInfo secondEndpoint) {
return getVisualHighlightShape(firstEndpoint, secondEndpoint, getNaturalBounds());
}
/**
* Return a path enclosing the logical selection in the given range,
* extended to bounds.
* <p>
* If the selection range includes the first logical character, the
* selection is extended to the portion of bounds before the start of the
* layout. If the range includes the last logical character, the
* selection is extended to the portion of bounds after the end of
* the layout. The height (width on vertical lines) of the selection is
* always extended to bounds.
* <p>
* The selection can be discontiguous on lines with mixed-direction text.
* Only those characters in the logical range between start and limit will
* appear selected. For example consider the text 'ABCdef' where capital
* letters indicate right-to-left text, rendered on a right-to-left line,
* with a logical selection from 0 to 4 ('ABCd'). The text appears as
* follows, with bold standing in for the selection, and underlining for
* the extension:
* <br><pre>
* <u><b>d</b></u>ef<u><b>CBA </b></u>
* </pre>
* The selection is discontiguous because the selected characters are
* visually discontiguous. Also note that since the range includes the
* first logical character (A), the selection is extended to the portion
* of the bounds before the start of the layout, which in this case
* (a right-to-left line) is the right portion of the bounds.
*
* @param firstEndpoint an endpoint in the range of characters to select
* @param secondEndpoint the other endpoint of the range of characters
* to select. Can be less than <code>firstEndpoint</code>. The range
* includes the character at min(firstEndpoint, secondEndpoint), but
* excludes max(firstEndpoint, secondEndpoint).
* @param bounds the bounding rectangle to which to extend the selection
* @return an area enclosing the selection
*
* @see #getVisualHighlight
*/
public Shape getLogicalHighlightShape(int firstEndpoint,
int secondEndpoint,
Rectangle2D bounds) {
if (bounds == null) {
throw new IllegalArgumentException("Null Rectangle2D passed to TextLayout.getLogicalHighlight()");
}
ensureCache();
if (firstEndpoint > secondEndpoint) {
int t = firstEndpoint;
firstEndpoint = secondEndpoint;
secondEndpoint = t;
}
if(firstEndpoint < 0 || secondEndpoint > characterCount) {
throw new IllegalArgumentException("Range is invalid in TextLayout.getLogicalHighlight()");
}
int[] carets = new int[10]; // would this ever not handle all cases?
int count = 0;
if (firstEndpoint < secondEndpoint) {
GlyphIterator iter = createGlyphIterator();
iter.setLogicalGlyph(firstEndpoint);
do {
carets[count++] = hitToCaret(TextHitInfo.leading(iter.logicalIndex()));
boolean ltr = iter.glyphIsLTR();
do {
iter.nextLogicalGlyph();
} while (iter.isValid() && iter.logicalIndex() < secondEndpoint && iter.glyphIsLTR() == ltr);
int hitCh = (iter.isValid())? iter.logicalIndex() : iter.limit();
carets[count++] = hitToCaret(TextHitInfo.trailing(hitCh - 1));
if (count == carets.length) {
int[] temp = new int[carets.length + 10];
System.arraycopy(carets, 0, temp, 0, count);
carets = temp;
}
} while (iter.isValid() && iter.logicalIndex() < secondEndpoint);
}
else {
count = 2;
carets[0] = carets[1] = hitToCaret(TextHitInfo.leading(firstEndpoint));
}
// now create paths for pairs of carets
GeneralPath result = new GeneralPath(GeneralPath.EVEN_ODD);
for (int i = 0; i < count; i += 2) {
result.append(caretBoundingShape(carets[i], carets[i+1], bounds),
false);
}
if ((isDirectionLTR && firstEndpoint == 0) || (!isDirectionLTR &&
secondEndpoint == characterCount)) {
result.append(leftShape(bounds), false);
}
if ((isDirectionLTR && secondEndpoint == characterCount) ||
(!isDirectionLTR && firstEndpoint == 0)) {
result.append(rightShape(bounds), false);
}
return result;
}
/**
* A convenience overload which uses the natural bounds of the layout.
*/
public Shape getLogicalHighlightShape(int firstEndpoint, int secondEndpoint) {
return getLogicalHighlightShape(firstEndpoint, secondEndpoint, getNaturalBounds());
}
/**
* Return the black box bounds of the characters in the given range.
*
* The black box bounds is an area consisting of the union of the bounding
* boxes of all the glyphs corresponding to the characters between start
* and limit. This path may be disjoint.
*
* @param firstEndpoint one end of the character range
* @param secondEndpoint the other end of the character range. Can be
* less than <code>firstEndpoint</code>.
* @return a path enclosing the black box bounds
*/
public Shape getBlackBoxBounds(int firstEndpoint, int secondEndpoint) {
ensureCache();
if (firstEndpoint > secondEndpoint) {
int t = firstEndpoint;
firstEndpoint = secondEndpoint;
secondEndpoint = t;
}
if(firstEndpoint < 0 || secondEndpoint > characterCount) {
throw new IllegalArgumentException("Invalid range passed to TextLayout.getBlackBoxBounds()");
}
/*
* return an area that consists of the bounding boxes of all the
* characters from firstEndpoint to limit
*/
GeneralPath result = new GeneralPath(GeneralPath.EVEN_ODD);
if (firstEndpoint < characterCount) {
GlyphIterator iter = createGlyphIterator();
for (iter.setLogicalGlyph(firstEndpoint);
iter.isValid() && iter.logicalIndex() < secondEndpoint;
iter.nextLogicalGlyph()) {
if (!iter.isWhitespace()) {
Rectangle2D r = iter.glyphBounds();
result.append(r, false);
}
}
}
if (dx != 0 || dy != 0) {
AffineTransform translate = new AffineTransform();
translate.setToTranslation(dx, dy);
result = (GeneralPath) result.createTransformedShape(translate);
}
//return new Highlight(result, false);
return result;
}
/**
* Accumulate the advances of the characters at and after startPos, until a
* character is reached whose advance would equal or exceed width.
* Return the index of that character.
*/
int getLineBreakIndex(int startPos, float width) {
ensureCache();
int accChars = 0;
for (int i = 0; i < glyphs.length; i++) {
TextLayoutComponent set = glyphs[i];
int numCharacters = set.getNumCharacters();
if (startPos >= numCharacters) {
startPos -= numCharacters; // skip sets before startPos
} else {
int possibleBreak = set.getLineBreakIndex(startPos, width);
if (possibleBreak < numCharacters) { // found it
return accChars + possibleBreak;
} else {
if (startPos == 0) {
width -= set.getAdvance();
} else {
width -= set.getAdvanceBetween(startPos, numCharacters);
/*
* start looking at the first character of the next
* glyph set
*/
startPos = 0;
}
}
}
accChars += numCharacters;
}
return characterCount;
}
/**
* Return the distance from the point (x, y) to the caret along the line
* direction defined in caretInfo. Distance is negative if the point is
* to the left of the caret on a horizontal line, or above the caret on
* a vertical line.
* Utility for use by hitTestChar.
*/
private float caretToPointDistance(float[] caretInfo, float x, float y) {
// distanceOffBaseline is negative if you're 'above' baseline
float lineDistance = isVerticalLine? y : x;
float distanceOffBaseline = isVerticalLine? -x : y;
return lineDistance - caretInfo[0] +
(distanceOffBaseline*caretInfo[1]);
}
/**
* Return a TextHitInfo corresponding to the point.
*
* Coordinates outside the bounds of the layout map to hits on the leading
* edge of the first logical character, or the trailing edge of the last
* logical character, as appropriate, regardless of the position of that
* character in the line. Only the direction along the baseline is used
* to make this evaluation.
*
* @param x the x offset from the origin of the layout
* @param y the y offset from the origin of the layout
* @return a hit describing the character and edge (leading or trailing)
* under the point
*/
public TextHitInfo hitTestChar(float x, float y, Rectangle2D bounds) {
ensureCache();
int hitLB, hitUB;
float[] caretInfo;
hitLB = 0;
caretInfo = getCaretInfo(hitLB, bounds);
GlyphIterator iter = createGlyphIterator();
if (caretToPointDistance(caretInfo, x, y) < 0) {
return isDirectionLTR? TextHitInfo.trailing(-1) :
TextHitInfo.leading(characterCount);
}
hitUB = characterCount;
caretInfo = getCaretInfo(hitUB, bounds);
if (caretToPointDistance(caretInfo, x, y) >= 0) {
return isDirectionLTR? TextHitInfo.leading(characterCount) :
TextHitInfo.trailing(-1);
}
while (true) {
// if there are no valid caret positions between
// hitLB and hitUB then exit this loop; otherwise
// set test to a valid caret position in the
// interval (hitLB, hitUB)
if (hitLB + 1 == hitUB)
break;
int test = (hitLB + hitUB) / 2;
iter.setVisualGlyph(test);
while(!iterIsAtValidCaret(iter))
iter.nextVisualGlyph();
test = iter.isValid()? iter.visualIndex() : characterCount;
if (test == hitUB) {
// If we're here then there were no valid caret
// positions between the halfway point and the
// end of the test region. Reset test and back
// up to a valid caret position.
iter.setVisualGlyph((hitLB + hitUB) / 2);
do {
iter.previousVisualGlyph();
} while (!iterIsAtValidCaret(iter));
test = iter.visualIndex();
if (test == hitLB)
break;
}
caretInfo = getCaretInfo(test, bounds);
float caretDist = caretToPointDistance(caretInfo, x, y);
if (caretDist == 0) {
// return a hit on the left side of the glyph at test
// test is a valid position, since it is less than characterCount
iter.setVisualGlyph(test);
int charIndex = iter.logicalIndex();
boolean leading = iter.glyphIsLTR();
return leading? TextHitInfo.leading(charIndex) :
TextHitInfo.trailing(charIndex);
}
else if (caretDist < 0) {
hitUB = test;
}
else {
hitLB = test;
}
}
// now hit char is either to the right of hitLB
// or left of hitUB
// make caretInfo be center of glyph:
iter.setVisualGlyph(hitLB);
float hitAdvance = isVerticalLine? iter.glyphYPosition() :
iter.glyphXPosition()-dx;
// performance note: dividing by 2 in the following loop is
// the best thing to do, since the loop will usually only go
// one iteration, and almost never more than two iterations
for (int i = hitLB; i < hitUB; i++) {
if (i == hitUB-1) {
hitAdvance += iter.glyphAdvance()/2;
} else {
hitAdvance += iter.distanceToNextGlyph()/2;
iter.nextVisualGlyph();
}
}
caretInfo = new float[2];
caretInfo[0] = hitAdvance;
caretInfo[1] = iter.glyphAngle();
if (caretInfo[1] != 0) {
caretInfo[0] += caretInfo[1] *
(isVerticalLine?
iter.glyphXPosition() : iter.glyphYPosition());
}
float centerDist = caretToPointDistance(caretInfo, x, y);
TextHitInfo rval;
if (centerDist < 0) {
iter.setVisualGlyph(hitLB);
rval = iter.glyphIsLTR()? TextHitInfo.leading(iter.logicalIndex())
: TextHitInfo.trailing(iter.logicalIndex());
}
else {
if (hitUB < characterCount) {
iter.setVisualGlyph(hitUB);
iter.previousVisualGlyph();
boolean leading = !iter.glyphIsLTR();
rval = leading? TextHitInfo.leading(iter.logicalIndex()) :
TextHitInfo.trailing(iter.logicalIndex());
}
else {
iter.setVisualGlyph(hitUB-1);
boolean leading = !iter.glyphIsLTR();
rval = leading? TextHitInfo.leading(iter.logicalIndex()) :
TextHitInfo.trailing(iter.logicalIndex());
}
}
return rval;
}
/**
* A convenience overload which uses the natural bounds of the layout.
*/
public TextHitInfo hitTestChar(float x, float y) {
return hitTestChar(x, y, getNaturalBounds());
}
/**
* Return a layout that represents a subsection of this layout. The
* number of characters must be >= 1. The original layout must not be
* justified. The new layout will apply the bidi 'line reordering' rules
* to the text.
*
* @param firstEndpoint the index of the first character to use
* @param limit the index past the last character to use
* @return a new layout
*/
// note: eventually this method will be removed from TextLayout and an equivalent method
// added to TextMeasurer. For now, TextMeasurer is implemented using TextLayout, but it
// should be the only client of this method.
TextLayout sublayout(int start, int limit) {
if (start < 0 || limit < start || characterCount < limit) {
throw new IllegalArgumentException("Invalid rantge passed to TextLayout.sublayout()");
}
return new TextLayout(this, start, limit); // new subset
}
// === sublayout stuff: ///
/**
* Return a glyphset computed from the glyph iterator, up to limitIndex.
* If we're getting trailing whitespace (whose direction is determined by
* the Layout, not by the glyphset containing the whitespace) then
* useOverrideLevel is true, and override level is 0x0 for ltr and 0x1 for
* rtl.
*/
private static TextLayoutComponent getNextSetAtIter(GlyphIterator sourceIter,
int limitIndex) {
int startIndex = sourceIter.logicalIndex();
TextLayoutComponent currentSet = sourceIter.currentGlyphSet();
int startPosInSet = startIndex - sourceIter.logicalStartOfCurrentSet();
int limitPosInSet = startPosInSet + (limitIndex - startIndex);
if (limitPosInSet > currentSet.getNumCharacters()) {
limitPosInSet = currentSet.getNumCharacters();
}
TextLayoutComponent rval = currentSet.subset(startPosInSet, limitPosInSet);
int setLimit = startIndex + (limitPosInSet-startPosInSet);
if (setLimit < sourceIter.limit()) {
sourceIter.setLogicalGlyph(setLimit);
}
else {
sourceIter.invalidate();
}
return rval;
}
private static int[] addToIntArray(int[] old, int end) {
int len = (old == null)? 1 : old.length + 1;
int[] newArray = new int[len];
if (old != null) {
System.arraycopy(old, 0, newArray, 0, len-1);
}
newArray[len-1] = end;
return newArray;
}
// for newest "sublayout" constructor:
private static TextLayoutComponent[] addToSetArray(
TextLayoutComponent[] setArray,
TextLayoutComponent set) {
int len = (setArray == null)? 1 : setArray.length + 1;
TextLayoutComponent[] newArray = new TextLayoutComponent[len];
if (setArray != null) {
System.arraycopy(setArray, 0, newArray, 0, len-1);
}
newArray[len-1] = set;
return newArray;
}
private TextLayout(TextLayout source, final int start, final int limit) {
baseline = source.baseline;
baselineOffsets = new float[source.baselineOffsets.length];
System.arraycopy(source.baselineOffsets, 0, baselineOffsets, 0, baselineOffsets.length);
isDirectionLTR = source.isDirectionLTR;
isVerticalLine = source.isVerticalLine;
justifyRatio = source.justifyRatio;
characterCount = limit - start;
dx = dy = 0;
TextLayoutComponent[] newSets = null;
int[] newOrder = null;
{
GlyphIterator sourceIter = source.createGlyphIterator();
// is there trailing whitespace to float to the end ?
sourceIter.setLogicalGlyph(limit-1);
while (sourceIter.isValid() && sourceIter.isWhitespace()) {
sourceIter.previousLogicalGlyph();
}
int whitespaceStart;
if (sourceIter.isValid()) {
if (sourceIter.glyphIsLTR() != isDirectionLTR) {
whitespaceStart = sourceIter.logicalIndex() + 1;
} else {
whitespaceStart = limit;
}
} else {
whitespaceStart = start;
}
sourceIter.setLogicalGlyph(start);
int tempOrder;
int minOrder = Integer.MAX_VALUE, maxOrder = Integer.MIN_VALUE;
while (sourceIter.isValid() &&
sourceIter.logicalIndex() < whitespaceStart) {
tempOrder = sourceIter.visualIndex();
if (tempOrder < minOrder) {
minOrder = tempOrder;
}
if (tempOrder > maxOrder) {
maxOrder = tempOrder;
}
TextLayoutComponent nextSet =
getNextSetAtIter(sourceIter, whitespaceStart);
newSets = addToSetArray(newSets, nextSet);
newOrder = addToIntArray(newOrder, tempOrder);
}
while (sourceIter.isValid() && sourceIter.logicalIndex() < limit) {
tempOrder = isDirectionLTR? (++maxOrder) : (--minOrder);
TextLayoutComponent nextSet = getNextSetAtIter(sourceIter, limit);
nextSet = nextSet.setDirection(isDirectionLTR);
newSets = addToSetArray(newSets, nextSet);
newOrder = addToIntArray(newOrder, tempOrder);
}
}
newOrder = GlyphSet.getContiguousOrder(newOrder);
glyphs = newSets;
glyphsOrder = GlyphSet.getInverseOrder(newOrder);
}
/**
* Used for insert/delete char editing. Clone this TextLayout and replace
* oldSet with newSet in clone.
*/
private TextLayout cloneAndReplaceSet(TextLayoutComponent oldSet,
TextLayoutComponent newSet) {
TextLayout newLayout = (TextLayout) this.clone();
// deep-copy glyphs array, since it will change:
newLayout.glyphs = new TextLayoutComponent[glyphs.length];
System.arraycopy(glyphs, 0, newLayout.glyphs, 0, glyphs.length);
TextLayoutComponent[] newSets = newLayout.glyphs;
// find oldSet:
int i;
for (i=0; i<newSets.length; i++)
if (newSets[i] == oldSet) {
newSets[i] = newSet;
break;
}
if (i == newSets.length) {
throw new Error("Didn't find oldSet in cloneAndReplaceSet.");
}
newLayout.protoIterator = null;
// newLayout.buildCache();
return newLayout;
}
/**
* An optimization to facilitate inserting single characters into a
* paragraph.
*
* @param newParagraph the complete text for the new layout. This
* represents the text after the insertion
* occurred, restricted to the text which will go in the new layout.
* @param insertPos the position, relative to the text (not the start of
* the layout), at which the single character was inserted.
* @return a new layout representing newParagraph
*/
TextLayout insertChar(AttributedCharacterIterator newParagraph,
int textInsertPos)
{
ensureCache();
if (newParagraph == null) {
throw new IllegalArgumentException("Null AttributedCharacterIterator passed to TextLayout.insertChar().");
}
int newCharacterCount = characterCount+1;
if (newParagraph.getEndIndex() - newParagraph.getBeginIndex() !=
newCharacterCount) {
throw new IllegalArgumentException("TextLayout.insertChar() only handles inserting a single character.");
}
if (textInsertPos < newParagraph.getBeginIndex() ||
textInsertPos >= newParagraph.getEndIndex()) {
throw new IllegalArgumentException("insertPos is out of range in TextLayout.insertChar().");
}
int insertPos = textInsertPos - newParagraph.getBeginIndex();
TextLayoutComponent changeSet;
// the offset in newParagraph where changeSet's text begins
int setStartInText;
// if insertPos is on a glyphset boundary, we'll try to append to the
// previous set instead of inserting into first position in next set
if (insertPos == characterCount) {
changeSet = glyphs[glyphs.length-1];
setStartInText = newParagraph.getBeginIndex() +
characterCount - changeSet.getNumCharacters();
} else {
GlyphIterator iter = createGlyphIterator();
iter.setLogicalGlyph(insertPos==0? 0 : insertPos-1);
changeSet = iter.currentGlyphSet();
setStartInText = newParagraph.getBeginIndex() +
iter.logicalStartOfCurrentSet();
}
{
boolean doItFromScratch = false;
// check style compatability - if style run at textInsertPos doesn't
// start at textInsertPos then styles are compatible
newParagraph.setIndex(textInsertPos);
if (textInsertPos == newParagraph.getBeginIndex()) {
if (newParagraph.getRunLimit() <= textInsertPos + 1) {
doItFromScratch = true;
}
} else {
if (newParagraph.getRunStart() == textInsertPos) {
doItFromScratch = true;
}
}
if (doItFromScratch) {
return new TextLayout(newParagraph);
}
}
boolean rerunBidi;
if (!isDirectionLTR || !changeSet.isCompletelyLTR()) {
rerunBidi = true;
}
else {
// check dir class of inserted character
char insertedChar = newParagraph.
setIndex(newParagraph.getBeginIndex() + insertPos);
// insertedChar must be ltr in this context
byte dirClass = IncrementalBidi.getDirectionClass(insertedChar);
rerunBidi = dirClass == IncrementalBidi.R;
}
byte[] levels = null;
int[] logicalOrdering = null;
if (rerunBidi) {
return new TextLayout(newParagraph);
//IncrementalBidi bidi = new BidiInfo(newParagraph, isDirectionLTR? 0x0 : 0x1, null, null);
//levels = bidi.createLevels();
//int[] temp = bidi.createVisualToLogicalOrdering();
//logicalOrdering = GlyphSet.getInverseOrder(temp);
}
int setLimitInText = setStartInText + changeSet.getNumCharacters() + 1;
TextLayoutComponent newSet = changeSet.insertChar(newParagraph,
setStartInText, setLimitInText,
textInsertPos, logicalOrdering,
levels);
TextLayout result = cloneAndReplaceSet(changeSet, newSet);
/*
* no need to let font modify previous glyphset; since we always
* append, the only way the first glyph of a set gets changed is if
* the set is first in the layout
*/
if (setLimitInText == (textInsertPos-1) &&
setLimitInText < newParagraph.getRunLimit()) {
// need to let font have a chance to modify following GlyphSet
GlyphIterator iter = createGlyphIterator();
iter.setLogicalGlyph(setLimitInText-newParagraph.getRunStart()-1);
TextLayoutComponent nextSet = iter.currentGlyphSet();
int nextStartInText = newParagraph.getBeginIndex() +
iter.logicalStartOfCurrentSet() + 1;
TextLayoutComponent otherSet2 = nextSet.reshape(newParagraph,
nextStartInText,
nextStartInText +
nextSet.getNumCharacters(),
textInsertPos,
logicalOrdering, levels);
if (nextSet != otherSet2) {
result = result.cloneAndReplaceSet(nextSet, otherSet2);
}
}
/*
* now we don't always call buildCache on result, so cc isn't updated
* after clone
*/
result.characterCount = newCharacterCount;
return result;
}
/**
* An optimization to facilitate deleting single characters from a
* paragraph.
*
* @param newParagraph the complete text for the new paragraph. This
* represents the text after the deletion occurred, restricted to the
* text which will go in the new layout.
* @param textDeletePos the position, relative to the text (not the start
* of the layout), at which the character was deleted.
* @return a new layout representing newParagraph
*/
TextLayout deleteChar(AttributedCharacterIterator newParagraph,
int textDeletePos) {
ensureCache();
if(newParagraph == null) {
throw new IllegalArgumentException("Null AttributedCharacterIterator passed to TextLayout.deleteChar().");
}
int newCharacterCount = characterCount - 1;
if (newParagraph.getEndIndex() - newParagraph.getBeginIndex() !=
newCharacterCount)
{
throw new IllegalArgumentException("TextLayout.deleteChar() only handles deleting a single character.");
}
int deletePos = textDeletePos - newParagraph.getBeginIndex();
TextLayoutComponent changeSet;
int setStartInText; // the offset in newParagraph where changeSet begins
GlyphIterator iter = createGlyphIterator();
iter.setLogicalGlyph(deletePos);
changeSet = iter.currentGlyphSet();
setStartInText = newParagraph.getBeginIndex() +
iter.logicalStartOfCurrentSet();
// if we're deleting and entire glyphset, just redo from scratch:
if (changeSet.getNumCharacters() == 1) {
return new TextLayout(newParagraph);
}
// now check to see if we need to rerun bidi:
int[] logicalOrdering = null;
byte[] levels = null;
if (!isDirectionLTR || !changeSet.isCompletelyLTR()) {
return new TextLayout(newParagraph);
//BidiInfo bidi = new BidiInfo(newParagraph, isDirectionLTR? 0x0 : 0x1, null, null);
//levels = bidi.createLevels();
//int[] temp = bidi.createVisualToLogicalOrdering();
//logicalOrdering = GlyphSet.getInverseOrder(temp);
}
int setLimitInText = setStartInText + changeSet.getNumCharacters() - 1;
TextLayoutComponent newSet = changeSet.deleteChar(newParagraph,
setStartInText, setLimitInText,
textDeletePos, logicalOrdering,
levels);
TextLayout result = cloneAndReplaceSet(changeSet, newSet);
if (setStartInText == textDeletePos &&
setStartInText > newParagraph.getBeginIndex())
{
GlyphIterator iter2 = createGlyphIterator();
iter2.setLogicalGlyph(setStartInText -
newParagraph.getBeginIndex() - 1);
TextLayoutComponent previousSet = iter2.currentGlyphSet();
int prevStartInText = newParagraph.getBeginIndex() +
iter2.logicalStartOfCurrentSet();
TextLayoutComponent otherSet = previousSet.reshape(newParagraph,
prevStartInText,
setStartInText,
textDeletePos,
logicalOrdering,
levels);
if (previousSet != otherSet) {
result = result.cloneAndReplaceSet(previousSet, otherSet);
}
}
if (setLimitInText == textDeletePos &&
setLimitInText < newParagraph.getEndIndex()) {
GlyphIterator iter2 = createGlyphIterator();
iter2.setLogicalGlyph(setLimitInText -
newParagraph.getBeginIndex() + 1);
TextLayoutComponent nextSet = iter2.currentGlyphSet();
int nextStartInText = setLimitInText;
TextLayoutComponent otherSet2 = nextSet.reshape(newParagraph,
nextStartInText,
nextStartInText +
nextSet.getNumCharacters(),
textDeletePos-1,
logicalOrdering, levels);
if (nextSet != otherSet2) {
result = result.cloneAndReplaceSet(nextSet, otherSet2);
}
}
/*
* now we don't always call buildCache on result, so cc isn't
* updated after clone
*/
result.characterCount = newCharacterCount;
return result;
}
/**
* Return the hash code of this layout.
*/
public int hashCode() {
if (hashCodeCache == 0) {
hashCodeCache = (glyphs.length << 16) ^
(glyphs[0].hashCode() << 3) ^ characterCount;
}
return hashCodeCache;
}
/**
* Return true if the object is a TextLayout and this equals the object.
*/
public boolean equals(Object obj) {
return (obj instanceof TextLayout) && equals((TextLayout)obj);
}
/**
* Return true if the two layouts are equal.
*
* Two layouts are equal if they contain equal glyphsets in the same order.
*
* @param layout the layout to which to compare this layout.
*/
/*
* !!! Does it make sense to implement equality for layouts?
* I don't see why you'd want to do this. Stephen's line layout used to
* use it to see when it is safe to stop justifying lines, but I don't
* think it's required for that, and the implementation here may not quite
* work as it doesn't compare attributes or baselines except as through the
* glyphsets.
*/
public boolean equals(TextLayout layout) {
if (layout == null) {
return false;
}
if (layout == this) {
return true;
}
if (glyphs.length != layout.glyphs.length) {
return false;
}
for (int i = 0; i < glyphs.length; i++) {
if (glyphs[i].hashCode() != layout.glyphs[i].hashCode()) {
return false;
}
}
for (int i = 0; i < glyphs.length; i++) {
if (!glyphs[i].equals(layout.glyphs[i])) {
return false;
}
}
return true;
}
/**
* Display the glyphsets contained in the layout, for debugging only.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < glyphs.length; i++) {
buf.append(glyphs[i]);
}
buf.append("\n");
return buf.toString();
}
/**
* Render the layout at the provided location in the graphics.
*
* The origin of the layout is placed at x, y. Rendering may touch any
* point within getBounds() of this position. This leaves the graphics
* unchanged.
*
* @param g2 the graphics into which to render the layout
* @param x the x position for the origin of the layout
* @param y the y position for the origin of the layout
* @see #getBounds
*/
public void draw(Graphics2D g2, float x, float y) {
if (g2 == null) {
throw new IllegalArgumentException("Null Graphics2D passed to TextLayout.draw()");
}
float nx = x - dx;
float ny = y - dy;
for (int i = 0; i < glyphs.length; i++) {
int vi = glyphsOrder == null ? i : glyphsOrder[i];
TextLayoutComponent gs = glyphs[vi];
float gx = isVerticalLine ? nx +
baselineOffsets[gs.getBaseline()] : nx;
float gy = isVerticalLine ? ny : ny +
baselineOffsets[gs.getBaseline()];
gs.draw(g2, gx, gy, this);
if (isVerticalLine) {
ny += gs.getAdvance();
} else {
nx += gs.getAdvance();
}
}
}
/**
* Create an iterator over the glyphs in this layout.
*
* The iterator is used for accessing most information about a glyph,
* including position, logical and physical index, font, metrics, and so on.
*
* This method is package-visible for testing.
*
* @see GlyphIterator
*/
GlyphIterator createGlyphIterator() {
if (protoIterator == null) {
protoIterator = new GlyphIterator(this, glyphs, glyphsOrder);
}
return new GlyphIterator(protoIterator);
}
}