OSDN Git Service

Fix crash during cursor moving on BiDi text
[android-x86/frameworks-base.git] / core / java / android / text / Layout.java
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package android.text;
18
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;
33
34 import com.android.internal.annotations.VisibleForTesting;
35 import com.android.internal.util.ArrayUtils;
36 import com.android.internal.util.GrowingArrayUtils;
37
38 import java.lang.annotation.Retention;
39 import java.lang.annotation.RetentionPolicy;
40 import java.util.Arrays;
41
42 /**
43  * A base class that manages text layout in visual elements on
44  * the screen.
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}.
48  */
49 public abstract class Layout {
50     /** @hide */
51     @IntDef(prefix = { "BREAK_STRATEGY_" }, value = {
52             BREAK_STRATEGY_SIMPLE,
53             BREAK_STRATEGY_HIGH_QUALITY,
54             BREAK_STRATEGY_BALANCED
55     })
56     @Retention(RetentionPolicy.SOURCE)
57     public @interface BreakStrategy {}
58
59     /**
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.
64      */
65     public static final int BREAK_STRATEGY_SIMPLE = 0;
66
67     /**
68      * Value for break strategy indicating high quality line breaking, including automatic
69      * hyphenation and doing whole-paragraph optimization of line breaks.
70      */
71     public static final int BREAK_STRATEGY_HIGH_QUALITY = 1;
72
73     /**
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.
76      */
77     public static final int BREAK_STRATEGY_BALANCED = 2;
78
79     /** @hide */
80     @IntDef(prefix = { "HYPHENATION_FREQUENCY_" }, value = {
81             HYPHENATION_FREQUENCY_NORMAL,
82             HYPHENATION_FREQUENCY_FULL,
83             HYPHENATION_FREQUENCY_NONE
84     })
85     @Retention(RetentionPolicy.SOURCE)
86     public @interface HyphenationFrequency {}
87
88     /**
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.
94      */
95     public static final int HYPHENATION_FREQUENCY_NONE = 0;
96
97     /**
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
100      * messages.
101      */
102     public static final int HYPHENATION_FREQUENCY_NORMAL = 1;
103
104     /**
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.
108      */
109     public static final int HYPHENATION_FREQUENCY_FULL = 2;
110
111     private static final ParagraphStyle[] NO_PARA_SPANS =
112         ArrayUtils.emptyArray(ParagraphStyle.class);
113
114     /** @hide */
115     @IntDef(prefix = { "JUSTIFICATION_MODE_" }, value = {
116             JUSTIFICATION_MODE_NONE,
117             JUSTIFICATION_MODE_INTER_WORD
118     })
119     @Retention(RetentionPolicy.SOURCE)
120     public @interface JustificationMode {}
121
122     /**
123      * Value for justification mode indicating no justification.
124      */
125     public static final int JUSTIFICATION_MODE_NONE = 0;
126
127     /**
128      * Value for justification mode indicating the text is justified by stretching word spacing.
129      */
130     public static final int JUSTIFICATION_MODE_INTER_WORD = 1;
131
132     /*
133      * Line spacing multiplier for default line spacing.
134      */
135     public static final float DEFAULT_LINESPACING_MULTIPLIER = 1.0f;
136
137     /*
138      * Line spacing addition for default line spacing.
139      */
140     public static final float DEFAULT_LINESPACING_ADDITION = 0.0f;
141
142     /**
143      * Return how wide a layout must be in order to display the specified text with one line per
144      * paragraph.
145      *
146      * <p>As of O, Uses
147      * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
148      * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
149      */
150     public static float getDesiredWidth(CharSequence source,
151                                         TextPaint paint) {
152         return getDesiredWidth(source, 0, source.length(), paint);
153     }
154
155     /**
156      * Return how wide a layout must be in order to display the specified text slice with one
157      * line per paragraph.
158      *
159      * <p>As of O, Uses
160      * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
161      * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
162      */
163     public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint) {
164         return getDesiredWidth(source, start, end, paint, TextDirectionHeuristics.FIRSTSTRONG_LTR);
165     }
166
167     /**
168      * Return how wide a layout must be in order to display the
169      * specified text slice with one line per paragraph.
170      *
171      * @hide
172      */
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);
176     }
177     /**
178      * Return how wide a layout must be in order to display the
179      * specified text slice with one line per paragraph.
180      *
181      * If the measured width exceeds given limit, returns limit value instead.
182      * @hide
183      */
184     public static float getDesiredWidthWithLimit(CharSequence source, int start, int end,
185             TextPaint paint, TextDirectionHeuristic textDir, float upperLimit) {
186         float need = 0;
187
188         int next;
189         for (int i = start; i <= end; i = next) {
190             next = TextUtils.indexOf(source, '\n', i, end);
191
192             if (next < 0)
193                 next = end;
194
195             // note, omits trailing paragraph char
196             float w = measurePara(paint, source, i, next, textDir);
197             if (w > upperLimit) {
198                 return upperLimit;
199             }
200
201             if (w > need)
202                 need = w;
203
204             next++;
205         }
206
207         return need;
208     }
209
210     /**
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
222      */
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);
228     }
229
230     /**
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
242      *
243      * @hide
244      */
245     protected Layout(CharSequence text, TextPaint paint,
246                      int width, Alignment align, TextDirectionHeuristic textDir,
247                      float spacingMult, float spacingAdd) {
248
249         if (width < 0)
250             throw new IllegalArgumentException("Layout: " + width + " < 0");
251
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.
256         if (paint != null) {
257             paint.bgColor = 0;
258             paint.baselineShift = 0;
259         }
260
261         mText = text;
262         mPaint = paint;
263         mWidth = width;
264         mAlignment = align;
265         mSpacingMult = spacingMult;
266         mSpacingAdd = spacingAdd;
267         mSpannedText = text instanceof Spanned;
268         mTextDir = textDir;
269     }
270
271     /** @hide */
272     protected void setJustificationMode(@JustificationMode int justificationMode) {
273         mJustificationMode = justificationMode;
274     }
275
276     /**
277      * Replace constructor properties of this Layout with new ones.  Be careful.
278      */
279     /* package */ void replaceWith(CharSequence text, TextPaint paint,
280                               int width, Alignment align,
281                               float spacingmult, float spacingadd) {
282         if (width < 0) {
283             throw new IllegalArgumentException("Layout: " + width + " < 0");
284         }
285
286         mText = text;
287         mPaint = paint;
288         mWidth = width;
289         mAlignment = align;
290         mSpacingMult = spacingmult;
291         mSpacingAdd = spacingadd;
292         mSpannedText = text instanceof Spanned;
293     }
294
295     /**
296      * Draw this Layout on the specified Canvas.
297      */
298     public void draw(Canvas c) {
299         draw(c, null, null, 0);
300     }
301
302     /**
303      * Draw this Layout on the specified canvas, with the highlight path drawn
304      * between the background and the text.
305      *
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
311      */
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;
318
319         drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
320                 firstLine, lastLine);
321         drawText(canvas, firstLine, lastLine);
322     }
323
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';
328     }
329
330     private float getJustifyWidth(int lineNum) {
331         Alignment paraAlign = mAlignment;
332
333         int left = 0;
334         int right = mWidth;
335
336         final int dir = getParagraphDirection(lineNum);
337
338         ParagraphStyle[] spans = NO_PARA_SPANS;
339         if (mSpannedText) {
340             Spanned sp = (Spanned) mText;
341             final int start = getLineStart(lineNum);
342
343             final boolean isFirstParaLine = (start == 0 || mText.charAt(start - 1) == '\n');
344
345             if (isFirstParaLine) {
346                 final int spanEnd = sp.nextSpanTransition(start, mText.length(),
347                         ParagraphStyle.class);
348                 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
349
350                 for (int n = spans.length - 1; n >= 0; n--) {
351                     if (spans[n] instanceof AlignmentSpan) {
352                         paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
353                         break;
354                     }
355                 }
356             }
357
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;
366                         break;
367                     }
368                 }
369             }
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);
375                     } else {
376                         left += margin.getLeadingMargin(useFirstLineMargin);
377                     }
378                 }
379             }
380         }
381
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;
387         } else {
388             align = paraAlign;
389         }
390
391         final int indentWidth;
392         if (align == Alignment.ALIGN_NORMAL) {
393             if (dir == DIR_LEFT_TO_RIGHT) {
394                 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
395             } else {
396                 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
397             }
398         } else if (align == Alignment.ALIGN_OPPOSITE) {
399             if (dir == DIR_LEFT_TO_RIGHT) {
400                 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
401             } else {
402                 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
403             }
404         } else { // Alignment.ALIGN_CENTER
405             indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
406         }
407
408         return right - left - indentWidth;
409     }
410
411     /**
412      * @hide
413      */
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;
418         int spanEnd = 0;
419         final TextPaint paint = mWorkPaint;
420         paint.set(mPaint);
421         CharSequence buf = mText;
422
423         Alignment paraAlign = mAlignment;
424         TabStops tabStops = null;
425         boolean tabStopsIsInitialized = false;
426
427         TextLine tl = TextLine.obtain();
428
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));
437
438             int ltop = previousLineBottom;
439             int lbottom = getLineTop(lineNum + 1);
440             previousLineBottom = lbottom;
441             int lbaseline = lbottom - getLineDescent(lineNum);
442
443             int dir = getParagraphDirection(lineNum);
444             int left = 0;
445             int right = mWidth;
446
447             if (mSpannedText) {
448                 Spanned sp = (Spanned) buf;
449                 int textLength = buf.length();
450                 boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
451
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
455                 // tabs.
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
461                 // our problem.
462                 if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
463                     spanEnd = sp.nextSpanTransition(start, textLength,
464                                                     ParagraphStyle.class);
465                     spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
466
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();
471                             break;
472                         }
473                     }
474
475                     tabStopsIsInitialized = false;
476                 }
477
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;
490                             break;
491                         }
492                     }
493                 }
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);
502                         } else {
503                             margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
504                                                      lbaseline, lbottom, buf,
505                                                      start, end, isFirstParaLine, this);
506                             left += margin.getLeadingMargin(useFirstLineMargin);
507                         }
508                     }
509                 }
510             }
511
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);
517                 } else {
518                     tabStops.reset(TAB_INCREMENT, spans);
519                 }
520                 tabStopsIsInitialized = true;
521             }
522
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;
531             }
532
533             int x;
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;
539                 } else {
540                     indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
541                     x = right - indentWidth;
542                 }
543             } else {
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;
549                     } else {
550                         indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
551                         x = left - max + indentWidth;
552                     }
553                 } else { // Alignment.ALIGN_CENTER
554                     indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
555                     max = max & ~1;
556                     x = ((right + left - max) >> 1) + indentWidth;
557                 }
558             }
559
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);
564             } else {
565                 tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops,
566                         getEllipsisStart(lineNum),
567                         getEllipsisStart(lineNum) + getEllipsisCount(lineNum));
568                 if (justify) {
569                     tl.justify(right - left - indentWidth);
570                 }
571                 tl.draw(canvas, x, ltop, lbaseline, lbottom);
572             }
573         }
574
575         TextLine.recycle(tl);
576     }
577
578     /**
579      * @hide
580      */
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.
587         if (mSpannedText) {
588             if (mLineBackgroundSpans == null) {
589                 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
590             }
591
592             Spanned buffer = (Spanned) mText;
593             int textLength = buffer.length();
594             mLineBackgroundSpans.init(buffer, 0, textLength);
595
596             if (mLineBackgroundSpans.numberOfSpans > 0) {
597                 int previousLineBottom = getLineTop(firstLine);
598                 int previousLineEnd = getLineStart(firstLine);
599                 ParagraphStyle[] spans = NO_PARA_SPANS;
600                 int spansLength = 0;
601                 TextPaint paint = mPaint;
602                 int spanEnd = 0;
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;
608
609                     int ltop = previousLineBottom;
610                     int lbottom = getLineTop(i + 1);
611                     previousLineBottom = lbottom;
612                     int lbaseline = lbottom - getLineDescent(i);
613
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.
619                         spansLength = 0;
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
626                                 // construction
627                                 if (mLineBackgroundSpans.spanStarts[j] >= end ||
628                                         mLineBackgroundSpans.spanEnds[j] <= start) continue;
629                                 spans = GrowingArrayUtils.append(
630                                         spans, spansLength, mLineBackgroundSpans.spans[j]);
631                                 spansLength++;
632                             }
633                         }
634                     }
635
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);
641                     }
642                 }
643             }
644             mLineBackgroundSpans.recycle();
645         }
646
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);
653         }
654     }
655
656     /**
657      * @param canvas
658      * @return The range of lines that need to be drawn, possibly empty.
659      * @hide
660      */
661     public long getLineRangeForDraw(Canvas canvas) {
662         int dtop, dbottom;
663
664         synchronized (sTempRect) {
665             if (!canvas.getClipBounds(sTempRect)) {
666                 // Negative range end used as a special flag
667                 return TextUtils.packRangeInLong(0, -1);
668             }
669
670             dtop = sTempRect.top;
671             dbottom = sTempRect.bottom;
672         }
673
674         final int top = Math.max(dtop, 0);
675         final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
676
677         if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
678         return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
679     }
680
681     /**
682      * Return the start position of the line, given the left and right bounds
683      * of the margins.
684      *
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)
689      */
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);
695
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;
700         }
701
702         int x;
703         if (align == Alignment.ALIGN_NORMAL) {
704             if (dir == DIR_LEFT_TO_RIGHT) {
705                 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
706             } else {
707                 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
708             }
709         } else {
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(),
715                         TabStopSpan.class);
716                 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
717                         TabStopSpan.class);
718                 if (tabSpans.length > 0) {
719                     tabStops = new TabStops(TAB_INCREMENT, tabSpans);
720                 }
721             }
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);
726                 } else {
727                     // max is negative here
728                     x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
729                 }
730             } else { // Alignment.ALIGN_CENTER
731                 max = max & ~1;
732                 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
733             }
734         }
735         return x;
736     }
737
738     /**
739      * Return the text that is displayed by this Layout.
740      */
741     public final CharSequence getText() {
742         return mText;
743     }
744
745     /**
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.
749      */
750     public final TextPaint getPaint() {
751         return mPaint;
752     }
753
754     /**
755      * Return the width of this layout.
756      */
757     public final int getWidth() {
758         return mWidth;
759     }
760
761     /**
762      * Return the width to which this Layout is ellipsizing, or
763      * {@link #getWidth} if it is not doing anything special.
764      */
765     public int getEllipsizedWidth() {
766         return mWidth;
767     }
768
769     /**
770      * Increase the width of this layout to the specified width.
771      * Be careful to use this only when you know it is appropriate&mdash;
772      * it does not cause the text to reflow to use the full new width.
773      */
774     public final void increaseWidthTo(int wid) {
775         if (wid < mWidth) {
776             throw new RuntimeException("attempted to reduce Layout width");
777         }
778
779         mWidth = wid;
780     }
781
782     /**
783      * Return the total height of this layout.
784      */
785     public int getHeight() {
786         return getLineTop(getLineCount());
787     }
788
789     /**
790      * Return the total height of this layout.
791      *
792      * @param cap if true and max lines is set, returns the height of the layout at the max lines.
793      *
794      * @hide
795      */
796     public int getHeight(boolean cap) {
797         return getHeight();
798     }
799
800     /**
801      * Return the base alignment of this layout.
802      */
803     public final Alignment getAlignment() {
804         return mAlignment;
805     }
806
807     /**
808      * Return what the text height is multiplied by to get the line height.
809      */
810     public final float getSpacingMultiplier() {
811         return mSpacingMult;
812     }
813
814     /**
815      * Return the number of units of leading that are added to each line.
816      */
817     public final float getSpacingAdd() {
818         return mSpacingAdd;
819     }
820
821     /**
822      * Return the heuristic used to determine paragraph text direction.
823      * @hide
824      */
825     public final TextDirectionHeuristic getTextDirectionHeuristic() {
826         return mTextDir;
827     }
828
829     /**
830      * Return the number of lines of text in this layout.
831      */
832     public abstract int getLineCount();
833
834     /**
835      * Return the baseline for the specified line (0&hellip;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
841      */
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);
848         }
849         return getLineBaseline(line);
850     }
851
852     /**
853      * Return the vertical position of the top of the specified line
854      * (0&hellip;getLineCount()).
855      * If the specified line is equal to the line count, returns the
856      * bottom of the last line.
857      */
858     public abstract int getLineTop(int line);
859
860     /**
861      * Return the descent of the specified line(0&hellip;getLineCount() - 1).
862      */
863     public abstract int getLineDescent(int line);
864
865     /**
866      * Return the text offset of the beginning of the specified line (
867      * 0&hellip;getLineCount()). If the specified line is equal to the line
868      * count, returns the length of the text.
869      */
870     public abstract int getLineStart(int line);
871
872     /**
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}).
876      */
877     public abstract int getParagraphDirection(int line);
878
879     /**
880      * Returns whether the specified line contains one or more
881      * characters that need to be handled specially, like tabs.
882      */
883     public abstract boolean getLineContainsTab(int line);
884
885     /**
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.
889      *
890      * <p>NOTE: this is inadequate to support bidirectional text, and will change.
891      */
892     public abstract Directions getLineDirections(int line);
893
894     /**
895      * Returns the (negative) number of extra pixels of ascent padding in the
896      * top line of the Layout.
897      */
898     public abstract int getTopPadding();
899
900     /**
901      * Returns the number of extra pixels of descent padding in the
902      * bottom line of the Layout.
903      */
904     public abstract int getBottomPadding();
905
906     /**
907      * Returns the hyphen edit for a line.
908      *
909      * @hide
910      */
911     public int getHyphen(int line) {
912         return 0;
913     }
914
915     /**
916      * Returns the left indent for a line.
917      *
918      * @hide
919      */
920     public int getIndentAdjust(int line, Alignment alignment) {
921         return 0;
922     }
923
924     /**
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
929      * @hide
930      */
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) {
935             return false;
936         }
937
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;
945         }
946
947         offset -= lineStart;
948         for (int i = 0; i < runs.length; i += 2) {
949             if (offset == runs[i]) {
950                 return true;
951             }
952         }
953         return false;
954     }
955
956     /**
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
960      */
961     public boolean isRtlCharAt(int offset) {
962         int line = getLineForOffset(offset);
963         Directions dirs = getLineDirections(line);
964         if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
965             return false;
966         }
967         if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
968             return  true;
969         }
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);
978             }
979         }
980         // Should happen only if the offset is "out of bounds"
981         return false;
982     }
983
984     /**
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
988      * @hide
989      */
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));
995         }
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);
1003             }
1004         }
1005         // Should happen only if the offset is "out of bounds"
1006         return TextUtils.packRangeInLong(0, getLineEnd(line));
1007     }
1008
1009     /**
1010      * Checks if the trailing BiDi level should be used for an offset
1011      *
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
1017      *
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:
1022      *
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
1026      *
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.
1031      *
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.
1034      * @hide
1035      */
1036     @VisibleForTesting
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;
1042
1043         int levelAt = -1;
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) {
1048                 limit = lineEnd;
1049             }
1050             if (offset >= start && offset < limit) {
1051                 if (offset > start) {
1052                     // Previous character is at same level, so don't use trailing.
1053                     return false;
1054                 }
1055                 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1056                 break;
1057             }
1058         }
1059         if (levelAt == -1) {
1060             // Offset was limit of line.
1061             levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
1062         }
1063
1064         // At level boundary, check previous level.
1065         int levelBefore = -1;
1066         if (offset == lineStart) {
1067             levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
1068         } else {
1069             offset -= 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) {
1074                     limit = lineEnd;
1075                 }
1076                 if (offset >= start && offset < limit) {
1077                     levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1078                     break;
1079                 }
1080             }
1081         }
1082
1083         return levelBefore < levelAt;
1084     }
1085
1086     /**
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
1091      * @hide
1092      */
1093     @VisibleForTesting
1094     public boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
1095         int lineStart = getLineStart(line);
1096         int lineEnd = getLineEnd(line);
1097         int[] runs = getLineDirections(line).mDirections;
1098
1099         boolean[] trailing = new boolean[lineEnd - lineStart + 1];
1100
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) {
1106                 limit = lineEnd;
1107             }
1108             level[limit - lineStart - 1] =
1109                     (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1110         }
1111
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]);
1118         }
1119
1120         return trailing;
1121     }
1122
1123     /**
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.
1127      */
1128     public float getPrimaryHorizontal(int offset) {
1129         return getPrimaryHorizontal(offset, false /* not clamped */);
1130     }
1131
1132     /**
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.
1135      * @hide
1136      */
1137     public float getPrimaryHorizontal(int offset, boolean clamped) {
1138         boolean trailing = primaryIsTrailingPrevious(offset);
1139         return getHorizontal(offset, trailing, clamped);
1140     }
1141
1142     /**
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.
1146      */
1147     public float getSecondaryHorizontal(int offset) {
1148         return getSecondaryHorizontal(offset, false /* not clamped */);
1149     }
1150
1151     /**
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.
1154      * @hide
1155      */
1156     public float getSecondaryHorizontal(int offset, boolean clamped) {
1157         boolean trailing = primaryIsTrailingPrevious(offset);
1158         return getHorizontal(offset, !trailing, clamped);
1159     }
1160
1161     private float getHorizontal(int offset, boolean primary) {
1162         return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
1163     }
1164
1165     private float getHorizontal(int offset, boolean trailing, boolean clamped) {
1166         int line = getLineForOffset(offset);
1167
1168         return getHorizontal(offset, trailing, line, clamped);
1169     }
1170
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);
1177
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
1185             }
1186         }
1187
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);
1193
1194         if (clamped && wid > mWidth) {
1195             wid = mWidth;
1196         }
1197         int left = getParagraphLeft(line);
1198         int right = getParagraphRight(line);
1199
1200         return getLineStartPos(line, left, right) + wid;
1201     }
1202
1203     /**
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
1210      */
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);
1217
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
1225             }
1226         }
1227
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);
1232         if (!primary) {
1233             for (int offset = 0; offset < trailings.length; ++offset) {
1234                 trailings[offset] = !trailings[offset];
1235             }
1236         }
1237         float[] wid = tl.measureAllOffsets(trailings, null);
1238         TextLine.recycle(tl);
1239
1240         if (clamped) {
1241             for (int offset = 0; offset <= wid.length; ++offset) {
1242                 if (wid[offset] > mWidth) {
1243                     wid[offset] = mWidth;
1244                 }
1245             }
1246         }
1247         int left = getParagraphLeft(line);
1248         int right = getParagraphRight(line);
1249
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];
1254         }
1255         return horizontal;
1256     }
1257
1258     /**
1259      * Get the leftmost position that should be exposed for horizontal
1260      * scrolling on the specified line.
1261      */
1262     public float getLineLeft(int line) {
1263         int dir = getParagraphDirection(line);
1264         Alignment align = getParagraphAlignment(line);
1265
1266         if (align == Alignment.ALIGN_LEFT) {
1267             return 0;
1268         } else if (align == Alignment.ALIGN_NORMAL) {
1269             if (dir == DIR_RIGHT_TO_LEFT)
1270                 return getParagraphRight(line) - getLineMax(line);
1271             else
1272                 return 0;
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)
1277                 return 0;
1278             else
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;
1284
1285             return left + ((right - left) - max) / 2;
1286         }
1287     }
1288
1289     /**
1290      * Get the rightmost position that should be exposed for horizontal
1291      * scrolling on the specified line.
1292      */
1293     public float getLineRight(int line) {
1294         int dir = getParagraphDirection(line);
1295         Alignment align = getParagraphAlignment(line);
1296
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)
1301                 return mWidth;
1302             else
1303                 return getParagraphLeft(line) + getLineMax(line);
1304         } else if (align == Alignment.ALIGN_RIGHT) {
1305             return mWidth;
1306         } else if (align == Alignment.ALIGN_OPPOSITE) {
1307             if (dir == DIR_RIGHT_TO_LEFT)
1308                 return getLineMax(line);
1309             else
1310                 return mWidth;
1311         } else { /* align == Alignment.ALIGN_CENTER */
1312             int left = getParagraphLeft(line);
1313             int right = getParagraphRight(line);
1314             int max = ((int) getLineMax(line)) & ~1;
1315
1316             return right - ((right - left) - max) / 2;
1317         }
1318     }
1319
1320     /**
1321      * Gets the unsigned horizontal extent of the specified line, including
1322      * leading margin indent, but excluding trailing whitespace.
1323      */
1324     public float getLineMax(int line) {
1325         float margin = getParagraphLeadingMargin(line);
1326         float signedExtent = getLineExtent(line, false);
1327         return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1328     }
1329
1330     /**
1331      * Gets the unsigned horizontal extent of the specified line, including
1332      * leading margin indent and trailing whitespace.
1333      */
1334     public float getLineWidth(int line) {
1335         float margin = getParagraphLeadingMargin(line);
1336         float signedExtent = getLineExtent(line, true);
1337         return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1338     }
1339
1340     /**
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
1346      */
1347     private float getLineExtent(int line, boolean full) {
1348         final int start = getLineStart(line);
1349         final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1350
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
1359             }
1360         }
1361         final Directions directions = getLineDirections(line);
1362         // Returned directions can actually be null
1363         if (directions == null) {
1364             return 0f;
1365         }
1366         final int dir = getParagraphDirection(line);
1367
1368         final TextLine tl = TextLine.obtain();
1369         final TextPaint paint = mWorkPaint;
1370         paint.set(mPaint);
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));
1376         }
1377         final float width = tl.metrics(null);
1378         TextLine.recycle(tl);
1379         return width;
1380     }
1381
1382     /**
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
1389      */
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);
1396
1397         final TextLine tl = TextLine.obtain();
1398         final TextPaint paint = mWorkPaint;
1399         paint.set(mPaint);
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));
1405         }
1406         final float width = tl.metrics(null);
1407         TextLine.recycle(tl);
1408         return width;
1409     }
1410
1411     /**
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.
1415      */
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;
1419
1420         while (high - low > 1) {
1421             guess = (high + low) / 2;
1422
1423             if (getLineTop(guess) > vertical)
1424                 high = guess;
1425             else
1426                 low = guess;
1427         }
1428
1429         if (low < 0)
1430             return 0;
1431         else
1432             return low;
1433     }
1434
1435     /**
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.
1439      */
1440     public int getLineForOffset(int offset) {
1441         int high = getLineCount(), low = -1, guess;
1442
1443         while (high - low > 1) {
1444             guess = (high + low) / 2;
1445
1446             if (getLineStart(guess) > offset)
1447                 high = guess;
1448             else
1449                 low = guess;
1450         }
1451
1452         if (low < 0) {
1453             return 0;
1454         } else {
1455             return low;
1456         }
1457     }
1458
1459     /**
1460      * Get the character offset on the specified line whose position is
1461      * closest to the specified horizontal position.
1462      */
1463     public int getOffsetForHorizontal(int line, float horiz) {
1464         return getOffsetForHorizontal(line, horiz, true);
1465     }
1466
1467     /**
1468      * Get the character offset on the specified line whose position is
1469      * closest to the specified horizontal position.
1470      *
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
1474      *
1475      * @hide
1476      */
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);
1481
1482         Directions dirs = getLineDirections(line);
1483
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,
1487                 false, null,
1488                 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
1489         final HorizontalMeasurementProvider horizontal =
1490                 new HorizontalMeasurementProvider(line, primary);
1491
1492         final int max;
1493         if (line == getLineCount() - 1) {
1494             max = lineEndOffset;
1495         } else {
1496             max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1497                     !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
1498         }
1499         int best = lineStartOffset;
1500         float bestdist = Math.abs(horizontal.get(lineStartOffset) - horiz);
1501
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;
1507
1508             if (there > max)
1509                 there = max;
1510             int high = there - 1 + 1, low = here + 1 - 1, guess;
1511
1512             while (high - low > 1) {
1513                 guess = (high + low) / 2;
1514                 int adguess = getOffsetAtStartOf(guess);
1515
1516                 if (horizontal.get(adguess) * swap >= horiz * swap) {
1517                     high = guess;
1518                 } else {
1519                     low = guess;
1520                 }
1521             }
1522
1523             if (low < here + 1)
1524                 low = here + 1;
1525
1526             if (low < there) {
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);
1531                     if (aft < there) {
1532                         float other = Math.abs(horizontal.get(aft) - horiz);
1533
1534                         if (other < dist) {
1535                             dist = other;
1536                             low = aft;
1537                         }
1538                     }
1539
1540                     if (dist < bestdist) {
1541                         bestdist = dist;
1542                         best = low;
1543                     }
1544                 }
1545             }
1546
1547             float dist = Math.abs(horizontal.get(here) - horiz);
1548
1549             if (dist < bestdist) {
1550                 bestdist = dist;
1551                 best = here;
1552             }
1553         }
1554
1555         float dist = Math.abs(horizontal.get(max) - horiz);
1556
1557         if (dist <= bestdist) {
1558             best = max;
1559         }
1560
1561         TextLine.recycle(tl);
1562         return best;
1563     }
1564
1565     /**
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
1571      * contexts.
1572      */
1573     private class HorizontalMeasurementProvider {
1574         private final int mLine;
1575         private final boolean mPrimary;
1576
1577         private float[] mHorizontals;
1578         private int mLineStartOffset;
1579
1580         HorizontalMeasurementProvider(final int line, final boolean primary) {
1581             mLine = line;
1582             mPrimary = primary;
1583             init();
1584         }
1585
1586         private void init() {
1587             final Directions dirs = getLineDirections(mLine);
1588             if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1589                 return;
1590             }
1591
1592             mHorizontals = getLineHorizontals(mLine, false, mPrimary);
1593             mLineStartOffset = getLineStart(mLine);
1594         }
1595
1596         float get(final int offset) {
1597             if (mHorizontals == null || offset < 0 || offset >= mHorizontals.length) {
1598                 return getHorizontal(offset, mPrimary);
1599             } else {
1600                 return mHorizontals[offset - mLineStartOffset];
1601             }
1602         }
1603     }
1604
1605     /**
1606      * Return the text offset after the last character on the specified line.
1607      */
1608     public final int getLineEnd(int line) {
1609         return getLineStart(line + 1);
1610     }
1611
1612     /**
1613      * Return the text offset after the last visible character (so whitespace
1614      * is not counted) on the specified line.
1615      */
1616     public int getLineVisibleEnd(int line) {
1617         return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1618     }
1619
1620     private int getLineVisibleEnd(int line, int start, int end) {
1621         CharSequence text = mText;
1622         char ch;
1623         if (line == getLineCount() - 1) {
1624             return end;
1625         }
1626
1627         for (; end > start; end--) {
1628             ch = text.charAt(end - 1);
1629
1630             if (ch == '\n') {
1631                 return end - 1;
1632             }
1633
1634             if (!TextLine.isLineEndSpace(ch)) {
1635                 break;
1636             }
1637
1638         }
1639
1640         return end;
1641     }
1642
1643     /**
1644      * Return the vertical position of the bottom of the specified line.
1645      */
1646     public final int getLineBottom(int line) {
1647         return getLineTop(line + 1);
1648     }
1649
1650     /**
1651      * Return the vertical position of the bottom of the specified line without the line spacing
1652      * added.
1653      *
1654      * @hide
1655      */
1656     public final int getLineBottomWithoutSpacing(int line) {
1657         return getLineTop(line + 1) - getLineExtra(line);
1658     }
1659
1660     /**
1661      * Return the vertical position of the baseline of the specified line.
1662      */
1663     public final int getLineBaseline(int line) {
1664         // getLineTop(line+1) == getLineTop(line)
1665         return getLineTop(line+1) - getLineDescent(line);
1666     }
1667
1668     /**
1669      * Get the ascent of the text on the specified line.
1670      * The return value is negative to match the Paint.ascent() convention.
1671      */
1672     public final int getLineAscent(int line) {
1673         // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1674         return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1675     }
1676
1677     /**
1678      * Return the extra space added as a result of line spacing attributes
1679      * {@link #getSpacingAdd()} and {@link #getSpacingMultiplier()}. Default value is {@code zero}.
1680      *
1681      * @param line the index of the line, the value should be equal or greater than {@code zero}
1682      * @hide
1683      */
1684     public int getLineExtra(@IntRange(from = 0) int line) {
1685         return 0;
1686     }
1687
1688     public int getOffsetToLeftOf(int offset) {
1689         return getOffsetToLeftRightOf(offset, true);
1690     }
1691
1692     public int getOffsetToRightOf(int offset) {
1693         return getOffsetToLeftRightOf(offset, false);
1694     }
1695
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);
1701
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
1705         if (advance) {
1706             if (caret == lineEnd) {
1707                 if (line < getLineCount() - 1) {
1708                     lineChanged = true;
1709                     ++line;
1710                 } else {
1711                     return caret; // at very end, don't move
1712                 }
1713             }
1714         } else {
1715             if (caret == lineStart) {
1716                 if (line > 0) {
1717                     lineChanged = true;
1718                     --line;
1719                 } else {
1720                     return caret; // at very start, don't move
1721                 }
1722             }
1723         }
1724
1725         if (lineChanged) {
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.
1733                 toLeft = !toLeft;
1734                 lineDir = newDir;
1735             }
1736         }
1737
1738         Directions directions = getLineDirections(line);
1739
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);
1746         return caret;
1747     }
1748
1749     private int getOffsetAtStartOf(int offset) {
1750         // XXX this probably should skip local reorderings and
1751         // zero-width characters, look at callers
1752         if (offset == 0)
1753             return 0;
1754
1755         CharSequence text = mText;
1756         char c = text.charAt(offset);
1757
1758         if (c >= '\uDC00' && c <= '\uDFFF') {
1759             char c1 = text.charAt(offset - 1);
1760
1761             if (c1 >= '\uD800' && c1 <= '\uDBFF')
1762                 offset -= 1;
1763         }
1764
1765         if (mSpannedText) {
1766             ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1767                                                        ReplacementSpan.class);
1768
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]);
1772
1773                 if (start < offset && end > offset)
1774                     offset = start;
1775             }
1776         }
1777
1778         return offset;
1779     }
1780
1781     /**
1782      * Determine whether we should clamp cursor position. Currently it's
1783      * only robust for left-aligned displays.
1784      * @hide
1785      */
1786     public boolean shouldClampCursor(int line) {
1787         // Only clamp cursor position in left-aligned displays.
1788         switch (getParagraphAlignment(line)) {
1789             case ALIGN_LEFT:
1790                 return true;
1791             case ALIGN_NORMAL:
1792                 return getParagraphDirection(line) > 0;
1793             default:
1794                 return false;
1795         }
1796
1797     }
1798     /**
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
1802      * directionalities.
1803      */
1804     public void getCursorPath(final int point, final Path dest, final CharSequence editingBuffer) {
1805         dest.reset();
1806
1807         int line = getLineForOffset(point);
1808         int top = getLineTop(line);
1809         int bottom = getLineBottomWithoutSpacing(line);
1810
1811         boolean clamped = shouldClampCursor(line);
1812         float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1813         float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
1814
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);
1818         int dist = 0;
1819
1820         if (caps != 0 || fn != 0) {
1821             dist = (bottom - top) >> 2;
1822
1823             if (fn != 0)
1824                 top += dist;
1825             if (caps != 0)
1826                 bottom -= dist;
1827         }
1828
1829         if (h1 < 0.5f)
1830             h1 = 0.5f;
1831         if (h2 < 0.5f)
1832             h2 = 0.5f;
1833
1834         if (Float.compare(h1, h2) == 0) {
1835             dest.moveTo(h1, top);
1836             dest.lineTo(h1, bottom);
1837         } else {
1838             dest.moveTo(h1, top);
1839             dest.lineTo(h1, (top + bottom) >> 1);
1840
1841             dest.moveTo(h2, (top + bottom) >> 1);
1842             dest.lineTo(h2, bottom);
1843         }
1844
1845         if (caps == 2) {
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);
1853
1854             dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1855             dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1856
1857             dest.moveTo(h2 + dist, bottom + dist);
1858             dest.lineTo(h2, bottom);
1859         }
1860
1861         if (fn == 2) {
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);
1869
1870             dest.moveTo(h1 - dist, top - dist + 0.5f);
1871             dest.lineTo(h1 + dist, top - dist + 0.5f);
1872
1873             dest.moveTo(h1 + dist, top - dist);
1874             dest.lineTo(h1, top);
1875         }
1876     }
1877
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);
1883
1884         if (lineend > linestart && mText.charAt(lineend - 1) == '\n') {
1885             lineend--;
1886         }
1887
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);
1891
1892             if (there > lineend) {
1893                 there = lineend;
1894             }
1895
1896             if (start <= there && end >= here) {
1897                 int st = Math.max(start, here);
1898                 int en = Math.min(end, there);
1899
1900                 if (st != en) {
1901                     float h1 = getHorizontal(st, false, line, false /* not clamped */);
1902                     float h2 = getHorizontal(en, true, line, false /* not clamped */);
1903
1904                     float left = Math.min(h1, h2);
1905                     float right = Math.max(h1, h2);
1906
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;
1911
1912                     consumer.accept(left, top, right, bottom, layout);
1913                 }
1914             }
1915         }
1916     }
1917
1918     /**
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.
1923      */
1924     public void getSelectionPath(int start, int end, Path dest) {
1925         dest.reset();
1926         getSelection(start, end, (left, top, right, bottom, textSelectionLayout) ->
1927                 dest.addRect(left, top, right, bottom, Path.Direction.CW));
1928     }
1929
1930     /**
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}.
1933      *
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.
1938      * @hide
1939      * @see #getSelectionPath(int, int, Path)
1940      */
1941     public final void getSelection(int start, int end, final SelectionRectangleConsumer consumer) {
1942         if (start == end) {
1943             return;
1944         }
1945
1946         if (end < start) {
1947             int temp = end;
1948             end = start;
1949             start = temp;
1950         }
1951
1952         final int startline = getLineForOffset(start);
1953         final int endline = getLineForOffset(end);
1954
1955         int top = getLineTop(startline);
1956         int bottom = getLineBottomWithoutSpacing(endline);
1957
1958         if (startline == endline) {
1959             addSelection(startline, start, end, top, bottom, consumer);
1960         } else {
1961             final float width = mWidth;
1962
1963             addSelection(startline, start, getLineEnd(startline),
1964                     top, getLineBottom(startline), consumer);
1965
1966             if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT) {
1967                 consumer.accept(getLineLeft(startline), top, 0, getLineBottom(startline),
1968                         TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
1969             } else {
1970                 consumer.accept(getLineRight(startline), top, width, getLineBottom(startline),
1971                         TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
1972             }
1973
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);
1979                 } else {
1980                     consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
1981                 }
1982             }
1983
1984             top = getLineTop(endline);
1985             bottom = getLineBottomWithoutSpacing(endline);
1986
1987             addSelection(endline, getLineStart(endline), end, top, bottom, consumer);
1988
1989             if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT) {
1990                 consumer.accept(width, top, getLineRight(endline), bottom,
1991                         TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
1992             } else {
1993                 consumer.accept(0, top, getLineLeft(endline), bottom,
1994                         TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
1995             }
1996         }
1997     }
1998
1999     /**
2000      * Get the alignment of the specified paragraph, taking into account
2001      * markup attached to it.
2002      */
2003     public final Alignment getParagraphAlignment(int line) {
2004         Alignment align = mAlignment;
2005
2006         if (mSpannedText) {
2007             Spanned sp = (Spanned) mText;
2008             AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
2009                                                 getLineEnd(line),
2010                                                 AlignmentSpan.class);
2011
2012             int spanLength = spans.length;
2013             if (spanLength > 0) {
2014                 align = spans[spanLength-1].getAlignment();
2015             }
2016         }
2017
2018         return align;
2019     }
2020
2021     /**
2022      * Get the left edge of the specified paragraph, inset by left margins.
2023      */
2024     public final int getParagraphLeft(int line) {
2025         int left = 0;
2026         int dir = getParagraphDirection(line);
2027         if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
2028             return left; // leading margin has no impact, or no styles
2029         }
2030         return getParagraphLeadingMargin(line);
2031     }
2032
2033     /**
2034      * Get the right edge of the specified paragraph, inset by right margins.
2035      */
2036     public final int getParagraphRight(int line) {
2037         int right = mWidth;
2038         int dir = getParagraphDirection(line);
2039         if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
2040             return right; // leading margin has no impact, or no styles
2041         }
2042         return right - getParagraphLeadingMargin(line);
2043     }
2044
2045     /**
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
2050      */
2051     private int getParagraphLeadingMargin(int line) {
2052         if (!mSpannedText) {
2053             return 0;
2054         }
2055         Spanned spanned = (Spanned) mText;
2056
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;
2065         }
2066
2067         int margin = 0;
2068
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;
2077             }
2078         }
2079         for (int i = 0; i < spans.length; i++) {
2080             LeadingMarginSpan span = spans[i];
2081             margin += span.getLeadingMargin(useFirstLineMargin);
2082         }
2083
2084         return margin;
2085     }
2086
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();
2091         try {
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
2100             int margin = 0;
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);
2107                 }
2108             }
2109             for (int i = 0; i < len; ++i) {
2110                 if (chars[i] == '\t') {
2111                     hasTabs = true;
2112                     if (text instanceof Spanned) {
2113                         Spanned spanned = (Spanned) text;
2114                         int spanEnd = spanned.nextSpanTransition(start, end,
2115                                 TabStopSpan.class);
2116                         TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
2117                                 TabStopSpan.class);
2118                         if (spans.length > 0) {
2119                             tabStops = new TabStops(TAB_INCREMENT, spans);
2120                         }
2121                     }
2122                     break;
2123                 }
2124             }
2125             tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops,
2126                     0 /* ellipsisStart */, 0 /* ellipsisEnd */);
2127             return margin + Math.abs(tl.metrics(null));
2128         } finally {
2129             TextLine.recycle(tl);
2130             if (mt != null) {
2131                 mt.recycle();
2132             }
2133         }
2134     }
2135
2136     /**
2137      * @hide
2138      */
2139     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2140     public static class TabStops {
2141         private int[] mStops;
2142         private int mNumStops;
2143         private int mIncrement;
2144
2145         public TabStops(int increment, Object[] spans) {
2146             reset(increment, spans);
2147         }
2148
2149         void reset(int increment, Object[] spans) {
2150             this.mIncrement = increment;
2151
2152             int ns = 0;
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];
2163                             }
2164                             stops = nstops;
2165                         }
2166                         stops[ns++] = ((TabStopSpan) o).getTabStop();
2167                     }
2168                 }
2169                 if (ns > 1) {
2170                     Arrays.sort(stops, 0, ns);
2171                 }
2172                 if (stops != this.mStops) {
2173                     this.mStops = stops;
2174                 }
2175             }
2176             this.mNumStops = ns;
2177         }
2178
2179         float nextTab(float h) {
2180             int ns = this.mNumStops;
2181             if (ns > 0) {
2182                 int[] stops = this.mStops;
2183                 for (int i = 0; i < ns; ++i) {
2184                     int stop = stops[i];
2185                     if (stop > h) {
2186                         return stop;
2187                     }
2188                 }
2189             }
2190             return nextDefaultStop(h, mIncrement);
2191         }
2192
2193         public static float nextDefaultStop(float h, int inc) {
2194             return ((int) ((h + inc) / inc)) * inc;
2195         }
2196     }
2197
2198     /**
2199      * Returns the position of the next tab stop after h on the line.
2200      *
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.
2209      */
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;
2214
2215         if (text instanceof Spanned) {
2216             if (tabs == null) {
2217                 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
2218                 alltabs = true;
2219             }
2220
2221             for (int i = 0; i < tabs.length; i++) {
2222                 if (!alltabs) {
2223                     if (!(tabs[i] instanceof TabStopSpan))
2224                         continue;
2225                 }
2226
2227                 int where = ((TabStopSpan) tabs[i]).getTabStop();
2228
2229                 if (where < nh && where > h)
2230                     nh = where;
2231             }
2232
2233             if (nh != Float.MAX_VALUE)
2234                 return nh;
2235         }
2236
2237         return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
2238     }
2239
2240     protected final boolean isSpanned() {
2241         return mSpannedText;
2242     }
2243
2244     /**
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.
2249      * <p>
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).
2258      * <p>
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.
2267      */
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);
2271         }
2272
2273         if(text instanceof SpannableStringBuilder) {
2274             return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2275         } else {
2276             return text.getSpans(start, end, type);
2277         }
2278     }
2279
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) {
2284             return;
2285         }
2286         final int ellipsisStart = getEllipsisStart(line);
2287         final int lineStart = getLineStart(line);
2288
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++) {
2294             final char c;
2295             if (useEllipsisString && i < ellipsisStringLen) {
2296                 c = ellipsisString.charAt(i);
2297             } else {
2298                 c = TextUtils.ELLIPSIS_FILLER;
2299             }
2300
2301             final int a = i + ellipsisStart + lineStart;
2302             if (start <= a && a < end) {
2303                 dest[destoff + a - start] = c;
2304             }
2305         }
2306     }
2307
2308     /**
2309      * Stores information about bidirectional (left-to-right or right-to-left)
2310      * text within the layout of a line.
2311      */
2312     public static class Directions {
2313         /**
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.
2321          * @hide
2322          */
2323         @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2324         public int[] mDirections;
2325
2326         /**
2327          * @hide
2328          */
2329         @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2330         public Directions(int[] dirs) {
2331             mDirections = dirs;
2332         }
2333     }
2334
2335     /**
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().)
2339      */
2340     public abstract int getEllipsisStart(int line);
2341
2342     /**
2343      * Returns the number of characters to be ellipsized away, or 0 if
2344      * no ellipsis is to take place.
2345      */
2346     public abstract int getEllipsisCount(int line);
2347
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;
2353
2354         public Ellipsizer(CharSequence s) {
2355             mText = s;
2356         }
2357
2358         public char charAt(int off) {
2359             char[] buf = TextUtils.obtain(1);
2360             getChars(off, off + 1, buf, 0);
2361             char ret = buf[0];
2362
2363             TextUtils.recycle(buf);
2364             return ret;
2365         }
2366
2367         public void getChars(int start, int end, char[] dest, int destoff) {
2368             int line1 = mLayout.getLineForOffset(start);
2369             int line2 = mLayout.getLineForOffset(end);
2370
2371             TextUtils.getChars(mText, start, end, dest, destoff);
2372
2373             for (int i = line1; i <= line2; i++) {
2374                 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
2375             }
2376         }
2377
2378         public int length() {
2379             return mText.length();
2380         }
2381
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);
2386         }
2387
2388         @Override
2389         public String toString() {
2390             char[] s = new char[length()];
2391             getChars(0, length(), s, 0);
2392             return new String(s);
2393         }
2394
2395     }
2396
2397     /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
2398         private Spanned mSpanned;
2399
2400         public SpannedEllipsizer(CharSequence display) {
2401             super(display);
2402             mSpanned = (Spanned) display;
2403         }
2404
2405         public <T> T[] getSpans(int start, int end, Class<T> type) {
2406             return mSpanned.getSpans(start, end, type);
2407         }
2408
2409         public int getSpanStart(Object tag) {
2410             return mSpanned.getSpanStart(tag);
2411         }
2412
2413         public int getSpanEnd(Object tag) {
2414             return mSpanned.getSpanEnd(tag);
2415         }
2416
2417         public int getSpanFlags(Object tag) {
2418             return mSpanned.getSpanFlags(tag);
2419         }
2420
2421         @SuppressWarnings("rawtypes")
2422         public int nextSpanTransition(int start, int limit, Class type) {
2423             return mSpanned.nextSpanTransition(start, limit, type);
2424         }
2425
2426         @Override
2427         public CharSequence subSequence(int start, int end) {
2428             char[] s = new char[end - start];
2429             getChars(start, end, s, 0);
2430
2431             SpannableString ss = new SpannableString(new String(s));
2432             TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2433             return ss;
2434         }
2435     }
2436
2437     private CharSequence mText;
2438     private TextPaint mPaint;
2439     private TextPaint mWorkPaint = new TextPaint();
2440     private int mWidth;
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;
2449
2450     /** @hide */
2451     @IntDef(prefix = { "DIR_" }, value = {
2452             DIR_LEFT_TO_RIGHT,
2453             DIR_RIGHT_TO_LEFT
2454     })
2455     @Retention(RetentionPolicy.SOURCE)
2456     public @interface Direction {}
2457
2458     public static final int DIR_LEFT_TO_RIGHT = 1;
2459     public static final int DIR_RIGHT_TO_LEFT = -1;
2460
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;
2465
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;
2470
2471     public enum Alignment {
2472         ALIGN_NORMAL,
2473         ALIGN_OPPOSITE,
2474         ALIGN_CENTER,
2475         /** @hide */
2476         ALIGN_LEFT,
2477         /** @hide */
2478         ALIGN_RIGHT,
2479     }
2480
2481     private static final int TAB_INCREMENT = 20;
2482
2483     /** @hide */
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 });
2487
2488     /** @hide */
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 });
2492
2493     /** @hide */
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
2498     })
2499     public @interface TextSelectionLayout {}
2500
2501     /** @hide */
2502     public static final int TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT = 0;
2503     /** @hide */
2504     public static final int TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT = 1;
2505
2506     /** @hide */
2507     @FunctionalInterface
2508     public interface SelectionRectangleConsumer {
2509         /**
2510          * Performs this operation on the given rectangle.
2511          *
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
2518          */
2519         void accept(float left, float top, float right, float bottom,
2520                 @TextSelectionLayout int textSelectionLayout);
2521     }
2522
2523 }