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.emoji.EmojiFactory;
21 import android.graphics.Canvas;
22 import android.graphics.Paint;
23 import android.graphics.Path;
24 import android.graphics.Rect;
25 import android.text.method.TextKeyListener;
26 import android.text.style.AlignmentSpan;
27 import android.text.style.LeadingMarginSpan;
28 import android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
29 import android.text.style.LineBackgroundSpan;
30 import android.text.style.ParagraphStyle;
31 import android.text.style.ReplacementSpan;
32 import android.text.style.TabStopSpan;
34 import com.android.internal.util.ArrayUtils;
35 import com.android.internal.util.GrowingArrayUtils;
37 import java.lang.annotation.Retention;
38 import java.lang.annotation.RetentionPolicy;
39 import java.util.Arrays;
42 * A base class that manages text layout in visual elements on
44 * <p>For text that will be edited, use a {@link DynamicLayout},
45 * which will be updated as the text changes.
46 * For text that will not change, use a {@link StaticLayout}.
48 public abstract class Layout {
50 @IntDef({BREAK_STRATEGY_SIMPLE, BREAK_STRATEGY_HIGH_QUALITY, BREAK_STRATEGY_BALANCED})
51 @Retention(RetentionPolicy.SOURCE)
52 public @interface BreakStrategy {}
55 * Value for break strategy indicating simple line breaking. Automatic hyphens are not added
56 * (though soft hyphens are respected), and modifying text generally doesn't affect the layout
57 * before it (which yields a more consistent user experience when editing), but layout may not
58 * be the highest quality.
60 public static final int BREAK_STRATEGY_SIMPLE = 0;
63 * Value for break strategy indicating high quality line breaking, including automatic
64 * hyphenation and doing whole-paragraph optimization of line breaks.
66 public static final int BREAK_STRATEGY_HIGH_QUALITY = 1;
69 * Value for break strategy indicating balanced line breaking. The breaks are chosen to
70 * make all lines as close to the same length as possible, including automatic hyphenation.
72 public static final int BREAK_STRATEGY_BALANCED = 2;
75 @IntDef({HYPHENATION_FREQUENCY_NORMAL, HYPHENATION_FREQUENCY_FULL,
76 HYPHENATION_FREQUENCY_NONE})
77 @Retention(RetentionPolicy.SOURCE)
78 public @interface HyphenationFrequency {}
81 * Value for hyphenation frequency indicating no automatic hyphenation. Useful
82 * for backward compatibility, and for cases where the automatic hyphenation algorithm results
83 * in incorrect hyphenation. Mid-word breaks may still happen when a word is wider than the
84 * layout and there is otherwise no valid break. Soft hyphens are ignored and will not be used
85 * as suggestions for potential line breaks.
87 public static final int HYPHENATION_FREQUENCY_NONE = 0;
90 * Value for hyphenation frequency indicating a light amount of automatic hyphenation, which
91 * is a conservative default. Useful for informal cases, such as short sentences or chat
94 public static final int HYPHENATION_FREQUENCY_NORMAL = 1;
97 * Value for hyphenation frequency indicating the full amount of automatic hyphenation, typical
98 * in typography. Useful for running text and where it's important to put the maximum amount of
99 * text in a screen with limited space.
101 public static final int HYPHENATION_FREQUENCY_FULL = 2;
103 private static final ParagraphStyle[] NO_PARA_SPANS =
104 ArrayUtils.emptyArray(ParagraphStyle.class);
106 /* package */ static final EmojiFactory EMOJI_FACTORY = EmojiFactory.newAvailableInstance();
107 /* package */ static final int MIN_EMOJI, MAX_EMOJI;
110 if (EMOJI_FACTORY != null) {
111 MIN_EMOJI = EMOJI_FACTORY.getMinimumAndroidPua();
112 MAX_EMOJI = EMOJI_FACTORY.getMaximumAndroidPua();
120 * Return how wide a layout must be in order to display the
121 * specified text with one line per paragraph.
123 public static float getDesiredWidth(CharSequence source,
125 return getDesiredWidth(source, 0, source.length(), paint);
129 * Return how wide a layout must be in order to display the
130 * specified text slice with one line per paragraph.
132 public static float getDesiredWidth(CharSequence source,
138 for (int i = start; i <= end; i = next) {
139 next = TextUtils.indexOf(source, '\n', i, end);
144 // note, omits trailing paragraph char
145 float w = measurePara(paint, source, i, next);
157 * Subclasses of Layout use this constructor to set the display text,
158 * width, and other standard properties.
159 * @param text the text to render
160 * @param paint the default paint for the layout. Styles can override
161 * various attributes of the paint.
162 * @param width the wrapping width for the text.
163 * @param align whether to left, right, or center the text. Styles can
164 * override the alignment.
165 * @param spacingMult factor by which to scale the font size to get the
166 * default line spacing
167 * @param spacingAdd amount to add to the default line spacing
169 protected Layout(CharSequence text, TextPaint paint,
170 int width, Alignment align,
171 float spacingMult, float spacingAdd) {
172 this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
173 spacingMult, spacingAdd);
177 * Subclasses of Layout use this constructor to set the display text,
178 * width, and other standard properties.
179 * @param text the text to render
180 * @param paint the default paint for the layout. Styles can override
181 * various attributes of the paint.
182 * @param width the wrapping width for the text.
183 * @param align whether to left, right, or center the text. Styles can
184 * override the alignment.
185 * @param spacingMult factor by which to scale the font size to get the
186 * default line spacing
187 * @param spacingAdd amount to add to the default line spacing
191 protected Layout(CharSequence text, TextPaint paint,
192 int width, Alignment align, TextDirectionHeuristic textDir,
193 float spacingMult, float spacingAdd) {
196 throw new IllegalArgumentException("Layout: " + width + " < 0");
198 // Ensure paint doesn't have baselineShift set.
199 // While normally we don't modify the paint the user passed in,
200 // we were already doing this in Styled.drawUniformRun with both
201 // baselineShift and bgColor. We probably should reevaluate bgColor.
204 paint.baselineShift = 0;
211 mSpacingMult = spacingMult;
212 mSpacingAdd = spacingAdd;
213 mSpannedText = text instanceof Spanned;
218 * Replace constructor properties of this Layout with new ones. Be careful.
220 /* package */ void replaceWith(CharSequence text, TextPaint paint,
221 int width, Alignment align,
222 float spacingmult, float spacingadd) {
224 throw new IllegalArgumentException("Layout: " + width + " < 0");
231 mSpacingMult = spacingmult;
232 mSpacingAdd = spacingadd;
233 mSpannedText = text instanceof Spanned;
237 * Draw this Layout on the specified Canvas.
239 public void draw(Canvas c) {
240 draw(c, null, null, 0);
244 * Draw this Layout on the specified canvas, with the highlight path drawn
245 * between the background and the text.
247 * @param canvas the canvas
248 * @param highlight the path of the highlight or cursor; can be null
249 * @param highlightPaint the paint for the highlight
250 * @param cursorOffsetVertical the amount to temporarily translate the
251 * canvas while rendering the highlight
253 public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
254 int cursorOffsetVertical) {
255 final long lineRange = getLineRangeForDraw(canvas);
256 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
257 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
258 if (lastLine < 0) return;
260 drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
261 firstLine, lastLine);
262 drawText(canvas, firstLine, lastLine);
268 public void drawText(Canvas canvas, int firstLine, int lastLine) {
269 int previousLineBottom = getLineTop(firstLine);
270 int previousLineEnd = getLineStart(firstLine);
271 ParagraphStyle[] spans = NO_PARA_SPANS;
273 TextPaint paint = mPaint;
274 CharSequence buf = mText;
276 Alignment paraAlign = mAlignment;
277 TabStops tabStops = null;
278 boolean tabStopsIsInitialized = false;
280 TextLine tl = TextLine.obtain();
282 // Draw the lines, one at a time.
283 // The baseline is the top of the following line minus the current line's descent.
284 for (int lineNum = firstLine; lineNum <= lastLine; lineNum++) {
285 int start = previousLineEnd;
286 previousLineEnd = getLineStart(lineNum + 1);
287 int end = getLineVisibleEnd(lineNum, start, previousLineEnd);
289 int ltop = previousLineBottom;
290 int lbottom = getLineTop(lineNum + 1);
291 previousLineBottom = lbottom;
292 int lbaseline = lbottom - getLineDescent(lineNum);
294 int dir = getParagraphDirection(lineNum);
299 Spanned sp = (Spanned) buf;
300 int textLength = buf.length();
301 boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
303 // New batch of paragraph styles, collect into spans array.
304 // Compute the alignment, last alignment style wins.
305 // Reset tabStops, we'll rebuild if we encounter a line with
307 // We expect paragraph spans to be relatively infrequent, use
308 // spanEnd so that we can check less frequently. Since
309 // paragraph styles ought to apply to entire paragraphs, we can
310 // just collect the ones present at the start of the paragraph.
311 // If spanEnd is before the end of the paragraph, that's not
313 if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
314 spanEnd = sp.nextSpanTransition(start, textLength,
315 ParagraphStyle.class);
316 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
318 paraAlign = mAlignment;
319 for (int n = spans.length - 1; n >= 0; n--) {
320 if (spans[n] instanceof AlignmentSpan) {
321 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
326 tabStopsIsInitialized = false;
329 // Draw all leading margin spans. Adjust left or right according
330 // to the paragraph direction of the line.
331 final int length = spans.length;
332 boolean useFirstLineMargin = isFirstParaLine;
333 for (int n = 0; n < length; n++) {
334 if (spans[n] instanceof LeadingMarginSpan2) {
335 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
336 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
337 // if there is more than one LeadingMarginSpan2, use
338 // the count that is greatest
339 if (lineNum < startLine + count) {
340 useFirstLineMargin = true;
345 for (int n = 0; n < length; n++) {
346 if (spans[n] instanceof LeadingMarginSpan) {
347 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
348 if (dir == DIR_RIGHT_TO_LEFT) {
349 margin.drawLeadingMargin(canvas, paint, right, dir, ltop,
350 lbaseline, lbottom, buf,
351 start, end, isFirstParaLine, this);
352 right -= margin.getLeadingMargin(useFirstLineMargin);
354 margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
355 lbaseline, lbottom, buf,
356 start, end, isFirstParaLine, this);
357 left += margin.getLeadingMargin(useFirstLineMargin);
363 boolean hasTabOrEmoji = getLineContainsTab(lineNum);
364 // Can't tell if we have tabs for sure, currently
365 if (hasTabOrEmoji && !tabStopsIsInitialized) {
366 if (tabStops == null) {
367 tabStops = new TabStops(TAB_INCREMENT, spans);
369 tabStops.reset(TAB_INCREMENT, spans);
371 tabStopsIsInitialized = true;
374 // Determine whether the line aligns to normal, opposite, or center.
375 Alignment align = paraAlign;
376 if (align == Alignment.ALIGN_LEFT) {
377 align = (dir == DIR_LEFT_TO_RIGHT) ?
378 Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
379 } else if (align == Alignment.ALIGN_RIGHT) {
380 align = (dir == DIR_LEFT_TO_RIGHT) ?
381 Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
385 if (align == Alignment.ALIGN_NORMAL) {
386 if (dir == DIR_LEFT_TO_RIGHT) {
387 x = left + getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
389 x = right + getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
392 int max = (int)getLineExtent(lineNum, tabStops, false);
393 if (align == Alignment.ALIGN_OPPOSITE) {
394 if (dir == DIR_LEFT_TO_RIGHT) {
395 x = right - max + getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
397 x = left - max + getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
399 } else { // Alignment.ALIGN_CENTER
401 x = ((right + left - max) >> 1) +
402 getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
406 paint.setHyphenEdit(getHyphen(lineNum));
407 Directions directions = getLineDirections(lineNum);
408 if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTabOrEmoji) {
409 // XXX: assumes there's nothing additional to be done
410 canvas.drawText(buf, start, end, x, lbaseline, paint);
412 tl.set(paint, buf, start, end, dir, directions, hasTabOrEmoji, tabStops);
413 tl.draw(canvas, x, ltop, lbaseline, lbottom);
415 paint.setHyphenEdit(0);
418 TextLine.recycle(tl);
424 public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
425 int cursorOffsetVertical, int firstLine, int lastLine) {
426 // First, draw LineBackgroundSpans.
427 // LineBackgroundSpans know nothing about the alignment, margins, or
428 // direction of the layout or line. XXX: Should they?
429 // They are evaluated at each line.
431 if (mLineBackgroundSpans == null) {
432 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
435 Spanned buffer = (Spanned) mText;
436 int textLength = buffer.length();
437 mLineBackgroundSpans.init(buffer, 0, textLength);
439 if (mLineBackgroundSpans.numberOfSpans > 0) {
440 int previousLineBottom = getLineTop(firstLine);
441 int previousLineEnd = getLineStart(firstLine);
442 ParagraphStyle[] spans = NO_PARA_SPANS;
444 TextPaint paint = mPaint;
446 final int width = mWidth;
447 for (int i = firstLine; i <= lastLine; i++) {
448 int start = previousLineEnd;
449 int end = getLineStart(i + 1);
450 previousLineEnd = end;
452 int ltop = previousLineBottom;
453 int lbottom = getLineTop(i + 1);
454 previousLineBottom = lbottom;
455 int lbaseline = lbottom - getLineDescent(i);
457 if (start >= spanEnd) {
458 // These should be infrequent, so we'll use this so that
459 // we don't have to check as often.
460 spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
461 // All LineBackgroundSpans on a line contribute to its background.
463 // Duplication of the logic of getParagraphSpans
464 if (start != end || start == 0) {
465 // Equivalent to a getSpans(start, end), but filling the 'spans' local
466 // array instead to reduce memory allocation
467 for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
468 // equal test is valid since both intervals are not empty by
470 if (mLineBackgroundSpans.spanStarts[j] >= end ||
471 mLineBackgroundSpans.spanEnds[j] <= start) continue;
472 spans = GrowingArrayUtils.append(
473 spans, spansLength, mLineBackgroundSpans.spans[j]);
479 for (int n = 0; n < spansLength; n++) {
480 LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
481 lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
482 ltop, lbaseline, lbottom,
483 buffer, start, end, i);
487 mLineBackgroundSpans.recycle();
490 // There can be a highlight even without spans if we are drawing
491 // a non-spanned transformation of a spanned editing buffer.
492 if (highlight != null) {
493 if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
494 canvas.drawPath(highlight, highlightPaint);
495 if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
501 * @return The range of lines that need to be drawn, possibly empty.
504 public long getLineRangeForDraw(Canvas canvas) {
507 synchronized (sTempRect) {
508 if (!canvas.getClipBounds(sTempRect)) {
509 // Negative range end used as a special flag
510 return TextUtils.packRangeInLong(0, -1);
513 dtop = sTempRect.top;
514 dbottom = sTempRect.bottom;
517 final int top = Math.max(dtop, 0);
518 final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
520 if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
521 return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
525 * Return the start position of the line, given the left and right bounds
528 * @param line the line index
529 * @param left the left bounds (0, or leading margin if ltr para)
530 * @param right the right bounds (width, minus leading margin if rtl para)
531 * @return the start position of the line (to right of line if rtl para)
533 private int getLineStartPos(int line, int left, int right) {
534 // Adjust the point at which to start rendering depending on the
535 // alignment of the paragraph.
536 Alignment align = getParagraphAlignment(line);
537 int dir = getParagraphDirection(line);
539 if (align == Alignment.ALIGN_LEFT) {
540 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
541 } else if (align == Alignment.ALIGN_RIGHT) {
542 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
546 if (align == Alignment.ALIGN_NORMAL) {
547 if (dir == DIR_LEFT_TO_RIGHT) {
548 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
550 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
553 TabStops tabStops = null;
554 if (mSpannedText && getLineContainsTab(line)) {
555 Spanned spanned = (Spanned) mText;
556 int start = getLineStart(line);
557 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
559 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
561 if (tabSpans.length > 0) {
562 tabStops = new TabStops(TAB_INCREMENT, tabSpans);
565 int max = (int)getLineExtent(line, tabStops, false);
566 if (align == Alignment.ALIGN_OPPOSITE) {
567 if (dir == DIR_LEFT_TO_RIGHT) {
568 x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
570 // max is negative here
571 x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
573 } else { // Alignment.ALIGN_CENTER
575 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
582 * Return the text that is displayed by this Layout.
584 public final CharSequence getText() {
589 * Return the base Paint properties for this layout.
590 * Do NOT change the paint, which may result in funny
591 * drawing for this layout.
593 public final TextPaint getPaint() {
598 * Return the width of this layout.
600 public final int getWidth() {
605 * Return the width to which this Layout is ellipsizing, or
606 * {@link #getWidth} if it is not doing anything special.
608 public int getEllipsizedWidth() {
613 * Increase the width of this layout to the specified width.
614 * Be careful to use this only when you know it is appropriate—
615 * it does not cause the text to reflow to use the full new width.
617 public final void increaseWidthTo(int wid) {
619 throw new RuntimeException("attempted to reduce Layout width");
626 * Return the total height of this layout.
628 public int getHeight() {
629 return getLineTop(getLineCount());
633 * Return the base alignment of this layout.
635 public final Alignment getAlignment() {
640 * Return what the text height is multiplied by to get the line height.
642 public final float getSpacingMultiplier() {
647 * Return the number of units of leading that are added to each line.
649 public final float getSpacingAdd() {
654 * Return the heuristic used to determine paragraph text direction.
657 public final TextDirectionHeuristic getTextDirectionHeuristic() {
662 * Return the number of lines of text in this layout.
664 public abstract int getLineCount();
667 * Return the baseline for the specified line (0…getLineCount() - 1)
668 * If bounds is not null, return the top, left, right, bottom extents
669 * of the specified line in it.
670 * @param line which line to examine (0..getLineCount() - 1)
671 * @param bounds Optional. If not null, it returns the extent of the line
672 * @return the Y-coordinate of the baseline
674 public int getLineBounds(int line, Rect bounds) {
675 if (bounds != null) {
676 bounds.left = 0; // ???
677 bounds.top = getLineTop(line);
678 bounds.right = mWidth; // ???
679 bounds.bottom = getLineTop(line + 1);
681 return getLineBaseline(line);
685 * Return the vertical position of the top of the specified line
686 * (0…getLineCount()).
687 * If the specified line is equal to the line count, returns the
688 * bottom of the last line.
690 public abstract int getLineTop(int line);
693 * Return the descent of the specified line(0…getLineCount() - 1).
695 public abstract int getLineDescent(int line);
698 * Return the text offset of the beginning of the specified line (
699 * 0…getLineCount()). If the specified line is equal to the line
700 * count, returns the length of the text.
702 public abstract int getLineStart(int line);
705 * Returns the primary directionality of the paragraph containing the
706 * specified line, either 1 for left-to-right lines, or -1 for right-to-left
707 * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
709 public abstract int getParagraphDirection(int line);
712 * Returns whether the specified line contains one or more
713 * characters that need to be handled specially, like tabs
716 public abstract boolean getLineContainsTab(int line);
719 * Returns the directional run information for the specified line.
720 * The array alternates counts of characters in left-to-right
721 * and right-to-left segments of the line.
723 * <p>NOTE: this is inadequate to support bidirectional text, and will change.
725 public abstract Directions getLineDirections(int line);
728 * Returns the (negative) number of extra pixels of ascent padding in the
729 * top line of the Layout.
731 public abstract int getTopPadding();
734 * Returns the number of extra pixels of descent padding in the
735 * bottom line of the Layout.
737 public abstract int getBottomPadding();
740 * Returns the hyphen edit for a line.
744 public int getHyphen(int line) {
749 * Returns the left indent for a line.
753 public int getIndentAdjust(int line, Alignment alignment) {
758 * Returns true if the character at offset and the preceding character
759 * are at different run levels (and thus there's a split caret).
760 * @param offset the offset
761 * @return true if at a level boundary
764 public boolean isLevelBoundary(int offset) {
765 int line = getLineForOffset(offset);
766 Directions dirs = getLineDirections(line);
767 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
771 int[] runs = dirs.mDirections;
772 int lineStart = getLineStart(line);
773 int lineEnd = getLineEnd(line);
774 if (offset == lineStart || offset == lineEnd) {
775 int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
776 int runIndex = offset == lineStart ? 0 : runs.length - 2;
777 return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
781 for (int i = 0; i < runs.length; i += 2) {
782 if (offset == runs[i]) {
790 * Returns true if the character at offset is right to left (RTL).
791 * @param offset the offset
792 * @return true if the character is RTL, false if it is LTR
794 public boolean isRtlCharAt(int offset) {
795 int line = getLineForOffset(offset);
796 Directions dirs = getLineDirections(line);
797 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
800 if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
803 int[] runs = dirs.mDirections;
804 int lineStart = getLineStart(line);
805 for (int i = 0; i < runs.length; i += 2) {
806 int start = lineStart + runs[i];
807 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
808 if (offset >= start && offset < limit) {
809 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
810 return ((level & 1) != 0);
813 // Should happen only if the offset is "out of bounds"
818 * Checks if the trailing BiDi level should be used for an offset
820 * This method is useful when the offset is at the BiDi level transition point and determine
821 * which run need to be used. For example, let's think about following input: (L* denotes
822 * Left-to-Right characters, R* denotes Right-to-Left characters.)
823 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
824 * Input (Display Order): L1 L2 L3 R3 R2 R1 L4 L5 L6
826 * Then, think about selecting the range (3, 6). The offset=3 and offset=6 are ambiguous here
827 * since they are at the BiDi transition point. In Android, the offset is considered to be
828 * associated with the trailing run if the BiDi level of the trailing run is higher than of the
829 * previous run. In this case, the BiDi level of the input text is as follows:
831 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
832 * BiDi Run: [ Run 0 ][ Run 1 ][ Run 2 ]
833 * BiDi Level: 0 0 0 1 1 1 0 0 0
835 * Thus, offset = 3 is part of Run 1 and this method returns true for offset = 3, since the BiDi
836 * level of Run 1 is higher than the level of Run 0. Similarly, the offset = 6 is a part of Run
837 * 1 and this method returns false for the offset = 6 since the BiDi level of Run 1 is higher
838 * than the level of Run 2.
840 * @returns true if offset is at the BiDi level transition point and trailing BiDi level is
841 * higher than previous BiDi level. See above for the detail.
843 private boolean primaryIsTrailingPrevious(int offset) {
844 int line = getLineForOffset(offset);
845 int lineStart = getLineStart(line);
846 int lineEnd = getLineEnd(line);
847 int[] runs = getLineDirections(line).mDirections;
850 for (int i = 0; i < runs.length; i += 2) {
851 int start = lineStart + runs[i];
852 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
853 if (limit > lineEnd) {
856 if (offset >= start && offset < limit) {
857 if (offset > start) {
858 // Previous character is at same level, so don't use trailing.
861 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
866 // Offset was limit of line.
867 levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
870 // At level boundary, check previous level.
871 int levelBefore = -1;
872 if (offset == lineStart) {
873 levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
876 for (int i = 0; i < runs.length; i += 2) {
877 int start = lineStart + runs[i];
878 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
879 if (limit > lineEnd) {
882 if (offset >= start && offset < limit) {
883 levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
889 return levelBefore < levelAt;
893 * Computes in linear time the results of calling
894 * #primaryIsTrailingPrevious for all offsets on a line.
895 * @param line The line giving the offsets we compute the information for
896 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
898 private boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
899 int lineStart = getLineStart(line);
900 int lineEnd = getLineEnd(line);
901 int[] runs = getLineDirections(line).mDirections;
903 boolean[] trailing = new boolean[lineEnd - lineStart + 1];
905 byte[] level = new byte[lineEnd - lineStart + 1];
906 for (int i = 0; i < runs.length; i += 2) {
907 int start = lineStart + runs[i];
908 int limit = start + (runs[i + 1] & RUN_LENGTH_MASK);
909 if (limit > lineEnd) {
912 level[limit - lineStart - 1] =
913 (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
916 for (int i = 0; i < runs.length; i += 2) {
917 int start = lineStart + runs[i];
918 byte currentLevel = (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
919 trailing[start - lineStart] = currentLevel > (start == lineStart
920 ? (getParagraphDirection(line) == 1 ? 0 : 1)
921 : level[start - lineStart - 1]);
928 * Get the primary horizontal position for the specified text offset.
929 * This is the location where a new character would be inserted in
930 * the paragraph's primary direction.
932 public float getPrimaryHorizontal(int offset) {
933 return getPrimaryHorizontal(offset, false /* not clamped */);
937 * Get the primary horizontal position for the specified text offset, but
938 * optionally clamp it so that it doesn't exceed the width of the layout.
941 public float getPrimaryHorizontal(int offset, boolean clamped) {
942 boolean trailing = primaryIsTrailingPrevious(offset);
943 return getHorizontal(offset, trailing, clamped);
947 * Get the secondary horizontal position for the specified text offset.
948 * This is the location where a new character would be inserted in
949 * the direction other than the paragraph's primary direction.
951 public float getSecondaryHorizontal(int offset) {
952 return getSecondaryHorizontal(offset, false /* not clamped */);
956 * Get the secondary horizontal position for the specified text offset, but
957 * optionally clamp it so that it doesn't exceed the width of the layout.
960 public float getSecondaryHorizontal(int offset, boolean clamped) {
961 boolean trailing = primaryIsTrailingPrevious(offset);
962 return getHorizontal(offset, !trailing, clamped);
965 private float getHorizontal(int offset, boolean trailing, boolean clamped) {
966 int line = getLineForOffset(offset);
968 return getHorizontal(offset, trailing, line, clamped);
971 private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
972 int start = getLineStart(line);
973 int end = getLineEnd(line);
974 int dir = getParagraphDirection(line);
975 boolean hasTabOrEmoji = getLineContainsTab(line);
976 Directions directions = getLineDirections(line);
978 TabStops tabStops = null;
979 if (hasTabOrEmoji && mText instanceof Spanned) {
980 // Just checking this line should be good enough, tabs should be
981 // consistent across all lines in a paragraph.
982 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
983 if (tabs.length > 0) {
984 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
988 TextLine tl = TextLine.obtain();
989 tl.set(mPaint, mText, start, end, dir, directions, hasTabOrEmoji, tabStops);
990 float wid = tl.measure(offset - start, trailing, null);
991 TextLine.recycle(tl);
993 if (clamped && wid > mWidth) {
996 int left = getParagraphLeft(line);
997 int right = getParagraphRight(line);
999 return getLineStartPos(line, left, right) + wid;
1003 * Computes in linear time the results of calling
1004 * #getHorizontal for all offsets on a line.
1005 * @param line The line giving the offsets we compute information for
1006 * @param clamped Whether to clamp the results to the width of the layout
1007 * @param primary Whether the results should be the primary or the secondary horizontal
1008 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1010 private float[] getLineHorizontals(int line, boolean clamped, boolean primary) {
1011 int start = getLineStart(line);
1012 int end = getLineEnd(line);
1013 int dir = getParagraphDirection(line);
1014 boolean hasTab = getLineContainsTab(line);
1015 Directions directions = getLineDirections(line);
1017 TabStops tabStops = null;
1018 if (hasTab && mText instanceof Spanned) {
1019 // Just checking this line should be good enough, tabs should be
1020 // consistent across all lines in a paragraph.
1021 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1022 if (tabs.length > 0) {
1023 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1027 TextLine tl = TextLine.obtain();
1028 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
1029 boolean[] trailings = primaryIsTrailingPreviousAllLineOffsets(line);
1031 for (int offset = 0; offset < trailings.length; ++offset) {
1032 trailings[offset] = !trailings[offset];
1035 float[] wid = tl.measureAllOffsets(trailings, null);
1036 TextLine.recycle(tl);
1039 for (int offset = 0; offset <= wid.length; ++offset) {
1040 if (wid[offset] > mWidth) {
1041 wid[offset] = mWidth;
1045 int left = getParagraphLeft(line);
1046 int right = getParagraphRight(line);
1048 int lineStartPos = getLineStartPos(line, left, right);
1049 float[] horizontal = new float[end - start + 1];
1050 for (int offset = 0; offset < horizontal.length; ++offset) {
1051 horizontal[offset] = lineStartPos + wid[offset];
1057 * Get the leftmost position that should be exposed for horizontal
1058 * scrolling on the specified line.
1060 public float getLineLeft(int line) {
1061 int dir = getParagraphDirection(line);
1062 Alignment align = getParagraphAlignment(line);
1064 if (align == Alignment.ALIGN_LEFT) {
1066 } else if (align == Alignment.ALIGN_NORMAL) {
1067 if (dir == DIR_RIGHT_TO_LEFT)
1068 return getParagraphRight(line) - getLineMax(line);
1071 } else if (align == Alignment.ALIGN_RIGHT) {
1072 return mWidth - getLineMax(line);
1073 } else if (align == Alignment.ALIGN_OPPOSITE) {
1074 if (dir == DIR_RIGHT_TO_LEFT)
1077 return mWidth - getLineMax(line);
1078 } else { /* align == Alignment.ALIGN_CENTER */
1079 int left = getParagraphLeft(line);
1080 int right = getParagraphRight(line);
1081 int max = ((int) getLineMax(line)) & ~1;
1083 return left + ((right - left) - max) / 2;
1088 * Get the rightmost position that should be exposed for horizontal
1089 * scrolling on the specified line.
1091 public float getLineRight(int line) {
1092 int dir = getParagraphDirection(line);
1093 Alignment align = getParagraphAlignment(line);
1095 if (align == Alignment.ALIGN_LEFT) {
1096 return getParagraphLeft(line) + getLineMax(line);
1097 } else if (align == Alignment.ALIGN_NORMAL) {
1098 if (dir == DIR_RIGHT_TO_LEFT)
1101 return getParagraphLeft(line) + getLineMax(line);
1102 } else if (align == Alignment.ALIGN_RIGHT) {
1104 } else if (align == Alignment.ALIGN_OPPOSITE) {
1105 if (dir == DIR_RIGHT_TO_LEFT)
1106 return getLineMax(line);
1109 } else { /* align == Alignment.ALIGN_CENTER */
1110 int left = getParagraphLeft(line);
1111 int right = getParagraphRight(line);
1112 int max = ((int) getLineMax(line)) & ~1;
1114 return right - ((right - left) - max) / 2;
1119 * Gets the unsigned horizontal extent of the specified line, including
1120 * leading margin indent, but excluding trailing whitespace.
1122 public float getLineMax(int line) {
1123 float margin = getParagraphLeadingMargin(line);
1124 float signedExtent = getLineExtent(line, false);
1125 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1129 * Gets the unsigned horizontal extent of the specified line, including
1130 * leading margin indent and trailing whitespace.
1132 public float getLineWidth(int line) {
1133 float margin = getParagraphLeadingMargin(line);
1134 float signedExtent = getLineExtent(line, true);
1135 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1139 * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1140 * tab stops instead of using the ones passed in.
1141 * @param line the index of the line
1142 * @param full whether to include trailing whitespace
1143 * @return the extent of the line
1145 private float getLineExtent(int line, boolean full) {
1146 int start = getLineStart(line);
1147 int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1149 boolean hasTabsOrEmoji = getLineContainsTab(line);
1150 TabStops tabStops = null;
1151 if (hasTabsOrEmoji && mText instanceof Spanned) {
1152 // Just checking this line should be good enough, tabs should be
1153 // consistent across all lines in a paragraph.
1154 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1155 if (tabs.length > 0) {
1156 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1159 Directions directions = getLineDirections(line);
1160 // Returned directions can actually be null
1161 if (directions == null) {
1164 int dir = getParagraphDirection(line);
1166 TextLine tl = TextLine.obtain();
1167 tl.set(mPaint, mText, start, end, dir, directions, hasTabsOrEmoji, tabStops);
1168 float width = tl.metrics(null);
1169 TextLine.recycle(tl);
1174 * Returns the signed horizontal extent of the specified line, excluding
1175 * leading margin. If full is false, excludes trailing whitespace.
1176 * @param line the index of the line
1177 * @param tabStops the tab stops, can be null if we know they're not used.
1178 * @param full whether to include trailing whitespace
1179 * @return the extent of the text on this line
1181 private float getLineExtent(int line, TabStops tabStops, boolean full) {
1182 int start = getLineStart(line);
1183 int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1184 boolean hasTabsOrEmoji = getLineContainsTab(line);
1185 Directions directions = getLineDirections(line);
1186 int dir = getParagraphDirection(line);
1188 TextLine tl = TextLine.obtain();
1189 tl.set(mPaint, mText, start, end, dir, directions, hasTabsOrEmoji, tabStops);
1190 float width = tl.metrics(null);
1191 TextLine.recycle(tl);
1196 * Get the line number corresponding to the specified vertical position.
1197 * If you ask for a position above 0, you get 0; if you ask for a position
1198 * below the bottom of the text, you get the last line.
1200 // FIXME: It may be faster to do a linear search for layouts without many lines.
1201 public int getLineForVertical(int vertical) {
1202 int high = getLineCount(), low = -1, guess;
1204 while (high - low > 1) {
1205 guess = (high + low) / 2;
1207 if (getLineTop(guess) > vertical)
1220 * Get the line number on which the specified text offset appears.
1221 * If you ask for a position before 0, you get 0; if you ask for a position
1222 * beyond the end of the text, you get the last line.
1224 public int getLineForOffset(int offset) {
1225 int high = getLineCount(), low = -1, guess;
1227 while (high - low > 1) {
1228 guess = (high + low) / 2;
1230 if (getLineStart(guess) > offset)
1243 * Get the character offset on the specified line whose position is
1244 * closest to the specified horizontal position.
1246 public int getOffsetForHorizontal(int line, float horiz) {
1247 // TODO: use Paint.getOffsetForAdvance to avoid binary search
1248 int max = getLineEnd(line) - 1;
1249 int min = getLineStart(line);
1250 Directions dirs = getLineDirections(line);
1252 if (line == getLineCount() - 1)
1255 final HorizontalMeasurementProvider horizontal =
1256 new HorizontalMeasurementProvider(line);
1258 float bestdist = Math.abs(horizontal.get(best) - horiz);
1260 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1261 int here = min + dirs.mDirections[i];
1262 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1263 int swap = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0 ? -1 : 1;
1267 int high = there - 1 + 1, low = here + 1 - 1, guess;
1269 while (high - low > 1) {
1270 guess = (high + low) / 2;
1271 int adguess = getOffsetAtStartOf(guess);
1273 if (horizontal.get(adguess) * swap >= horiz * swap)
1283 low = getOffsetAtStartOf(low);
1285 float dist = Math.abs(horizontal.get(low) - horiz);
1287 int aft = TextUtils.getOffsetAfter(mText, low);
1289 float other = Math.abs(horizontal.get(aft) - horiz);
1297 if (dist < bestdist) {
1303 float dist = Math.abs(horizontal.get(here) - horiz);
1305 if (dist < bestdist) {
1311 float dist = Math.abs(horizontal.get(max) - horiz);
1313 if (dist <= bestdist) {
1322 * Responds to #getHorizontal queries, by selecting the better strategy between:
1323 * - calling #getHorizontal explicitly for each query
1324 * - precomputing all #getHorizontal measurements, and responding to any query in constant time
1325 * The first strategy is used for LTR-only text, while the second is used for all other cases.
1326 * The class is currently only used in #getOffsetForHorizontal, so reuse with care in other
1329 private class HorizontalMeasurementProvider {
1330 private final int mLine;
1332 private float[] mHorizontals;
1333 private int mLineStartOffset;
1335 HorizontalMeasurementProvider(final int line) {
1340 private void init() {
1341 final Directions dirs = getLineDirections(mLine);
1342 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1346 mHorizontals = getLineHorizontals(mLine, false, true);
1347 mLineStartOffset = getLineStart(mLine);
1350 float get(final int offset) {
1351 if (mHorizontals == null || offset < mLineStartOffset
1352 || offset >= mLineStartOffset + mHorizontals.length) {
1353 return getPrimaryHorizontal(offset);
1355 return mHorizontals[offset - mLineStartOffset];
1361 * Return the text offset after the last character on the specified line.
1363 public final int getLineEnd(int line) {
1364 return getLineStart(line + 1);
1368 * Return the text offset after the last visible character (so whitespace
1369 * is not counted) on the specified line.
1371 public int getLineVisibleEnd(int line) {
1372 return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1375 private int getLineVisibleEnd(int line, int start, int end) {
1376 CharSequence text = mText;
1378 if (line == getLineCount() - 1) {
1382 for (; end > start; end--) {
1383 ch = text.charAt(end - 1);
1389 // Note: keep this in sync with Minikin LineBreaker::isLineEndSpace()
1390 if (!(ch == ' ' || ch == '\t' || ch == 0x1680 ||
1391 (0x2000 <= ch && ch <= 0x200A && ch != 0x2007) ||
1392 ch == 0x205F || ch == 0x3000)) {
1402 * Return the vertical position of the bottom of the specified line.
1404 public final int getLineBottom(int line) {
1405 return getLineTop(line + 1);
1409 * Return the vertical position of the baseline of the specified line.
1411 public final int getLineBaseline(int line) {
1412 // getLineTop(line+1) == getLineTop(line)
1413 return getLineTop(line+1) - getLineDescent(line);
1417 * Get the ascent of the text on the specified line.
1418 * The return value is negative to match the Paint.ascent() convention.
1420 public final int getLineAscent(int line) {
1421 // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1422 return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1425 public int getOffsetToLeftOf(int offset) {
1426 return getOffsetToLeftRightOf(offset, true);
1429 public int getOffsetToRightOf(int offset) {
1430 return getOffsetToLeftRightOf(offset, false);
1433 private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1434 int line = getLineForOffset(caret);
1435 int lineStart = getLineStart(line);
1436 int lineEnd = getLineEnd(line);
1437 int lineDir = getParagraphDirection(line);
1439 boolean lineChanged = false;
1440 boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
1441 // if walking off line, look at the line we're headed to
1443 if (caret == lineEnd) {
1444 if (line < getLineCount() - 1) {
1448 return caret; // at very end, don't move
1452 if (caret == lineStart) {
1457 return caret; // at very start, don't move
1463 lineStart = getLineStart(line);
1464 lineEnd = getLineEnd(line);
1465 int newDir = getParagraphDirection(line);
1466 if (newDir != lineDir) {
1467 // unusual case. we want to walk onto the line, but it runs
1468 // in a different direction than this one, so we fake movement
1469 // in the opposite direction.
1475 Directions directions = getLineDirections(line);
1477 TextLine tl = TextLine.obtain();
1478 // XXX: we don't care about tabs
1479 tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null);
1480 caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
1481 tl = TextLine.recycle(tl);
1485 private int getOffsetAtStartOf(int offset) {
1486 // XXX this probably should skip local reorderings and
1487 // zero-width characters, look at callers
1491 CharSequence text = mText;
1492 char c = text.charAt(offset);
1494 if (c >= '\uDC00' && c <= '\uDFFF') {
1495 char c1 = text.charAt(offset - 1);
1497 if (c1 >= '\uD800' && c1 <= '\uDBFF')
1502 ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1503 ReplacementSpan.class);
1505 for (int i = 0; i < spans.length; i++) {
1506 int start = ((Spanned) text).getSpanStart(spans[i]);
1507 int end = ((Spanned) text).getSpanEnd(spans[i]);
1509 if (start < offset && end > offset)
1518 * Determine whether we should clamp cursor position. Currently it's
1519 * only robust for left-aligned displays.
1522 public boolean shouldClampCursor(int line) {
1523 // Only clamp cursor position in left-aligned displays.
1524 switch (getParagraphAlignment(line)) {
1528 return getParagraphDirection(line) > 0;
1535 * Fills in the specified Path with a representation of a cursor
1536 * at the specified offset. This will often be a vertical line
1537 * but can be multiple discontinuous lines in text with multiple
1540 public void getCursorPath(int point, Path dest,
1541 CharSequence editingBuffer) {
1544 int line = getLineForOffset(point);
1545 int top = getLineTop(line);
1546 int bottom = getLineTop(line+1);
1548 boolean clamped = shouldClampCursor(line);
1549 float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1550 float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
1552 int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1553 TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1554 int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
1557 if (caps != 0 || fn != 0) {
1558 dist = (bottom - top) >> 2;
1571 if (Float.compare(h1, h2) == 0) {
1572 dest.moveTo(h1, top);
1573 dest.lineTo(h1, bottom);
1575 dest.moveTo(h1, top);
1576 dest.lineTo(h1, (top + bottom) >> 1);
1578 dest.moveTo(h2, (top + bottom) >> 1);
1579 dest.lineTo(h2, bottom);
1583 dest.moveTo(h2, bottom);
1584 dest.lineTo(h2 - dist, bottom + dist);
1585 dest.lineTo(h2, bottom);
1586 dest.lineTo(h2 + dist, bottom + dist);
1587 } else if (caps == 1) {
1588 dest.moveTo(h2, bottom);
1589 dest.lineTo(h2 - dist, bottom + dist);
1591 dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1592 dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1594 dest.moveTo(h2 + dist, bottom + dist);
1595 dest.lineTo(h2, bottom);
1599 dest.moveTo(h1, top);
1600 dest.lineTo(h1 - dist, top - dist);
1601 dest.lineTo(h1, top);
1602 dest.lineTo(h1 + dist, top - dist);
1603 } else if (fn == 1) {
1604 dest.moveTo(h1, top);
1605 dest.lineTo(h1 - dist, top - dist);
1607 dest.moveTo(h1 - dist, top - dist + 0.5f);
1608 dest.lineTo(h1 + dist, top - dist + 0.5f);
1610 dest.moveTo(h1 + dist, top - dist);
1611 dest.lineTo(h1, top);
1615 private void addSelection(int line, int start, int end,
1616 int top, int bottom, Path dest) {
1617 int linestart = getLineStart(line);
1618 int lineend = getLineEnd(line);
1619 Directions dirs = getLineDirections(line);
1621 if (lineend > linestart && mText.charAt(lineend - 1) == '\n')
1624 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1625 int here = linestart + dirs.mDirections[i];
1626 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1628 if (there > lineend)
1631 if (start <= there && end >= here) {
1632 int st = Math.max(start, here);
1633 int en = Math.min(end, there);
1636 float h1 = getHorizontal(st, false, line, false /* not clamped */);
1637 float h2 = getHorizontal(en, true, line, false /* not clamped */);
1639 float left = Math.min(h1, h2);
1640 float right = Math.max(h1, h2);
1642 dest.addRect(left, top, right, bottom, Path.Direction.CW);
1649 * Fills in the specified Path with a representation of a highlight
1650 * between the specified offsets. This will often be a rectangle
1651 * or a potentially discontinuous set of rectangles. If the start
1652 * and end are the same, the returned path is empty.
1654 public void getSelectionPath(int start, int end, Path dest) {
1666 int startline = getLineForOffset(start);
1667 int endline = getLineForOffset(end);
1669 int top = getLineTop(startline);
1670 int bottom = getLineBottom(endline);
1672 if (startline == endline) {
1673 addSelection(startline, start, end, top, bottom, dest);
1675 final float width = mWidth;
1677 addSelection(startline, start, getLineEnd(startline),
1678 top, getLineBottom(startline), dest);
1680 if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT)
1681 dest.addRect(getLineLeft(startline), top,
1682 0, getLineBottom(startline), Path.Direction.CW);
1684 dest.addRect(getLineRight(startline), top,
1685 width, getLineBottom(startline), Path.Direction.CW);
1687 for (int i = startline + 1; i < endline; i++) {
1688 top = getLineTop(i);
1689 bottom = getLineBottom(i);
1690 dest.addRect(0, top, width, bottom, Path.Direction.CW);
1693 top = getLineTop(endline);
1694 bottom = getLineBottom(endline);
1696 addSelection(endline, getLineStart(endline), end,
1699 if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT)
1700 dest.addRect(width, top, getLineRight(endline), bottom, Path.Direction.CW);
1702 dest.addRect(0, top, getLineLeft(endline), bottom, Path.Direction.CW);
1707 * Get the alignment of the specified paragraph, taking into account
1708 * markup attached to it.
1710 public final Alignment getParagraphAlignment(int line) {
1711 Alignment align = mAlignment;
1714 Spanned sp = (Spanned) mText;
1715 AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
1717 AlignmentSpan.class);
1719 int spanLength = spans.length;
1720 if (spanLength > 0) {
1721 align = spans[spanLength-1].getAlignment();
1729 * Get the left edge of the specified paragraph, inset by left margins.
1731 public final int getParagraphLeft(int line) {
1733 int dir = getParagraphDirection(line);
1734 if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
1735 return left; // leading margin has no impact, or no styles
1737 return getParagraphLeadingMargin(line);
1741 * Get the right edge of the specified paragraph, inset by right margins.
1743 public final int getParagraphRight(int line) {
1745 int dir = getParagraphDirection(line);
1746 if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
1747 return right; // leading margin has no impact, or no styles
1749 return right - getParagraphLeadingMargin(line);
1753 * Returns the effective leading margin (unsigned) for this line,
1754 * taking into account LeadingMarginSpan and LeadingMarginSpan2.
1755 * @param line the line index
1756 * @return the leading margin of this line
1758 private int getParagraphLeadingMargin(int line) {
1759 if (!mSpannedText) {
1762 Spanned spanned = (Spanned) mText;
1764 int lineStart = getLineStart(line);
1765 int lineEnd = getLineEnd(line);
1766 int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
1767 LeadingMarginSpan.class);
1768 LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
1769 LeadingMarginSpan.class);
1770 if (spans.length == 0) {
1771 return 0; // no leading margin span;
1776 boolean isFirstParaLine = lineStart == 0 ||
1777 spanned.charAt(lineStart - 1) == '\n';
1779 boolean useFirstLineMargin = isFirstParaLine;
1780 for (int i = 0; i < spans.length; i++) {
1781 if (spans[i] instanceof LeadingMarginSpan2) {
1782 int spStart = spanned.getSpanStart(spans[i]);
1783 int spanLine = getLineForOffset(spStart);
1784 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
1785 // if there is more than one LeadingMarginSpan2, use the count that is greatest
1786 useFirstLineMargin |= line < spanLine + count;
1789 for (int i = 0; i < spans.length; i++) {
1790 LeadingMarginSpan span = spans[i];
1791 margin += span.getLeadingMargin(useFirstLineMargin);
1798 static float measurePara(TextPaint paint, CharSequence text, int start, int end) {
1800 MeasuredText mt = MeasuredText.obtain();
1801 TextLine tl = TextLine.obtain();
1803 mt.setPara(text, start, end, TextDirectionHeuristics.LTR, null);
1804 Directions directions;
1807 directions = DIRS_ALL_LEFT_TO_RIGHT;
1808 dir = Layout.DIR_LEFT_TO_RIGHT;
1810 directions = AndroidBidi.directions(mt.mDir, mt.mLevels,
1811 0, mt.mChars, 0, mt.mLen);
1814 char[] chars = mt.mChars;
1816 boolean hasTabs = false;
1817 TabStops tabStops = null;
1818 // leading margins should be taken into account when measuring a paragraph
1820 if (text instanceof Spanned) {
1821 Spanned spanned = (Spanned) text;
1822 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
1823 LeadingMarginSpan.class);
1824 for (LeadingMarginSpan lms : spans) {
1825 margin += lms.getLeadingMargin(true);
1828 for (int i = 0; i < len; ++i) {
1829 if (chars[i] == '\t') {
1831 if (text instanceof Spanned) {
1832 Spanned spanned = (Spanned) text;
1833 int spanEnd = spanned.nextSpanTransition(start, end,
1835 TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
1837 if (spans.length > 0) {
1838 tabStops = new TabStops(TAB_INCREMENT, spans);
1844 tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops);
1845 return margin + tl.metrics(null);
1847 TextLine.recycle(tl);
1848 MeasuredText.recycle(mt);
1855 /* package */ static class TabStops {
1856 private int[] mStops;
1857 private int mNumStops;
1858 private int mIncrement;
1860 TabStops(int increment, Object[] spans) {
1861 reset(increment, spans);
1864 void reset(int increment, Object[] spans) {
1865 this.mIncrement = increment;
1868 if (spans != null) {
1869 int[] stops = this.mStops;
1870 for (Object o : spans) {
1871 if (o instanceof TabStopSpan) {
1872 if (stops == null) {
1873 stops = new int[10];
1874 } else if (ns == stops.length) {
1875 int[] nstops = new int[ns * 2];
1876 for (int i = 0; i < ns; ++i) {
1877 nstops[i] = stops[i];
1881 stops[ns++] = ((TabStopSpan) o).getTabStop();
1885 Arrays.sort(stops, 0, ns);
1887 if (stops != this.mStops) {
1888 this.mStops = stops;
1891 this.mNumStops = ns;
1894 float nextTab(float h) {
1895 int ns = this.mNumStops;
1897 int[] stops = this.mStops;
1898 for (int i = 0; i < ns; ++i) {
1899 int stop = stops[i];
1905 return nextDefaultStop(h, mIncrement);
1908 public static float nextDefaultStop(float h, int inc) {
1909 return ((int) ((h + inc) / inc)) * inc;
1914 * Returns the position of the next tab stop after h on the line.
1916 * @param text the text
1917 * @param start start of the line
1918 * @param end limit of the line
1919 * @param h the current horizontal offset
1920 * @param tabs the tabs, can be null. If it is null, any tabs in effect
1921 * on the line will be used. If there are no tabs, a default offset
1922 * will be used to compute the tab stop.
1923 * @return the offset of the next tab stop.
1925 /* package */ static float nextTab(CharSequence text, int start, int end,
1926 float h, Object[] tabs) {
1927 float nh = Float.MAX_VALUE;
1928 boolean alltabs = false;
1930 if (text instanceof Spanned) {
1932 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
1936 for (int i = 0; i < tabs.length; i++) {
1938 if (!(tabs[i] instanceof TabStopSpan))
1942 int where = ((TabStopSpan) tabs[i]).getTabStop();
1944 if (where < nh && where > h)
1948 if (nh != Float.MAX_VALUE)
1952 return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
1955 protected final boolean isSpanned() {
1956 return mSpannedText;
1960 * Returns the same as <code>text.getSpans()</code>, except where
1961 * <code>start</code> and <code>end</code> are the same and are not
1962 * at the very beginning of the text, in which case an empty array
1963 * is returned instead.
1965 * This is needed because of the special case that <code>getSpans()</code>
1966 * on an empty range returns the spans adjacent to that range, which is
1967 * primarily for the sake of <code>TextWatchers</code> so they will get
1968 * notifications when text goes from empty to non-empty. But it also
1969 * has the unfortunate side effect that if the text ends with an empty
1970 * paragraph, that paragraph accidentally picks up the styles of the
1971 * preceding paragraph (even though those styles will not be picked up
1972 * by new text that is inserted into the empty paragraph).
1974 * The reason it just checks whether <code>start</code> and <code>end</code>
1975 * is the same is that the only time a line can contain 0 characters
1976 * is if it is the final paragraph of the Layout; otherwise any line will
1977 * contain at least one printing or newline character. The reason for the
1978 * additional check if <code>start</code> is greater than 0 is that
1979 * if the empty paragraph is the entire content of the buffer, paragraph
1980 * styles that are already applied to the buffer will apply to text that
1981 * is inserted into it.
1983 /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
1984 if (start == end && start > 0) {
1985 return ArrayUtils.emptyArray(type);
1988 return text.getSpans(start, end, type);
1991 private char getEllipsisChar(TextUtils.TruncateAt method) {
1992 return (method == TextUtils.TruncateAt.END_SMALL) ?
1993 TextUtils.ELLIPSIS_TWO_DOTS[0] :
1994 TextUtils.ELLIPSIS_NORMAL[0];
1997 private void ellipsize(int start, int end, int line,
1998 char[] dest, int destoff, TextUtils.TruncateAt method) {
1999 int ellipsisCount = getEllipsisCount(line);
2001 if (ellipsisCount == 0) {
2005 int ellipsisStart = getEllipsisStart(line);
2006 int linestart = getLineStart(line);
2008 for (int i = ellipsisStart; i < ellipsisStart + ellipsisCount; i++) {
2011 if (i == ellipsisStart) {
2012 c = getEllipsisChar(method); // ellipsis
2014 c = '\uFEFF'; // 0-width space
2017 int a = i + linestart;
2019 if (a >= start && a < end) {
2020 dest[destoff + a - start] = c;
2026 * Stores information about bidirectional (left-to-right or right-to-left)
2027 * text within the layout of a line.
2029 public static class Directions {
2030 // Directions represents directional runs within a line of text.
2031 // Runs are pairs of ints listed in visual order, starting from the
2032 // leading margin. The first int of each pair is the offset from
2033 // the first character of the line to the start of the run. The
2034 // second int represents both the length and level of the run.
2035 // The length is in the lower bits, accessed by masking with
2036 // DIR_LENGTH_MASK. The level is in the higher bits, accessed
2037 // by shifting by DIR_LEVEL_SHIFT and masking by DIR_LEVEL_MASK.
2038 // To simply test for an RTL direction, test the bit using
2039 // DIR_RTL_FLAG, if set then the direction is rtl.
2041 /* package */ int[] mDirections;
2042 /* package */ Directions(int[] dirs) {
2048 * Return the offset of the first character to be ellipsized away,
2049 * relative to the start of the line. (So 0 if the beginning of the
2050 * line is ellipsized, not getLineStart().)
2052 public abstract int getEllipsisStart(int line);
2055 * Returns the number of characters to be ellipsized away, or 0 if
2056 * no ellipsis is to take place.
2058 public abstract int getEllipsisCount(int line);
2060 /* package */ static class Ellipsizer implements CharSequence, GetChars {
2061 /* package */ CharSequence mText;
2062 /* package */ Layout mLayout;
2063 /* package */ int mWidth;
2064 /* package */ TextUtils.TruncateAt mMethod;
2066 public Ellipsizer(CharSequence s) {
2070 public char charAt(int off) {
2071 char[] buf = TextUtils.obtain(1);
2072 getChars(off, off + 1, buf, 0);
2075 TextUtils.recycle(buf);
2079 public void getChars(int start, int end, char[] dest, int destoff) {
2080 int line1 = mLayout.getLineForOffset(start);
2081 int line2 = mLayout.getLineForOffset(end);
2083 TextUtils.getChars(mText, start, end, dest, destoff);
2085 for (int i = line1; i <= line2; i++) {
2086 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
2090 public int length() {
2091 return mText.length();
2094 public CharSequence subSequence(int start, int end) {
2095 char[] s = new char[end - start];
2096 getChars(start, end, s, 0);
2097 return new String(s);
2101 public String toString() {
2102 char[] s = new char[length()];
2103 getChars(0, length(), s, 0);
2104 return new String(s);
2109 /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
2110 private Spanned mSpanned;
2112 public SpannedEllipsizer(CharSequence display) {
2114 mSpanned = (Spanned) display;
2117 public <T> T[] getSpans(int start, int end, Class<T> type) {
2118 return mSpanned.getSpans(start, end, type);
2121 public int getSpanStart(Object tag) {
2122 return mSpanned.getSpanStart(tag);
2125 public int getSpanEnd(Object tag) {
2126 return mSpanned.getSpanEnd(tag);
2129 public int getSpanFlags(Object tag) {
2130 return mSpanned.getSpanFlags(tag);
2133 @SuppressWarnings("rawtypes")
2134 public int nextSpanTransition(int start, int limit, Class type) {
2135 return mSpanned.nextSpanTransition(start, limit, type);
2139 public CharSequence subSequence(int start, int end) {
2140 char[] s = new char[end - start];
2141 getChars(start, end, s, 0);
2143 SpannableString ss = new SpannableString(new String(s));
2144 TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2149 private CharSequence mText;
2150 private TextPaint mPaint;
2152 private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2153 private float mSpacingMult;
2154 private float mSpacingAdd;
2155 private static final Rect sTempRect = new Rect();
2156 private boolean mSpannedText;
2157 private TextDirectionHeuristic mTextDir;
2158 private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
2160 public static final int DIR_LEFT_TO_RIGHT = 1;
2161 public static final int DIR_RIGHT_TO_LEFT = -1;
2163 /* package */ static final int DIR_REQUEST_LTR = 1;
2164 /* package */ static final int DIR_REQUEST_RTL = -1;
2165 /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2166 /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
2168 /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2169 /* package */ static final int RUN_LEVEL_SHIFT = 26;
2170 /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2171 /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2173 public enum Alignment {
2183 private static final int TAB_INCREMENT = 20;
2185 /* package */ static final Directions DIRS_ALL_LEFT_TO_RIGHT =
2186 new Directions(new int[] { 0, RUN_LENGTH_MASK });
2187 /* package */ static final Directions DIRS_ALL_RIGHT_TO_LEFT =
2188 new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });