OSDN Git Service

Optimise the hit test algorithm
[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.graphics.Canvas;
21 import android.graphics.Paint;
22 import android.graphics.Path;
23 import android.graphics.Rect;
24 import android.text.method.TextKeyListener;
25 import android.text.style.AlignmentSpan;
26 import android.text.style.LeadingMarginSpan;
27 import android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
28 import android.text.style.LineBackgroundSpan;
29 import android.text.style.ParagraphStyle;
30 import android.text.style.ReplacementSpan;
31 import android.text.style.TabStopSpan;
32
33 import com.android.internal.util.ArrayUtils;
34 import com.android.internal.util.GrowingArrayUtils;
35
36 import java.lang.annotation.Retention;
37 import java.lang.annotation.RetentionPolicy;
38 import java.util.Arrays;
39
40 /**
41  * A base class that manages text layout in visual elements on
42  * the screen.
43  * <p>For text that will be edited, use a {@link DynamicLayout},
44  * which will be updated as the text changes.
45  * For text that will not change, use a {@link StaticLayout}.
46  */
47 public abstract class Layout {
48     /** @hide */
49     @IntDef({BREAK_STRATEGY_SIMPLE, BREAK_STRATEGY_HIGH_QUALITY, BREAK_STRATEGY_BALANCED})
50     @Retention(RetentionPolicy.SOURCE)
51     public @interface BreakStrategy {}
52
53     /**
54      * Value for break strategy indicating simple line breaking. Automatic hyphens are not added
55      * (though soft hyphens are respected), and modifying text generally doesn't affect the layout
56      * before it (which yields a more consistent user experience when editing), but layout may not
57      * be the highest quality.
58      */
59     public static final int BREAK_STRATEGY_SIMPLE = 0;
60
61     /**
62      * Value for break strategy indicating high quality line breaking, including automatic
63      * hyphenation and doing whole-paragraph optimization of line breaks.
64      */
65     public static final int BREAK_STRATEGY_HIGH_QUALITY = 1;
66
67     /**
68      * Value for break strategy indicating balanced line breaking. The breaks are chosen to
69      * make all lines as close to the same length as possible, including automatic hyphenation.
70      */
71     public static final int BREAK_STRATEGY_BALANCED = 2;
72
73     /** @hide */
74     @IntDef({HYPHENATION_FREQUENCY_NORMAL, HYPHENATION_FREQUENCY_FULL,
75              HYPHENATION_FREQUENCY_NONE})
76     @Retention(RetentionPolicy.SOURCE)
77     public @interface HyphenationFrequency {}
78
79     /**
80      * Value for hyphenation frequency indicating no automatic hyphenation. Useful
81      * for backward compatibility, and for cases where the automatic hyphenation algorithm results
82      * in incorrect hyphenation. Mid-word breaks may still happen when a word is wider than the
83      * layout and there is otherwise no valid break. Soft hyphens are ignored and will not be used
84      * as suggestions for potential line breaks.
85      */
86     public static final int HYPHENATION_FREQUENCY_NONE = 0;
87
88     /**
89      * Value for hyphenation frequency indicating a light amount of automatic hyphenation, which
90      * is a conservative default. Useful for informal cases, such as short sentences or chat
91      * messages.
92      */
93     public static final int HYPHENATION_FREQUENCY_NORMAL = 1;
94
95     /**
96      * Value for hyphenation frequency indicating the full amount of automatic hyphenation, typical
97      * in typography. Useful for running text and where it's important to put the maximum amount of
98      * text in a screen with limited space.
99      */
100     public static final int HYPHENATION_FREQUENCY_FULL = 2;
101
102     private static final ParagraphStyle[] NO_PARA_SPANS =
103         ArrayUtils.emptyArray(ParagraphStyle.class);
104
105     /**
106      * Return how wide a layout must be in order to display the
107      * specified text with one line per paragraph.
108      */
109     public static float getDesiredWidth(CharSequence source,
110                                         TextPaint paint) {
111         return getDesiredWidth(source, 0, source.length(), paint);
112     }
113
114     /**
115      * Return how wide a layout must be in order to display the
116      * specified text slice with one line per paragraph.
117      */
118     public static float getDesiredWidth(CharSequence source,
119                                         int start, int end,
120                                         TextPaint paint) {
121         float need = 0;
122
123         int next;
124         for (int i = start; i <= end; i = next) {
125             next = TextUtils.indexOf(source, '\n', i, end);
126
127             if (next < 0)
128                 next = end;
129
130             // note, omits trailing paragraph char
131             float w = measurePara(paint, source, i, next);
132
133             if (w > need)
134                 need = w;
135
136             next++;
137         }
138
139         return need;
140     }
141
142     /**
143      * Subclasses of Layout use this constructor to set the display text,
144      * width, and other standard properties.
145      * @param text the text to render
146      * @param paint the default paint for the layout.  Styles can override
147      * various attributes of the paint.
148      * @param width the wrapping width for the text.
149      * @param align whether to left, right, or center the text.  Styles can
150      * override the alignment.
151      * @param spacingMult factor by which to scale the font size to get the
152      * default line spacing
153      * @param spacingAdd amount to add to the default line spacing
154      */
155     protected Layout(CharSequence text, TextPaint paint,
156                      int width, Alignment align,
157                      float spacingMult, float spacingAdd) {
158         this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
159                 spacingMult, spacingAdd);
160     }
161
162     /**
163      * Subclasses of Layout use this constructor to set the display text,
164      * width, and other standard properties.
165      * @param text the text to render
166      * @param paint the default paint for the layout.  Styles can override
167      * various attributes of the paint.
168      * @param width the wrapping width for the text.
169      * @param align whether to left, right, or center the text.  Styles can
170      * override the alignment.
171      * @param spacingMult factor by which to scale the font size to get the
172      * default line spacing
173      * @param spacingAdd amount to add to the default line spacing
174      *
175      * @hide
176      */
177     protected Layout(CharSequence text, TextPaint paint,
178                      int width, Alignment align, TextDirectionHeuristic textDir,
179                      float spacingMult, float spacingAdd) {
180
181         if (width < 0)
182             throw new IllegalArgumentException("Layout: " + width + " < 0");
183
184         // Ensure paint doesn't have baselineShift set.
185         // While normally we don't modify the paint the user passed in,
186         // we were already doing this in Styled.drawUniformRun with both
187         // baselineShift and bgColor.  We probably should reevaluate bgColor.
188         if (paint != null) {
189             paint.bgColor = 0;
190             paint.baselineShift = 0;
191         }
192
193         mText = text;
194         mPaint = paint;
195         mWidth = width;
196         mAlignment = align;
197         mSpacingMult = spacingMult;
198         mSpacingAdd = spacingAdd;
199         mSpannedText = text instanceof Spanned;
200         mTextDir = textDir;
201     }
202
203     /**
204      * Replace constructor properties of this Layout with new ones.  Be careful.
205      */
206     /* package */ void replaceWith(CharSequence text, TextPaint paint,
207                               int width, Alignment align,
208                               float spacingmult, float spacingadd) {
209         if (width < 0) {
210             throw new IllegalArgumentException("Layout: " + width + " < 0");
211         }
212
213         mText = text;
214         mPaint = paint;
215         mWidth = width;
216         mAlignment = align;
217         mSpacingMult = spacingmult;
218         mSpacingAdd = spacingadd;
219         mSpannedText = text instanceof Spanned;
220     }
221
222     /**
223      * Draw this Layout on the specified Canvas.
224      */
225     public void draw(Canvas c) {
226         draw(c, null, null, 0);
227     }
228
229     /**
230      * Draw this Layout on the specified canvas, with the highlight path drawn
231      * between the background and the text.
232      *
233      * @param canvas the canvas
234      * @param highlight the path of the highlight or cursor; can be null
235      * @param highlightPaint the paint for the highlight
236      * @param cursorOffsetVertical the amount to temporarily translate the
237      *        canvas while rendering the highlight
238      */
239     public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
240             int cursorOffsetVertical) {
241         final long lineRange = getLineRangeForDraw(canvas);
242         int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
243         int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
244         if (lastLine < 0) return;
245
246         drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
247                 firstLine, lastLine);
248         drawText(canvas, firstLine, lastLine);
249     }
250
251     /**
252      * @hide
253      */
254     public void drawText(Canvas canvas, int firstLine, int lastLine) {
255         int previousLineBottom = getLineTop(firstLine);
256         int previousLineEnd = getLineStart(firstLine);
257         ParagraphStyle[] spans = NO_PARA_SPANS;
258         int spanEnd = 0;
259         TextPaint paint = mPaint;
260         CharSequence buf = mText;
261
262         Alignment paraAlign = mAlignment;
263         TabStops tabStops = null;
264         boolean tabStopsIsInitialized = false;
265
266         TextLine tl = TextLine.obtain();
267
268         // Draw the lines, one at a time.
269         // The baseline is the top of the following line minus the current line's descent.
270         for (int lineNum = firstLine; lineNum <= lastLine; lineNum++) {
271             int start = previousLineEnd;
272             previousLineEnd = getLineStart(lineNum + 1);
273             int end = getLineVisibleEnd(lineNum, start, previousLineEnd);
274
275             int ltop = previousLineBottom;
276             int lbottom = getLineTop(lineNum + 1);
277             previousLineBottom = lbottom;
278             int lbaseline = lbottom - getLineDescent(lineNum);
279
280             int dir = getParagraphDirection(lineNum);
281             int left = 0;
282             int right = mWidth;
283
284             if (mSpannedText) {
285                 Spanned sp = (Spanned) buf;
286                 int textLength = buf.length();
287                 boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
288
289                 // New batch of paragraph styles, collect into spans array.
290                 // Compute the alignment, last alignment style wins.
291                 // Reset tabStops, we'll rebuild if we encounter a line with
292                 // tabs.
293                 // We expect paragraph spans to be relatively infrequent, use
294                 // spanEnd so that we can check less frequently.  Since
295                 // paragraph styles ought to apply to entire paragraphs, we can
296                 // just collect the ones present at the start of the paragraph.
297                 // If spanEnd is before the end of the paragraph, that's not
298                 // our problem.
299                 if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
300                     spanEnd = sp.nextSpanTransition(start, textLength,
301                                                     ParagraphStyle.class);
302                     spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
303
304                     paraAlign = mAlignment;
305                     for (int n = spans.length - 1; n >= 0; n--) {
306                         if (spans[n] instanceof AlignmentSpan) {
307                             paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
308                             break;
309                         }
310                     }
311
312                     tabStopsIsInitialized = false;
313                 }
314
315                 // Draw all leading margin spans.  Adjust left or right according
316                 // to the paragraph direction of the line.
317                 final int length = spans.length;
318                 boolean useFirstLineMargin = isFirstParaLine;
319                 for (int n = 0; n < length; n++) {
320                     if (spans[n] instanceof LeadingMarginSpan2) {
321                         int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
322                         int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
323                         // if there is more than one LeadingMarginSpan2, use
324                         // the count that is greatest
325                         if (lineNum < startLine + count) {
326                             useFirstLineMargin = true;
327                             break;
328                         }
329                     }
330                 }
331                 for (int n = 0; n < length; n++) {
332                     if (spans[n] instanceof LeadingMarginSpan) {
333                         LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
334                         if (dir == DIR_RIGHT_TO_LEFT) {
335                             margin.drawLeadingMargin(canvas, paint, right, dir, ltop,
336                                                      lbaseline, lbottom, buf,
337                                                      start, end, isFirstParaLine, this);
338                             right -= margin.getLeadingMargin(useFirstLineMargin);
339                         } else {
340                             margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
341                                                      lbaseline, lbottom, buf,
342                                                      start, end, isFirstParaLine, this);
343                             left += margin.getLeadingMargin(useFirstLineMargin);
344                         }
345                     }
346                 }
347             }
348
349             boolean hasTab = getLineContainsTab(lineNum);
350             // Can't tell if we have tabs for sure, currently
351             if (hasTab && !tabStopsIsInitialized) {
352                 if (tabStops == null) {
353                     tabStops = new TabStops(TAB_INCREMENT, spans);
354                 } else {
355                     tabStops.reset(TAB_INCREMENT, spans);
356                 }
357                 tabStopsIsInitialized = true;
358             }
359
360             // Determine whether the line aligns to normal, opposite, or center.
361             Alignment align = paraAlign;
362             if (align == Alignment.ALIGN_LEFT) {
363                 align = (dir == DIR_LEFT_TO_RIGHT) ?
364                     Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
365             } else if (align == Alignment.ALIGN_RIGHT) {
366                 align = (dir == DIR_LEFT_TO_RIGHT) ?
367                     Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
368             }
369
370             int x;
371             if (align == Alignment.ALIGN_NORMAL) {
372                 if (dir == DIR_LEFT_TO_RIGHT) {
373                     x = left + getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
374                 } else {
375                     x = right + getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
376                 }
377             } else {
378                 int max = (int)getLineExtent(lineNum, tabStops, false);
379                 if (align == Alignment.ALIGN_OPPOSITE) {
380                     if (dir == DIR_LEFT_TO_RIGHT) {
381                         x = right - max + getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
382                     } else {
383                         x = left - max + getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
384                     }
385                 } else { // Alignment.ALIGN_CENTER
386                     max = max & ~1;
387                     x = ((right + left - max) >> 1) +
388                             getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
389                 }
390             }
391
392             paint.setHyphenEdit(getHyphen(lineNum));
393             Directions directions = getLineDirections(lineNum);
394             if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTab) {
395                 // XXX: assumes there's nothing additional to be done
396                 canvas.drawText(buf, start, end, x, lbaseline, paint);
397             } else {
398                 tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops);
399                 tl.draw(canvas, x, ltop, lbaseline, lbottom);
400             }
401             paint.setHyphenEdit(0);
402         }
403
404         TextLine.recycle(tl);
405     }
406
407     /**
408      * @hide
409      */
410     public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
411             int cursorOffsetVertical, int firstLine, int lastLine) {
412         // First, draw LineBackgroundSpans.
413         // LineBackgroundSpans know nothing about the alignment, margins, or
414         // direction of the layout or line.  XXX: Should they?
415         // They are evaluated at each line.
416         if (mSpannedText) {
417             if (mLineBackgroundSpans == null) {
418                 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
419             }
420
421             Spanned buffer = (Spanned) mText;
422             int textLength = buffer.length();
423             mLineBackgroundSpans.init(buffer, 0, textLength);
424
425             if (mLineBackgroundSpans.numberOfSpans > 0) {
426                 int previousLineBottom = getLineTop(firstLine);
427                 int previousLineEnd = getLineStart(firstLine);
428                 ParagraphStyle[] spans = NO_PARA_SPANS;
429                 int spansLength = 0;
430                 TextPaint paint = mPaint;
431                 int spanEnd = 0;
432                 final int width = mWidth;
433                 for (int i = firstLine; i <= lastLine; i++) {
434                     int start = previousLineEnd;
435                     int end = getLineStart(i + 1);
436                     previousLineEnd = end;
437
438                     int ltop = previousLineBottom;
439                     int lbottom = getLineTop(i + 1);
440                     previousLineBottom = lbottom;
441                     int lbaseline = lbottom - getLineDescent(i);
442
443                     if (start >= spanEnd) {
444                         // These should be infrequent, so we'll use this so that
445                         // we don't have to check as often.
446                         spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
447                         // All LineBackgroundSpans on a line contribute to its background.
448                         spansLength = 0;
449                         // Duplication of the logic of getParagraphSpans
450                         if (start != end || start == 0) {
451                             // Equivalent to a getSpans(start, end), but filling the 'spans' local
452                             // array instead to reduce memory allocation
453                             for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
454                                 // equal test is valid since both intervals are not empty by
455                                 // construction
456                                 if (mLineBackgroundSpans.spanStarts[j] >= end ||
457                                         mLineBackgroundSpans.spanEnds[j] <= start) continue;
458                                 spans = GrowingArrayUtils.append(
459                                         spans, spansLength, mLineBackgroundSpans.spans[j]);
460                                 spansLength++;
461                             }
462                         }
463                     }
464
465                     for (int n = 0; n < spansLength; n++) {
466                         LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
467                         lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
468                                 ltop, lbaseline, lbottom,
469                                 buffer, start, end, i);
470                     }
471                 }
472             }
473             mLineBackgroundSpans.recycle();
474         }
475
476         // There can be a highlight even without spans if we are drawing
477         // a non-spanned transformation of a spanned editing buffer.
478         if (highlight != null) {
479             if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
480             canvas.drawPath(highlight, highlightPaint);
481             if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
482         }
483     }
484
485     /**
486      * @param canvas
487      * @return The range of lines that need to be drawn, possibly empty.
488      * @hide
489      */
490     public long getLineRangeForDraw(Canvas canvas) {
491         int dtop, dbottom;
492
493         synchronized (sTempRect) {
494             if (!canvas.getClipBounds(sTempRect)) {
495                 // Negative range end used as a special flag
496                 return TextUtils.packRangeInLong(0, -1);
497             }
498
499             dtop = sTempRect.top;
500             dbottom = sTempRect.bottom;
501         }
502
503         final int top = Math.max(dtop, 0);
504         final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
505
506         if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
507         return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
508     }
509
510     /**
511      * Return the start position of the line, given the left and right bounds
512      * of the margins.
513      *
514      * @param line the line index
515      * @param left the left bounds (0, or leading margin if ltr para)
516      * @param right the right bounds (width, minus leading margin if rtl para)
517      * @return the start position of the line (to right of line if rtl para)
518      */
519     private int getLineStartPos(int line, int left, int right) {
520         // Adjust the point at which to start rendering depending on the
521         // alignment of the paragraph.
522         Alignment align = getParagraphAlignment(line);
523         int dir = getParagraphDirection(line);
524
525         if (align == Alignment.ALIGN_LEFT) {
526             align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
527         } else if (align == Alignment.ALIGN_RIGHT) {
528             align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
529         }
530
531         int x;
532         if (align == Alignment.ALIGN_NORMAL) {
533             if (dir == DIR_LEFT_TO_RIGHT) {
534                 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
535             } else {
536                 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
537             }
538         } else {
539             TabStops tabStops = null;
540             if (mSpannedText && getLineContainsTab(line)) {
541                 Spanned spanned = (Spanned) mText;
542                 int start = getLineStart(line);
543                 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
544                         TabStopSpan.class);
545                 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
546                         TabStopSpan.class);
547                 if (tabSpans.length > 0) {
548                     tabStops = new TabStops(TAB_INCREMENT, tabSpans);
549                 }
550             }
551             int max = (int)getLineExtent(line, tabStops, false);
552             if (align == Alignment.ALIGN_OPPOSITE) {
553                 if (dir == DIR_LEFT_TO_RIGHT) {
554                     x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
555                 } else {
556                     // max is negative here
557                     x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
558                 }
559             } else { // Alignment.ALIGN_CENTER
560                 max = max & ~1;
561                 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
562             }
563         }
564         return x;
565     }
566
567     /**
568      * Return the text that is displayed by this Layout.
569      */
570     public final CharSequence getText() {
571         return mText;
572     }
573
574     /**
575      * Return the base Paint properties for this layout.
576      * Do NOT change the paint, which may result in funny
577      * drawing for this layout.
578      */
579     public final TextPaint getPaint() {
580         return mPaint;
581     }
582
583     /**
584      * Return the width of this layout.
585      */
586     public final int getWidth() {
587         return mWidth;
588     }
589
590     /**
591      * Return the width to which this Layout is ellipsizing, or
592      * {@link #getWidth} if it is not doing anything special.
593      */
594     public int getEllipsizedWidth() {
595         return mWidth;
596     }
597
598     /**
599      * Increase the width of this layout to the specified width.
600      * Be careful to use this only when you know it is appropriate&mdash;
601      * it does not cause the text to reflow to use the full new width.
602      */
603     public final void increaseWidthTo(int wid) {
604         if (wid < mWidth) {
605             throw new RuntimeException("attempted to reduce Layout width");
606         }
607
608         mWidth = wid;
609     }
610
611     /**
612      * Return the total height of this layout.
613      */
614     public int getHeight() {
615         return getLineTop(getLineCount());
616     }
617
618     /**
619      * Return the base alignment of this layout.
620      */
621     public final Alignment getAlignment() {
622         return mAlignment;
623     }
624
625     /**
626      * Return what the text height is multiplied by to get the line height.
627      */
628     public final float getSpacingMultiplier() {
629         return mSpacingMult;
630     }
631
632     /**
633      * Return the number of units of leading that are added to each line.
634      */
635     public final float getSpacingAdd() {
636         return mSpacingAdd;
637     }
638
639     /**
640      * Return the heuristic used to determine paragraph text direction.
641      * @hide
642      */
643     public final TextDirectionHeuristic getTextDirectionHeuristic() {
644         return mTextDir;
645     }
646
647     /**
648      * Return the number of lines of text in this layout.
649      */
650     public abstract int getLineCount();
651
652     /**
653      * Return the baseline for the specified line (0&hellip;getLineCount() - 1)
654      * If bounds is not null, return the top, left, right, bottom extents
655      * of the specified line in it.
656      * @param line which line to examine (0..getLineCount() - 1)
657      * @param bounds Optional. If not null, it returns the extent of the line
658      * @return the Y-coordinate of the baseline
659      */
660     public int getLineBounds(int line, Rect bounds) {
661         if (bounds != null) {
662             bounds.left = 0;     // ???
663             bounds.top = getLineTop(line);
664             bounds.right = mWidth;   // ???
665             bounds.bottom = getLineTop(line + 1);
666         }
667         return getLineBaseline(line);
668     }
669
670     /**
671      * Return the vertical position of the top of the specified line
672      * (0&hellip;getLineCount()).
673      * If the specified line is equal to the line count, returns the
674      * bottom of the last line.
675      */
676     public abstract int getLineTop(int line);
677
678     /**
679      * Return the descent of the specified line(0&hellip;getLineCount() - 1).
680      */
681     public abstract int getLineDescent(int line);
682
683     /**
684      * Return the text offset of the beginning of the specified line (
685      * 0&hellip;getLineCount()). If the specified line is equal to the line
686      * count, returns the length of the text.
687      */
688     public abstract int getLineStart(int line);
689
690     /**
691      * Returns the primary directionality of the paragraph containing the
692      * specified line, either 1 for left-to-right lines, or -1 for right-to-left
693      * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
694      */
695     public abstract int getParagraphDirection(int line);
696
697     /**
698      * Returns whether the specified line contains one or more
699      * characters that need to be handled specially, like tabs.
700      */
701     public abstract boolean getLineContainsTab(int line);
702
703     /**
704      * Returns the directional run information for the specified line.
705      * The array alternates counts of characters in left-to-right
706      * and right-to-left segments of the line.
707      *
708      * <p>NOTE: this is inadequate to support bidirectional text, and will change.
709      */
710     public abstract Directions getLineDirections(int line);
711
712     /**
713      * Returns the (negative) number of extra pixels of ascent padding in the
714      * top line of the Layout.
715      */
716     public abstract int getTopPadding();
717
718     /**
719      * Returns the number of extra pixels of descent padding in the
720      * bottom line of the Layout.
721      */
722     public abstract int getBottomPadding();
723
724     /**
725      * Returns the hyphen edit for a line.
726      *
727      * @hide
728      */
729     public int getHyphen(int line) {
730         return 0;
731     }
732
733     /**
734      * Returns the left indent for a line.
735      *
736      * @hide
737      */
738     public int getIndentAdjust(int line, Alignment alignment) {
739         return 0;
740     }
741
742     /**
743      * Returns true if the character at offset and the preceding character
744      * are at different run levels (and thus there's a split caret).
745      * @param offset the offset
746      * @return true if at a level boundary
747      * @hide
748      */
749     public boolean isLevelBoundary(int offset) {
750         int line = getLineForOffset(offset);
751         Directions dirs = getLineDirections(line);
752         if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
753             return false;
754         }
755
756         int[] runs = dirs.mDirections;
757         int lineStart = getLineStart(line);
758         int lineEnd = getLineEnd(line);
759         if (offset == lineStart || offset == lineEnd) {
760             int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
761             int runIndex = offset == lineStart ? 0 : runs.length - 2;
762             return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
763         }
764
765         offset -= lineStart;
766         for (int i = 0; i < runs.length; i += 2) {
767             if (offset == runs[i]) {
768                 return true;
769             }
770         }
771         return false;
772     }
773
774     /**
775      * Returns true if the character at offset is right to left (RTL).
776      * @param offset the offset
777      * @return true if the character is RTL, false if it is LTR
778      */
779     public boolean isRtlCharAt(int offset) {
780         int line = getLineForOffset(offset);
781         Directions dirs = getLineDirections(line);
782         if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
783             return false;
784         }
785         if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
786             return  true;
787         }
788         int[] runs = dirs.mDirections;
789         int lineStart = getLineStart(line);
790         for (int i = 0; i < runs.length; i += 2) {
791             int start = lineStart + runs[i];
792             int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
793             if (offset >= start && offset < limit) {
794                 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
795                 return ((level & 1) != 0);
796             }
797         }
798         // Should happen only if the offset is "out of bounds"
799         return false;
800     }
801
802     /**
803      * Returns the range of the run that the character at offset belongs to.
804      * @param offset the offset
805      * @return The range of the run
806      * @hide
807      */
808     public long getRunRange(int offset) {
809         int line = getLineForOffset(offset);
810         Directions dirs = getLineDirections(line);
811         if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
812             return TextUtils.packRangeInLong(0, getLineEnd(line));
813         }
814         int[] runs = dirs.mDirections;
815         int lineStart = getLineStart(line);
816         for (int i = 0; i < runs.length; i += 2) {
817             int start = lineStart + runs[i];
818             int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
819             if (offset >= start && offset < limit) {
820                 return TextUtils.packRangeInLong(start, limit);
821             }
822         }
823         // Should happen only if the offset is "out of bounds"
824         return TextUtils.packRangeInLong(0, getLineEnd(line));
825     }
826
827     /**
828      * Checks if the trailing BiDi level should be used for an offset
829      *
830      * This method is useful when the offset is at the BiDi level transition point and determine
831      * which run need to be used. For example, let's think about following input: (L* denotes
832      * Left-to-Right characters, R* denotes Right-to-Left characters.)
833      * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
834      * Input (Display Order): L1 L2 L3 R3 R2 R1 L4 L5 L6
835      *
836      * Then, think about selecting the range (3, 6). The offset=3 and offset=6 are ambiguous here
837      * since they are at the BiDi transition point.  In Android, the offset is considered to be
838      * associated with the trailing run if the BiDi level of the trailing run is higher than of the
839      * previous run.  In this case, the BiDi level of the input text is as follows:
840      *
841      * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
842      *              BiDi Run: [ Run 0 ][ Run 1 ][ Run 2 ]
843      *            BiDi Level:  0  0  0  1  1  1  0  0  0
844      *
845      * Thus, offset = 3 is part of Run 1 and this method returns true for offset = 3, since the BiDi
846      * level of Run 1 is higher than the level of Run 0.  Similarly, the offset = 6 is a part of Run
847      * 1 and this method returns false for the offset = 6 since the BiDi level of Run 1 is higher
848      * than the level of Run 2.
849      *
850      * @returns true if offset is at the BiDi level transition point and trailing BiDi level is
851      *          higher than previous BiDi level. See above for the detail.
852      */
853     private boolean primaryIsTrailingPrevious(int offset) {
854         int line = getLineForOffset(offset);
855         int lineStart = getLineStart(line);
856         int lineEnd = getLineEnd(line);
857         int[] runs = getLineDirections(line).mDirections;
858
859         int levelAt = -1;
860         for (int i = 0; i < runs.length; i += 2) {
861             int start = lineStart + runs[i];
862             int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
863             if (limit > lineEnd) {
864                 limit = lineEnd;
865             }
866             if (offset >= start && offset < limit) {
867                 if (offset > start) {
868                     // Previous character is at same level, so don't use trailing.
869                     return false;
870                 }
871                 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
872                 break;
873             }
874         }
875         if (levelAt == -1) {
876             // Offset was limit of line.
877             levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
878         }
879
880         // At level boundary, check previous level.
881         int levelBefore = -1;
882         if (offset == lineStart) {
883             levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
884         } else {
885             offset -= 1;
886             for (int i = 0; i < runs.length; i += 2) {
887                 int start = lineStart + runs[i];
888                 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
889                 if (limit > lineEnd) {
890                     limit = lineEnd;
891                 }
892                 if (offset >= start && offset < limit) {
893                     levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
894                     break;
895                 }
896             }
897         }
898
899         return levelBefore < levelAt;
900     }
901
902     /**
903      * Computes in linear time the results of calling
904      * #primaryIsTrailingPrevious for all offsets on a line.
905      * @param line The line giving the offsets we compute the information for
906      * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
907      */
908     private boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
909         int lineStart = getLineStart(line);
910         int lineEnd = getLineEnd(line);
911         int[] runs = getLineDirections(line).mDirections;
912
913         boolean[] trailing = new boolean[lineEnd - lineStart + 1];
914
915         byte[] level = new byte[lineEnd - lineStart + 1];
916         for (int i = 0; i < runs.length; i += 2) {
917             int start = lineStart + runs[i];
918             int limit = start + (runs[i + 1] & RUN_LENGTH_MASK);
919             if (limit > lineEnd) {
920                 limit = lineEnd;
921             }
922             level[limit - lineStart - 1] =
923                     (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
924         }
925
926         for (int i = 0; i < runs.length; i += 2) {
927             int start = lineStart + runs[i];
928             byte currentLevel = (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
929             trailing[start - lineStart] = currentLevel > (start == lineStart
930                     ? (getParagraphDirection(line) == 1 ? 0 : 1)
931                     : level[start - lineStart - 1]);
932         }
933
934         return trailing;
935     }
936
937     /**
938      * Get the primary horizontal position for the specified text offset.
939      * This is the location where a new character would be inserted in
940      * the paragraph's primary direction.
941      */
942     public float getPrimaryHorizontal(int offset) {
943         return getPrimaryHorizontal(offset, false /* not clamped */);
944     }
945
946     /**
947      * Get the primary horizontal position for the specified text offset, but
948      * optionally clamp it so that it doesn't exceed the width of the layout.
949      * @hide
950      */
951     public float getPrimaryHorizontal(int offset, boolean clamped) {
952         boolean trailing = primaryIsTrailingPrevious(offset);
953         return getHorizontal(offset, trailing, clamped);
954     }
955
956     /**
957      * Get the secondary horizontal position for the specified text offset.
958      * This is the location where a new character would be inserted in
959      * the direction other than the paragraph's primary direction.
960      */
961     public float getSecondaryHorizontal(int offset) {
962         return getSecondaryHorizontal(offset, false /* not clamped */);
963     }
964
965     /**
966      * Get the secondary horizontal position for the specified text offset, but
967      * optionally clamp it so that it doesn't exceed the width of the layout.
968      * @hide
969      */
970     public float getSecondaryHorizontal(int offset, boolean clamped) {
971         boolean trailing = primaryIsTrailingPrevious(offset);
972         return getHorizontal(offset, !trailing, clamped);
973     }
974
975     private float getHorizontal(int offset, boolean primary) {
976         return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
977     }
978
979     private float getHorizontal(int offset, boolean trailing, boolean clamped) {
980         int line = getLineForOffset(offset);
981
982         return getHorizontal(offset, trailing, line, clamped);
983     }
984
985     private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
986         int start = getLineStart(line);
987         int end = getLineEnd(line);
988         int dir = getParagraphDirection(line);
989         boolean hasTab = getLineContainsTab(line);
990         Directions directions = getLineDirections(line);
991
992         TabStops tabStops = null;
993         if (hasTab && mText instanceof Spanned) {
994             // Just checking this line should be good enough, tabs should be
995             // consistent across all lines in a paragraph.
996             TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
997             if (tabs.length > 0) {
998                 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
999             }
1000         }
1001
1002         TextLine tl = TextLine.obtain();
1003         tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
1004         float wid = tl.measure(offset - start, trailing, null);
1005         TextLine.recycle(tl);
1006
1007         if (clamped && wid > mWidth) {
1008             wid = mWidth;
1009         }
1010         int left = getParagraphLeft(line);
1011         int right = getParagraphRight(line);
1012
1013         return getLineStartPos(line, left, right) + wid;
1014     }
1015
1016     /**
1017      * Computes in linear time the results of calling
1018      * #getHorizontal for all offsets on a line.
1019      * @param line The line giving the offsets we compute information for
1020      * @param clamped Whether to clamp the results to the width of the layout
1021      * @param primary Whether the results should be the primary or the secondary horizontal
1022      * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1023      */
1024     private float[] getLineHorizontals(int line, boolean clamped, boolean primary) {
1025         int start = getLineStart(line);
1026         int end = getLineEnd(line);
1027         int dir = getParagraphDirection(line);
1028         boolean hasTab = getLineContainsTab(line);
1029         Directions directions = getLineDirections(line);
1030
1031         TabStops tabStops = null;
1032         if (hasTab && mText instanceof Spanned) {
1033             // Just checking this line should be good enough, tabs should be
1034             // consistent across all lines in a paragraph.
1035             TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1036             if (tabs.length > 0) {
1037                 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1038             }
1039         }
1040
1041         TextLine tl = TextLine.obtain();
1042         tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
1043         boolean[] trailings = primaryIsTrailingPreviousAllLineOffsets(line);
1044         if (!primary) {
1045             for (int offset = 0; offset < trailings.length; ++offset) {
1046                 trailings[offset] = !trailings[offset];
1047             }
1048         }
1049         float[] wid = tl.measureAllOffsets(trailings, null);
1050         TextLine.recycle(tl);
1051
1052         if (clamped) {
1053             for (int offset = 0; offset <= wid.length; ++offset) {
1054                 if (wid[offset] > mWidth) {
1055                     wid[offset] = mWidth;
1056                 }
1057             }
1058         }
1059         int left = getParagraphLeft(line);
1060         int right = getParagraphRight(line);
1061
1062         int lineStartPos = getLineStartPos(line, left, right);
1063         float[] horizontal = new float[end - start + 1];
1064         for (int offset = 0; offset < horizontal.length; ++offset) {
1065             horizontal[offset] = lineStartPos + wid[offset];
1066         }
1067         return horizontal;
1068     }
1069
1070     /**
1071      * Get the leftmost position that should be exposed for horizontal
1072      * scrolling on the specified line.
1073      */
1074     public float getLineLeft(int line) {
1075         int dir = getParagraphDirection(line);
1076         Alignment align = getParagraphAlignment(line);
1077
1078         if (align == Alignment.ALIGN_LEFT) {
1079             return 0;
1080         } else if (align == Alignment.ALIGN_NORMAL) {
1081             if (dir == DIR_RIGHT_TO_LEFT)
1082                 return getParagraphRight(line) - getLineMax(line);
1083             else
1084                 return 0;
1085         } else if (align == Alignment.ALIGN_RIGHT) {
1086             return mWidth - getLineMax(line);
1087         } else if (align == Alignment.ALIGN_OPPOSITE) {
1088             if (dir == DIR_RIGHT_TO_LEFT)
1089                 return 0;
1090             else
1091                 return mWidth - getLineMax(line);
1092         } else { /* align == Alignment.ALIGN_CENTER */
1093             int left = getParagraphLeft(line);
1094             int right = getParagraphRight(line);
1095             int max = ((int) getLineMax(line)) & ~1;
1096
1097             return left + ((right - left) - max) / 2;
1098         }
1099     }
1100
1101     /**
1102      * Get the rightmost position that should be exposed for horizontal
1103      * scrolling on the specified line.
1104      */
1105     public float getLineRight(int line) {
1106         int dir = getParagraphDirection(line);
1107         Alignment align = getParagraphAlignment(line);
1108
1109         if (align == Alignment.ALIGN_LEFT) {
1110             return getParagraphLeft(line) + getLineMax(line);
1111         } else if (align == Alignment.ALIGN_NORMAL) {
1112             if (dir == DIR_RIGHT_TO_LEFT)
1113                 return mWidth;
1114             else
1115                 return getParagraphLeft(line) + getLineMax(line);
1116         } else if (align == Alignment.ALIGN_RIGHT) {
1117             return mWidth;
1118         } else if (align == Alignment.ALIGN_OPPOSITE) {
1119             if (dir == DIR_RIGHT_TO_LEFT)
1120                 return getLineMax(line);
1121             else
1122                 return mWidth;
1123         } else { /* align == Alignment.ALIGN_CENTER */
1124             int left = getParagraphLeft(line);
1125             int right = getParagraphRight(line);
1126             int max = ((int) getLineMax(line)) & ~1;
1127
1128             return right - ((right - left) - max) / 2;
1129         }
1130     }
1131
1132     /**
1133      * Gets the unsigned horizontal extent of the specified line, including
1134      * leading margin indent, but excluding trailing whitespace.
1135      */
1136     public float getLineMax(int line) {
1137         float margin = getParagraphLeadingMargin(line);
1138         float signedExtent = getLineExtent(line, false);
1139         return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1140     }
1141
1142     /**
1143      * Gets the unsigned horizontal extent of the specified line, including
1144      * leading margin indent and trailing whitespace.
1145      */
1146     public float getLineWidth(int line) {
1147         float margin = getParagraphLeadingMargin(line);
1148         float signedExtent = getLineExtent(line, true);
1149         return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1150     }
1151
1152     /**
1153      * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1154      * tab stops instead of using the ones passed in.
1155      * @param line the index of the line
1156      * @param full whether to include trailing whitespace
1157      * @return the extent of the line
1158      */
1159     private float getLineExtent(int line, boolean full) {
1160         int start = getLineStart(line);
1161         int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1162
1163         boolean hasTabs = getLineContainsTab(line);
1164         TabStops tabStops = null;
1165         if (hasTabs && mText instanceof Spanned) {
1166             // Just checking this line should be good enough, tabs should be
1167             // consistent across all lines in a paragraph.
1168             TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1169             if (tabs.length > 0) {
1170                 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1171             }
1172         }
1173         Directions directions = getLineDirections(line);
1174         // Returned directions can actually be null
1175         if (directions == null) {
1176             return 0f;
1177         }
1178         int dir = getParagraphDirection(line);
1179
1180         TextLine tl = TextLine.obtain();
1181         tl.set(mPaint, mText, start, end, dir, directions, hasTabs, tabStops);
1182         float width = tl.metrics(null);
1183         TextLine.recycle(tl);
1184         return width;
1185     }
1186
1187     /**
1188      * Returns the signed horizontal extent of the specified line, excluding
1189      * leading margin.  If full is false, excludes trailing whitespace.
1190      * @param line the index of the line
1191      * @param tabStops the tab stops, can be null if we know they're not used.
1192      * @param full whether to include trailing whitespace
1193      * @return the extent of the text on this line
1194      */
1195     private float getLineExtent(int line, TabStops tabStops, boolean full) {
1196         int start = getLineStart(line);
1197         int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1198         boolean hasTabs = getLineContainsTab(line);
1199         Directions directions = getLineDirections(line);
1200         int dir = getParagraphDirection(line);
1201
1202         TextLine tl = TextLine.obtain();
1203         tl.set(mPaint, mText, start, end, dir, directions, hasTabs, tabStops);
1204         float width = tl.metrics(null);
1205         TextLine.recycle(tl);
1206         return width;
1207     }
1208
1209     /**
1210      * Get the line number corresponding to the specified vertical position.
1211      * If you ask for a position above 0, you get 0; if you ask for a position
1212      * below the bottom of the text, you get the last line.
1213      */
1214     // FIXME: It may be faster to do a linear search for layouts without many lines.
1215     public int getLineForVertical(int vertical) {
1216         int high = getLineCount(), low = -1, guess;
1217
1218         while (high - low > 1) {
1219             guess = (high + low) / 2;
1220
1221             if (getLineTop(guess) > vertical)
1222                 high = guess;
1223             else
1224                 low = guess;
1225         }
1226
1227         if (low < 0)
1228             return 0;
1229         else
1230             return low;
1231     }
1232
1233     /**
1234      * Get the line number on which the specified text offset appears.
1235      * If you ask for a position before 0, you get 0; if you ask for a position
1236      * beyond the end of the text, you get the last line.
1237      */
1238     public int getLineForOffset(int offset) {
1239         int high = getLineCount(), low = -1, guess;
1240
1241         while (high - low > 1) {
1242             guess = (high + low) / 2;
1243
1244             if (getLineStart(guess) > offset)
1245                 high = guess;
1246             else
1247                 low = guess;
1248         }
1249
1250         if (low < 0)
1251             return 0;
1252         else
1253             return low;
1254     }
1255
1256     /**
1257      * Get the character offset on the specified line whose position is
1258      * closest to the specified horizontal position.
1259      */
1260     public int getOffsetForHorizontal(int line, float horiz) {
1261         return getOffsetForHorizontal(line, horiz, true);
1262     }
1263
1264     /**
1265      * Get the character offset on the specified line whose position is
1266      * closest to the specified horizontal position.
1267      *
1268      * @param line the line used to find the closest offset
1269      * @param horiz the horizontal position used to find the closest offset
1270      * @param primary whether to use the primary position or secondary position to find the offset
1271      *
1272      * @hide
1273      */
1274     public int getOffsetForHorizontal(int line, float horiz, boolean primary) {
1275         // TODO: use Paint.getOffsetForAdvance to avoid binary search
1276         final int lineEndOffset = getLineEnd(line);
1277         final int lineStartOffset = getLineStart(line);
1278
1279         Directions dirs = getLineDirections(line);
1280
1281         TextLine tl = TextLine.obtain();
1282         // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1283         tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
1284                 false, null);
1285         final HorizontalMeasurementProvider horizontal =
1286                 new HorizontalMeasurementProvider(line, primary);
1287
1288         final int max;
1289         if (line == getLineCount() - 1) {
1290             max = lineEndOffset;
1291         } else {
1292             max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1293                     !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
1294         }
1295         int best = lineStartOffset;
1296         float bestdist = Math.abs(horizontal.get(lineStartOffset) - horiz);
1297
1298         for (int i = 0; i < dirs.mDirections.length; i += 2) {
1299             int here = lineStartOffset + dirs.mDirections[i];
1300             int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1301             boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1302             int swap = isRtl ? -1 : 1;
1303
1304             if (there > max)
1305                 there = max;
1306             int high = there - 1 + 1, low = here + 1 - 1, guess;
1307
1308             while (high - low > 1) {
1309                 guess = (high + low) / 2;
1310                 int adguess = getOffsetAtStartOf(guess);
1311
1312                 if (horizontal.get(adguess) * swap >= horiz * swap)
1313                     high = guess;
1314                 else
1315                     low = guess;
1316             }
1317
1318             if (low < here + 1)
1319                 low = here + 1;
1320
1321             if (low < there) {
1322                 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1323                 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1324                 if (low >= here && low < there) {
1325                     float dist = Math.abs(horizontal.get(low) - horiz);
1326                     if (aft < there) {
1327                         float other = Math.abs(horizontal.get(aft) - horiz);
1328
1329                         if (other < dist) {
1330                             dist = other;
1331                             low = aft;
1332                         }
1333                     }
1334
1335                     if (dist < bestdist) {
1336                         bestdist = dist;
1337                         best = low;
1338                     }
1339                 }
1340             }
1341
1342             float dist = Math.abs(horizontal.get(here) - horiz);
1343
1344             if (dist < bestdist) {
1345                 bestdist = dist;
1346                 best = here;
1347             }
1348         }
1349
1350         float dist = Math.abs(horizontal.get(max) - horiz);
1351
1352         if (dist <= bestdist) {
1353             bestdist = dist;
1354             best = max;
1355         }
1356
1357         TextLine.recycle(tl);
1358         return best;
1359     }
1360
1361     /**
1362      * Responds to #getHorizontal queries, by selecting the better strategy between:
1363      * - calling #getHorizontal explicitly for each query
1364      * - precomputing all #getHorizontal measurements, and responding to any query in constant time
1365      * The first strategy is used for LTR-only text, while the second is used for all other cases.
1366      * The class is currently only used in #getOffsetForHorizontal, so reuse with care in other
1367      * contexts.
1368      */
1369     private class HorizontalMeasurementProvider {
1370         private final int mLine;
1371         private final boolean mPrimary;
1372
1373         private float[] mHorizontals;
1374         private int mLineStartOffset;
1375
1376         HorizontalMeasurementProvider(final int line, final boolean primary) {
1377             mLine = line;
1378             mPrimary = primary;
1379             init();
1380         }
1381
1382         private void init() {
1383             final Directions dirs = getLineDirections(mLine);
1384             if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1385                 return;
1386             }
1387
1388             mHorizontals = getLineHorizontals(mLine, false, mPrimary);
1389             mLineStartOffset = getLineStart(mLine);
1390         }
1391
1392         float get(final int offset) {
1393             if (mHorizontals == null) {
1394                 return getHorizontal(offset, mPrimary);
1395             } else {
1396                 return mHorizontals[offset - mLineStartOffset];
1397             }
1398         }
1399     }
1400
1401     /**
1402      * Return the text offset after the last character on the specified line.
1403      */
1404     public final int getLineEnd(int line) {
1405         return getLineStart(line + 1);
1406     }
1407
1408     /**
1409      * Return the text offset after the last visible character (so whitespace
1410      * is not counted) on the specified line.
1411      */
1412     public int getLineVisibleEnd(int line) {
1413         return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1414     }
1415
1416     private int getLineVisibleEnd(int line, int start, int end) {
1417         CharSequence text = mText;
1418         char ch;
1419         if (line == getLineCount() - 1) {
1420             return end;
1421         }
1422
1423         for (; end > start; end--) {
1424             ch = text.charAt(end - 1);
1425
1426             if (ch == '\n') {
1427                 return end - 1;
1428             }
1429
1430             // Note: keep this in sync with Minikin LineBreaker::isLineEndSpace()
1431             if (!(ch == ' ' || ch == '\t' || ch == 0x1680 ||
1432                     (0x2000 <= ch && ch <= 0x200A && ch != 0x2007) ||
1433                     ch == 0x205F || ch == 0x3000)) {
1434                 break;
1435             }
1436
1437         }
1438
1439         return end;
1440     }
1441
1442     /**
1443      * Return the vertical position of the bottom of the specified line.
1444      */
1445     public final int getLineBottom(int line) {
1446         return getLineTop(line + 1);
1447     }
1448
1449     /**
1450      * Return the vertical position of the baseline of the specified line.
1451      */
1452     public final int getLineBaseline(int line) {
1453         // getLineTop(line+1) == getLineTop(line)
1454         return getLineTop(line+1) - getLineDescent(line);
1455     }
1456
1457     /**
1458      * Get the ascent of the text on the specified line.
1459      * The return value is negative to match the Paint.ascent() convention.
1460      */
1461     public final int getLineAscent(int line) {
1462         // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1463         return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1464     }
1465
1466     public int getOffsetToLeftOf(int offset) {
1467         return getOffsetToLeftRightOf(offset, true);
1468     }
1469
1470     public int getOffsetToRightOf(int offset) {
1471         return getOffsetToLeftRightOf(offset, false);
1472     }
1473
1474     private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1475         int line = getLineForOffset(caret);
1476         int lineStart = getLineStart(line);
1477         int lineEnd = getLineEnd(line);
1478         int lineDir = getParagraphDirection(line);
1479
1480         boolean lineChanged = false;
1481         boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
1482         // if walking off line, look at the line we're headed to
1483         if (advance) {
1484             if (caret == lineEnd) {
1485                 if (line < getLineCount() - 1) {
1486                     lineChanged = true;
1487                     ++line;
1488                 } else {
1489                     return caret; // at very end, don't move
1490                 }
1491             }
1492         } else {
1493             if (caret == lineStart) {
1494                 if (line > 0) {
1495                     lineChanged = true;
1496                     --line;
1497                 } else {
1498                     return caret; // at very start, don't move
1499                 }
1500             }
1501         }
1502
1503         if (lineChanged) {
1504             lineStart = getLineStart(line);
1505             lineEnd = getLineEnd(line);
1506             int newDir = getParagraphDirection(line);
1507             if (newDir != lineDir) {
1508                 // unusual case.  we want to walk onto the line, but it runs
1509                 // in a different direction than this one, so we fake movement
1510                 // in the opposite direction.
1511                 toLeft = !toLeft;
1512                 lineDir = newDir;
1513             }
1514         }
1515
1516         Directions directions = getLineDirections(line);
1517
1518         TextLine tl = TextLine.obtain();
1519         // XXX: we don't care about tabs
1520         tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null);
1521         caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
1522         tl = TextLine.recycle(tl);
1523         return caret;
1524     }
1525
1526     private int getOffsetAtStartOf(int offset) {
1527         // XXX this probably should skip local reorderings and
1528         // zero-width characters, look at callers
1529         if (offset == 0)
1530             return 0;
1531
1532         CharSequence text = mText;
1533         char c = text.charAt(offset);
1534
1535         if (c >= '\uDC00' && c <= '\uDFFF') {
1536             char c1 = text.charAt(offset - 1);
1537
1538             if (c1 >= '\uD800' && c1 <= '\uDBFF')
1539                 offset -= 1;
1540         }
1541
1542         if (mSpannedText) {
1543             ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1544                                                        ReplacementSpan.class);
1545
1546             for (int i = 0; i < spans.length; i++) {
1547                 int start = ((Spanned) text).getSpanStart(spans[i]);
1548                 int end = ((Spanned) text).getSpanEnd(spans[i]);
1549
1550                 if (start < offset && end > offset)
1551                     offset = start;
1552             }
1553         }
1554
1555         return offset;
1556     }
1557
1558     /**
1559      * Determine whether we should clamp cursor position. Currently it's
1560      * only robust for left-aligned displays.
1561      * @hide
1562      */
1563     public boolean shouldClampCursor(int line) {
1564         // Only clamp cursor position in left-aligned displays.
1565         switch (getParagraphAlignment(line)) {
1566             case ALIGN_LEFT:
1567                 return true;
1568             case ALIGN_NORMAL:
1569                 return getParagraphDirection(line) > 0;
1570             default:
1571                 return false;
1572         }
1573
1574     }
1575     /**
1576      * Fills in the specified Path with a representation of a cursor
1577      * at the specified offset.  This will often be a vertical line
1578      * but can be multiple discontinuous lines in text with multiple
1579      * directionalities.
1580      */
1581     public void getCursorPath(int point, Path dest,
1582                               CharSequence editingBuffer) {
1583         dest.reset();
1584
1585         int line = getLineForOffset(point);
1586         int top = getLineTop(line);
1587         int bottom = getLineTop(line+1);
1588
1589         boolean clamped = shouldClampCursor(line);
1590         float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1591         float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
1592
1593         int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1594                    TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1595         int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
1596         int dist = 0;
1597
1598         if (caps != 0 || fn != 0) {
1599             dist = (bottom - top) >> 2;
1600
1601             if (fn != 0)
1602                 top += dist;
1603             if (caps != 0)
1604                 bottom -= dist;
1605         }
1606
1607         if (h1 < 0.5f)
1608             h1 = 0.5f;
1609         if (h2 < 0.5f)
1610             h2 = 0.5f;
1611
1612         if (Float.compare(h1, h2) == 0) {
1613             dest.moveTo(h1, top);
1614             dest.lineTo(h1, bottom);
1615         } else {
1616             dest.moveTo(h1, top);
1617             dest.lineTo(h1, (top + bottom) >> 1);
1618
1619             dest.moveTo(h2, (top + bottom) >> 1);
1620             dest.lineTo(h2, bottom);
1621         }
1622
1623         if (caps == 2) {
1624             dest.moveTo(h2, bottom);
1625             dest.lineTo(h2 - dist, bottom + dist);
1626             dest.lineTo(h2, bottom);
1627             dest.lineTo(h2 + dist, bottom + dist);
1628         } else if (caps == 1) {
1629             dest.moveTo(h2, bottom);
1630             dest.lineTo(h2 - dist, bottom + dist);
1631
1632             dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1633             dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1634
1635             dest.moveTo(h2 + dist, bottom + dist);
1636             dest.lineTo(h2, bottom);
1637         }
1638
1639         if (fn == 2) {
1640             dest.moveTo(h1, top);
1641             dest.lineTo(h1 - dist, top - dist);
1642             dest.lineTo(h1, top);
1643             dest.lineTo(h1 + dist, top - dist);
1644         } else if (fn == 1) {
1645             dest.moveTo(h1, top);
1646             dest.lineTo(h1 - dist, top - dist);
1647
1648             dest.moveTo(h1 - dist, top - dist + 0.5f);
1649             dest.lineTo(h1 + dist, top - dist + 0.5f);
1650
1651             dest.moveTo(h1 + dist, top - dist);
1652             dest.lineTo(h1, top);
1653         }
1654     }
1655
1656     private void addSelection(int line, int start, int end,
1657                               int top, int bottom, Path dest) {
1658         int linestart = getLineStart(line);
1659         int lineend = getLineEnd(line);
1660         Directions dirs = getLineDirections(line);
1661
1662         if (lineend > linestart && mText.charAt(lineend - 1) == '\n')
1663             lineend--;
1664
1665         for (int i = 0; i < dirs.mDirections.length; i += 2) {
1666             int here = linestart + dirs.mDirections[i];
1667             int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1668
1669             if (there > lineend)
1670                 there = lineend;
1671
1672             if (start <= there && end >= here) {
1673                 int st = Math.max(start, here);
1674                 int en = Math.min(end, there);
1675
1676                 if (st != en) {
1677                     float h1 = getHorizontal(st, false, line, false /* not clamped */);
1678                     float h2 = getHorizontal(en, true, line, false /* not clamped */);
1679
1680                     float left = Math.min(h1, h2);
1681                     float right = Math.max(h1, h2);
1682
1683                     dest.addRect(left, top, right, bottom, Path.Direction.CW);
1684                 }
1685             }
1686         }
1687     }
1688
1689     /**
1690      * Fills in the specified Path with a representation of a highlight
1691      * between the specified offsets.  This will often be a rectangle
1692      * or a potentially discontinuous set of rectangles.  If the start
1693      * and end are the same, the returned path is empty.
1694      */
1695     public void getSelectionPath(int start, int end, Path dest) {
1696         dest.reset();
1697
1698         if (start == end)
1699             return;
1700
1701         if (end < start) {
1702             int temp = end;
1703             end = start;
1704             start = temp;
1705         }
1706
1707         int startline = getLineForOffset(start);
1708         int endline = getLineForOffset(end);
1709
1710         int top = getLineTop(startline);
1711         int bottom = getLineBottom(endline);
1712
1713         if (startline == endline) {
1714             addSelection(startline, start, end, top, bottom, dest);
1715         } else {
1716             final float width = mWidth;
1717
1718             addSelection(startline, start, getLineEnd(startline),
1719                          top, getLineBottom(startline), dest);
1720
1721             if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT)
1722                 dest.addRect(getLineLeft(startline), top,
1723                               0, getLineBottom(startline), Path.Direction.CW);
1724             else
1725                 dest.addRect(getLineRight(startline), top,
1726                               width, getLineBottom(startline), Path.Direction.CW);
1727
1728             for (int i = startline + 1; i < endline; i++) {
1729                 top = getLineTop(i);
1730                 bottom = getLineBottom(i);
1731                 dest.addRect(0, top, width, bottom, Path.Direction.CW);
1732             }
1733
1734             top = getLineTop(endline);
1735             bottom = getLineBottom(endline);
1736
1737             addSelection(endline, getLineStart(endline), end,
1738                          top, bottom, dest);
1739
1740             if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT)
1741                 dest.addRect(width, top, getLineRight(endline), bottom, Path.Direction.CW);
1742             else
1743                 dest.addRect(0, top, getLineLeft(endline), bottom, Path.Direction.CW);
1744         }
1745     }
1746
1747     /**
1748      * Get the alignment of the specified paragraph, taking into account
1749      * markup attached to it.
1750      */
1751     public final Alignment getParagraphAlignment(int line) {
1752         Alignment align = mAlignment;
1753
1754         if (mSpannedText) {
1755             Spanned sp = (Spanned) mText;
1756             AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
1757                                                 getLineEnd(line),
1758                                                 AlignmentSpan.class);
1759
1760             int spanLength = spans.length;
1761             if (spanLength > 0) {
1762                 align = spans[spanLength-1].getAlignment();
1763             }
1764         }
1765
1766         return align;
1767     }
1768
1769     /**
1770      * Get the left edge of the specified paragraph, inset by left margins.
1771      */
1772     public final int getParagraphLeft(int line) {
1773         int left = 0;
1774         int dir = getParagraphDirection(line);
1775         if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
1776             return left; // leading margin has no impact, or no styles
1777         }
1778         return getParagraphLeadingMargin(line);
1779     }
1780
1781     /**
1782      * Get the right edge of the specified paragraph, inset by right margins.
1783      */
1784     public final int getParagraphRight(int line) {
1785         int right = mWidth;
1786         int dir = getParagraphDirection(line);
1787         if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
1788             return right; // leading margin has no impact, or no styles
1789         }
1790         return right - getParagraphLeadingMargin(line);
1791     }
1792
1793     /**
1794      * Returns the effective leading margin (unsigned) for this line,
1795      * taking into account LeadingMarginSpan and LeadingMarginSpan2.
1796      * @param line the line index
1797      * @return the leading margin of this line
1798      */
1799     private int getParagraphLeadingMargin(int line) {
1800         if (!mSpannedText) {
1801             return 0;
1802         }
1803         Spanned spanned = (Spanned) mText;
1804
1805         int lineStart = getLineStart(line);
1806         int lineEnd = getLineEnd(line);
1807         int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
1808                 LeadingMarginSpan.class);
1809         LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
1810                                                 LeadingMarginSpan.class);
1811         if (spans.length == 0) {
1812             return 0; // no leading margin span;
1813         }
1814
1815         int margin = 0;
1816
1817         boolean isFirstParaLine = lineStart == 0 ||
1818             spanned.charAt(lineStart - 1) == '\n';
1819
1820         boolean useFirstLineMargin = isFirstParaLine;
1821         for (int i = 0; i < spans.length; i++) {
1822             if (spans[i] instanceof LeadingMarginSpan2) {
1823                 int spStart = spanned.getSpanStart(spans[i]);
1824                 int spanLine = getLineForOffset(spStart);
1825                 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
1826                 // if there is more than one LeadingMarginSpan2, use the count that is greatest
1827                 useFirstLineMargin |= line < spanLine + count;
1828             }
1829         }
1830         for (int i = 0; i < spans.length; i++) {
1831             LeadingMarginSpan span = spans[i];
1832             margin += span.getLeadingMargin(useFirstLineMargin);
1833         }
1834
1835         return margin;
1836     }
1837
1838     /* package */
1839     static float measurePara(TextPaint paint, CharSequence text, int start, int end) {
1840
1841         MeasuredText mt = MeasuredText.obtain();
1842         TextLine tl = TextLine.obtain();
1843         try {
1844             mt.setPara(text, start, end, TextDirectionHeuristics.LTR, null);
1845             Directions directions;
1846             int dir;
1847             if (mt.mEasy) {
1848                 directions = DIRS_ALL_LEFT_TO_RIGHT;
1849                 dir = Layout.DIR_LEFT_TO_RIGHT;
1850             } else {
1851                 directions = AndroidBidi.directions(mt.mDir, mt.mLevels,
1852                     0, mt.mChars, 0, mt.mLen);
1853                 dir = mt.mDir;
1854             }
1855             char[] chars = mt.mChars;
1856             int len = mt.mLen;
1857             boolean hasTabs = false;
1858             TabStops tabStops = null;
1859             // leading margins should be taken into account when measuring a paragraph
1860             int margin = 0;
1861             if (text instanceof Spanned) {
1862                 Spanned spanned = (Spanned) text;
1863                 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
1864                         LeadingMarginSpan.class);
1865                 for (LeadingMarginSpan lms : spans) {
1866                     margin += lms.getLeadingMargin(true);
1867                 }
1868             }
1869             for (int i = 0; i < len; ++i) {
1870                 if (chars[i] == '\t') {
1871                     hasTabs = true;
1872                     if (text instanceof Spanned) {
1873                         Spanned spanned = (Spanned) text;
1874                         int spanEnd = spanned.nextSpanTransition(start, end,
1875                                 TabStopSpan.class);
1876                         TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
1877                                 TabStopSpan.class);
1878                         if (spans.length > 0) {
1879                             tabStops = new TabStops(TAB_INCREMENT, spans);
1880                         }
1881                     }
1882                     break;
1883                 }
1884             }
1885             tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops);
1886             return margin + tl.metrics(null);
1887         } finally {
1888             TextLine.recycle(tl);
1889             MeasuredText.recycle(mt);
1890         }
1891     }
1892
1893     /**
1894      * @hide
1895      */
1896     /* package */ static class TabStops {
1897         private int[] mStops;
1898         private int mNumStops;
1899         private int mIncrement;
1900
1901         TabStops(int increment, Object[] spans) {
1902             reset(increment, spans);
1903         }
1904
1905         void reset(int increment, Object[] spans) {
1906             this.mIncrement = increment;
1907
1908             int ns = 0;
1909             if (spans != null) {
1910                 int[] stops = this.mStops;
1911                 for (Object o : spans) {
1912                     if (o instanceof TabStopSpan) {
1913                         if (stops == null) {
1914                             stops = new int[10];
1915                         } else if (ns == stops.length) {
1916                             int[] nstops = new int[ns * 2];
1917                             for (int i = 0; i < ns; ++i) {
1918                                 nstops[i] = stops[i];
1919                             }
1920                             stops = nstops;
1921                         }
1922                         stops[ns++] = ((TabStopSpan) o).getTabStop();
1923                     }
1924                 }
1925                 if (ns > 1) {
1926                     Arrays.sort(stops, 0, ns);
1927                 }
1928                 if (stops != this.mStops) {
1929                     this.mStops = stops;
1930                 }
1931             }
1932             this.mNumStops = ns;
1933         }
1934
1935         float nextTab(float h) {
1936             int ns = this.mNumStops;
1937             if (ns > 0) {
1938                 int[] stops = this.mStops;
1939                 for (int i = 0; i < ns; ++i) {
1940                     int stop = stops[i];
1941                     if (stop > h) {
1942                         return stop;
1943                     }
1944                 }
1945             }
1946             return nextDefaultStop(h, mIncrement);
1947         }
1948
1949         public static float nextDefaultStop(float h, int inc) {
1950             return ((int) ((h + inc) / inc)) * inc;
1951         }
1952     }
1953
1954     /**
1955      * Returns the position of the next tab stop after h on the line.
1956      *
1957      * @param text the text
1958      * @param start start of the line
1959      * @param end limit of the line
1960      * @param h the current horizontal offset
1961      * @param tabs the tabs, can be null.  If it is null, any tabs in effect
1962      * on the line will be used.  If there are no tabs, a default offset
1963      * will be used to compute the tab stop.
1964      * @return the offset of the next tab stop.
1965      */
1966     /* package */ static float nextTab(CharSequence text, int start, int end,
1967                                        float h, Object[] tabs) {
1968         float nh = Float.MAX_VALUE;
1969         boolean alltabs = false;
1970
1971         if (text instanceof Spanned) {
1972             if (tabs == null) {
1973                 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
1974                 alltabs = true;
1975             }
1976
1977             for (int i = 0; i < tabs.length; i++) {
1978                 if (!alltabs) {
1979                     if (!(tabs[i] instanceof TabStopSpan))
1980                         continue;
1981                 }
1982
1983                 int where = ((TabStopSpan) tabs[i]).getTabStop();
1984
1985                 if (where < nh && where > h)
1986                     nh = where;
1987             }
1988
1989             if (nh != Float.MAX_VALUE)
1990                 return nh;
1991         }
1992
1993         return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
1994     }
1995
1996     protected final boolean isSpanned() {
1997         return mSpannedText;
1998     }
1999
2000     /**
2001      * Returns the same as <code>text.getSpans()</code>, except where
2002      * <code>start</code> and <code>end</code> are the same and are not
2003      * at the very beginning of the text, in which case an empty array
2004      * is returned instead.
2005      * <p>
2006      * This is needed because of the special case that <code>getSpans()</code>
2007      * on an empty range returns the spans adjacent to that range, which is
2008      * primarily for the sake of <code>TextWatchers</code> so they will get
2009      * notifications when text goes from empty to non-empty.  But it also
2010      * has the unfortunate side effect that if the text ends with an empty
2011      * paragraph, that paragraph accidentally picks up the styles of the
2012      * preceding paragraph (even though those styles will not be picked up
2013      * by new text that is inserted into the empty paragraph).
2014      * <p>
2015      * The reason it just checks whether <code>start</code> and <code>end</code>
2016      * is the same is that the only time a line can contain 0 characters
2017      * is if it is the final paragraph of the Layout; otherwise any line will
2018      * contain at least one printing or newline character.  The reason for the
2019      * additional check if <code>start</code> is greater than 0 is that
2020      * if the empty paragraph is the entire content of the buffer, paragraph
2021      * styles that are already applied to the buffer will apply to text that
2022      * is inserted into it.
2023      */
2024     /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
2025         if (start == end && start > 0) {
2026             return ArrayUtils.emptyArray(type);
2027         }
2028
2029         if(text instanceof SpannableStringBuilder) {
2030             return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2031         } else {
2032             return text.getSpans(start, end, type);
2033         }
2034     }
2035
2036     private char getEllipsisChar(TextUtils.TruncateAt method) {
2037         return (method == TextUtils.TruncateAt.END_SMALL) ?
2038                 TextUtils.ELLIPSIS_TWO_DOTS[0] :
2039                 TextUtils.ELLIPSIS_NORMAL[0];
2040     }
2041
2042     private void ellipsize(int start, int end, int line,
2043                            char[] dest, int destoff, TextUtils.TruncateAt method) {
2044         int ellipsisCount = getEllipsisCount(line);
2045
2046         if (ellipsisCount == 0) {
2047             return;
2048         }
2049
2050         int ellipsisStart = getEllipsisStart(line);
2051         int linestart = getLineStart(line);
2052
2053         for (int i = ellipsisStart; i < ellipsisStart + ellipsisCount; i++) {
2054             char c;
2055
2056             if (i == ellipsisStart) {
2057                 c = getEllipsisChar(method); // ellipsis
2058             } else {
2059                 c = '\uFEFF'; // 0-width space
2060             }
2061
2062             int a = i + linestart;
2063
2064             if (a >= start && a < end) {
2065                 dest[destoff + a - start] = c;
2066             }
2067         }
2068     }
2069
2070     /**
2071      * Stores information about bidirectional (left-to-right or right-to-left)
2072      * text within the layout of a line.
2073      */
2074     public static class Directions {
2075         // Directions represents directional runs within a line of text.
2076         // Runs are pairs of ints listed in visual order, starting from the
2077         // leading margin.  The first int of each pair is the offset from
2078         // the first character of the line to the start of the run.  The
2079         // second int represents both the length and level of the run.
2080         // The length is in the lower bits, accessed by masking with
2081         // DIR_LENGTH_MASK.  The level is in the higher bits, accessed
2082         // by shifting by DIR_LEVEL_SHIFT and masking by DIR_LEVEL_MASK.
2083         // To simply test for an RTL direction, test the bit using
2084         // DIR_RTL_FLAG, if set then the direction is rtl.
2085
2086         /* package */ int[] mDirections;
2087         /* package */ Directions(int[] dirs) {
2088             mDirections = dirs;
2089         }
2090     }
2091
2092     /**
2093      * Return the offset of the first character to be ellipsized away,
2094      * relative to the start of the line.  (So 0 if the beginning of the
2095      * line is ellipsized, not getLineStart().)
2096      */
2097     public abstract int getEllipsisStart(int line);
2098
2099     /**
2100      * Returns the number of characters to be ellipsized away, or 0 if
2101      * no ellipsis is to take place.
2102      */
2103     public abstract int getEllipsisCount(int line);
2104
2105     /* package */ static class Ellipsizer implements CharSequence, GetChars {
2106         /* package */ CharSequence mText;
2107         /* package */ Layout mLayout;
2108         /* package */ int mWidth;
2109         /* package */ TextUtils.TruncateAt mMethod;
2110
2111         public Ellipsizer(CharSequence s) {
2112             mText = s;
2113         }
2114
2115         public char charAt(int off) {
2116             char[] buf = TextUtils.obtain(1);
2117             getChars(off, off + 1, buf, 0);
2118             char ret = buf[0];
2119
2120             TextUtils.recycle(buf);
2121             return ret;
2122         }
2123
2124         public void getChars(int start, int end, char[] dest, int destoff) {
2125             int line1 = mLayout.getLineForOffset(start);
2126             int line2 = mLayout.getLineForOffset(end);
2127
2128             TextUtils.getChars(mText, start, end, dest, destoff);
2129
2130             for (int i = line1; i <= line2; i++) {
2131                 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
2132             }
2133         }
2134
2135         public int length() {
2136             return mText.length();
2137         }
2138
2139         public CharSequence subSequence(int start, int end) {
2140             char[] s = new char[end - start];
2141             getChars(start, end, s, 0);
2142             return new String(s);
2143         }
2144
2145         @Override
2146         public String toString() {
2147             char[] s = new char[length()];
2148             getChars(0, length(), s, 0);
2149             return new String(s);
2150         }
2151
2152     }
2153
2154     /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
2155         private Spanned mSpanned;
2156
2157         public SpannedEllipsizer(CharSequence display) {
2158             super(display);
2159             mSpanned = (Spanned) display;
2160         }
2161
2162         public <T> T[] getSpans(int start, int end, Class<T> type) {
2163             return mSpanned.getSpans(start, end, type);
2164         }
2165
2166         public int getSpanStart(Object tag) {
2167             return mSpanned.getSpanStart(tag);
2168         }
2169
2170         public int getSpanEnd(Object tag) {
2171             return mSpanned.getSpanEnd(tag);
2172         }
2173
2174         public int getSpanFlags(Object tag) {
2175             return mSpanned.getSpanFlags(tag);
2176         }
2177
2178         @SuppressWarnings("rawtypes")
2179         public int nextSpanTransition(int start, int limit, Class type) {
2180             return mSpanned.nextSpanTransition(start, limit, type);
2181         }
2182
2183         @Override
2184         public CharSequence subSequence(int start, int end) {
2185             char[] s = new char[end - start];
2186             getChars(start, end, s, 0);
2187
2188             SpannableString ss = new SpannableString(new String(s));
2189             TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2190             return ss;
2191         }
2192     }
2193
2194     private CharSequence mText;
2195     private TextPaint mPaint;
2196     private int mWidth;
2197     private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2198     private float mSpacingMult;
2199     private float mSpacingAdd;
2200     private static final Rect sTempRect = new Rect();
2201     private boolean mSpannedText;
2202     private TextDirectionHeuristic mTextDir;
2203     private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
2204
2205     public static final int DIR_LEFT_TO_RIGHT = 1;
2206     public static final int DIR_RIGHT_TO_LEFT = -1;
2207
2208     /* package */ static final int DIR_REQUEST_LTR = 1;
2209     /* package */ static final int DIR_REQUEST_RTL = -1;
2210     /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2211     /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
2212
2213     /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2214     /* package */ static final int RUN_LEVEL_SHIFT = 26;
2215     /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2216     /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2217
2218     public enum Alignment {
2219         ALIGN_NORMAL,
2220         ALIGN_OPPOSITE,
2221         ALIGN_CENTER,
2222         /** @hide */
2223         ALIGN_LEFT,
2224         /** @hide */
2225         ALIGN_RIGHT,
2226     }
2227
2228     private static final int TAB_INCREMENT = 20;
2229
2230     /* package */ static final Directions DIRS_ALL_LEFT_TO_RIGHT =
2231         new Directions(new int[] { 0, RUN_LENGTH_MASK });
2232     /* package */ static final Directions DIRS_ALL_RIGHT_TO_LEFT =
2233         new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });
2234
2235 }