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);
567 tl.justify(right - left - indentWidth);
569 tl.draw(canvas, x, ltop, lbaseline, lbottom);
573 TextLine.recycle(tl);
579 public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
580 int cursorOffsetVertical, int firstLine, int lastLine) {
581 // First, draw LineBackgroundSpans.
582 // LineBackgroundSpans know nothing about the alignment, margins, or
583 // direction of the layout or line. XXX: Should they?
584 // They are evaluated at each line.
586 if (mLineBackgroundSpans == null) {
587 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
590 Spanned buffer = (Spanned) mText;
591 int textLength = buffer.length();
592 mLineBackgroundSpans.init(buffer, 0, textLength);
594 if (mLineBackgroundSpans.numberOfSpans > 0) {
595 int previousLineBottom = getLineTop(firstLine);
596 int previousLineEnd = getLineStart(firstLine);
597 ParagraphStyle[] spans = NO_PARA_SPANS;
599 TextPaint paint = mPaint;
601 final int width = mWidth;
602 for (int i = firstLine; i <= lastLine; i++) {
603 int start = previousLineEnd;
604 int end = getLineStart(i + 1);
605 previousLineEnd = end;
607 int ltop = previousLineBottom;
608 int lbottom = getLineTop(i + 1);
609 previousLineBottom = lbottom;
610 int lbaseline = lbottom - getLineDescent(i);
612 if (start >= spanEnd) {
613 // These should be infrequent, so we'll use this so that
614 // we don't have to check as often.
615 spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
616 // All LineBackgroundSpans on a line contribute to its background.
618 // Duplication of the logic of getParagraphSpans
619 if (start != end || start == 0) {
620 // Equivalent to a getSpans(start, end), but filling the 'spans' local
621 // array instead to reduce memory allocation
622 for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
623 // equal test is valid since both intervals are not empty by
625 if (mLineBackgroundSpans.spanStarts[j] >= end ||
626 mLineBackgroundSpans.spanEnds[j] <= start) continue;
627 spans = GrowingArrayUtils.append(
628 spans, spansLength, mLineBackgroundSpans.spans[j]);
634 for (int n = 0; n < spansLength; n++) {
635 LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
636 lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
637 ltop, lbaseline, lbottom,
638 buffer, start, end, i);
642 mLineBackgroundSpans.recycle();
645 // There can be a highlight even without spans if we are drawing
646 // a non-spanned transformation of a spanned editing buffer.
647 if (highlight != null) {
648 if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
649 canvas.drawPath(highlight, highlightPaint);
650 if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
656 * @return The range of lines that need to be drawn, possibly empty.
659 public long getLineRangeForDraw(Canvas canvas) {
662 synchronized (sTempRect) {
663 if (!canvas.getClipBounds(sTempRect)) {
664 // Negative range end used as a special flag
665 return TextUtils.packRangeInLong(0, -1);
668 dtop = sTempRect.top;
669 dbottom = sTempRect.bottom;
672 final int top = Math.max(dtop, 0);
673 final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
675 if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
676 return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
680 * Return the start position of the line, given the left and right bounds
683 * @param line the line index
684 * @param left the left bounds (0, or leading margin if ltr para)
685 * @param right the right bounds (width, minus leading margin if rtl para)
686 * @return the start position of the line (to right of line if rtl para)
688 private int getLineStartPos(int line, int left, int right) {
689 // Adjust the point at which to start rendering depending on the
690 // alignment of the paragraph.
691 Alignment align = getParagraphAlignment(line);
692 int dir = getParagraphDirection(line);
694 if (align == Alignment.ALIGN_LEFT) {
695 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
696 } else if (align == Alignment.ALIGN_RIGHT) {
697 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
701 if (align == Alignment.ALIGN_NORMAL) {
702 if (dir == DIR_LEFT_TO_RIGHT) {
703 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
705 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
708 TabStops tabStops = null;
709 if (mSpannedText && getLineContainsTab(line)) {
710 Spanned spanned = (Spanned) mText;
711 int start = getLineStart(line);
712 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
714 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
716 if (tabSpans.length > 0) {
717 tabStops = new TabStops(TAB_INCREMENT, tabSpans);
720 int max = (int)getLineExtent(line, tabStops, false);
721 if (align == Alignment.ALIGN_OPPOSITE) {
722 if (dir == DIR_LEFT_TO_RIGHT) {
723 x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
725 // max is negative here
726 x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
728 } else { // Alignment.ALIGN_CENTER
730 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
737 * Return the text that is displayed by this Layout.
739 public final CharSequence getText() {
744 * Return the base Paint properties for this layout.
745 * Do NOT change the paint, which may result in funny
746 * drawing for this layout.
748 public final TextPaint getPaint() {
753 * Return the width of this layout.
755 public final int getWidth() {
760 * Return the width to which this Layout is ellipsizing, or
761 * {@link #getWidth} if it is not doing anything special.
763 public int getEllipsizedWidth() {
768 * Increase the width of this layout to the specified width.
769 * Be careful to use this only when you know it is appropriate—
770 * it does not cause the text to reflow to use the full new width.
772 public final void increaseWidthTo(int wid) {
774 throw new RuntimeException("attempted to reduce Layout width");
781 * Return the total height of this layout.
783 public int getHeight() {
784 return getLineTop(getLineCount());
788 * Return the total height of this layout.
790 * @param cap if true and max lines is set, returns the height of the layout at the max lines.
794 public int getHeight(boolean cap) {
799 * Return the base alignment of this layout.
801 public final Alignment getAlignment() {
806 * Return what the text height is multiplied by to get the line height.
808 public final float getSpacingMultiplier() {
813 * Return the number of units of leading that are added to each line.
815 public final float getSpacingAdd() {
820 * Return the heuristic used to determine paragraph text direction.
823 public final TextDirectionHeuristic getTextDirectionHeuristic() {
828 * Return the number of lines of text in this layout.
830 public abstract int getLineCount();
833 * Return the baseline for the specified line (0…getLineCount() - 1)
834 * If bounds is not null, return the top, left, right, bottom extents
835 * of the specified line in it.
836 * @param line which line to examine (0..getLineCount() - 1)
837 * @param bounds Optional. If not null, it returns the extent of the line
838 * @return the Y-coordinate of the baseline
840 public int getLineBounds(int line, Rect bounds) {
841 if (bounds != null) {
842 bounds.left = 0; // ???
843 bounds.top = getLineTop(line);
844 bounds.right = mWidth; // ???
845 bounds.bottom = getLineTop(line + 1);
847 return getLineBaseline(line);
851 * Return the vertical position of the top of the specified line
852 * (0…getLineCount()).
853 * If the specified line is equal to the line count, returns the
854 * bottom of the last line.
856 public abstract int getLineTop(int line);
859 * Return the descent of the specified line(0…getLineCount() - 1).
861 public abstract int getLineDescent(int line);
864 * Return the text offset of the beginning of the specified line (
865 * 0…getLineCount()). If the specified line is equal to the line
866 * count, returns the length of the text.
868 public abstract int getLineStart(int line);
871 * Returns the primary directionality of the paragraph containing the
872 * specified line, either 1 for left-to-right lines, or -1 for right-to-left
873 * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
875 public abstract int getParagraphDirection(int line);
878 * Returns whether the specified line contains one or more
879 * characters that need to be handled specially, like tabs.
881 public abstract boolean getLineContainsTab(int line);
884 * Returns the directional run information for the specified line.
885 * The array alternates counts of characters in left-to-right
886 * and right-to-left segments of the line.
888 * <p>NOTE: this is inadequate to support bidirectional text, and will change.
890 public abstract Directions getLineDirections(int line);
893 * Returns the (negative) number of extra pixels of ascent padding in the
894 * top line of the Layout.
896 public abstract int getTopPadding();
899 * Returns the number of extra pixels of descent padding in the
900 * bottom line of the Layout.
902 public abstract int getBottomPadding();
905 * Returns the hyphen edit for a line.
909 public int getHyphen(int line) {
914 * Returns the left indent for a line.
918 public int getIndentAdjust(int line, Alignment alignment) {
923 * Returns true if the character at offset and the preceding character
924 * are at different run levels (and thus there's a split caret).
925 * @param offset the offset
926 * @return true if at a level boundary
929 public boolean isLevelBoundary(int offset) {
930 int line = getLineForOffset(offset);
931 Directions dirs = getLineDirections(line);
932 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
936 int[] runs = dirs.mDirections;
937 int lineStart = getLineStart(line);
938 int lineEnd = getLineEnd(line);
939 if (offset == lineStart || offset == lineEnd) {
940 int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
941 int runIndex = offset == lineStart ? 0 : runs.length - 2;
942 return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
946 for (int i = 0; i < runs.length; i += 2) {
947 if (offset == runs[i]) {
955 * Returns true if the character at offset is right to left (RTL).
956 * @param offset the offset
957 * @return true if the character is RTL, false if it is LTR
959 public boolean isRtlCharAt(int offset) {
960 int line = getLineForOffset(offset);
961 Directions dirs = getLineDirections(line);
962 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
965 if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
968 int[] runs = dirs.mDirections;
969 int lineStart = getLineStart(line);
970 for (int i = 0; i < runs.length; i += 2) {
971 int start = lineStart + runs[i];
972 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
973 if (offset >= start && offset < limit) {
974 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
975 return ((level & 1) != 0);
978 // Should happen only if the offset is "out of bounds"
983 * Returns the range of the run that the character at offset belongs to.
984 * @param offset the offset
985 * @return The range of the run
988 public long getRunRange(int offset) {
989 int line = getLineForOffset(offset);
990 Directions dirs = getLineDirections(line);
991 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
992 return TextUtils.packRangeInLong(0, getLineEnd(line));
994 int[] runs = dirs.mDirections;
995 int lineStart = getLineStart(line);
996 for (int i = 0; i < runs.length; i += 2) {
997 int start = lineStart + runs[i];
998 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
999 if (offset >= start && offset < limit) {
1000 return TextUtils.packRangeInLong(start, limit);
1003 // Should happen only if the offset is "out of bounds"
1004 return TextUtils.packRangeInLong(0, getLineEnd(line));
1007 private boolean primaryIsTrailingPrevious(int offset) {
1008 int line = getLineForOffset(offset);
1009 int lineStart = getLineStart(line);
1010 int lineEnd = getLineEnd(line);
1011 int[] runs = getLineDirections(line).mDirections;
1014 for (int i = 0; i < runs.length; i += 2) {
1015 int start = lineStart + runs[i];
1016 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1017 if (limit > lineEnd) {
1020 if (offset >= start && offset < limit) {
1021 if (offset > start) {
1022 // Previous character is at same level, so don't use trailing.
1025 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1029 if (levelAt == -1) {
1030 // Offset was limit of line.
1031 levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
1034 // At level boundary, check previous level.
1035 int levelBefore = -1;
1036 if (offset == lineStart) {
1037 levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
1040 for (int i = 0; i < runs.length; i += 2) {
1041 int start = lineStart + runs[i];
1042 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1043 if (limit > lineEnd) {
1046 if (offset >= start && offset < limit) {
1047 levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1053 return levelBefore < levelAt;
1057 * Get the primary horizontal position for the specified text offset.
1058 * This is the location where a new character would be inserted in
1059 * the paragraph's primary direction.
1061 public float getPrimaryHorizontal(int offset) {
1062 return getPrimaryHorizontal(offset, false /* not clamped */);
1066 * Get the primary horizontal position for the specified text offset, but
1067 * optionally clamp it so that it doesn't exceed the width of the layout.
1070 public float getPrimaryHorizontal(int offset, boolean clamped) {
1071 boolean trailing = primaryIsTrailingPrevious(offset);
1072 return getHorizontal(offset, trailing, clamped);
1076 * Get the secondary horizontal position for the specified text offset.
1077 * This is the location where a new character would be inserted in
1078 * the direction other than the paragraph's primary direction.
1080 public float getSecondaryHorizontal(int offset) {
1081 return getSecondaryHorizontal(offset, false /* not clamped */);
1085 * Get the secondary horizontal position for the specified text offset, but
1086 * optionally clamp it so that it doesn't exceed the width of the layout.
1089 public float getSecondaryHorizontal(int offset, boolean clamped) {
1090 boolean trailing = primaryIsTrailingPrevious(offset);
1091 return getHorizontal(offset, !trailing, clamped);
1094 private float getHorizontal(int offset, boolean primary) {
1095 return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
1098 private float getHorizontal(int offset, boolean trailing, boolean clamped) {
1099 int line = getLineForOffset(offset);
1101 return getHorizontal(offset, trailing, line, clamped);
1104 private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
1105 int start = getLineStart(line);
1106 int end = getLineEnd(line);
1107 int dir = getParagraphDirection(line);
1108 boolean hasTab = getLineContainsTab(line);
1109 Directions directions = getLineDirections(line);
1111 TabStops tabStops = null;
1112 if (hasTab && mText instanceof Spanned) {
1113 // Just checking this line should be good enough, tabs should be
1114 // consistent across all lines in a paragraph.
1115 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1116 if (tabs.length > 0) {
1117 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1121 TextLine tl = TextLine.obtain();
1122 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
1123 float wid = tl.measure(offset - start, trailing, null);
1124 TextLine.recycle(tl);
1126 if (clamped && wid > mWidth) {
1129 int left = getParagraphLeft(line);
1130 int right = getParagraphRight(line);
1132 return getLineStartPos(line, left, right) + wid;
1136 * Get the leftmost position that should be exposed for horizontal
1137 * scrolling on the specified line.
1139 public float getLineLeft(int line) {
1140 int dir = getParagraphDirection(line);
1141 Alignment align = getParagraphAlignment(line);
1143 if (align == Alignment.ALIGN_LEFT) {
1145 } else if (align == Alignment.ALIGN_NORMAL) {
1146 if (dir == DIR_RIGHT_TO_LEFT)
1147 return getParagraphRight(line) - getLineMax(line);
1150 } else if (align == Alignment.ALIGN_RIGHT) {
1151 return mWidth - getLineMax(line);
1152 } else if (align == Alignment.ALIGN_OPPOSITE) {
1153 if (dir == DIR_RIGHT_TO_LEFT)
1156 return mWidth - getLineMax(line);
1157 } else { /* align == Alignment.ALIGN_CENTER */
1158 int left = getParagraphLeft(line);
1159 int right = getParagraphRight(line);
1160 int max = ((int) getLineMax(line)) & ~1;
1162 return left + ((right - left) - max) / 2;
1167 * Get the rightmost position that should be exposed for horizontal
1168 * scrolling on the specified line.
1170 public float getLineRight(int line) {
1171 int dir = getParagraphDirection(line);
1172 Alignment align = getParagraphAlignment(line);
1174 if (align == Alignment.ALIGN_LEFT) {
1175 return getParagraphLeft(line) + getLineMax(line);
1176 } else if (align == Alignment.ALIGN_NORMAL) {
1177 if (dir == DIR_RIGHT_TO_LEFT)
1180 return getParagraphLeft(line) + getLineMax(line);
1181 } else if (align == Alignment.ALIGN_RIGHT) {
1183 } else if (align == Alignment.ALIGN_OPPOSITE) {
1184 if (dir == DIR_RIGHT_TO_LEFT)
1185 return getLineMax(line);
1188 } else { /* align == Alignment.ALIGN_CENTER */
1189 int left = getParagraphLeft(line);
1190 int right = getParagraphRight(line);
1191 int max = ((int) getLineMax(line)) & ~1;
1193 return right - ((right - left) - max) / 2;
1198 * Gets the unsigned horizontal extent of the specified line, including
1199 * leading margin indent, but excluding trailing whitespace.
1201 public float getLineMax(int line) {
1202 float margin = getParagraphLeadingMargin(line);
1203 float signedExtent = getLineExtent(line, false);
1204 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1208 * Gets the unsigned horizontal extent of the specified line, including
1209 * leading margin indent and trailing whitespace.
1211 public float getLineWidth(int line) {
1212 float margin = getParagraphLeadingMargin(line);
1213 float signedExtent = getLineExtent(line, true);
1214 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1218 * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1219 * tab stops instead of using the ones passed in.
1220 * @param line the index of the line
1221 * @param full whether to include trailing whitespace
1222 * @return the extent of the line
1224 private float getLineExtent(int line, boolean full) {
1225 final int start = getLineStart(line);
1226 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1228 final boolean hasTabs = getLineContainsTab(line);
1229 TabStops tabStops = null;
1230 if (hasTabs && mText instanceof Spanned) {
1231 // Just checking this line should be good enough, tabs should be
1232 // consistent across all lines in a paragraph.
1233 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1234 if (tabs.length > 0) {
1235 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1238 final Directions directions = getLineDirections(line);
1239 // Returned directions can actually be null
1240 if (directions == null) {
1243 final int dir = getParagraphDirection(line);
1245 final TextLine tl = TextLine.obtain();
1246 final TextPaint paint = mWorkPaint;
1248 paint.setHyphenEdit(getHyphen(line));
1249 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops);
1250 if (isJustificationRequired(line)) {
1251 tl.justify(getJustifyWidth(line));
1253 final float width = tl.metrics(null);
1254 TextLine.recycle(tl);
1259 * Returns the signed horizontal extent of the specified line, excluding
1260 * leading margin. If full is false, excludes trailing whitespace.
1261 * @param line the index of the line
1262 * @param tabStops the tab stops, can be null if we know they're not used.
1263 * @param full whether to include trailing whitespace
1264 * @return the extent of the text on this line
1266 private float getLineExtent(int line, TabStops tabStops, boolean full) {
1267 final int start = getLineStart(line);
1268 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1269 final boolean hasTabs = getLineContainsTab(line);
1270 final Directions directions = getLineDirections(line);
1271 final int dir = getParagraphDirection(line);
1273 final TextLine tl = TextLine.obtain();
1274 final TextPaint paint = mWorkPaint;
1276 paint.setHyphenEdit(getHyphen(line));
1277 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops);
1278 if (isJustificationRequired(line)) {
1279 tl.justify(getJustifyWidth(line));
1281 final float width = tl.metrics(null);
1282 TextLine.recycle(tl);
1287 * Get the line number corresponding to the specified vertical position.
1288 * If you ask for a position above 0, you get 0; if you ask for a position
1289 * below the bottom of the text, you get the last line.
1291 // FIXME: It may be faster to do a linear search for layouts without many lines.
1292 public int getLineForVertical(int vertical) {
1293 int high = getLineCount(), low = -1, guess;
1295 while (high - low > 1) {
1296 guess = (high + low) / 2;
1298 if (getLineTop(guess) > vertical)
1311 * Get the line number on which the specified text offset appears.
1312 * If you ask for a position before 0, you get 0; if you ask for a position
1313 * beyond the end of the text, you get the last line.
1315 public int getLineForOffset(int offset) {
1316 int high = getLineCount(), low = -1, guess;
1318 while (high - low > 1) {
1319 guess = (high + low) / 2;
1321 if (getLineStart(guess) > offset)
1335 * Get the character offset on the specified line whose position is
1336 * closest to the specified horizontal position.
1338 public int getOffsetForHorizontal(int line, float horiz) {
1339 return getOffsetForHorizontal(line, horiz, true);
1343 * Get the character offset on the specified line whose position is
1344 * closest to the specified horizontal position.
1346 * @param line the line used to find the closest offset
1347 * @param horiz the horizontal position used to find the closest offset
1348 * @param primary whether to use the primary position or secondary position to find the offset
1352 public int getOffsetForHorizontal(int line, float horiz, boolean primary) {
1353 // TODO: use Paint.getOffsetForAdvance to avoid binary search
1354 final int lineEndOffset = getLineEnd(line);
1355 final int lineStartOffset = getLineStart(line);
1357 Directions dirs = getLineDirections(line);
1359 TextLine tl = TextLine.obtain();
1360 // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1361 tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
1365 if (line == getLineCount() - 1) {
1366 max = lineEndOffset;
1368 max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1369 !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
1371 int best = lineStartOffset;
1372 float bestdist = Math.abs(getHorizontal(best, primary) - horiz);
1374 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1375 int here = lineStartOffset + dirs.mDirections[i];
1376 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1377 boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1378 int swap = isRtl ? -1 : 1;
1382 int high = there - 1 + 1, low = here + 1 - 1, guess;
1384 while (high - low > 1) {
1385 guess = (high + low) / 2;
1386 int adguess = getOffsetAtStartOf(guess);
1388 if (getHorizontal(adguess, primary) * swap >= horiz * swap) {
1399 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1400 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1401 if (low >= here && low < there) {
1402 float dist = Math.abs(getHorizontal(low, primary) - horiz);
1404 float other = Math.abs(getHorizontal(aft, primary) - horiz);
1412 if (dist < bestdist) {
1419 float dist = Math.abs(getHorizontal(here, primary) - horiz);
1421 if (dist < bestdist) {
1427 float dist = Math.abs(getHorizontal(max, primary) - horiz);
1429 if (dist <= bestdist) {
1433 TextLine.recycle(tl);
1438 * Return the text offset after the last character on the specified line.
1440 public final int getLineEnd(int line) {
1441 return getLineStart(line + 1);
1445 * Return the text offset after the last visible character (so whitespace
1446 * is not counted) on the specified line.
1448 public int getLineVisibleEnd(int line) {
1449 return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1452 private int getLineVisibleEnd(int line, int start, int end) {
1453 CharSequence text = mText;
1455 if (line == getLineCount() - 1) {
1459 for (; end > start; end--) {
1460 ch = text.charAt(end - 1);
1466 if (!TextLine.isLineEndSpace(ch)) {
1476 * Return the vertical position of the bottom of the specified line.
1478 public final int getLineBottom(int line) {
1479 return getLineTop(line + 1);
1483 * Return the vertical position of the bottom of the specified line without the line spacing
1488 public final int getLineBottomWithoutSpacing(int line) {
1489 return getLineTop(line + 1) - getLineExtra(line);
1493 * Return the vertical position of the baseline of the specified line.
1495 public final int getLineBaseline(int line) {
1496 // getLineTop(line+1) == getLineTop(line)
1497 return getLineTop(line+1) - getLineDescent(line);
1501 * Get the ascent of the text on the specified line.
1502 * The return value is negative to match the Paint.ascent() convention.
1504 public final int getLineAscent(int line) {
1505 // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1506 return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1510 * Return the extra space added as a result of line spacing attributes
1511 * {@link #getSpacingAdd()} and {@link #getSpacingMultiplier()}. Default value is {@code zero}.
1513 * @param line the index of the line, the value should be equal or greater than {@code zero}
1516 public int getLineExtra(@IntRange(from = 0) int line) {
1520 public int getOffsetToLeftOf(int offset) {
1521 return getOffsetToLeftRightOf(offset, true);
1524 public int getOffsetToRightOf(int offset) {
1525 return getOffsetToLeftRightOf(offset, false);
1528 private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1529 int line = getLineForOffset(caret);
1530 int lineStart = getLineStart(line);
1531 int lineEnd = getLineEnd(line);
1532 int lineDir = getParagraphDirection(line);
1534 boolean lineChanged = false;
1535 boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
1536 // if walking off line, look at the line we're headed to
1538 if (caret == lineEnd) {
1539 if (line < getLineCount() - 1) {
1543 return caret; // at very end, don't move
1547 if (caret == lineStart) {
1552 return caret; // at very start, don't move
1558 lineStart = getLineStart(line);
1559 lineEnd = getLineEnd(line);
1560 int newDir = getParagraphDirection(line);
1561 if (newDir != lineDir) {
1562 // unusual case. we want to walk onto the line, but it runs
1563 // in a different direction than this one, so we fake movement
1564 // in the opposite direction.
1570 Directions directions = getLineDirections(line);
1572 TextLine tl = TextLine.obtain();
1573 // XXX: we don't care about tabs
1574 tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null);
1575 caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
1576 TextLine.recycle(tl);
1580 private int getOffsetAtStartOf(int offset) {
1581 // XXX this probably should skip local reorderings and
1582 // zero-width characters, look at callers
1586 CharSequence text = mText;
1587 char c = text.charAt(offset);
1589 if (c >= '\uDC00' && c <= '\uDFFF') {
1590 char c1 = text.charAt(offset - 1);
1592 if (c1 >= '\uD800' && c1 <= '\uDBFF')
1597 ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1598 ReplacementSpan.class);
1600 for (int i = 0; i < spans.length; i++) {
1601 int start = ((Spanned) text).getSpanStart(spans[i]);
1602 int end = ((Spanned) text).getSpanEnd(spans[i]);
1604 if (start < offset && end > offset)
1613 * Determine whether we should clamp cursor position. Currently it's
1614 * only robust for left-aligned displays.
1617 public boolean shouldClampCursor(int line) {
1618 // Only clamp cursor position in left-aligned displays.
1619 switch (getParagraphAlignment(line)) {
1623 return getParagraphDirection(line) > 0;
1630 * Fills in the specified Path with a representation of a cursor
1631 * at the specified offset. This will often be a vertical line
1632 * but can be multiple discontinuous lines in text with multiple
1635 public void getCursorPath(final int point, final Path dest, final CharSequence editingBuffer) {
1638 int line = getLineForOffset(point);
1639 int top = getLineTop(line);
1640 int bottom = getLineBottomWithoutSpacing(line);
1642 boolean clamped = shouldClampCursor(line);
1643 float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1644 float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
1646 int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1647 TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1648 int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
1651 if (caps != 0 || fn != 0) {
1652 dist = (bottom - top) >> 2;
1665 if (Float.compare(h1, h2) == 0) {
1666 dest.moveTo(h1, top);
1667 dest.lineTo(h1, bottom);
1669 dest.moveTo(h1, top);
1670 dest.lineTo(h1, (top + bottom) >> 1);
1672 dest.moveTo(h2, (top + bottom) >> 1);
1673 dest.lineTo(h2, bottom);
1677 dest.moveTo(h2, bottom);
1678 dest.lineTo(h2 - dist, bottom + dist);
1679 dest.lineTo(h2, bottom);
1680 dest.lineTo(h2 + dist, bottom + dist);
1681 } else if (caps == 1) {
1682 dest.moveTo(h2, bottom);
1683 dest.lineTo(h2 - dist, bottom + dist);
1685 dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1686 dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1688 dest.moveTo(h2 + dist, bottom + dist);
1689 dest.lineTo(h2, bottom);
1693 dest.moveTo(h1, top);
1694 dest.lineTo(h1 - dist, top - dist);
1695 dest.lineTo(h1, top);
1696 dest.lineTo(h1 + dist, top - dist);
1697 } else if (fn == 1) {
1698 dest.moveTo(h1, top);
1699 dest.lineTo(h1 - dist, top - dist);
1701 dest.moveTo(h1 - dist, top - dist + 0.5f);
1702 dest.lineTo(h1 + dist, top - dist + 0.5f);
1704 dest.moveTo(h1 + dist, top - dist);
1705 dest.lineTo(h1, top);
1709 private void addSelection(int line, int start, int end,
1710 int top, int bottom, SelectionRectangleConsumer consumer) {
1711 int linestart = getLineStart(line);
1712 int lineend = getLineEnd(line);
1713 Directions dirs = getLineDirections(line);
1715 if (lineend > linestart && mText.charAt(lineend - 1) == '\n') {
1719 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1720 int here = linestart + dirs.mDirections[i];
1721 int there = here + (dirs.mDirections[i + 1] & RUN_LENGTH_MASK);
1723 if (there > lineend) {
1727 if (start <= there && end >= here) {
1728 int st = Math.max(start, here);
1729 int en = Math.min(end, there);
1732 float h1 = getHorizontal(st, false, line, false /* not clamped */);
1733 float h2 = getHorizontal(en, true, line, false /* not clamped */);
1735 float left = Math.min(h1, h2);
1736 float right = Math.max(h1, h2);
1738 final @TextSelectionLayout int layout =
1739 ((dirs.mDirections[i + 1] & RUN_RTL_FLAG) != 0)
1740 ? TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT
1741 : TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT;
1743 consumer.accept(left, top, right, bottom, layout);
1750 * Fills in the specified Path with a representation of a highlight
1751 * between the specified offsets. This will often be a rectangle
1752 * or a potentially discontinuous set of rectangles. If the start
1753 * and end are the same, the returned path is empty.
1755 public void getSelectionPath(int start, int end, Path dest) {
1757 getSelection(start, end, (left, top, right, bottom, textSelectionLayout) ->
1758 dest.addRect(left, top, right, bottom, Path.Direction.CW));
1762 * Calculates the rectangles which should be highlighted to indicate a selection between start
1763 * and end and feeds them into the given {@link SelectionRectangleConsumer}.
1765 * @param start the starting index of the selection
1766 * @param end the ending index of the selection
1767 * @param consumer the {@link SelectionRectangleConsumer} which will receive the generated
1768 * rectangles. It will be called every time a rectangle is generated.
1770 * @see #getSelectionPath(int, int, Path)
1772 public final void getSelection(int start, int end, final SelectionRectangleConsumer consumer) {
1783 final int startline = getLineForOffset(start);
1784 final int endline = getLineForOffset(end);
1786 int top = getLineTop(startline);
1787 int bottom = getLineBottomWithoutSpacing(endline);
1789 if (startline == endline) {
1790 addSelection(startline, start, end, top, bottom, consumer);
1792 final float width = mWidth;
1794 addSelection(startline, start, getLineEnd(startline),
1795 top, getLineBottom(startline), consumer);
1797 if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT) {
1798 consumer.accept(getLineLeft(startline), top, 0, getLineBottom(startline),
1799 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
1801 consumer.accept(getLineRight(startline), top, width, getLineBottom(startline),
1802 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
1805 for (int i = startline + 1; i < endline; i++) {
1806 top = getLineTop(i);
1807 bottom = getLineBottom(i);
1808 if (getParagraphDirection(i) == DIR_RIGHT_TO_LEFT) {
1809 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
1811 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
1815 top = getLineTop(endline);
1816 bottom = getLineBottomWithoutSpacing(endline);
1818 addSelection(endline, getLineStart(endline), end, top, bottom, consumer);
1820 if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT) {
1821 consumer.accept(width, top, getLineRight(endline), bottom,
1822 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
1824 consumer.accept(0, top, getLineLeft(endline), bottom,
1825 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
1831 * Get the alignment of the specified paragraph, taking into account
1832 * markup attached to it.
1834 public final Alignment getParagraphAlignment(int line) {
1835 Alignment align = mAlignment;
1838 Spanned sp = (Spanned) mText;
1839 AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
1841 AlignmentSpan.class);
1843 int spanLength = spans.length;
1844 if (spanLength > 0) {
1845 align = spans[spanLength-1].getAlignment();
1853 * Get the left edge of the specified paragraph, inset by left margins.
1855 public final int getParagraphLeft(int line) {
1857 int dir = getParagraphDirection(line);
1858 if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
1859 return left; // leading margin has no impact, or no styles
1861 return getParagraphLeadingMargin(line);
1865 * Get the right edge of the specified paragraph, inset by right margins.
1867 public final int getParagraphRight(int line) {
1869 int dir = getParagraphDirection(line);
1870 if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
1871 return right; // leading margin has no impact, or no styles
1873 return right - getParagraphLeadingMargin(line);
1877 * Returns the effective leading margin (unsigned) for this line,
1878 * taking into account LeadingMarginSpan and LeadingMarginSpan2.
1879 * @param line the line index
1880 * @return the leading margin of this line
1882 private int getParagraphLeadingMargin(int line) {
1883 if (!mSpannedText) {
1886 Spanned spanned = (Spanned) mText;
1888 int lineStart = getLineStart(line);
1889 int lineEnd = getLineEnd(line);
1890 int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
1891 LeadingMarginSpan.class);
1892 LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
1893 LeadingMarginSpan.class);
1894 if (spans.length == 0) {
1895 return 0; // no leading margin span;
1900 boolean useFirstLineMargin = lineStart == 0 || spanned.charAt(lineStart - 1) == '\n';
1901 for (int i = 0; i < spans.length; i++) {
1902 if (spans[i] instanceof LeadingMarginSpan2) {
1903 int spStart = spanned.getSpanStart(spans[i]);
1904 int spanLine = getLineForOffset(spStart);
1905 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
1906 // if there is more than one LeadingMarginSpan2, use the count that is greatest
1907 useFirstLineMargin |= line < spanLine + count;
1910 for (int i = 0; i < spans.length; i++) {
1911 LeadingMarginSpan span = spans[i];
1912 margin += span.getLeadingMargin(useFirstLineMargin);
1918 private static float measurePara(TextPaint paint, CharSequence text, int start, int end,
1919 TextDirectionHeuristic textDir) {
1920 MeasuredParagraph mt = null;
1921 TextLine tl = TextLine.obtain();
1923 mt = MeasuredParagraph.buildForBidi(text, start, end, textDir, mt);
1924 final char[] chars = mt.getChars();
1925 final int len = chars.length;
1926 final Directions directions = mt.getDirections(0, len);
1927 final int dir = mt.getParagraphDir();
1928 boolean hasTabs = false;
1929 TabStops tabStops = null;
1930 // leading margins should be taken into account when measuring a paragraph
1932 if (text instanceof Spanned) {
1933 Spanned spanned = (Spanned) text;
1934 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
1935 LeadingMarginSpan.class);
1936 for (LeadingMarginSpan lms : spans) {
1937 margin += lms.getLeadingMargin(true);
1940 for (int i = 0; i < len; ++i) {
1941 if (chars[i] == '\t') {
1943 if (text instanceof Spanned) {
1944 Spanned spanned = (Spanned) text;
1945 int spanEnd = spanned.nextSpanTransition(start, end,
1947 TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
1949 if (spans.length > 0) {
1950 tabStops = new TabStops(TAB_INCREMENT, spans);
1956 tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops);
1957 return margin + Math.abs(tl.metrics(null));
1959 TextLine.recycle(tl);
1969 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1970 public static class TabStops {
1971 private int[] mStops;
1972 private int mNumStops;
1973 private int mIncrement;
1975 public TabStops(int increment, Object[] spans) {
1976 reset(increment, spans);
1979 void reset(int increment, Object[] spans) {
1980 this.mIncrement = increment;
1983 if (spans != null) {
1984 int[] stops = this.mStops;
1985 for (Object o : spans) {
1986 if (o instanceof TabStopSpan) {
1987 if (stops == null) {
1988 stops = new int[10];
1989 } else if (ns == stops.length) {
1990 int[] nstops = new int[ns * 2];
1991 for (int i = 0; i < ns; ++i) {
1992 nstops[i] = stops[i];
1996 stops[ns++] = ((TabStopSpan) o).getTabStop();
2000 Arrays.sort(stops, 0, ns);
2002 if (stops != this.mStops) {
2003 this.mStops = stops;
2006 this.mNumStops = ns;
2009 float nextTab(float h) {
2010 int ns = this.mNumStops;
2012 int[] stops = this.mStops;
2013 for (int i = 0; i < ns; ++i) {
2014 int stop = stops[i];
2020 return nextDefaultStop(h, mIncrement);
2023 public static float nextDefaultStop(float h, int inc) {
2024 return ((int) ((h + inc) / inc)) * inc;
2029 * Returns the position of the next tab stop after h on the line.
2031 * @param text the text
2032 * @param start start of the line
2033 * @param end limit of the line
2034 * @param h the current horizontal offset
2035 * @param tabs the tabs, can be null. If it is null, any tabs in effect
2036 * on the line will be used. If there are no tabs, a default offset
2037 * will be used to compute the tab stop.
2038 * @return the offset of the next tab stop.
2040 /* package */ static float nextTab(CharSequence text, int start, int end,
2041 float h, Object[] tabs) {
2042 float nh = Float.MAX_VALUE;
2043 boolean alltabs = false;
2045 if (text instanceof Spanned) {
2047 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
2051 for (int i = 0; i < tabs.length; i++) {
2053 if (!(tabs[i] instanceof TabStopSpan))
2057 int where = ((TabStopSpan) tabs[i]).getTabStop();
2059 if (where < nh && where > h)
2063 if (nh != Float.MAX_VALUE)
2067 return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
2070 protected final boolean isSpanned() {
2071 return mSpannedText;
2075 * Returns the same as <code>text.getSpans()</code>, except where
2076 * <code>start</code> and <code>end</code> are the same and are not
2077 * at the very beginning of the text, in which case an empty array
2078 * is returned instead.
2080 * This is needed because of the special case that <code>getSpans()</code>
2081 * on an empty range returns the spans adjacent to that range, which is
2082 * primarily for the sake of <code>TextWatchers</code> so they will get
2083 * notifications when text goes from empty to non-empty. But it also
2084 * has the unfortunate side effect that if the text ends with an empty
2085 * paragraph, that paragraph accidentally picks up the styles of the
2086 * preceding paragraph (even though those styles will not be picked up
2087 * by new text that is inserted into the empty paragraph).
2089 * The reason it just checks whether <code>start</code> and <code>end</code>
2090 * is the same is that the only time a line can contain 0 characters
2091 * is if it is the final paragraph of the Layout; otherwise any line will
2092 * contain at least one printing or newline character. The reason for the
2093 * additional check if <code>start</code> is greater than 0 is that
2094 * if the empty paragraph is the entire content of the buffer, paragraph
2095 * styles that are already applied to the buffer will apply to text that
2096 * is inserted into it.
2098 /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
2099 if (start == end && start > 0) {
2100 return ArrayUtils.emptyArray(type);
2103 if(text instanceof SpannableStringBuilder) {
2104 return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2106 return text.getSpans(start, end, type);
2110 private void ellipsize(int start, int end, int line,
2111 char[] dest, int destoff, TextUtils.TruncateAt method) {
2112 final int ellipsisCount = getEllipsisCount(line);
2113 if (ellipsisCount == 0) {
2116 final int ellipsisStart = getEllipsisStart(line);
2117 final int lineStart = getLineStart(line);
2119 final String ellipsisString = TextUtils.getEllipsisString(method);
2120 final int ellipsisStringLen = ellipsisString.length();
2121 // Use the ellipsis string only if there are that at least as many characters to replace.
2122 final boolean useEllipsisString = ellipsisCount >= ellipsisStringLen;
2123 for (int i = 0; i < ellipsisCount; i++) {
2125 if (useEllipsisString && i < ellipsisStringLen) {
2126 c = ellipsisString.charAt(i);
2128 c = TextUtils.ELLIPSIS_FILLER;
2131 final int a = i + ellipsisStart + lineStart;
2132 if (start <= a && a < end) {
2133 dest[destoff + a - start] = c;
2139 * Stores information about bidirectional (left-to-right or right-to-left)
2140 * text within the layout of a line.
2142 public static class Directions {
2144 * Directions represents directional runs within a line of text. Runs are pairs of ints
2145 * listed in visual order, starting from the leading margin. The first int of each pair is
2146 * the offset from the first character of the line to the start of the run. The second int
2147 * represents both the length and level of the run. The length is in the lower bits,
2148 * accessed by masking with RUN_LENGTH_MASK. The level is in the higher bits, accessed by
2149 * shifting by RUN_LEVEL_SHIFT and masking by RUN_LEVEL_MASK. To simply test for an RTL
2150 * direction, test the bit using RUN_RTL_FLAG, if set then the direction is rtl.
2153 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2154 public int[] mDirections;
2159 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2160 public Directions(int[] dirs) {
2166 * Return the offset of the first character to be ellipsized away,
2167 * relative to the start of the line. (So 0 if the beginning of the
2168 * line is ellipsized, not getLineStart().)
2170 public abstract int getEllipsisStart(int line);
2173 * Returns the number of characters to be ellipsized away, or 0 if
2174 * no ellipsis is to take place.
2176 public abstract int getEllipsisCount(int line);
2178 /* package */ static class Ellipsizer implements CharSequence, GetChars {
2179 /* package */ CharSequence mText;
2180 /* package */ Layout mLayout;
2181 /* package */ int mWidth;
2182 /* package */ TextUtils.TruncateAt mMethod;
2184 public Ellipsizer(CharSequence s) {
2188 public char charAt(int off) {
2189 char[] buf = TextUtils.obtain(1);
2190 getChars(off, off + 1, buf, 0);
2193 TextUtils.recycle(buf);
2197 public void getChars(int start, int end, char[] dest, int destoff) {
2198 int line1 = mLayout.getLineForOffset(start);
2199 int line2 = mLayout.getLineForOffset(end);
2201 TextUtils.getChars(mText, start, end, dest, destoff);
2203 for (int i = line1; i <= line2; i++) {
2204 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
2208 public int length() {
2209 return mText.length();
2212 public CharSequence subSequence(int start, int end) {
2213 char[] s = new char[end - start];
2214 getChars(start, end, s, 0);
2215 return new String(s);
2219 public String toString() {
2220 char[] s = new char[length()];
2221 getChars(0, length(), s, 0);
2222 return new String(s);
2227 /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
2228 private Spanned mSpanned;
2230 public SpannedEllipsizer(CharSequence display) {
2232 mSpanned = (Spanned) display;
2235 public <T> T[] getSpans(int start, int end, Class<T> type) {
2236 return mSpanned.getSpans(start, end, type);
2239 public int getSpanStart(Object tag) {
2240 return mSpanned.getSpanStart(tag);
2243 public int getSpanEnd(Object tag) {
2244 return mSpanned.getSpanEnd(tag);
2247 public int getSpanFlags(Object tag) {
2248 return mSpanned.getSpanFlags(tag);
2251 @SuppressWarnings("rawtypes")
2252 public int nextSpanTransition(int start, int limit, Class type) {
2253 return mSpanned.nextSpanTransition(start, limit, type);
2257 public CharSequence subSequence(int start, int end) {
2258 char[] s = new char[end - start];
2259 getChars(start, end, s, 0);
2261 SpannableString ss = new SpannableString(new String(s));
2262 TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2267 private CharSequence mText;
2268 private TextPaint mPaint;
2269 private TextPaint mWorkPaint = new TextPaint();
2271 private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2272 private float mSpacingMult;
2273 private float mSpacingAdd;
2274 private static final Rect sTempRect = new Rect();
2275 private boolean mSpannedText;
2276 private TextDirectionHeuristic mTextDir;
2277 private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
2278 private int mJustificationMode;
2281 @IntDef(prefix = { "DIR_" }, value = {
2285 @Retention(RetentionPolicy.SOURCE)
2286 public @interface Direction {}
2288 public static final int DIR_LEFT_TO_RIGHT = 1;
2289 public static final int DIR_RIGHT_TO_LEFT = -1;
2291 /* package */ static final int DIR_REQUEST_LTR = 1;
2292 /* package */ static final int DIR_REQUEST_RTL = -1;
2293 /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2294 /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
2296 /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2297 /* package */ static final int RUN_LEVEL_SHIFT = 26;
2298 /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2299 /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2301 public enum Alignment {
2311 private static final int TAB_INCREMENT = 20;
2314 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2315 public static final Directions DIRS_ALL_LEFT_TO_RIGHT =
2316 new Directions(new int[] { 0, RUN_LENGTH_MASK });
2319 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2320 public static final Directions DIRS_ALL_RIGHT_TO_LEFT =
2321 new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });
2324 @Retention(RetentionPolicy.SOURCE)
2325 @IntDef(prefix = { "TEXT_SELECTION_LAYOUT_" }, value = {
2326 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT,
2327 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT
2329 public @interface TextSelectionLayout {}
2332 public static final int TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT = 0;
2334 public static final int TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT = 1;
2337 @FunctionalInterface
2338 public interface SelectionRectangleConsumer {
2340 * Performs this operation on the given rectangle.
2342 * @param left the left edge of the rectangle
2343 * @param top the top edge of the rectangle
2344 * @param right the right edge of the rectangle
2345 * @param bottom the bottom edge of the rectangle
2346 * @param textSelectionLayout the layout (RTL or LTR) of the text covered by this
2347 * selection rectangle
2349 void accept(float left, float top, float right, float bottom,
2350 @TextSelectionLayout int textSelectionLayout);