2 * Copyright (C) 2006 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 import android.annotation.IntDef;
20 import android.graphics.Canvas;
21 import android.graphics.Paint;
22 import android.graphics.Path;
23 import android.graphics.Rect;
24 import android.text.method.TextKeyListener;
25 import android.text.style.AlignmentSpan;
26 import android.text.style.LeadingMarginSpan;
27 import android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
28 import android.text.style.LineBackgroundSpan;
29 import android.text.style.ParagraphStyle;
30 import android.text.style.ReplacementSpan;
31 import android.text.style.TabStopSpan;
33 import com.android.internal.util.ArrayUtils;
34 import com.android.internal.util.GrowingArrayUtils;
36 import java.lang.annotation.Retention;
37 import java.lang.annotation.RetentionPolicy;
38 import java.util.Arrays;
41 * A base class that manages text layout in visual elements on
43 * <p>For text that will be edited, use a {@link DynamicLayout},
44 * which will be updated as the text changes.
45 * For text that will not change, use a {@link StaticLayout}.
47 public abstract class Layout {
49 @IntDef({BREAK_STRATEGY_SIMPLE, BREAK_STRATEGY_HIGH_QUALITY, BREAK_STRATEGY_BALANCED})
50 @Retention(RetentionPolicy.SOURCE)
51 public @interface BreakStrategy {}
54 * Value for break strategy indicating simple line breaking. Automatic hyphens are not added
55 * (though soft hyphens are respected), and modifying text generally doesn't affect the layout
56 * before it (which yields a more consistent user experience when editing), but layout may not
57 * be the highest quality.
59 public static final int BREAK_STRATEGY_SIMPLE = 0;
62 * Value for break strategy indicating high quality line breaking, including automatic
63 * hyphenation and doing whole-paragraph optimization of line breaks.
65 public static final int BREAK_STRATEGY_HIGH_QUALITY = 1;
68 * Value for break strategy indicating balanced line breaking. The breaks are chosen to
69 * make all lines as close to the same length as possible, including automatic hyphenation.
71 public static final int BREAK_STRATEGY_BALANCED = 2;
74 @IntDef({HYPHENATION_FREQUENCY_NORMAL, HYPHENATION_FREQUENCY_FULL,
75 HYPHENATION_FREQUENCY_NONE})
76 @Retention(RetentionPolicy.SOURCE)
77 public @interface HyphenationFrequency {}
80 * Value for hyphenation frequency indicating no automatic hyphenation. Useful
81 * for backward compatibility, and for cases where the automatic hyphenation algorithm results
82 * in incorrect hyphenation. Mid-word breaks may still happen when a word is wider than the
83 * layout and there is otherwise no valid break. Soft hyphens are ignored and will not be used
84 * as suggestions for potential line breaks.
86 public static final int HYPHENATION_FREQUENCY_NONE = 0;
89 * Value for hyphenation frequency indicating a light amount of automatic hyphenation, which
90 * is a conservative default. Useful for informal cases, such as short sentences or chat
93 public static final int HYPHENATION_FREQUENCY_NORMAL = 1;
96 * Value for hyphenation frequency indicating the full amount of automatic hyphenation, typical
97 * in typography. Useful for running text and where it's important to put the maximum amount of
98 * text in a screen with limited space.
100 public static final int HYPHENATION_FREQUENCY_FULL = 2;
102 private static final ParagraphStyle[] NO_PARA_SPANS =
103 ArrayUtils.emptyArray(ParagraphStyle.class);
106 * Return how wide a layout must be in order to display the
107 * specified text with one line per paragraph.
109 public static float getDesiredWidth(CharSequence source,
111 return getDesiredWidth(source, 0, source.length(), paint);
115 * Return how wide a layout must be in order to display the
116 * specified text slice with one line per paragraph.
118 public static float getDesiredWidth(CharSequence source,
124 for (int i = start; i <= end; i = next) {
125 next = TextUtils.indexOf(source, '\n', i, end);
130 // note, omits trailing paragraph char
131 float w = measurePara(paint, source, i, next);
143 * Subclasses of Layout use this constructor to set the display text,
144 * width, and other standard properties.
145 * @param text the text to render
146 * @param paint the default paint for the layout. Styles can override
147 * various attributes of the paint.
148 * @param width the wrapping width for the text.
149 * @param align whether to left, right, or center the text. Styles can
150 * override the alignment.
151 * @param spacingMult factor by which to scale the font size to get the
152 * default line spacing
153 * @param spacingAdd amount to add to the default line spacing
155 protected Layout(CharSequence text, TextPaint paint,
156 int width, Alignment align,
157 float spacingMult, float spacingAdd) {
158 this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
159 spacingMult, spacingAdd);
163 * Subclasses of Layout use this constructor to set the display text,
164 * width, and other standard properties.
165 * @param text the text to render
166 * @param paint the default paint for the layout. Styles can override
167 * various attributes of the paint.
168 * @param width the wrapping width for the text.
169 * @param align whether to left, right, or center the text. Styles can
170 * override the alignment.
171 * @param spacingMult factor by which to scale the font size to get the
172 * default line spacing
173 * @param spacingAdd amount to add to the default line spacing
177 protected Layout(CharSequence text, TextPaint paint,
178 int width, Alignment align, TextDirectionHeuristic textDir,
179 float spacingMult, float spacingAdd) {
182 throw new IllegalArgumentException("Layout: " + width + " < 0");
184 // Ensure paint doesn't have baselineShift set.
185 // While normally we don't modify the paint the user passed in,
186 // we were already doing this in Styled.drawUniformRun with both
187 // baselineShift and bgColor. We probably should reevaluate bgColor.
190 paint.baselineShift = 0;
197 mSpacingMult = spacingMult;
198 mSpacingAdd = spacingAdd;
199 mSpannedText = text instanceof Spanned;
204 * Replace constructor properties of this Layout with new ones. Be careful.
206 /* package */ void replaceWith(CharSequence text, TextPaint paint,
207 int width, Alignment align,
208 float spacingmult, float spacingadd) {
210 throw new IllegalArgumentException("Layout: " + width + " < 0");
217 mSpacingMult = spacingmult;
218 mSpacingAdd = spacingadd;
219 mSpannedText = text instanceof Spanned;
223 * Draw this Layout on the specified Canvas.
225 public void draw(Canvas c) {
226 draw(c, null, null, 0);
230 * Draw this Layout on the specified canvas, with the highlight path drawn
231 * between the background and the text.
233 * @param canvas the canvas
234 * @param highlight the path of the highlight or cursor; can be null
235 * @param highlightPaint the paint for the highlight
236 * @param cursorOffsetVertical the amount to temporarily translate the
237 * canvas while rendering the highlight
239 public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
240 int cursorOffsetVertical) {
241 final long lineRange = getLineRangeForDraw(canvas);
242 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
243 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
244 if (lastLine < 0) return;
246 drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
247 firstLine, lastLine);
248 drawText(canvas, firstLine, lastLine);
254 public void drawText(Canvas canvas, int firstLine, int lastLine) {
255 int previousLineBottom = getLineTop(firstLine);
256 int previousLineEnd = getLineStart(firstLine);
257 ParagraphStyle[] spans = NO_PARA_SPANS;
259 TextPaint paint = mPaint;
260 CharSequence buf = mText;
262 Alignment paraAlign = mAlignment;
263 TabStops tabStops = null;
264 boolean tabStopsIsInitialized = false;
266 TextLine tl = TextLine.obtain();
268 // Draw the lines, one at a time.
269 // The baseline is the top of the following line minus the current line's descent.
270 for (int lineNum = firstLine; lineNum <= lastLine; lineNum++) {
271 int start = previousLineEnd;
272 previousLineEnd = getLineStart(lineNum + 1);
273 int end = getLineVisibleEnd(lineNum, start, previousLineEnd);
275 int ltop = previousLineBottom;
276 int lbottom = getLineTop(lineNum + 1);
277 previousLineBottom = lbottom;
278 int lbaseline = lbottom - getLineDescent(lineNum);
280 int dir = getParagraphDirection(lineNum);
285 Spanned sp = (Spanned) buf;
286 int textLength = buf.length();
287 boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
289 // New batch of paragraph styles, collect into spans array.
290 // Compute the alignment, last alignment style wins.
291 // Reset tabStops, we'll rebuild if we encounter a line with
293 // We expect paragraph spans to be relatively infrequent, use
294 // spanEnd so that we can check less frequently. Since
295 // paragraph styles ought to apply to entire paragraphs, we can
296 // just collect the ones present at the start of the paragraph.
297 // If spanEnd is before the end of the paragraph, that's not
299 if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
300 spanEnd = sp.nextSpanTransition(start, textLength,
301 ParagraphStyle.class);
302 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
304 paraAlign = mAlignment;
305 for (int n = spans.length - 1; n >= 0; n--) {
306 if (spans[n] instanceof AlignmentSpan) {
307 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
312 tabStopsIsInitialized = false;
315 // Draw all leading margin spans. Adjust left or right according
316 // to the paragraph direction of the line.
317 final int length = spans.length;
318 boolean useFirstLineMargin = isFirstParaLine;
319 for (int n = 0; n < length; n++) {
320 if (spans[n] instanceof LeadingMarginSpan2) {
321 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
322 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
323 // if there is more than one LeadingMarginSpan2, use
324 // the count that is greatest
325 if (lineNum < startLine + count) {
326 useFirstLineMargin = true;
331 for (int n = 0; n < length; n++) {
332 if (spans[n] instanceof LeadingMarginSpan) {
333 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
334 if (dir == DIR_RIGHT_TO_LEFT) {
335 margin.drawLeadingMargin(canvas, paint, right, dir, ltop,
336 lbaseline, lbottom, buf,
337 start, end, isFirstParaLine, this);
338 right -= margin.getLeadingMargin(useFirstLineMargin);
340 margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
341 lbaseline, lbottom, buf,
342 start, end, isFirstParaLine, this);
343 left += margin.getLeadingMargin(useFirstLineMargin);
349 boolean hasTab = getLineContainsTab(lineNum);
350 // Can't tell if we have tabs for sure, currently
351 if (hasTab && !tabStopsIsInitialized) {
352 if (tabStops == null) {
353 tabStops = new TabStops(TAB_INCREMENT, spans);
355 tabStops.reset(TAB_INCREMENT, spans);
357 tabStopsIsInitialized = true;
360 // Determine whether the line aligns to normal, opposite, or center.
361 Alignment align = paraAlign;
362 if (align == Alignment.ALIGN_LEFT) {
363 align = (dir == DIR_LEFT_TO_RIGHT) ?
364 Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
365 } else if (align == Alignment.ALIGN_RIGHT) {
366 align = (dir == DIR_LEFT_TO_RIGHT) ?
367 Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
371 if (align == Alignment.ALIGN_NORMAL) {
372 if (dir == DIR_LEFT_TO_RIGHT) {
373 x = left + getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
375 x = right + getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
378 int max = (int)getLineExtent(lineNum, tabStops, false);
379 if (align == Alignment.ALIGN_OPPOSITE) {
380 if (dir == DIR_LEFT_TO_RIGHT) {
381 x = right - max + getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
383 x = left - max + getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
385 } else { // Alignment.ALIGN_CENTER
387 x = ((right + left - max) >> 1) +
388 getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
392 paint.setHyphenEdit(getHyphen(lineNum));
393 Directions directions = getLineDirections(lineNum);
394 if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTab) {
395 // XXX: assumes there's nothing additional to be done
396 canvas.drawText(buf, start, end, x, lbaseline, paint);
398 tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops);
399 tl.draw(canvas, x, ltop, lbaseline, lbottom);
401 paint.setHyphenEdit(0);
404 TextLine.recycle(tl);
410 public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
411 int cursorOffsetVertical, int firstLine, int lastLine) {
412 // First, draw LineBackgroundSpans.
413 // LineBackgroundSpans know nothing about the alignment, margins, or
414 // direction of the layout or line. XXX: Should they?
415 // They are evaluated at each line.
417 if (mLineBackgroundSpans == null) {
418 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
421 Spanned buffer = (Spanned) mText;
422 int textLength = buffer.length();
423 mLineBackgroundSpans.init(buffer, 0, textLength);
425 if (mLineBackgroundSpans.numberOfSpans > 0) {
426 int previousLineBottom = getLineTop(firstLine);
427 int previousLineEnd = getLineStart(firstLine);
428 ParagraphStyle[] spans = NO_PARA_SPANS;
430 TextPaint paint = mPaint;
432 final int width = mWidth;
433 for (int i = firstLine; i <= lastLine; i++) {
434 int start = previousLineEnd;
435 int end = getLineStart(i + 1);
436 previousLineEnd = end;
438 int ltop = previousLineBottom;
439 int lbottom = getLineTop(i + 1);
440 previousLineBottom = lbottom;
441 int lbaseline = lbottom - getLineDescent(i);
443 if (start >= spanEnd) {
444 // These should be infrequent, so we'll use this so that
445 // we don't have to check as often.
446 spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
447 // All LineBackgroundSpans on a line contribute to its background.
449 // Duplication of the logic of getParagraphSpans
450 if (start != end || start == 0) {
451 // Equivalent to a getSpans(start, end), but filling the 'spans' local
452 // array instead to reduce memory allocation
453 for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
454 // equal test is valid since both intervals are not empty by
456 if (mLineBackgroundSpans.spanStarts[j] >= end ||
457 mLineBackgroundSpans.spanEnds[j] <= start) continue;
458 spans = GrowingArrayUtils.append(
459 spans, spansLength, mLineBackgroundSpans.spans[j]);
465 for (int n = 0; n < spansLength; n++) {
466 LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
467 lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
468 ltop, lbaseline, lbottom,
469 buffer, start, end, i);
473 mLineBackgroundSpans.recycle();
476 // There can be a highlight even without spans if we are drawing
477 // a non-spanned transformation of a spanned editing buffer.
478 if (highlight != null) {
479 if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
480 canvas.drawPath(highlight, highlightPaint);
481 if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
487 * @return The range of lines that need to be drawn, possibly empty.
490 public long getLineRangeForDraw(Canvas canvas) {
493 synchronized (sTempRect) {
494 if (!canvas.getClipBounds(sTempRect)) {
495 // Negative range end used as a special flag
496 return TextUtils.packRangeInLong(0, -1);
499 dtop = sTempRect.top;
500 dbottom = sTempRect.bottom;
503 final int top = Math.max(dtop, 0);
504 final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
506 if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
507 return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
511 * Return the start position of the line, given the left and right bounds
514 * @param line the line index
515 * @param left the left bounds (0, or leading margin if ltr para)
516 * @param right the right bounds (width, minus leading margin if rtl para)
517 * @return the start position of the line (to right of line if rtl para)
519 private int getLineStartPos(int line, int left, int right) {
520 // Adjust the point at which to start rendering depending on the
521 // alignment of the paragraph.
522 Alignment align = getParagraphAlignment(line);
523 int dir = getParagraphDirection(line);
525 if (align == Alignment.ALIGN_LEFT) {
526 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
527 } else if (align == Alignment.ALIGN_RIGHT) {
528 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
532 if (align == Alignment.ALIGN_NORMAL) {
533 if (dir == DIR_LEFT_TO_RIGHT) {
534 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
536 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
539 TabStops tabStops = null;
540 if (mSpannedText && getLineContainsTab(line)) {
541 Spanned spanned = (Spanned) mText;
542 int start = getLineStart(line);
543 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
545 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
547 if (tabSpans.length > 0) {
548 tabStops = new TabStops(TAB_INCREMENT, tabSpans);
551 int max = (int)getLineExtent(line, tabStops, false);
552 if (align == Alignment.ALIGN_OPPOSITE) {
553 if (dir == DIR_LEFT_TO_RIGHT) {
554 x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
556 // max is negative here
557 x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
559 } else { // Alignment.ALIGN_CENTER
561 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
568 * Return the text that is displayed by this Layout.
570 public final CharSequence getText() {
575 * Return the base Paint properties for this layout.
576 * Do NOT change the paint, which may result in funny
577 * drawing for this layout.
579 public final TextPaint getPaint() {
584 * Return the width of this layout.
586 public final int getWidth() {
591 * Return the width to which this Layout is ellipsizing, or
592 * {@link #getWidth} if it is not doing anything special.
594 public int getEllipsizedWidth() {
599 * Increase the width of this layout to the specified width.
600 * Be careful to use this only when you know it is appropriate—
601 * it does not cause the text to reflow to use the full new width.
603 public final void increaseWidthTo(int wid) {
605 throw new RuntimeException("attempted to reduce Layout width");
612 * Return the total height of this layout.
614 public int getHeight() {
615 return getLineTop(getLineCount());
619 * Return the base alignment of this layout.
621 public final Alignment getAlignment() {
626 * Return what the text height is multiplied by to get the line height.
628 public final float getSpacingMultiplier() {
633 * Return the number of units of leading that are added to each line.
635 public final float getSpacingAdd() {
640 * Return the heuristic used to determine paragraph text direction.
643 public final TextDirectionHeuristic getTextDirectionHeuristic() {
648 * Return the number of lines of text in this layout.
650 public abstract int getLineCount();
653 * Return the baseline for the specified line (0…getLineCount() - 1)
654 * If bounds is not null, return the top, left, right, bottom extents
655 * of the specified line in it.
656 * @param line which line to examine (0..getLineCount() - 1)
657 * @param bounds Optional. If not null, it returns the extent of the line
658 * @return the Y-coordinate of the baseline
660 public int getLineBounds(int line, Rect bounds) {
661 if (bounds != null) {
662 bounds.left = 0; // ???
663 bounds.top = getLineTop(line);
664 bounds.right = mWidth; // ???
665 bounds.bottom = getLineTop(line + 1);
667 return getLineBaseline(line);
671 * Return the vertical position of the top of the specified line
672 * (0…getLineCount()).
673 * If the specified line is equal to the line count, returns the
674 * bottom of the last line.
676 public abstract int getLineTop(int line);
679 * Return the descent of the specified line(0…getLineCount() - 1).
681 public abstract int getLineDescent(int line);
684 * Return the text offset of the beginning of the specified line (
685 * 0…getLineCount()). If the specified line is equal to the line
686 * count, returns the length of the text.
688 public abstract int getLineStart(int line);
691 * Returns the primary directionality of the paragraph containing the
692 * specified line, either 1 for left-to-right lines, or -1 for right-to-left
693 * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
695 public abstract int getParagraphDirection(int line);
698 * Returns whether the specified line contains one or more
699 * characters that need to be handled specially, like tabs.
701 public abstract boolean getLineContainsTab(int line);
704 * Returns the directional run information for the specified line.
705 * The array alternates counts of characters in left-to-right
706 * and right-to-left segments of the line.
708 * <p>NOTE: this is inadequate to support bidirectional text, and will change.
710 public abstract Directions getLineDirections(int line);
713 * Returns the (negative) number of extra pixels of ascent padding in the
714 * top line of the Layout.
716 public abstract int getTopPadding();
719 * Returns the number of extra pixels of descent padding in the
720 * bottom line of the Layout.
722 public abstract int getBottomPadding();
725 * Returns the hyphen edit for a line.
729 public int getHyphen(int line) {
734 * Returns the left indent for a line.
738 public int getIndentAdjust(int line, Alignment alignment) {
743 * Returns true if the character at offset and the preceding character
744 * are at different run levels (and thus there's a split caret).
745 * @param offset the offset
746 * @return true if at a level boundary
749 public boolean isLevelBoundary(int offset) {
750 int line = getLineForOffset(offset);
751 Directions dirs = getLineDirections(line);
752 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
756 int[] runs = dirs.mDirections;
757 int lineStart = getLineStart(line);
758 int lineEnd = getLineEnd(line);
759 if (offset == lineStart || offset == lineEnd) {
760 int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
761 int runIndex = offset == lineStart ? 0 : runs.length - 2;
762 return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
766 for (int i = 0; i < runs.length; i += 2) {
767 if (offset == runs[i]) {
775 * Returns true if the character at offset is right to left (RTL).
776 * @param offset the offset
777 * @return true if the character is RTL, false if it is LTR
779 public boolean isRtlCharAt(int offset) {
780 int line = getLineForOffset(offset);
781 Directions dirs = getLineDirections(line);
782 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
785 if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
788 int[] runs = dirs.mDirections;
789 int lineStart = getLineStart(line);
790 for (int i = 0; i < runs.length; i += 2) {
791 int start = lineStart + runs[i];
792 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
793 if (offset >= start && offset < limit) {
794 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
795 return ((level & 1) != 0);
798 // Should happen only if the offset is "out of bounds"
803 * Returns the range of the run that the character at offset belongs to.
804 * @param offset the offset
805 * @return The range of the run
808 public long getRunRange(int offset) {
809 int line = getLineForOffset(offset);
810 Directions dirs = getLineDirections(line);
811 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
812 return TextUtils.packRangeInLong(0, getLineEnd(line));
814 int[] runs = dirs.mDirections;
815 int lineStart = getLineStart(line);
816 for (int i = 0; i < runs.length; i += 2) {
817 int start = lineStart + runs[i];
818 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
819 if (offset >= start && offset < limit) {
820 return TextUtils.packRangeInLong(start, limit);
823 // Should happen only if the offset is "out of bounds"
824 return TextUtils.packRangeInLong(0, getLineEnd(line));
828 * Checks if the trailing BiDi level should be used for an offset
830 * This method is useful when the offset is at the BiDi level transition point and determine
831 * which run need to be used. For example, let's think about following input: (L* denotes
832 * Left-to-Right characters, R* denotes Right-to-Left characters.)
833 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
834 * Input (Display Order): L1 L2 L3 R3 R2 R1 L4 L5 L6
836 * Then, think about selecting the range (3, 6). The offset=3 and offset=6 are ambiguous here
837 * since they are at the BiDi transition point. In Android, the offset is considered to be
838 * associated with the trailing run if the BiDi level of the trailing run is higher than of the
839 * previous run. In this case, the BiDi level of the input text is as follows:
841 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
842 * BiDi Run: [ Run 0 ][ Run 1 ][ Run 2 ]
843 * BiDi Level: 0 0 0 1 1 1 0 0 0
845 * Thus, offset = 3 is part of Run 1 and this method returns true for offset = 3, since the BiDi
846 * level of Run 1 is higher than the level of Run 0. Similarly, the offset = 6 is a part of Run
847 * 1 and this method returns false for the offset = 6 since the BiDi level of Run 1 is higher
848 * than the level of Run 2.
850 * @returns true if offset is at the BiDi level transition point and trailing BiDi level is
851 * higher than previous BiDi level. See above for the detail.
853 private boolean primaryIsTrailingPrevious(int offset) {
854 int line = getLineForOffset(offset);
855 int lineStart = getLineStart(line);
856 int lineEnd = getLineEnd(line);
857 int[] runs = getLineDirections(line).mDirections;
860 for (int i = 0; i < runs.length; i += 2) {
861 int start = lineStart + runs[i];
862 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
863 if (limit > lineEnd) {
866 if (offset >= start && offset < limit) {
867 if (offset > start) {
868 // Previous character is at same level, so don't use trailing.
871 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
876 // Offset was limit of line.
877 levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
880 // At level boundary, check previous level.
881 int levelBefore = -1;
882 if (offset == lineStart) {
883 levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
886 for (int i = 0; i < runs.length; i += 2) {
887 int start = lineStart + runs[i];
888 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
889 if (limit > lineEnd) {
892 if (offset >= start && offset < limit) {
893 levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
899 return levelBefore < levelAt;
903 * Computes in linear time the results of calling
904 * #primaryIsTrailingPrevious for all offsets on a line.
905 * @param line The line giving the offsets we compute the information for
906 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
908 private boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
909 int lineStart = getLineStart(line);
910 int lineEnd = getLineEnd(line);
911 int[] runs = getLineDirections(line).mDirections;
913 boolean[] trailing = new boolean[lineEnd - lineStart + 1];
915 byte[] level = new byte[lineEnd - lineStart + 1];
916 for (int i = 0; i < runs.length; i += 2) {
917 int start = lineStart + runs[i];
918 int limit = start + (runs[i + 1] & RUN_LENGTH_MASK);
919 if (limit > lineEnd) {
922 level[limit - lineStart - 1] =
923 (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
926 for (int i = 0; i < runs.length; i += 2) {
927 int start = lineStart + runs[i];
928 byte currentLevel = (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
929 trailing[start - lineStart] = currentLevel > (start == lineStart
930 ? (getParagraphDirection(line) == 1 ? 0 : 1)
931 : level[start - lineStart - 1]);
938 * Get the primary horizontal position for the specified text offset.
939 * This is the location where a new character would be inserted in
940 * the paragraph's primary direction.
942 public float getPrimaryHorizontal(int offset) {
943 return getPrimaryHorizontal(offset, false /* not clamped */);
947 * Get the primary horizontal position for the specified text offset, but
948 * optionally clamp it so that it doesn't exceed the width of the layout.
951 public float getPrimaryHorizontal(int offset, boolean clamped) {
952 boolean trailing = primaryIsTrailingPrevious(offset);
953 return getHorizontal(offset, trailing, clamped);
957 * Get the secondary horizontal position for the specified text offset.
958 * This is the location where a new character would be inserted in
959 * the direction other than the paragraph's primary direction.
961 public float getSecondaryHorizontal(int offset) {
962 return getSecondaryHorizontal(offset, false /* not clamped */);
966 * Get the secondary horizontal position for the specified text offset, but
967 * optionally clamp it so that it doesn't exceed the width of the layout.
970 public float getSecondaryHorizontal(int offset, boolean clamped) {
971 boolean trailing = primaryIsTrailingPrevious(offset);
972 return getHorizontal(offset, !trailing, clamped);
975 private float getHorizontal(int offset, boolean primary) {
976 return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
979 private float getHorizontal(int offset, boolean trailing, boolean clamped) {
980 int line = getLineForOffset(offset);
982 return getHorizontal(offset, trailing, line, clamped);
985 private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
986 int start = getLineStart(line);
987 int end = getLineEnd(line);
988 int dir = getParagraphDirection(line);
989 boolean hasTab = getLineContainsTab(line);
990 Directions directions = getLineDirections(line);
992 TabStops tabStops = null;
993 if (hasTab && mText instanceof Spanned) {
994 // Just checking this line should be good enough, tabs should be
995 // consistent across all lines in a paragraph.
996 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
997 if (tabs.length > 0) {
998 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1002 TextLine tl = TextLine.obtain();
1003 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
1004 float wid = tl.measure(offset - start, trailing, null);
1005 TextLine.recycle(tl);
1007 if (clamped && wid > mWidth) {
1010 int left = getParagraphLeft(line);
1011 int right = getParagraphRight(line);
1013 return getLineStartPos(line, left, right) + wid;
1017 * Computes in linear time the results of calling
1018 * #getHorizontal for all offsets on a line.
1019 * @param line The line giving the offsets we compute information for
1020 * @param clamped Whether to clamp the results to the width of the layout
1021 * @param primary Whether the results should be the primary or the secondary horizontal
1022 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1024 private float[] getLineHorizontals(int line, boolean clamped, boolean primary) {
1025 int start = getLineStart(line);
1026 int end = getLineEnd(line);
1027 int dir = getParagraphDirection(line);
1028 boolean hasTab = getLineContainsTab(line);
1029 Directions directions = getLineDirections(line);
1031 TabStops tabStops = null;
1032 if (hasTab && mText instanceof Spanned) {
1033 // Just checking this line should be good enough, tabs should be
1034 // consistent across all lines in a paragraph.
1035 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1036 if (tabs.length > 0) {
1037 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1041 TextLine tl = TextLine.obtain();
1042 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
1043 boolean[] trailings = primaryIsTrailingPreviousAllLineOffsets(line);
1045 for (int offset = 0; offset < trailings.length; ++offset) {
1046 trailings[offset] = !trailings[offset];
1049 float[] wid = tl.measureAllOffsets(trailings, null);
1050 TextLine.recycle(tl);
1053 for (int offset = 0; offset <= wid.length; ++offset) {
1054 if (wid[offset] > mWidth) {
1055 wid[offset] = mWidth;
1059 int left = getParagraphLeft(line);
1060 int right = getParagraphRight(line);
1062 int lineStartPos = getLineStartPos(line, left, right);
1063 float[] horizontal = new float[end - start + 1];
1064 for (int offset = 0; offset < horizontal.length; ++offset) {
1065 horizontal[offset] = lineStartPos + wid[offset];
1071 * Get the leftmost position that should be exposed for horizontal
1072 * scrolling on the specified line.
1074 public float getLineLeft(int line) {
1075 int dir = getParagraphDirection(line);
1076 Alignment align = getParagraphAlignment(line);
1078 if (align == Alignment.ALIGN_LEFT) {
1080 } else if (align == Alignment.ALIGN_NORMAL) {
1081 if (dir == DIR_RIGHT_TO_LEFT)
1082 return getParagraphRight(line) - getLineMax(line);
1085 } else if (align == Alignment.ALIGN_RIGHT) {
1086 return mWidth - getLineMax(line);
1087 } else if (align == Alignment.ALIGN_OPPOSITE) {
1088 if (dir == DIR_RIGHT_TO_LEFT)
1091 return mWidth - getLineMax(line);
1092 } else { /* align == Alignment.ALIGN_CENTER */
1093 int left = getParagraphLeft(line);
1094 int right = getParagraphRight(line);
1095 int max = ((int) getLineMax(line)) & ~1;
1097 return left + ((right - left) - max) / 2;
1102 * Get the rightmost position that should be exposed for horizontal
1103 * scrolling on the specified line.
1105 public float getLineRight(int line) {
1106 int dir = getParagraphDirection(line);
1107 Alignment align = getParagraphAlignment(line);
1109 if (align == Alignment.ALIGN_LEFT) {
1110 return getParagraphLeft(line) + getLineMax(line);
1111 } else if (align == Alignment.ALIGN_NORMAL) {
1112 if (dir == DIR_RIGHT_TO_LEFT)
1115 return getParagraphLeft(line) + getLineMax(line);
1116 } else if (align == Alignment.ALIGN_RIGHT) {
1118 } else if (align == Alignment.ALIGN_OPPOSITE) {
1119 if (dir == DIR_RIGHT_TO_LEFT)
1120 return getLineMax(line);
1123 } else { /* align == Alignment.ALIGN_CENTER */
1124 int left = getParagraphLeft(line);
1125 int right = getParagraphRight(line);
1126 int max = ((int) getLineMax(line)) & ~1;
1128 return right - ((right - left) - max) / 2;
1133 * Gets the unsigned horizontal extent of the specified line, including
1134 * leading margin indent, but excluding trailing whitespace.
1136 public float getLineMax(int line) {
1137 float margin = getParagraphLeadingMargin(line);
1138 float signedExtent = getLineExtent(line, false);
1139 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1143 * Gets the unsigned horizontal extent of the specified line, including
1144 * leading margin indent and trailing whitespace.
1146 public float getLineWidth(int line) {
1147 float margin = getParagraphLeadingMargin(line);
1148 float signedExtent = getLineExtent(line, true);
1149 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1153 * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1154 * tab stops instead of using the ones passed in.
1155 * @param line the index of the line
1156 * @param full whether to include trailing whitespace
1157 * @return the extent of the line
1159 private float getLineExtent(int line, boolean full) {
1160 int start = getLineStart(line);
1161 int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1163 boolean hasTabs = getLineContainsTab(line);
1164 TabStops tabStops = null;
1165 if (hasTabs && mText instanceof Spanned) {
1166 // Just checking this line should be good enough, tabs should be
1167 // consistent across all lines in a paragraph.
1168 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1169 if (tabs.length > 0) {
1170 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1173 Directions directions = getLineDirections(line);
1174 // Returned directions can actually be null
1175 if (directions == null) {
1178 int dir = getParagraphDirection(line);
1180 TextLine tl = TextLine.obtain();
1181 tl.set(mPaint, mText, start, end, dir, directions, hasTabs, tabStops);
1182 float width = tl.metrics(null);
1183 TextLine.recycle(tl);
1188 * Returns the signed horizontal extent of the specified line, excluding
1189 * leading margin. If full is false, excludes trailing whitespace.
1190 * @param line the index of the line
1191 * @param tabStops the tab stops, can be null if we know they're not used.
1192 * @param full whether to include trailing whitespace
1193 * @return the extent of the text on this line
1195 private float getLineExtent(int line, TabStops tabStops, boolean full) {
1196 int start = getLineStart(line);
1197 int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1198 boolean hasTabs = getLineContainsTab(line);
1199 Directions directions = getLineDirections(line);
1200 int dir = getParagraphDirection(line);
1202 TextLine tl = TextLine.obtain();
1203 tl.set(mPaint, mText, start, end, dir, directions, hasTabs, tabStops);
1204 float width = tl.metrics(null);
1205 TextLine.recycle(tl);
1210 * Get the line number corresponding to the specified vertical position.
1211 * If you ask for a position above 0, you get 0; if you ask for a position
1212 * below the bottom of the text, you get the last line.
1214 // FIXME: It may be faster to do a linear search for layouts without many lines.
1215 public int getLineForVertical(int vertical) {
1216 int high = getLineCount(), low = -1, guess;
1218 while (high - low > 1) {
1219 guess = (high + low) / 2;
1221 if (getLineTop(guess) > vertical)
1234 * Get the line number on which the specified text offset appears.
1235 * If you ask for a position before 0, you get 0; if you ask for a position
1236 * beyond the end of the text, you get the last line.
1238 public int getLineForOffset(int offset) {
1239 int high = getLineCount(), low = -1, guess;
1241 while (high - low > 1) {
1242 guess = (high + low) / 2;
1244 if (getLineStart(guess) > offset)
1257 * Get the character offset on the specified line whose position is
1258 * closest to the specified horizontal position.
1260 public int getOffsetForHorizontal(int line, float horiz) {
1261 return getOffsetForHorizontal(line, horiz, true);
1265 * Get the character offset on the specified line whose position is
1266 * closest to the specified horizontal position.
1268 * @param line the line used to find the closest offset
1269 * @param horiz the horizontal position used to find the closest offset
1270 * @param primary whether to use the primary position or secondary position to find the offset
1274 public int getOffsetForHorizontal(int line, float horiz, boolean primary) {
1275 // TODO: use Paint.getOffsetForAdvance to avoid binary search
1276 final int lineEndOffset = getLineEnd(line);
1277 final int lineStartOffset = getLineStart(line);
1279 Directions dirs = getLineDirections(line);
1281 TextLine tl = TextLine.obtain();
1282 // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1283 tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
1285 final HorizontalMeasurementProvider horizontal =
1286 new HorizontalMeasurementProvider(line, primary);
1289 if (line == getLineCount() - 1) {
1290 max = lineEndOffset;
1292 max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1293 !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
1295 int best = lineStartOffset;
1296 float bestdist = Math.abs(horizontal.get(lineStartOffset) - horiz);
1298 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1299 int here = lineStartOffset + dirs.mDirections[i];
1300 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1301 boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1302 int swap = isRtl ? -1 : 1;
1306 int high = there - 1 + 1, low = here + 1 - 1, guess;
1308 while (high - low > 1) {
1309 guess = (high + low) / 2;
1310 int adguess = getOffsetAtStartOf(guess);
1312 if (horizontal.get(adguess) * swap >= horiz * swap)
1322 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1323 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1324 if (low >= here && low < there) {
1325 float dist = Math.abs(horizontal.get(low) - horiz);
1327 float other = Math.abs(horizontal.get(aft) - horiz);
1335 if (dist < bestdist) {
1342 float dist = Math.abs(horizontal.get(here) - horiz);
1344 if (dist < bestdist) {
1350 float dist = Math.abs(horizontal.get(max) - horiz);
1352 if (dist <= bestdist) {
1357 TextLine.recycle(tl);
1362 * Responds to #getHorizontal queries, by selecting the better strategy between:
1363 * - calling #getHorizontal explicitly for each query
1364 * - precomputing all #getHorizontal measurements, and responding to any query in constant time
1365 * The first strategy is used for LTR-only text, while the second is used for all other cases.
1366 * The class is currently only used in #getOffsetForHorizontal, so reuse with care in other
1369 private class HorizontalMeasurementProvider {
1370 private final int mLine;
1371 private final boolean mPrimary;
1373 private float[] mHorizontals;
1374 private int mLineStartOffset;
1376 HorizontalMeasurementProvider(final int line, final boolean primary) {
1382 private void init() {
1383 final Directions dirs = getLineDirections(mLine);
1384 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1388 mHorizontals = getLineHorizontals(mLine, false, mPrimary);
1389 mLineStartOffset = getLineStart(mLine);
1392 float get(final int offset) {
1393 if (mHorizontals == null || offset < mLineStartOffset
1394 || offset >= mLineStartOffset + mHorizontals.length) {
1395 return getHorizontal(offset, mPrimary);
1397 return mHorizontals[offset - mLineStartOffset];
1403 * Return the text offset after the last character on the specified line.
1405 public final int getLineEnd(int line) {
1406 return getLineStart(line + 1);
1410 * Return the text offset after the last visible character (so whitespace
1411 * is not counted) on the specified line.
1413 public int getLineVisibleEnd(int line) {
1414 return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1417 private int getLineVisibleEnd(int line, int start, int end) {
1418 CharSequence text = mText;
1420 if (line == getLineCount() - 1) {
1424 for (; end > start; end--) {
1425 ch = text.charAt(end - 1);
1431 // Note: keep this in sync with Minikin LineBreaker::isLineEndSpace()
1432 if (!(ch == ' ' || ch == '\t' || ch == 0x1680 ||
1433 (0x2000 <= ch && ch <= 0x200A && ch != 0x2007) ||
1434 ch == 0x205F || ch == 0x3000)) {
1444 * Return the vertical position of the bottom of the specified line.
1446 public final int getLineBottom(int line) {
1447 return getLineTop(line + 1);
1451 * Return the vertical position of the baseline of the specified line.
1453 public final int getLineBaseline(int line) {
1454 // getLineTop(line+1) == getLineTop(line)
1455 return getLineTop(line+1) - getLineDescent(line);
1459 * Get the ascent of the text on the specified line.
1460 * The return value is negative to match the Paint.ascent() convention.
1462 public final int getLineAscent(int line) {
1463 // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1464 return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1467 public int getOffsetToLeftOf(int offset) {
1468 return getOffsetToLeftRightOf(offset, true);
1471 public int getOffsetToRightOf(int offset) {
1472 return getOffsetToLeftRightOf(offset, false);
1475 private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1476 int line = getLineForOffset(caret);
1477 int lineStart = getLineStart(line);
1478 int lineEnd = getLineEnd(line);
1479 int lineDir = getParagraphDirection(line);
1481 boolean lineChanged = false;
1482 boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
1483 // if walking off line, look at the line we're headed to
1485 if (caret == lineEnd) {
1486 if (line < getLineCount() - 1) {
1490 return caret; // at very end, don't move
1494 if (caret == lineStart) {
1499 return caret; // at very start, don't move
1505 lineStart = getLineStart(line);
1506 lineEnd = getLineEnd(line);
1507 int newDir = getParagraphDirection(line);
1508 if (newDir != lineDir) {
1509 // unusual case. we want to walk onto the line, but it runs
1510 // in a different direction than this one, so we fake movement
1511 // in the opposite direction.
1517 Directions directions = getLineDirections(line);
1519 TextLine tl = TextLine.obtain();
1520 // XXX: we don't care about tabs
1521 tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null);
1522 caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
1523 tl = TextLine.recycle(tl);
1527 private int getOffsetAtStartOf(int offset) {
1528 // XXX this probably should skip local reorderings and
1529 // zero-width characters, look at callers
1533 CharSequence text = mText;
1534 char c = text.charAt(offset);
1536 if (c >= '\uDC00' && c <= '\uDFFF') {
1537 char c1 = text.charAt(offset - 1);
1539 if (c1 >= '\uD800' && c1 <= '\uDBFF')
1544 ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1545 ReplacementSpan.class);
1547 for (int i = 0; i < spans.length; i++) {
1548 int start = ((Spanned) text).getSpanStart(spans[i]);
1549 int end = ((Spanned) text).getSpanEnd(spans[i]);
1551 if (start < offset && end > offset)
1560 * Determine whether we should clamp cursor position. Currently it's
1561 * only robust for left-aligned displays.
1564 public boolean shouldClampCursor(int line) {
1565 // Only clamp cursor position in left-aligned displays.
1566 switch (getParagraphAlignment(line)) {
1570 return getParagraphDirection(line) > 0;
1577 * Fills in the specified Path with a representation of a cursor
1578 * at the specified offset. This will often be a vertical line
1579 * but can be multiple discontinuous lines in text with multiple
1582 public void getCursorPath(int point, Path dest,
1583 CharSequence editingBuffer) {
1586 int line = getLineForOffset(point);
1587 int top = getLineTop(line);
1588 int bottom = getLineTop(line+1);
1590 boolean clamped = shouldClampCursor(line);
1591 float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1592 float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
1594 int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1595 TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1596 int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
1599 if (caps != 0 || fn != 0) {
1600 dist = (bottom - top) >> 2;
1613 if (Float.compare(h1, h2) == 0) {
1614 dest.moveTo(h1, top);
1615 dest.lineTo(h1, bottom);
1617 dest.moveTo(h1, top);
1618 dest.lineTo(h1, (top + bottom) >> 1);
1620 dest.moveTo(h2, (top + bottom) >> 1);
1621 dest.lineTo(h2, bottom);
1625 dest.moveTo(h2, bottom);
1626 dest.lineTo(h2 - dist, bottom + dist);
1627 dest.lineTo(h2, bottom);
1628 dest.lineTo(h2 + dist, bottom + dist);
1629 } else if (caps == 1) {
1630 dest.moveTo(h2, bottom);
1631 dest.lineTo(h2 - dist, bottom + dist);
1633 dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1634 dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1636 dest.moveTo(h2 + dist, bottom + dist);
1637 dest.lineTo(h2, bottom);
1641 dest.moveTo(h1, top);
1642 dest.lineTo(h1 - dist, top - dist);
1643 dest.lineTo(h1, top);
1644 dest.lineTo(h1 + dist, top - dist);
1645 } else if (fn == 1) {
1646 dest.moveTo(h1, top);
1647 dest.lineTo(h1 - dist, top - dist);
1649 dest.moveTo(h1 - dist, top - dist + 0.5f);
1650 dest.lineTo(h1 + dist, top - dist + 0.5f);
1652 dest.moveTo(h1 + dist, top - dist);
1653 dest.lineTo(h1, top);
1657 private void addSelection(int line, int start, int end,
1658 int top, int bottom, Path dest) {
1659 int linestart = getLineStart(line);
1660 int lineend = getLineEnd(line);
1661 Directions dirs = getLineDirections(line);
1663 if (lineend > linestart && mText.charAt(lineend - 1) == '\n')
1666 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1667 int here = linestart + dirs.mDirections[i];
1668 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1670 if (there > lineend)
1673 if (start <= there && end >= here) {
1674 int st = Math.max(start, here);
1675 int en = Math.min(end, there);
1678 float h1 = getHorizontal(st, false, line, false /* not clamped */);
1679 float h2 = getHorizontal(en, true, line, false /* not clamped */);
1681 float left = Math.min(h1, h2);
1682 float right = Math.max(h1, h2);
1684 dest.addRect(left, top, right, bottom, Path.Direction.CW);
1691 * Fills in the specified Path with a representation of a highlight
1692 * between the specified offsets. This will often be a rectangle
1693 * or a potentially discontinuous set of rectangles. If the start
1694 * and end are the same, the returned path is empty.
1696 public void getSelectionPath(int start, int end, Path dest) {
1708 int startline = getLineForOffset(start);
1709 int endline = getLineForOffset(end);
1711 int top = getLineTop(startline);
1712 int bottom = getLineBottom(endline);
1714 if (startline == endline) {
1715 addSelection(startline, start, end, top, bottom, dest);
1717 final float width = mWidth;
1719 addSelection(startline, start, getLineEnd(startline),
1720 top, getLineBottom(startline), dest);
1722 if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT)
1723 dest.addRect(getLineLeft(startline), top,
1724 0, getLineBottom(startline), Path.Direction.CW);
1726 dest.addRect(getLineRight(startline), top,
1727 width, getLineBottom(startline), Path.Direction.CW);
1729 for (int i = startline + 1; i < endline; i++) {
1730 top = getLineTop(i);
1731 bottom = getLineBottom(i);
1732 dest.addRect(0, top, width, bottom, Path.Direction.CW);
1735 top = getLineTop(endline);
1736 bottom = getLineBottom(endline);
1738 addSelection(endline, getLineStart(endline), end,
1741 if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT)
1742 dest.addRect(width, top, getLineRight(endline), bottom, Path.Direction.CW);
1744 dest.addRect(0, top, getLineLeft(endline), bottom, Path.Direction.CW);
1749 * Get the alignment of the specified paragraph, taking into account
1750 * markup attached to it.
1752 public final Alignment getParagraphAlignment(int line) {
1753 Alignment align = mAlignment;
1756 Spanned sp = (Spanned) mText;
1757 AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
1759 AlignmentSpan.class);
1761 int spanLength = spans.length;
1762 if (spanLength > 0) {
1763 align = spans[spanLength-1].getAlignment();
1771 * Get the left edge of the specified paragraph, inset by left margins.
1773 public final int getParagraphLeft(int line) {
1775 int dir = getParagraphDirection(line);
1776 if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
1777 return left; // leading margin has no impact, or no styles
1779 return getParagraphLeadingMargin(line);
1783 * Get the right edge of the specified paragraph, inset by right margins.
1785 public final int getParagraphRight(int line) {
1787 int dir = getParagraphDirection(line);
1788 if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
1789 return right; // leading margin has no impact, or no styles
1791 return right - getParagraphLeadingMargin(line);
1795 * Returns the effective leading margin (unsigned) for this line,
1796 * taking into account LeadingMarginSpan and LeadingMarginSpan2.
1797 * @param line the line index
1798 * @return the leading margin of this line
1800 private int getParagraphLeadingMargin(int line) {
1801 if (!mSpannedText) {
1804 Spanned spanned = (Spanned) mText;
1806 int lineStart = getLineStart(line);
1807 int lineEnd = getLineEnd(line);
1808 int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
1809 LeadingMarginSpan.class);
1810 LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
1811 LeadingMarginSpan.class);
1812 if (spans.length == 0) {
1813 return 0; // no leading margin span;
1818 boolean isFirstParaLine = lineStart == 0 ||
1819 spanned.charAt(lineStart - 1) == '\n';
1821 boolean useFirstLineMargin = isFirstParaLine;
1822 for (int i = 0; i < spans.length; i++) {
1823 if (spans[i] instanceof LeadingMarginSpan2) {
1824 int spStart = spanned.getSpanStart(spans[i]);
1825 int spanLine = getLineForOffset(spStart);
1826 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
1827 // if there is more than one LeadingMarginSpan2, use the count that is greatest
1828 useFirstLineMargin |= line < spanLine + count;
1831 for (int i = 0; i < spans.length; i++) {
1832 LeadingMarginSpan span = spans[i];
1833 margin += span.getLeadingMargin(useFirstLineMargin);
1840 static float measurePara(TextPaint paint, CharSequence text, int start, int end) {
1842 MeasuredText mt = MeasuredText.obtain();
1843 TextLine tl = TextLine.obtain();
1845 mt.setPara(text, start, end, TextDirectionHeuristics.LTR, null);
1846 Directions directions;
1849 directions = DIRS_ALL_LEFT_TO_RIGHT;
1850 dir = Layout.DIR_LEFT_TO_RIGHT;
1852 directions = AndroidBidi.directions(mt.mDir, mt.mLevels,
1853 0, mt.mChars, 0, mt.mLen);
1856 char[] chars = mt.mChars;
1858 boolean hasTabs = false;
1859 TabStops tabStops = null;
1860 // leading margins should be taken into account when measuring a paragraph
1862 if (text instanceof Spanned) {
1863 Spanned spanned = (Spanned) text;
1864 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
1865 LeadingMarginSpan.class);
1866 for (LeadingMarginSpan lms : spans) {
1867 margin += lms.getLeadingMargin(true);
1870 for (int i = 0; i < len; ++i) {
1871 if (chars[i] == '\t') {
1873 if (text instanceof Spanned) {
1874 Spanned spanned = (Spanned) text;
1875 int spanEnd = spanned.nextSpanTransition(start, end,
1877 TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
1879 if (spans.length > 0) {
1880 tabStops = new TabStops(TAB_INCREMENT, spans);
1886 tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops);
1887 return margin + tl.metrics(null);
1889 TextLine.recycle(tl);
1890 MeasuredText.recycle(mt);
1897 /* package */ static class TabStops {
1898 private int[] mStops;
1899 private int mNumStops;
1900 private int mIncrement;
1902 TabStops(int increment, Object[] spans) {
1903 reset(increment, spans);
1906 void reset(int increment, Object[] spans) {
1907 this.mIncrement = increment;
1910 if (spans != null) {
1911 int[] stops = this.mStops;
1912 for (Object o : spans) {
1913 if (o instanceof TabStopSpan) {
1914 if (stops == null) {
1915 stops = new int[10];
1916 } else if (ns == stops.length) {
1917 int[] nstops = new int[ns * 2];
1918 for (int i = 0; i < ns; ++i) {
1919 nstops[i] = stops[i];
1923 stops[ns++] = ((TabStopSpan) o).getTabStop();
1927 Arrays.sort(stops, 0, ns);
1929 if (stops != this.mStops) {
1930 this.mStops = stops;
1933 this.mNumStops = ns;
1936 float nextTab(float h) {
1937 int ns = this.mNumStops;
1939 int[] stops = this.mStops;
1940 for (int i = 0; i < ns; ++i) {
1941 int stop = stops[i];
1947 return nextDefaultStop(h, mIncrement);
1950 public static float nextDefaultStop(float h, int inc) {
1951 return ((int) ((h + inc) / inc)) * inc;
1956 * Returns the position of the next tab stop after h on the line.
1958 * @param text the text
1959 * @param start start of the line
1960 * @param end limit of the line
1961 * @param h the current horizontal offset
1962 * @param tabs the tabs, can be null. If it is null, any tabs in effect
1963 * on the line will be used. If there are no tabs, a default offset
1964 * will be used to compute the tab stop.
1965 * @return the offset of the next tab stop.
1967 /* package */ static float nextTab(CharSequence text, int start, int end,
1968 float h, Object[] tabs) {
1969 float nh = Float.MAX_VALUE;
1970 boolean alltabs = false;
1972 if (text instanceof Spanned) {
1974 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
1978 for (int i = 0; i < tabs.length; i++) {
1980 if (!(tabs[i] instanceof TabStopSpan))
1984 int where = ((TabStopSpan) tabs[i]).getTabStop();
1986 if (where < nh && where > h)
1990 if (nh != Float.MAX_VALUE)
1994 return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
1997 protected final boolean isSpanned() {
1998 return mSpannedText;
2002 * Returns the same as <code>text.getSpans()</code>, except where
2003 * <code>start</code> and <code>end</code> are the same and are not
2004 * at the very beginning of the text, in which case an empty array
2005 * is returned instead.
2007 * This is needed because of the special case that <code>getSpans()</code>
2008 * on an empty range returns the spans adjacent to that range, which is
2009 * primarily for the sake of <code>TextWatchers</code> so they will get
2010 * notifications when text goes from empty to non-empty. But it also
2011 * has the unfortunate side effect that if the text ends with an empty
2012 * paragraph, that paragraph accidentally picks up the styles of the
2013 * preceding paragraph (even though those styles will not be picked up
2014 * by new text that is inserted into the empty paragraph).
2016 * The reason it just checks whether <code>start</code> and <code>end</code>
2017 * is the same is that the only time a line can contain 0 characters
2018 * is if it is the final paragraph of the Layout; otherwise any line will
2019 * contain at least one printing or newline character. The reason for the
2020 * additional check if <code>start</code> is greater than 0 is that
2021 * if the empty paragraph is the entire content of the buffer, paragraph
2022 * styles that are already applied to the buffer will apply to text that
2023 * is inserted into it.
2025 /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
2026 if (start == end && start > 0) {
2027 return ArrayUtils.emptyArray(type);
2030 if(text instanceof SpannableStringBuilder) {
2031 return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2033 return text.getSpans(start, end, type);
2037 private char getEllipsisChar(TextUtils.TruncateAt method) {
2038 return (method == TextUtils.TruncateAt.END_SMALL) ?
2039 TextUtils.ELLIPSIS_TWO_DOTS[0] :
2040 TextUtils.ELLIPSIS_NORMAL[0];
2043 private void ellipsize(int start, int end, int line,
2044 char[] dest, int destoff, TextUtils.TruncateAt method) {
2045 int ellipsisCount = getEllipsisCount(line);
2047 if (ellipsisCount == 0) {
2051 int ellipsisStart = getEllipsisStart(line);
2052 int linestart = getLineStart(line);
2054 for (int i = ellipsisStart; i < ellipsisStart + ellipsisCount; i++) {
2057 if (i == ellipsisStart) {
2058 c = getEllipsisChar(method); // ellipsis
2060 c = '\uFEFF'; // 0-width space
2063 int a = i + linestart;
2065 if (a >= start && a < end) {
2066 dest[destoff + a - start] = c;
2072 * Stores information about bidirectional (left-to-right or right-to-left)
2073 * text within the layout of a line.
2075 public static class Directions {
2076 // Directions represents directional runs within a line of text.
2077 // Runs are pairs of ints listed in visual order, starting from the
2078 // leading margin. The first int of each pair is the offset from
2079 // the first character of the line to the start of the run. The
2080 // second int represents both the length and level of the run.
2081 // The length is in the lower bits, accessed by masking with
2082 // DIR_LENGTH_MASK. The level is in the higher bits, accessed
2083 // by shifting by DIR_LEVEL_SHIFT and masking by DIR_LEVEL_MASK.
2084 // To simply test for an RTL direction, test the bit using
2085 // DIR_RTL_FLAG, if set then the direction is rtl.
2087 /* package */ int[] mDirections;
2088 /* package */ Directions(int[] dirs) {
2094 * Return the offset of the first character to be ellipsized away,
2095 * relative to the start of the line. (So 0 if the beginning of the
2096 * line is ellipsized, not getLineStart().)
2098 public abstract int getEllipsisStart(int line);
2101 * Returns the number of characters to be ellipsized away, or 0 if
2102 * no ellipsis is to take place.
2104 public abstract int getEllipsisCount(int line);
2106 /* package */ static class Ellipsizer implements CharSequence, GetChars {
2107 /* package */ CharSequence mText;
2108 /* package */ Layout mLayout;
2109 /* package */ int mWidth;
2110 /* package */ TextUtils.TruncateAt mMethod;
2112 public Ellipsizer(CharSequence s) {
2116 public char charAt(int off) {
2117 char[] buf = TextUtils.obtain(1);
2118 getChars(off, off + 1, buf, 0);
2121 TextUtils.recycle(buf);
2125 public void getChars(int start, int end, char[] dest, int destoff) {
2126 int line1 = mLayout.getLineForOffset(start);
2127 int line2 = mLayout.getLineForOffset(end);
2129 TextUtils.getChars(mText, start, end, dest, destoff);
2131 for (int i = line1; i <= line2; i++) {
2132 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
2136 public int length() {
2137 return mText.length();
2140 public CharSequence subSequence(int start, int end) {
2141 char[] s = new char[end - start];
2142 getChars(start, end, s, 0);
2143 return new String(s);
2147 public String toString() {
2148 char[] s = new char[length()];
2149 getChars(0, length(), s, 0);
2150 return new String(s);
2155 /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
2156 private Spanned mSpanned;
2158 public SpannedEllipsizer(CharSequence display) {
2160 mSpanned = (Spanned) display;
2163 public <T> T[] getSpans(int start, int end, Class<T> type) {
2164 return mSpanned.getSpans(start, end, type);
2167 public int getSpanStart(Object tag) {
2168 return mSpanned.getSpanStart(tag);
2171 public int getSpanEnd(Object tag) {
2172 return mSpanned.getSpanEnd(tag);
2175 public int getSpanFlags(Object tag) {
2176 return mSpanned.getSpanFlags(tag);
2179 @SuppressWarnings("rawtypes")
2180 public int nextSpanTransition(int start, int limit, Class type) {
2181 return mSpanned.nextSpanTransition(start, limit, type);
2185 public CharSequence subSequence(int start, int end) {
2186 char[] s = new char[end - start];
2187 getChars(start, end, s, 0);
2189 SpannableString ss = new SpannableString(new String(s));
2190 TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2195 private CharSequence mText;
2196 private TextPaint mPaint;
2198 private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2199 private float mSpacingMult;
2200 private float mSpacingAdd;
2201 private static final Rect sTempRect = new Rect();
2202 private boolean mSpannedText;
2203 private TextDirectionHeuristic mTextDir;
2204 private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
2206 public static final int DIR_LEFT_TO_RIGHT = 1;
2207 public static final int DIR_RIGHT_TO_LEFT = -1;
2209 /* package */ static final int DIR_REQUEST_LTR = 1;
2210 /* package */ static final int DIR_REQUEST_RTL = -1;
2211 /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2212 /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
2214 /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2215 /* package */ static final int RUN_LEVEL_SHIFT = 26;
2216 /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2217 /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2219 public enum Alignment {
2229 private static final int TAB_INCREMENT = 20;
2231 /* package */ static final Directions DIRS_ALL_LEFT_TO_RIGHT =
2232 new Directions(new int[] { 0, RUN_LENGTH_MASK });
2233 /* package */ static final Directions DIRS_ALL_RIGHT_TO_LEFT =
2234 new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });