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.annotation.IntRange;
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.annotations.VisibleForTesting;
35 import com.android.internal.util.ArrayUtils;
36 import com.android.internal.util.GrowingArrayUtils;
38 import java.lang.annotation.Retention;
39 import java.lang.annotation.RetentionPolicy;
40 import java.util.Arrays;
43 * A base class that manages text layout in visual elements on
45 * <p>For text that will be edited, use a {@link DynamicLayout},
46 * which will be updated as the text changes.
47 * For text that will not change, use a {@link StaticLayout}.
49 public abstract class Layout {
51 @IntDef(prefix = { "BREAK_STRATEGY_" }, value = {
52 BREAK_STRATEGY_SIMPLE,
53 BREAK_STRATEGY_HIGH_QUALITY,
54 BREAK_STRATEGY_BALANCED
56 @Retention(RetentionPolicy.SOURCE)
57 public @interface BreakStrategy {}
60 * Value for break strategy indicating simple line breaking. Automatic hyphens are not added
61 * (though soft hyphens are respected), and modifying text generally doesn't affect the layout
62 * before it (which yields a more consistent user experience when editing), but layout may not
63 * be the highest quality.
65 public static final int BREAK_STRATEGY_SIMPLE = 0;
68 * Value for break strategy indicating high quality line breaking, including automatic
69 * hyphenation and doing whole-paragraph optimization of line breaks.
71 public static final int BREAK_STRATEGY_HIGH_QUALITY = 1;
74 * Value for break strategy indicating balanced line breaking. The breaks are chosen to
75 * make all lines as close to the same length as possible, including automatic hyphenation.
77 public static final int BREAK_STRATEGY_BALANCED = 2;
80 @IntDef(prefix = { "HYPHENATION_FREQUENCY_" }, value = {
81 HYPHENATION_FREQUENCY_NORMAL,
82 HYPHENATION_FREQUENCY_FULL,
83 HYPHENATION_FREQUENCY_NONE
85 @Retention(RetentionPolicy.SOURCE)
86 public @interface HyphenationFrequency {}
89 * Value for hyphenation frequency indicating no automatic hyphenation. Useful
90 * for backward compatibility, and for cases where the automatic hyphenation algorithm results
91 * in incorrect hyphenation. Mid-word breaks may still happen when a word is wider than the
92 * layout and there is otherwise no valid break. Soft hyphens are ignored and will not be used
93 * as suggestions for potential line breaks.
95 public static final int HYPHENATION_FREQUENCY_NONE = 0;
98 * Value for hyphenation frequency indicating a light amount of automatic hyphenation, which
99 * is a conservative default. Useful for informal cases, such as short sentences or chat
102 public static final int HYPHENATION_FREQUENCY_NORMAL = 1;
105 * Value for hyphenation frequency indicating the full amount of automatic hyphenation, typical
106 * in typography. Useful for running text and where it's important to put the maximum amount of
107 * text in a screen with limited space.
109 public static final int HYPHENATION_FREQUENCY_FULL = 2;
111 private static final ParagraphStyle[] NO_PARA_SPANS =
112 ArrayUtils.emptyArray(ParagraphStyle.class);
115 @IntDef(prefix = { "JUSTIFICATION_MODE_" }, value = {
116 JUSTIFICATION_MODE_NONE,
117 JUSTIFICATION_MODE_INTER_WORD
119 @Retention(RetentionPolicy.SOURCE)
120 public @interface JustificationMode {}
123 * Value for justification mode indicating no justification.
125 public static final int JUSTIFICATION_MODE_NONE = 0;
128 * Value for justification mode indicating the text is justified by stretching word spacing.
130 public static final int JUSTIFICATION_MODE_INTER_WORD = 1;
133 * Line spacing multiplier for default line spacing.
135 public static final float DEFAULT_LINESPACING_MULTIPLIER = 1.0f;
138 * Line spacing addition for default line spacing.
140 public static final float DEFAULT_LINESPACING_ADDITION = 0.0f;
143 * Return how wide a layout must be in order to display the specified text with one line per
147 * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
148 * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
150 public static float getDesiredWidth(CharSequence source,
152 return getDesiredWidth(source, 0, source.length(), paint);
156 * Return how wide a layout must be in order to display the specified text slice with one
157 * line per paragraph.
160 * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
161 * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
163 public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint) {
164 return getDesiredWidth(source, start, end, paint, TextDirectionHeuristics.FIRSTSTRONG_LTR);
168 * Return how wide a layout must be in order to display the
169 * specified text slice with one line per paragraph.
173 public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint,
174 TextDirectionHeuristic textDir) {
175 return getDesiredWidthWithLimit(source, start, end, paint, textDir, Float.MAX_VALUE);
178 * Return how wide a layout must be in order to display the
179 * specified text slice with one line per paragraph.
181 * If the measured width exceeds given limit, returns limit value instead.
184 public static float getDesiredWidthWithLimit(CharSequence source, int start, int end,
185 TextPaint paint, TextDirectionHeuristic textDir, float upperLimit) {
189 for (int i = start; i <= end; i = next) {
190 next = TextUtils.indexOf(source, '\n', i, end);
195 // note, omits trailing paragraph char
196 float w = measurePara(paint, source, i, next, textDir);
197 if (w > upperLimit) {
211 * Subclasses of Layout use this constructor to set the display text,
212 * width, and other standard properties.
213 * @param text the text to render
214 * @param paint the default paint for the layout. Styles can override
215 * various attributes of the paint.
216 * @param width the wrapping width for the text.
217 * @param align whether to left, right, or center the text. Styles can
218 * override the alignment.
219 * @param spacingMult factor by which to scale the font size to get the
220 * default line spacing
221 * @param spacingAdd amount to add to the default line spacing
223 protected Layout(CharSequence text, TextPaint paint,
224 int width, Alignment align,
225 float spacingMult, float spacingAdd) {
226 this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
227 spacingMult, spacingAdd);
231 * Subclasses of Layout use this constructor to set the display text,
232 * width, and other standard properties.
233 * @param text the text to render
234 * @param paint the default paint for the layout. Styles can override
235 * various attributes of the paint.
236 * @param width the wrapping width for the text.
237 * @param align whether to left, right, or center the text. Styles can
238 * override the alignment.
239 * @param spacingMult factor by which to scale the font size to get the
240 * default line spacing
241 * @param spacingAdd amount to add to the default line spacing
245 protected Layout(CharSequence text, TextPaint paint,
246 int width, Alignment align, TextDirectionHeuristic textDir,
247 float spacingMult, float spacingAdd) {
250 throw new IllegalArgumentException("Layout: " + width + " < 0");
252 // Ensure paint doesn't have baselineShift set.
253 // While normally we don't modify the paint the user passed in,
254 // we were already doing this in Styled.drawUniformRun with both
255 // baselineShift and bgColor. We probably should reevaluate bgColor.
258 paint.baselineShift = 0;
265 mSpacingMult = spacingMult;
266 mSpacingAdd = spacingAdd;
267 mSpannedText = text instanceof Spanned;
272 protected void setJustificationMode(@JustificationMode int justificationMode) {
273 mJustificationMode = justificationMode;
277 * Replace constructor properties of this Layout with new ones. Be careful.
279 /* package */ void replaceWith(CharSequence text, TextPaint paint,
280 int width, Alignment align,
281 float spacingmult, float spacingadd) {
283 throw new IllegalArgumentException("Layout: " + width + " < 0");
290 mSpacingMult = spacingmult;
291 mSpacingAdd = spacingadd;
292 mSpannedText = text instanceof Spanned;
296 * Draw this Layout on the specified Canvas.
298 public void draw(Canvas c) {
299 draw(c, null, null, 0);
303 * Draw this Layout on the specified canvas, with the highlight path drawn
304 * between the background and the text.
306 * @param canvas the canvas
307 * @param highlight the path of the highlight or cursor; can be null
308 * @param highlightPaint the paint for the highlight
309 * @param cursorOffsetVertical the amount to temporarily translate the
310 * canvas while rendering the highlight
312 public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
313 int cursorOffsetVertical) {
314 final long lineRange = getLineRangeForDraw(canvas);
315 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
316 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
317 if (lastLine < 0) return;
319 drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
320 firstLine, lastLine);
321 drawText(canvas, firstLine, lastLine);
324 private boolean isJustificationRequired(int lineNum) {
325 if (mJustificationMode == JUSTIFICATION_MODE_NONE) return false;
326 final int lineEnd = getLineEnd(lineNum);
327 return lineEnd < mText.length() && mText.charAt(lineEnd - 1) != '\n';
330 private float getJustifyWidth(int lineNum) {
331 Alignment paraAlign = mAlignment;
336 final int dir = getParagraphDirection(lineNum);
338 ParagraphStyle[] spans = NO_PARA_SPANS;
340 Spanned sp = (Spanned) mText;
341 final int start = getLineStart(lineNum);
343 final boolean isFirstParaLine = (start == 0 || mText.charAt(start - 1) == '\n');
345 if (isFirstParaLine) {
346 final int spanEnd = sp.nextSpanTransition(start, mText.length(),
347 ParagraphStyle.class);
348 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
350 for (int n = spans.length - 1; n >= 0; n--) {
351 if (spans[n] instanceof AlignmentSpan) {
352 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
358 final int length = spans.length;
359 boolean useFirstLineMargin = isFirstParaLine;
360 for (int n = 0; n < length; n++) {
361 if (spans[n] instanceof LeadingMarginSpan2) {
362 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
363 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
364 if (lineNum < startLine + count) {
365 useFirstLineMargin = true;
370 for (int n = 0; n < length; n++) {
371 if (spans[n] instanceof LeadingMarginSpan) {
372 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
373 if (dir == DIR_RIGHT_TO_LEFT) {
374 right -= margin.getLeadingMargin(useFirstLineMargin);
376 left += margin.getLeadingMargin(useFirstLineMargin);
382 final Alignment align;
383 if (paraAlign == Alignment.ALIGN_LEFT) {
384 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
385 } else if (paraAlign == Alignment.ALIGN_RIGHT) {
386 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
391 final int indentWidth;
392 if (align == Alignment.ALIGN_NORMAL) {
393 if (dir == DIR_LEFT_TO_RIGHT) {
394 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
396 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
398 } else if (align == Alignment.ALIGN_OPPOSITE) {
399 if (dir == DIR_LEFT_TO_RIGHT) {
400 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
402 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
404 } else { // Alignment.ALIGN_CENTER
405 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
408 return right - left - indentWidth;
414 public void drawText(Canvas canvas, int firstLine, int lastLine) {
415 int previousLineBottom = getLineTop(firstLine);
416 int previousLineEnd = getLineStart(firstLine);
417 ParagraphStyle[] spans = NO_PARA_SPANS;
419 final TextPaint paint = mWorkPaint;
421 CharSequence buf = mText;
423 Alignment paraAlign = mAlignment;
424 TabStops tabStops = null;
425 boolean tabStopsIsInitialized = false;
427 TextLine tl = TextLine.obtain();
429 // Draw the lines, one at a time.
430 // The baseline is the top of the following line minus the current line's descent.
431 for (int lineNum = firstLine; lineNum <= lastLine; lineNum++) {
432 int start = previousLineEnd;
433 previousLineEnd = getLineStart(lineNum + 1);
434 final boolean justify = isJustificationRequired(lineNum);
435 int end = getLineVisibleEnd(lineNum, start, previousLineEnd);
436 paint.setHyphenEdit(getHyphen(lineNum));
438 int ltop = previousLineBottom;
439 int lbottom = getLineTop(lineNum + 1);
440 previousLineBottom = lbottom;
441 int lbaseline = lbottom - getLineDescent(lineNum);
443 int dir = getParagraphDirection(lineNum);
448 Spanned sp = (Spanned) buf;
449 int textLength = buf.length();
450 boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
452 // New batch of paragraph styles, collect into spans array.
453 // Compute the alignment, last alignment style wins.
454 // Reset tabStops, we'll rebuild if we encounter a line with
456 // We expect paragraph spans to be relatively infrequent, use
457 // spanEnd so that we can check less frequently. Since
458 // paragraph styles ought to apply to entire paragraphs, we can
459 // just collect the ones present at the start of the paragraph.
460 // If spanEnd is before the end of the paragraph, that's not
462 if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
463 spanEnd = sp.nextSpanTransition(start, textLength,
464 ParagraphStyle.class);
465 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
467 paraAlign = mAlignment;
468 for (int n = spans.length - 1; n >= 0; n--) {
469 if (spans[n] instanceof AlignmentSpan) {
470 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
475 tabStopsIsInitialized = false;
478 // Draw all leading margin spans. Adjust left or right according
479 // to the paragraph direction of the line.
480 final int length = spans.length;
481 boolean useFirstLineMargin = isFirstParaLine;
482 for (int n = 0; n < length; n++) {
483 if (spans[n] instanceof LeadingMarginSpan2) {
484 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
485 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
486 // if there is more than one LeadingMarginSpan2, use
487 // the count that is greatest
488 if (lineNum < startLine + count) {
489 useFirstLineMargin = true;
494 for (int n = 0; n < length; n++) {
495 if (spans[n] instanceof LeadingMarginSpan) {
496 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
497 if (dir == DIR_RIGHT_TO_LEFT) {
498 margin.drawLeadingMargin(canvas, paint, right, dir, ltop,
499 lbaseline, lbottom, buf,
500 start, end, isFirstParaLine, this);
501 right -= margin.getLeadingMargin(useFirstLineMargin);
503 margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
504 lbaseline, lbottom, buf,
505 start, end, isFirstParaLine, this);
506 left += margin.getLeadingMargin(useFirstLineMargin);
512 boolean hasTab = getLineContainsTab(lineNum);
513 // Can't tell if we have tabs for sure, currently
514 if (hasTab && !tabStopsIsInitialized) {
515 if (tabStops == null) {
516 tabStops = new TabStops(TAB_INCREMENT, spans);
518 tabStops.reset(TAB_INCREMENT, spans);
520 tabStopsIsInitialized = true;
523 // Determine whether the line aligns to normal, opposite, or center.
524 Alignment align = paraAlign;
525 if (align == Alignment.ALIGN_LEFT) {
526 align = (dir == DIR_LEFT_TO_RIGHT) ?
527 Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
528 } else if (align == Alignment.ALIGN_RIGHT) {
529 align = (dir == DIR_LEFT_TO_RIGHT) ?
530 Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
534 final int indentWidth;
535 if (align == Alignment.ALIGN_NORMAL) {
536 if (dir == DIR_LEFT_TO_RIGHT) {
537 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
538 x = left + indentWidth;
540 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
541 x = right - indentWidth;
544 int max = (int)getLineExtent(lineNum, tabStops, false);
545 if (align == Alignment.ALIGN_OPPOSITE) {
546 if (dir == DIR_LEFT_TO_RIGHT) {
547 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
548 x = right - max - indentWidth;
550 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
551 x = left - max + indentWidth;
553 } else { // Alignment.ALIGN_CENTER
554 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
556 x = ((right + left - max) >> 1) + indentWidth;
560 Directions directions = getLineDirections(lineNum);
561 if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTab && !justify) {
562 // XXX: assumes there's nothing additional to be done
563 canvas.drawText(buf, start, end, x, lbaseline, paint);
565 tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops,
566 getEllipsisStart(lineNum),
567 getEllipsisStart(lineNum) + getEllipsisCount(lineNum));
569 tl.justify(right - left - indentWidth);
571 tl.draw(canvas, x, ltop, lbaseline, lbottom);
575 TextLine.recycle(tl);
581 public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
582 int cursorOffsetVertical, int firstLine, int lastLine) {
583 // First, draw LineBackgroundSpans.
584 // LineBackgroundSpans know nothing about the alignment, margins, or
585 // direction of the layout or line. XXX: Should they?
586 // They are evaluated at each line.
588 if (mLineBackgroundSpans == null) {
589 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
592 Spanned buffer = (Spanned) mText;
593 int textLength = buffer.length();
594 mLineBackgroundSpans.init(buffer, 0, textLength);
596 if (mLineBackgroundSpans.numberOfSpans > 0) {
597 int previousLineBottom = getLineTop(firstLine);
598 int previousLineEnd = getLineStart(firstLine);
599 ParagraphStyle[] spans = NO_PARA_SPANS;
601 TextPaint paint = mPaint;
603 final int width = mWidth;
604 for (int i = firstLine; i <= lastLine; i++) {
605 int start = previousLineEnd;
606 int end = getLineStart(i + 1);
607 previousLineEnd = end;
609 int ltop = previousLineBottom;
610 int lbottom = getLineTop(i + 1);
611 previousLineBottom = lbottom;
612 int lbaseline = lbottom - getLineDescent(i);
614 if (start >= spanEnd) {
615 // These should be infrequent, so we'll use this so that
616 // we don't have to check as often.
617 spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
618 // All LineBackgroundSpans on a line contribute to its background.
620 // Duplication of the logic of getParagraphSpans
621 if (start != end || start == 0) {
622 // Equivalent to a getSpans(start, end), but filling the 'spans' local
623 // array instead to reduce memory allocation
624 for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
625 // equal test is valid since both intervals are not empty by
627 if (mLineBackgroundSpans.spanStarts[j] >= end ||
628 mLineBackgroundSpans.spanEnds[j] <= start) continue;
629 spans = GrowingArrayUtils.append(
630 spans, spansLength, mLineBackgroundSpans.spans[j]);
636 for (int n = 0; n < spansLength; n++) {
637 LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
638 lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
639 ltop, lbaseline, lbottom,
640 buffer, start, end, i);
644 mLineBackgroundSpans.recycle();
647 // There can be a highlight even without spans if we are drawing
648 // a non-spanned transformation of a spanned editing buffer.
649 if (highlight != null) {
650 if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
651 canvas.drawPath(highlight, highlightPaint);
652 if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
658 * @return The range of lines that need to be drawn, possibly empty.
661 public long getLineRangeForDraw(Canvas canvas) {
664 synchronized (sTempRect) {
665 if (!canvas.getClipBounds(sTempRect)) {
666 // Negative range end used as a special flag
667 return TextUtils.packRangeInLong(0, -1);
670 dtop = sTempRect.top;
671 dbottom = sTempRect.bottom;
674 final int top = Math.max(dtop, 0);
675 final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
677 if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
678 return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
682 * Return the start position of the line, given the left and right bounds
685 * @param line the line index
686 * @param left the left bounds (0, or leading margin if ltr para)
687 * @param right the right bounds (width, minus leading margin if rtl para)
688 * @return the start position of the line (to right of line if rtl para)
690 private int getLineStartPos(int line, int left, int right) {
691 // Adjust the point at which to start rendering depending on the
692 // alignment of the paragraph.
693 Alignment align = getParagraphAlignment(line);
694 int dir = getParagraphDirection(line);
696 if (align == Alignment.ALIGN_LEFT) {
697 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
698 } else if (align == Alignment.ALIGN_RIGHT) {
699 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
703 if (align == Alignment.ALIGN_NORMAL) {
704 if (dir == DIR_LEFT_TO_RIGHT) {
705 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
707 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
710 TabStops tabStops = null;
711 if (mSpannedText && getLineContainsTab(line)) {
712 Spanned spanned = (Spanned) mText;
713 int start = getLineStart(line);
714 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
716 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
718 if (tabSpans.length > 0) {
719 tabStops = new TabStops(TAB_INCREMENT, tabSpans);
722 int max = (int)getLineExtent(line, tabStops, false);
723 if (align == Alignment.ALIGN_OPPOSITE) {
724 if (dir == DIR_LEFT_TO_RIGHT) {
725 x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
727 // max is negative here
728 x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
730 } else { // Alignment.ALIGN_CENTER
732 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
739 * Return the text that is displayed by this Layout.
741 public final CharSequence getText() {
746 * Return the base Paint properties for this layout.
747 * Do NOT change the paint, which may result in funny
748 * drawing for this layout.
750 public final TextPaint getPaint() {
755 * Return the width of this layout.
757 public final int getWidth() {
762 * Return the width to which this Layout is ellipsizing, or
763 * {@link #getWidth} if it is not doing anything special.
765 public int getEllipsizedWidth() {
770 * Increase the width of this layout to the specified width.
771 * Be careful to use this only when you know it is appropriate—
772 * it does not cause the text to reflow to use the full new width.
774 public final void increaseWidthTo(int wid) {
776 throw new RuntimeException("attempted to reduce Layout width");
783 * Return the total height of this layout.
785 public int getHeight() {
786 return getLineTop(getLineCount());
790 * Return the total height of this layout.
792 * @param cap if true and max lines is set, returns the height of the layout at the max lines.
796 public int getHeight(boolean cap) {
801 * Return the base alignment of this layout.
803 public final Alignment getAlignment() {
808 * Return what the text height is multiplied by to get the line height.
810 public final float getSpacingMultiplier() {
815 * Return the number of units of leading that are added to each line.
817 public final float getSpacingAdd() {
822 * Return the heuristic used to determine paragraph text direction.
825 public final TextDirectionHeuristic getTextDirectionHeuristic() {
830 * Return the number of lines of text in this layout.
832 public abstract int getLineCount();
835 * Return the baseline for the specified line (0…getLineCount() - 1)
836 * If bounds is not null, return the top, left, right, bottom extents
837 * of the specified line in it.
838 * @param line which line to examine (0..getLineCount() - 1)
839 * @param bounds Optional. If not null, it returns the extent of the line
840 * @return the Y-coordinate of the baseline
842 public int getLineBounds(int line, Rect bounds) {
843 if (bounds != null) {
844 bounds.left = 0; // ???
845 bounds.top = getLineTop(line);
846 bounds.right = mWidth; // ???
847 bounds.bottom = getLineTop(line + 1);
849 return getLineBaseline(line);
853 * Return the vertical position of the top of the specified line
854 * (0…getLineCount()).
855 * If the specified line is equal to the line count, returns the
856 * bottom of the last line.
858 public abstract int getLineTop(int line);
861 * Return the descent of the specified line(0…getLineCount() - 1).
863 public abstract int getLineDescent(int line);
866 * Return the text offset of the beginning of the specified line (
867 * 0…getLineCount()). If the specified line is equal to the line
868 * count, returns the length of the text.
870 public abstract int getLineStart(int line);
873 * Returns the primary directionality of the paragraph containing the
874 * specified line, either 1 for left-to-right lines, or -1 for right-to-left
875 * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
877 public abstract int getParagraphDirection(int line);
880 * Returns whether the specified line contains one or more
881 * characters that need to be handled specially, like tabs.
883 public abstract boolean getLineContainsTab(int line);
886 * Returns the directional run information for the specified line.
887 * The array alternates counts of characters in left-to-right
888 * and right-to-left segments of the line.
890 * <p>NOTE: this is inadequate to support bidirectional text, and will change.
892 public abstract Directions getLineDirections(int line);
895 * Returns the (negative) number of extra pixels of ascent padding in the
896 * top line of the Layout.
898 public abstract int getTopPadding();
901 * Returns the number of extra pixels of descent padding in the
902 * bottom line of the Layout.
904 public abstract int getBottomPadding();
907 * Returns the hyphen edit for a line.
911 public int getHyphen(int line) {
916 * Returns the left indent for a line.
920 public int getIndentAdjust(int line, Alignment alignment) {
925 * Returns true if the character at offset and the preceding character
926 * are at different run levels (and thus there's a split caret).
927 * @param offset the offset
928 * @return true if at a level boundary
931 public boolean isLevelBoundary(int offset) {
932 int line = getLineForOffset(offset);
933 Directions dirs = getLineDirections(line);
934 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
938 int[] runs = dirs.mDirections;
939 int lineStart = getLineStart(line);
940 int lineEnd = getLineEnd(line);
941 if (offset == lineStart || offset == lineEnd) {
942 int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
943 int runIndex = offset == lineStart ? 0 : runs.length - 2;
944 return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
948 for (int i = 0; i < runs.length; i += 2) {
949 if (offset == runs[i]) {
957 * Returns true if the character at offset is right to left (RTL).
958 * @param offset the offset
959 * @return true if the character is RTL, false if it is LTR
961 public boolean isRtlCharAt(int offset) {
962 int line = getLineForOffset(offset);
963 Directions dirs = getLineDirections(line);
964 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
967 if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
970 int[] runs = dirs.mDirections;
971 int lineStart = getLineStart(line);
972 for (int i = 0; i < runs.length; i += 2) {
973 int start = lineStart + runs[i];
974 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
975 if (offset >= start && offset < limit) {
976 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
977 return ((level & 1) != 0);
980 // Should happen only if the offset is "out of bounds"
985 * Returns the range of the run that the character at offset belongs to.
986 * @param offset the offset
987 * @return The range of the run
990 public long getRunRange(int offset) {
991 int line = getLineForOffset(offset);
992 Directions dirs = getLineDirections(line);
993 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
994 return TextUtils.packRangeInLong(0, getLineEnd(line));
996 int[] runs = dirs.mDirections;
997 int lineStart = getLineStart(line);
998 for (int i = 0; i < runs.length; i += 2) {
999 int start = lineStart + runs[i];
1000 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1001 if (offset >= start && offset < limit) {
1002 return TextUtils.packRangeInLong(start, limit);
1005 // Should happen only if the offset is "out of bounds"
1006 return TextUtils.packRangeInLong(0, getLineEnd(line));
1010 * Checks if the trailing BiDi level should be used for an offset
1012 * This method is useful when the offset is at the BiDi level transition point and determine
1013 * which run need to be used. For example, let's think about following input: (L* denotes
1014 * Left-to-Right characters, R* denotes Right-to-Left characters.)
1015 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1016 * Input (Display Order): L1 L2 L3 R3 R2 R1 L4 L5 L6
1018 * Then, think about selecting the range (3, 6). The offset=3 and offset=6 are ambiguous here
1019 * since they are at the BiDi transition point. In Android, the offset is considered to be
1020 * associated with the trailing run if the BiDi level of the trailing run is higher than of the
1021 * previous run. In this case, the BiDi level of the input text is as follows:
1023 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1024 * BiDi Run: [ Run 0 ][ Run 1 ][ Run 2 ]
1025 * BiDi Level: 0 0 0 1 1 1 0 0 0
1027 * Thus, offset = 3 is part of Run 1 and this method returns true for offset = 3, since the BiDi
1028 * level of Run 1 is higher than the level of Run 0. Similarly, the offset = 6 is a part of Run
1029 * 1 and this method returns false for the offset = 6 since the BiDi level of Run 1 is higher
1030 * than the level of Run 2.
1032 * @returns true if offset is at the BiDi level transition point and trailing BiDi level is
1033 * higher than previous BiDi level. See above for the detail.
1037 public boolean primaryIsTrailingPrevious(int offset) {
1038 int line = getLineForOffset(offset);
1039 int lineStart = getLineStart(line);
1040 int lineEnd = getLineEnd(line);
1041 int[] runs = getLineDirections(line).mDirections;
1044 for (int i = 0; i < runs.length; i += 2) {
1045 int start = lineStart + runs[i];
1046 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1047 if (limit > lineEnd) {
1050 if (offset >= start && offset < limit) {
1051 if (offset > start) {
1052 // Previous character is at same level, so don't use trailing.
1055 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1059 if (levelAt == -1) {
1060 // Offset was limit of line.
1061 levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
1064 // At level boundary, check previous level.
1065 int levelBefore = -1;
1066 if (offset == lineStart) {
1067 levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
1070 for (int i = 0; i < runs.length; i += 2) {
1071 int start = lineStart + runs[i];
1072 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1073 if (limit > lineEnd) {
1076 if (offset >= start && offset < limit) {
1077 levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1083 return levelBefore < levelAt;
1087 * Computes in linear time the results of calling
1088 * #primaryIsTrailingPrevious for all offsets on a line.
1089 * @param line The line giving the offsets we compute the information for
1090 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1094 public boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
1095 int lineStart = getLineStart(line);
1096 int lineEnd = getLineEnd(line);
1097 int[] runs = getLineDirections(line).mDirections;
1099 boolean[] trailing = new boolean[lineEnd - lineStart + 1];
1101 byte[] level = new byte[lineEnd - lineStart + 1];
1102 for (int i = 0; i < runs.length; i += 2) {
1103 int start = lineStart + runs[i];
1104 int limit = start + (runs[i + 1] & RUN_LENGTH_MASK);
1105 if (limit > lineEnd) {
1108 level[limit - lineStart - 1] =
1109 (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1112 for (int i = 0; i < runs.length; i += 2) {
1113 int start = lineStart + runs[i];
1114 byte currentLevel = (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1115 trailing[start - lineStart] = currentLevel > (start == lineStart
1116 ? (getParagraphDirection(line) == 1 ? 0 : 1)
1117 : level[start - lineStart - 1]);
1124 * Get the primary horizontal position for the specified text offset.
1125 * This is the location where a new character would be inserted in
1126 * the paragraph's primary direction.
1128 public float getPrimaryHorizontal(int offset) {
1129 return getPrimaryHorizontal(offset, false /* not clamped */);
1133 * Get the primary horizontal position for the specified text offset, but
1134 * optionally clamp it so that it doesn't exceed the width of the layout.
1137 public float getPrimaryHorizontal(int offset, boolean clamped) {
1138 boolean trailing = primaryIsTrailingPrevious(offset);
1139 return getHorizontal(offset, trailing, clamped);
1143 * Get the secondary horizontal position for the specified text offset.
1144 * This is the location where a new character would be inserted in
1145 * the direction other than the paragraph's primary direction.
1147 public float getSecondaryHorizontal(int offset) {
1148 return getSecondaryHorizontal(offset, false /* not clamped */);
1152 * Get the secondary horizontal position for the specified text offset, but
1153 * optionally clamp it so that it doesn't exceed the width of the layout.
1156 public float getSecondaryHorizontal(int offset, boolean clamped) {
1157 boolean trailing = primaryIsTrailingPrevious(offset);
1158 return getHorizontal(offset, !trailing, clamped);
1161 private float getHorizontal(int offset, boolean primary) {
1162 return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
1165 private float getHorizontal(int offset, boolean trailing, boolean clamped) {
1166 int line = getLineForOffset(offset);
1168 return getHorizontal(offset, trailing, line, clamped);
1171 private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
1172 int start = getLineStart(line);
1173 int end = getLineEnd(line);
1174 int dir = getParagraphDirection(line);
1175 boolean hasTab = getLineContainsTab(line);
1176 Directions directions = getLineDirections(line);
1178 TabStops tabStops = null;
1179 if (hasTab && mText instanceof Spanned) {
1180 // Just checking this line should be good enough, tabs should be
1181 // consistent across all lines in a paragraph.
1182 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1183 if (tabs.length > 0) {
1184 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1188 TextLine tl = TextLine.obtain();
1189 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops,
1190 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
1191 float wid = tl.measure(offset - start, trailing, null);
1192 TextLine.recycle(tl);
1194 if (clamped && wid > mWidth) {
1197 int left = getParagraphLeft(line);
1198 int right = getParagraphRight(line);
1200 return getLineStartPos(line, left, right) + wid;
1204 * Computes in linear time the results of calling
1205 * #getHorizontal for all offsets on a line.
1206 * @param line The line giving the offsets we compute information for
1207 * @param clamped Whether to clamp the results to the width of the layout
1208 * @param primary Whether the results should be the primary or the secondary horizontal
1209 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1211 private float[] getLineHorizontals(int line, boolean clamped, boolean primary) {
1212 int start = getLineStart(line);
1213 int end = getLineEnd(line);
1214 int dir = getParagraphDirection(line);
1215 boolean hasTab = getLineContainsTab(line);
1216 Directions directions = getLineDirections(line);
1218 TabStops tabStops = null;
1219 if (hasTab && mText instanceof Spanned) {
1220 // Just checking this line should be good enough, tabs should be
1221 // consistent across all lines in a paragraph.
1222 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1223 if (tabs.length > 0) {
1224 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1228 TextLine tl = TextLine.obtain();
1229 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops,
1230 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
1231 boolean[] trailings = primaryIsTrailingPreviousAllLineOffsets(line);
1233 for (int offset = 0; offset < trailings.length; ++offset) {
1234 trailings[offset] = !trailings[offset];
1237 float[] wid = tl.measureAllOffsets(trailings, null);
1238 TextLine.recycle(tl);
1241 for (int offset = 0; offset <= wid.length; ++offset) {
1242 if (wid[offset] > mWidth) {
1243 wid[offset] = mWidth;
1247 int left = getParagraphLeft(line);
1248 int right = getParagraphRight(line);
1250 int lineStartPos = getLineStartPos(line, left, right);
1251 float[] horizontal = new float[end - start + 1];
1252 for (int offset = 0; offset < horizontal.length; ++offset) {
1253 horizontal[offset] = lineStartPos + wid[offset];
1259 * Get the leftmost position that should be exposed for horizontal
1260 * scrolling on the specified line.
1262 public float getLineLeft(int line) {
1263 int dir = getParagraphDirection(line);
1264 Alignment align = getParagraphAlignment(line);
1266 if (align == Alignment.ALIGN_LEFT) {
1268 } else if (align == Alignment.ALIGN_NORMAL) {
1269 if (dir == DIR_RIGHT_TO_LEFT)
1270 return getParagraphRight(line) - getLineMax(line);
1273 } else if (align == Alignment.ALIGN_RIGHT) {
1274 return mWidth - getLineMax(line);
1275 } else if (align == Alignment.ALIGN_OPPOSITE) {
1276 if (dir == DIR_RIGHT_TO_LEFT)
1279 return mWidth - getLineMax(line);
1280 } else { /* align == Alignment.ALIGN_CENTER */
1281 int left = getParagraphLeft(line);
1282 int right = getParagraphRight(line);
1283 int max = ((int) getLineMax(line)) & ~1;
1285 return left + ((right - left) - max) / 2;
1290 * Get the rightmost position that should be exposed for horizontal
1291 * scrolling on the specified line.
1293 public float getLineRight(int line) {
1294 int dir = getParagraphDirection(line);
1295 Alignment align = getParagraphAlignment(line);
1297 if (align == Alignment.ALIGN_LEFT) {
1298 return getParagraphLeft(line) + getLineMax(line);
1299 } else if (align == Alignment.ALIGN_NORMAL) {
1300 if (dir == DIR_RIGHT_TO_LEFT)
1303 return getParagraphLeft(line) + getLineMax(line);
1304 } else if (align == Alignment.ALIGN_RIGHT) {
1306 } else if (align == Alignment.ALIGN_OPPOSITE) {
1307 if (dir == DIR_RIGHT_TO_LEFT)
1308 return getLineMax(line);
1311 } else { /* align == Alignment.ALIGN_CENTER */
1312 int left = getParagraphLeft(line);
1313 int right = getParagraphRight(line);
1314 int max = ((int) getLineMax(line)) & ~1;
1316 return right - ((right - left) - max) / 2;
1321 * Gets the unsigned horizontal extent of the specified line, including
1322 * leading margin indent, but excluding trailing whitespace.
1324 public float getLineMax(int line) {
1325 float margin = getParagraphLeadingMargin(line);
1326 float signedExtent = getLineExtent(line, false);
1327 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1331 * Gets the unsigned horizontal extent of the specified line, including
1332 * leading margin indent and trailing whitespace.
1334 public float getLineWidth(int line) {
1335 float margin = getParagraphLeadingMargin(line);
1336 float signedExtent = getLineExtent(line, true);
1337 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1341 * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1342 * tab stops instead of using the ones passed in.
1343 * @param line the index of the line
1344 * @param full whether to include trailing whitespace
1345 * @return the extent of the line
1347 private float getLineExtent(int line, boolean full) {
1348 final int start = getLineStart(line);
1349 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1351 final boolean hasTabs = getLineContainsTab(line);
1352 TabStops tabStops = null;
1353 if (hasTabs && mText instanceof Spanned) {
1354 // Just checking this line should be good enough, tabs should be
1355 // consistent across all lines in a paragraph.
1356 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1357 if (tabs.length > 0) {
1358 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1361 final Directions directions = getLineDirections(line);
1362 // Returned directions can actually be null
1363 if (directions == null) {
1366 final int dir = getParagraphDirection(line);
1368 final TextLine tl = TextLine.obtain();
1369 final TextPaint paint = mWorkPaint;
1371 paint.setHyphenEdit(getHyphen(line));
1372 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops,
1373 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
1374 if (isJustificationRequired(line)) {
1375 tl.justify(getJustifyWidth(line));
1377 final float width = tl.metrics(null);
1378 TextLine.recycle(tl);
1383 * Returns the signed horizontal extent of the specified line, excluding
1384 * leading margin. If full is false, excludes trailing whitespace.
1385 * @param line the index of the line
1386 * @param tabStops the tab stops, can be null if we know they're not used.
1387 * @param full whether to include trailing whitespace
1388 * @return the extent of the text on this line
1390 private float getLineExtent(int line, TabStops tabStops, boolean full) {
1391 final int start = getLineStart(line);
1392 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1393 final boolean hasTabs = getLineContainsTab(line);
1394 final Directions directions = getLineDirections(line);
1395 final int dir = getParagraphDirection(line);
1397 final TextLine tl = TextLine.obtain();
1398 final TextPaint paint = mWorkPaint;
1400 paint.setHyphenEdit(getHyphen(line));
1401 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops,
1402 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
1403 if (isJustificationRequired(line)) {
1404 tl.justify(getJustifyWidth(line));
1406 final float width = tl.metrics(null);
1407 TextLine.recycle(tl);
1412 * Get the line number corresponding to the specified vertical position.
1413 * If you ask for a position above 0, you get 0; if you ask for a position
1414 * below the bottom of the text, you get the last line.
1416 // FIXME: It may be faster to do a linear search for layouts without many lines.
1417 public int getLineForVertical(int vertical) {
1418 int high = getLineCount(), low = -1, guess;
1420 while (high - low > 1) {
1421 guess = (high + low) / 2;
1423 if (getLineTop(guess) > vertical)
1436 * Get the line number on which the specified text offset appears.
1437 * If you ask for a position before 0, you get 0; if you ask for a position
1438 * beyond the end of the text, you get the last line.
1440 public int getLineForOffset(int offset) {
1441 int high = getLineCount(), low = -1, guess;
1443 while (high - low > 1) {
1444 guess = (high + low) / 2;
1446 if (getLineStart(guess) > offset)
1460 * Get the character offset on the specified line whose position is
1461 * closest to the specified horizontal position.
1463 public int getOffsetForHorizontal(int line, float horiz) {
1464 return getOffsetForHorizontal(line, horiz, true);
1468 * Get the character offset on the specified line whose position is
1469 * closest to the specified horizontal position.
1471 * @param line the line used to find the closest offset
1472 * @param horiz the horizontal position used to find the closest offset
1473 * @param primary whether to use the primary position or secondary position to find the offset
1477 public int getOffsetForHorizontal(int line, float horiz, boolean primary) {
1478 // TODO: use Paint.getOffsetForAdvance to avoid binary search
1479 final int lineEndOffset = getLineEnd(line);
1480 final int lineStartOffset = getLineStart(line);
1482 Directions dirs = getLineDirections(line);
1484 TextLine tl = TextLine.obtain();
1485 // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1486 tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
1488 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
1489 final HorizontalMeasurementProvider horizontal =
1490 new HorizontalMeasurementProvider(line, primary);
1493 if (line == getLineCount() - 1) {
1494 max = lineEndOffset;
1496 max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1497 !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
1499 int best = lineStartOffset;
1500 float bestdist = Math.abs(horizontal.get(lineStartOffset) - horiz);
1502 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1503 int here = lineStartOffset + dirs.mDirections[i];
1504 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1505 boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1506 int swap = isRtl ? -1 : 1;
1510 int high = there - 1 + 1, low = here + 1 - 1, guess;
1512 while (high - low > 1) {
1513 guess = (high + low) / 2;
1514 int adguess = getOffsetAtStartOf(guess);
1516 if (horizontal.get(adguess) * swap >= horiz * swap) {
1527 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1528 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1529 if (low >= here && low < there) {
1530 float dist = Math.abs(horizontal.get(low) - horiz);
1532 float other = Math.abs(horizontal.get(aft) - horiz);
1540 if (dist < bestdist) {
1547 float dist = Math.abs(horizontal.get(here) - horiz);
1549 if (dist < bestdist) {
1555 float dist = Math.abs(horizontal.get(max) - horiz);
1557 if (dist <= bestdist) {
1561 TextLine.recycle(tl);
1566 * Responds to #getHorizontal queries, by selecting the better strategy between:
1567 * - calling #getHorizontal explicitly for each query
1568 * - precomputing all #getHorizontal measurements, and responding to any query in constant time
1569 * The first strategy is used for LTR-only text, while the second is used for all other cases.
1570 * The class is currently only used in #getOffsetForHorizontal, so reuse with care in other
1573 private class HorizontalMeasurementProvider {
1574 private final int mLine;
1575 private final boolean mPrimary;
1577 private float[] mHorizontals;
1578 private int mLineStartOffset;
1580 HorizontalMeasurementProvider(final int line, final boolean primary) {
1586 private void init() {
1587 final Directions dirs = getLineDirections(mLine);
1588 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1592 mHorizontals = getLineHorizontals(mLine, false, mPrimary);
1593 mLineStartOffset = getLineStart(mLine);
1596 float get(final int offset) {
1597 if (mHorizontals == null || offset < 0 || offset >= mHorizontals.length) {
1598 return getHorizontal(offset, mPrimary);
1600 return mHorizontals[offset - mLineStartOffset];
1606 * Return the text offset after the last character on the specified line.
1608 public final int getLineEnd(int line) {
1609 return getLineStart(line + 1);
1613 * Return the text offset after the last visible character (so whitespace
1614 * is not counted) on the specified line.
1616 public int getLineVisibleEnd(int line) {
1617 return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1620 private int getLineVisibleEnd(int line, int start, int end) {
1621 CharSequence text = mText;
1623 if (line == getLineCount() - 1) {
1627 for (; end > start; end--) {
1628 ch = text.charAt(end - 1);
1634 if (!TextLine.isLineEndSpace(ch)) {
1644 * Return the vertical position of the bottom of the specified line.
1646 public final int getLineBottom(int line) {
1647 return getLineTop(line + 1);
1651 * Return the vertical position of the bottom of the specified line without the line spacing
1656 public final int getLineBottomWithoutSpacing(int line) {
1657 return getLineTop(line + 1) - getLineExtra(line);
1661 * Return the vertical position of the baseline of the specified line.
1663 public final int getLineBaseline(int line) {
1664 // getLineTop(line+1) == getLineTop(line)
1665 return getLineTop(line+1) - getLineDescent(line);
1669 * Get the ascent of the text on the specified line.
1670 * The return value is negative to match the Paint.ascent() convention.
1672 public final int getLineAscent(int line) {
1673 // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1674 return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1678 * Return the extra space added as a result of line spacing attributes
1679 * {@link #getSpacingAdd()} and {@link #getSpacingMultiplier()}. Default value is {@code zero}.
1681 * @param line the index of the line, the value should be equal or greater than {@code zero}
1684 public int getLineExtra(@IntRange(from = 0) int line) {
1688 public int getOffsetToLeftOf(int offset) {
1689 return getOffsetToLeftRightOf(offset, true);
1692 public int getOffsetToRightOf(int offset) {
1693 return getOffsetToLeftRightOf(offset, false);
1696 private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1697 int line = getLineForOffset(caret);
1698 int lineStart = getLineStart(line);
1699 int lineEnd = getLineEnd(line);
1700 int lineDir = getParagraphDirection(line);
1702 boolean lineChanged = false;
1703 boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
1704 // if walking off line, look at the line we're headed to
1706 if (caret == lineEnd) {
1707 if (line < getLineCount() - 1) {
1711 return caret; // at very end, don't move
1715 if (caret == lineStart) {
1720 return caret; // at very start, don't move
1726 lineStart = getLineStart(line);
1727 lineEnd = getLineEnd(line);
1728 int newDir = getParagraphDirection(line);
1729 if (newDir != lineDir) {
1730 // unusual case. we want to walk onto the line, but it runs
1731 // in a different direction than this one, so we fake movement
1732 // in the opposite direction.
1738 Directions directions = getLineDirections(line);
1740 TextLine tl = TextLine.obtain();
1741 // XXX: we don't care about tabs
1742 tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null,
1743 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
1744 caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
1745 TextLine.recycle(tl);
1749 private int getOffsetAtStartOf(int offset) {
1750 // XXX this probably should skip local reorderings and
1751 // zero-width characters, look at callers
1755 CharSequence text = mText;
1756 char c = text.charAt(offset);
1758 if (c >= '\uDC00' && c <= '\uDFFF') {
1759 char c1 = text.charAt(offset - 1);
1761 if (c1 >= '\uD800' && c1 <= '\uDBFF')
1766 ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1767 ReplacementSpan.class);
1769 for (int i = 0; i < spans.length; i++) {
1770 int start = ((Spanned) text).getSpanStart(spans[i]);
1771 int end = ((Spanned) text).getSpanEnd(spans[i]);
1773 if (start < offset && end > offset)
1782 * Determine whether we should clamp cursor position. Currently it's
1783 * only robust for left-aligned displays.
1786 public boolean shouldClampCursor(int line) {
1787 // Only clamp cursor position in left-aligned displays.
1788 switch (getParagraphAlignment(line)) {
1792 return getParagraphDirection(line) > 0;
1799 * Fills in the specified Path with a representation of a cursor
1800 * at the specified offset. This will often be a vertical line
1801 * but can be multiple discontinuous lines in text with multiple
1804 public void getCursorPath(final int point, final Path dest, final CharSequence editingBuffer) {
1807 int line = getLineForOffset(point);
1808 int top = getLineTop(line);
1809 int bottom = getLineBottomWithoutSpacing(line);
1811 boolean clamped = shouldClampCursor(line);
1812 float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1813 float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
1815 int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1816 TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1817 int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
1820 if (caps != 0 || fn != 0) {
1821 dist = (bottom - top) >> 2;
1834 if (Float.compare(h1, h2) == 0) {
1835 dest.moveTo(h1, top);
1836 dest.lineTo(h1, bottom);
1838 dest.moveTo(h1, top);
1839 dest.lineTo(h1, (top + bottom) >> 1);
1841 dest.moveTo(h2, (top + bottom) >> 1);
1842 dest.lineTo(h2, bottom);
1846 dest.moveTo(h2, bottom);
1847 dest.lineTo(h2 - dist, bottom + dist);
1848 dest.lineTo(h2, bottom);
1849 dest.lineTo(h2 + dist, bottom + dist);
1850 } else if (caps == 1) {
1851 dest.moveTo(h2, bottom);
1852 dest.lineTo(h2 - dist, bottom + dist);
1854 dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1855 dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1857 dest.moveTo(h2 + dist, bottom + dist);
1858 dest.lineTo(h2, bottom);
1862 dest.moveTo(h1, top);
1863 dest.lineTo(h1 - dist, top - dist);
1864 dest.lineTo(h1, top);
1865 dest.lineTo(h1 + dist, top - dist);
1866 } else if (fn == 1) {
1867 dest.moveTo(h1, top);
1868 dest.lineTo(h1 - dist, top - dist);
1870 dest.moveTo(h1 - dist, top - dist + 0.5f);
1871 dest.lineTo(h1 + dist, top - dist + 0.5f);
1873 dest.moveTo(h1 + dist, top - dist);
1874 dest.lineTo(h1, top);
1878 private void addSelection(int line, int start, int end,
1879 int top, int bottom, SelectionRectangleConsumer consumer) {
1880 int linestart = getLineStart(line);
1881 int lineend = getLineEnd(line);
1882 Directions dirs = getLineDirections(line);
1884 if (lineend > linestart && mText.charAt(lineend - 1) == '\n') {
1888 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1889 int here = linestart + dirs.mDirections[i];
1890 int there = here + (dirs.mDirections[i + 1] & RUN_LENGTH_MASK);
1892 if (there > lineend) {
1896 if (start <= there && end >= here) {
1897 int st = Math.max(start, here);
1898 int en = Math.min(end, there);
1901 float h1 = getHorizontal(st, false, line, false /* not clamped */);
1902 float h2 = getHorizontal(en, true, line, false /* not clamped */);
1904 float left = Math.min(h1, h2);
1905 float right = Math.max(h1, h2);
1907 final @TextSelectionLayout int layout =
1908 ((dirs.mDirections[i + 1] & RUN_RTL_FLAG) != 0)
1909 ? TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT
1910 : TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT;
1912 consumer.accept(left, top, right, bottom, layout);
1919 * Fills in the specified Path with a representation of a highlight
1920 * between the specified offsets. This will often be a rectangle
1921 * or a potentially discontinuous set of rectangles. If the start
1922 * and end are the same, the returned path is empty.
1924 public void getSelectionPath(int start, int end, Path dest) {
1926 getSelection(start, end, (left, top, right, bottom, textSelectionLayout) ->
1927 dest.addRect(left, top, right, bottom, Path.Direction.CW));
1931 * Calculates the rectangles which should be highlighted to indicate a selection between start
1932 * and end and feeds them into the given {@link SelectionRectangleConsumer}.
1934 * @param start the starting index of the selection
1935 * @param end the ending index of the selection
1936 * @param consumer the {@link SelectionRectangleConsumer} which will receive the generated
1937 * rectangles. It will be called every time a rectangle is generated.
1939 * @see #getSelectionPath(int, int, Path)
1941 public final void getSelection(int start, int end, final SelectionRectangleConsumer consumer) {
1952 final int startline = getLineForOffset(start);
1953 final int endline = getLineForOffset(end);
1955 int top = getLineTop(startline);
1956 int bottom = getLineBottomWithoutSpacing(endline);
1958 if (startline == endline) {
1959 addSelection(startline, start, end, top, bottom, consumer);
1961 final float width = mWidth;
1963 addSelection(startline, start, getLineEnd(startline),
1964 top, getLineBottom(startline), consumer);
1966 if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT) {
1967 consumer.accept(getLineLeft(startline), top, 0, getLineBottom(startline),
1968 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
1970 consumer.accept(getLineRight(startline), top, width, getLineBottom(startline),
1971 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
1974 for (int i = startline + 1; i < endline; i++) {
1975 top = getLineTop(i);
1976 bottom = getLineBottom(i);
1977 if (getParagraphDirection(i) == DIR_RIGHT_TO_LEFT) {
1978 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
1980 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
1984 top = getLineTop(endline);
1985 bottom = getLineBottomWithoutSpacing(endline);
1987 addSelection(endline, getLineStart(endline), end, top, bottom, consumer);
1989 if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT) {
1990 consumer.accept(width, top, getLineRight(endline), bottom,
1991 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
1993 consumer.accept(0, top, getLineLeft(endline), bottom,
1994 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
2000 * Get the alignment of the specified paragraph, taking into account
2001 * markup attached to it.
2003 public final Alignment getParagraphAlignment(int line) {
2004 Alignment align = mAlignment;
2007 Spanned sp = (Spanned) mText;
2008 AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
2010 AlignmentSpan.class);
2012 int spanLength = spans.length;
2013 if (spanLength > 0) {
2014 align = spans[spanLength-1].getAlignment();
2022 * Get the left edge of the specified paragraph, inset by left margins.
2024 public final int getParagraphLeft(int line) {
2026 int dir = getParagraphDirection(line);
2027 if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
2028 return left; // leading margin has no impact, or no styles
2030 return getParagraphLeadingMargin(line);
2034 * Get the right edge of the specified paragraph, inset by right margins.
2036 public final int getParagraphRight(int line) {
2038 int dir = getParagraphDirection(line);
2039 if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
2040 return right; // leading margin has no impact, or no styles
2042 return right - getParagraphLeadingMargin(line);
2046 * Returns the effective leading margin (unsigned) for this line,
2047 * taking into account LeadingMarginSpan and LeadingMarginSpan2.
2048 * @param line the line index
2049 * @return the leading margin of this line
2051 private int getParagraphLeadingMargin(int line) {
2052 if (!mSpannedText) {
2055 Spanned spanned = (Spanned) mText;
2057 int lineStart = getLineStart(line);
2058 int lineEnd = getLineEnd(line);
2059 int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
2060 LeadingMarginSpan.class);
2061 LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
2062 LeadingMarginSpan.class);
2063 if (spans.length == 0) {
2064 return 0; // no leading margin span;
2069 boolean useFirstLineMargin = lineStart == 0 || spanned.charAt(lineStart - 1) == '\n';
2070 for (int i = 0; i < spans.length; i++) {
2071 if (spans[i] instanceof LeadingMarginSpan2) {
2072 int spStart = spanned.getSpanStart(spans[i]);
2073 int spanLine = getLineForOffset(spStart);
2074 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
2075 // if there is more than one LeadingMarginSpan2, use the count that is greatest
2076 useFirstLineMargin |= line < spanLine + count;
2079 for (int i = 0; i < spans.length; i++) {
2080 LeadingMarginSpan span = spans[i];
2081 margin += span.getLeadingMargin(useFirstLineMargin);
2087 private static float measurePara(TextPaint paint, CharSequence text, int start, int end,
2088 TextDirectionHeuristic textDir) {
2089 MeasuredParagraph mt = null;
2090 TextLine tl = TextLine.obtain();
2092 mt = MeasuredParagraph.buildForBidi(text, start, end, textDir, mt);
2093 final char[] chars = mt.getChars();
2094 final int len = chars.length;
2095 final Directions directions = mt.getDirections(0, len);
2096 final int dir = mt.getParagraphDir();
2097 boolean hasTabs = false;
2098 TabStops tabStops = null;
2099 // leading margins should be taken into account when measuring a paragraph
2101 if (text instanceof Spanned) {
2102 Spanned spanned = (Spanned) text;
2103 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
2104 LeadingMarginSpan.class);
2105 for (LeadingMarginSpan lms : spans) {
2106 margin += lms.getLeadingMargin(true);
2109 for (int i = 0; i < len; ++i) {
2110 if (chars[i] == '\t') {
2112 if (text instanceof Spanned) {
2113 Spanned spanned = (Spanned) text;
2114 int spanEnd = spanned.nextSpanTransition(start, end,
2116 TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
2118 if (spans.length > 0) {
2119 tabStops = new TabStops(TAB_INCREMENT, spans);
2125 tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops,
2126 0 /* ellipsisStart */, 0 /* ellipsisEnd */);
2127 return margin + Math.abs(tl.metrics(null));
2129 TextLine.recycle(tl);
2139 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2140 public static class TabStops {
2141 private int[] mStops;
2142 private int mNumStops;
2143 private int mIncrement;
2145 public TabStops(int increment, Object[] spans) {
2146 reset(increment, spans);
2149 void reset(int increment, Object[] spans) {
2150 this.mIncrement = increment;
2153 if (spans != null) {
2154 int[] stops = this.mStops;
2155 for (Object o : spans) {
2156 if (o instanceof TabStopSpan) {
2157 if (stops == null) {
2158 stops = new int[10];
2159 } else if (ns == stops.length) {
2160 int[] nstops = new int[ns * 2];
2161 for (int i = 0; i < ns; ++i) {
2162 nstops[i] = stops[i];
2166 stops[ns++] = ((TabStopSpan) o).getTabStop();
2170 Arrays.sort(stops, 0, ns);
2172 if (stops != this.mStops) {
2173 this.mStops = stops;
2176 this.mNumStops = ns;
2179 float nextTab(float h) {
2180 int ns = this.mNumStops;
2182 int[] stops = this.mStops;
2183 for (int i = 0; i < ns; ++i) {
2184 int stop = stops[i];
2190 return nextDefaultStop(h, mIncrement);
2193 public static float nextDefaultStop(float h, int inc) {
2194 return ((int) ((h + inc) / inc)) * inc;
2199 * Returns the position of the next tab stop after h on the line.
2201 * @param text the text
2202 * @param start start of the line
2203 * @param end limit of the line
2204 * @param h the current horizontal offset
2205 * @param tabs the tabs, can be null. If it is null, any tabs in effect
2206 * on the line will be used. If there are no tabs, a default offset
2207 * will be used to compute the tab stop.
2208 * @return the offset of the next tab stop.
2210 /* package */ static float nextTab(CharSequence text, int start, int end,
2211 float h, Object[] tabs) {
2212 float nh = Float.MAX_VALUE;
2213 boolean alltabs = false;
2215 if (text instanceof Spanned) {
2217 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
2221 for (int i = 0; i < tabs.length; i++) {
2223 if (!(tabs[i] instanceof TabStopSpan))
2227 int where = ((TabStopSpan) tabs[i]).getTabStop();
2229 if (where < nh && where > h)
2233 if (nh != Float.MAX_VALUE)
2237 return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
2240 protected final boolean isSpanned() {
2241 return mSpannedText;
2245 * Returns the same as <code>text.getSpans()</code>, except where
2246 * <code>start</code> and <code>end</code> are the same and are not
2247 * at the very beginning of the text, in which case an empty array
2248 * is returned instead.
2250 * This is needed because of the special case that <code>getSpans()</code>
2251 * on an empty range returns the spans adjacent to that range, which is
2252 * primarily for the sake of <code>TextWatchers</code> so they will get
2253 * notifications when text goes from empty to non-empty. But it also
2254 * has the unfortunate side effect that if the text ends with an empty
2255 * paragraph, that paragraph accidentally picks up the styles of the
2256 * preceding paragraph (even though those styles will not be picked up
2257 * by new text that is inserted into the empty paragraph).
2259 * The reason it just checks whether <code>start</code> and <code>end</code>
2260 * is the same is that the only time a line can contain 0 characters
2261 * is if it is the final paragraph of the Layout; otherwise any line will
2262 * contain at least one printing or newline character. The reason for the
2263 * additional check if <code>start</code> is greater than 0 is that
2264 * if the empty paragraph is the entire content of the buffer, paragraph
2265 * styles that are already applied to the buffer will apply to text that
2266 * is inserted into it.
2268 /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
2269 if (start == end && start > 0) {
2270 return ArrayUtils.emptyArray(type);
2273 if(text instanceof SpannableStringBuilder) {
2274 return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2276 return text.getSpans(start, end, type);
2280 private void ellipsize(int start, int end, int line,
2281 char[] dest, int destoff, TextUtils.TruncateAt method) {
2282 final int ellipsisCount = getEllipsisCount(line);
2283 if (ellipsisCount == 0) {
2286 final int ellipsisStart = getEllipsisStart(line);
2287 final int lineStart = getLineStart(line);
2289 final String ellipsisString = TextUtils.getEllipsisString(method);
2290 final int ellipsisStringLen = ellipsisString.length();
2291 // Use the ellipsis string only if there are that at least as many characters to replace.
2292 final boolean useEllipsisString = ellipsisCount >= ellipsisStringLen;
2293 for (int i = 0; i < ellipsisCount; i++) {
2295 if (useEllipsisString && i < ellipsisStringLen) {
2296 c = ellipsisString.charAt(i);
2298 c = TextUtils.ELLIPSIS_FILLER;
2301 final int a = i + ellipsisStart + lineStart;
2302 if (start <= a && a < end) {
2303 dest[destoff + a - start] = c;
2309 * Stores information about bidirectional (left-to-right or right-to-left)
2310 * text within the layout of a line.
2312 public static class Directions {
2314 * Directions represents directional runs within a line of text. Runs are pairs of ints
2315 * listed in visual order, starting from the leading margin. The first int of each pair is
2316 * the offset from the first character of the line to the start of the run. The second int
2317 * represents both the length and level of the run. The length is in the lower bits,
2318 * accessed by masking with RUN_LENGTH_MASK. The level is in the higher bits, accessed by
2319 * shifting by RUN_LEVEL_SHIFT and masking by RUN_LEVEL_MASK. To simply test for an RTL
2320 * direction, test the bit using RUN_RTL_FLAG, if set then the direction is rtl.
2323 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2324 public int[] mDirections;
2329 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2330 public Directions(int[] dirs) {
2336 * Return the offset of the first character to be ellipsized away,
2337 * relative to the start of the line. (So 0 if the beginning of the
2338 * line is ellipsized, not getLineStart().)
2340 public abstract int getEllipsisStart(int line);
2343 * Returns the number of characters to be ellipsized away, or 0 if
2344 * no ellipsis is to take place.
2346 public abstract int getEllipsisCount(int line);
2348 /* package */ static class Ellipsizer implements CharSequence, GetChars {
2349 /* package */ CharSequence mText;
2350 /* package */ Layout mLayout;
2351 /* package */ int mWidth;
2352 /* package */ TextUtils.TruncateAt mMethod;
2354 public Ellipsizer(CharSequence s) {
2358 public char charAt(int off) {
2359 char[] buf = TextUtils.obtain(1);
2360 getChars(off, off + 1, buf, 0);
2363 TextUtils.recycle(buf);
2367 public void getChars(int start, int end, char[] dest, int destoff) {
2368 int line1 = mLayout.getLineForOffset(start);
2369 int line2 = mLayout.getLineForOffset(end);
2371 TextUtils.getChars(mText, start, end, dest, destoff);
2373 for (int i = line1; i <= line2; i++) {
2374 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
2378 public int length() {
2379 return mText.length();
2382 public CharSequence subSequence(int start, int end) {
2383 char[] s = new char[end - start];
2384 getChars(start, end, s, 0);
2385 return new String(s);
2389 public String toString() {
2390 char[] s = new char[length()];
2391 getChars(0, length(), s, 0);
2392 return new String(s);
2397 /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
2398 private Spanned mSpanned;
2400 public SpannedEllipsizer(CharSequence display) {
2402 mSpanned = (Spanned) display;
2405 public <T> T[] getSpans(int start, int end, Class<T> type) {
2406 return mSpanned.getSpans(start, end, type);
2409 public int getSpanStart(Object tag) {
2410 return mSpanned.getSpanStart(tag);
2413 public int getSpanEnd(Object tag) {
2414 return mSpanned.getSpanEnd(tag);
2417 public int getSpanFlags(Object tag) {
2418 return mSpanned.getSpanFlags(tag);
2421 @SuppressWarnings("rawtypes")
2422 public int nextSpanTransition(int start, int limit, Class type) {
2423 return mSpanned.nextSpanTransition(start, limit, type);
2427 public CharSequence subSequence(int start, int end) {
2428 char[] s = new char[end - start];
2429 getChars(start, end, s, 0);
2431 SpannableString ss = new SpannableString(new String(s));
2432 TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2437 private CharSequence mText;
2438 private TextPaint mPaint;
2439 private TextPaint mWorkPaint = new TextPaint();
2441 private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2442 private float mSpacingMult;
2443 private float mSpacingAdd;
2444 private static final Rect sTempRect = new Rect();
2445 private boolean mSpannedText;
2446 private TextDirectionHeuristic mTextDir;
2447 private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
2448 private int mJustificationMode;
2451 @IntDef(prefix = { "DIR_" }, value = {
2455 @Retention(RetentionPolicy.SOURCE)
2456 public @interface Direction {}
2458 public static final int DIR_LEFT_TO_RIGHT = 1;
2459 public static final int DIR_RIGHT_TO_LEFT = -1;
2461 /* package */ static final int DIR_REQUEST_LTR = 1;
2462 /* package */ static final int DIR_REQUEST_RTL = -1;
2463 /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2464 /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
2466 /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2467 /* package */ static final int RUN_LEVEL_SHIFT = 26;
2468 /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2469 /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2471 public enum Alignment {
2481 private static final int TAB_INCREMENT = 20;
2484 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2485 public static final Directions DIRS_ALL_LEFT_TO_RIGHT =
2486 new Directions(new int[] { 0, RUN_LENGTH_MASK });
2489 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2490 public static final Directions DIRS_ALL_RIGHT_TO_LEFT =
2491 new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });
2494 @Retention(RetentionPolicy.SOURCE)
2495 @IntDef(prefix = { "TEXT_SELECTION_LAYOUT_" }, value = {
2496 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT,
2497 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT
2499 public @interface TextSelectionLayout {}
2502 public static final int TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT = 0;
2504 public static final int TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT = 1;
2507 @FunctionalInterface
2508 public interface SelectionRectangleConsumer {
2510 * Performs this operation on the given rectangle.
2512 * @param left the left edge of the rectangle
2513 * @param top the top edge of the rectangle
2514 * @param right the right edge of the rectangle
2515 * @param bottom the bottom edge of the rectangle
2516 * @param textSelectionLayout the layout (RTL or LTR) of the text covered by this
2517 * selection rectangle
2519 void accept(float left, float top, float right, float bottom,
2520 @TextSelectionLayout int textSelectionLayout);