OSDN Git Service

Merge changes from topic "am-0f30ee3d-94a0-4dc3-bb14-762781265ad9" into cw-f-dev
[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 || offset < mLineStartOffset
1394                     || offset >= mLineStartOffset + mHorizontals.length) {
1395                 return getHorizontal(offset, mPrimary);
1396             } else {
1397                 return mHorizontals[offset - mLineStartOffset];
1398             }
1399         }
1400     }
1401
1402     /**
1403      * Return the text offset after the last character on the specified line.
1404      */
1405     public final int getLineEnd(int line) {
1406         return getLineStart(line + 1);
1407     }
1408
1409     /**
1410      * Return the text offset after the last visible character (so whitespace
1411      * is not counted) on the specified line.
1412      */
1413     public int getLineVisibleEnd(int line) {
1414         return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1415     }
1416
1417     private int getLineVisibleEnd(int line, int start, int end) {
1418         CharSequence text = mText;
1419         char ch;
1420         if (line == getLineCount() - 1) {
1421             return end;
1422         }
1423
1424         for (; end > start; end--) {
1425             ch = text.charAt(end - 1);
1426
1427             if (ch == '\n') {
1428                 return end - 1;
1429             }
1430
1431             // Note: keep this in sync with Minikin LineBreaker::isLineEndSpace()
1432             if (!(ch == ' ' || ch == '\t' || ch == 0x1680 ||
1433                     (0x2000 <= ch && ch <= 0x200A && ch != 0x2007) ||
1434                     ch == 0x205F || ch == 0x3000)) {
1435                 break;
1436             }
1437
1438         }
1439
1440         return end;
1441     }
1442
1443     /**
1444      * Return the vertical position of the bottom of the specified line.
1445      */
1446     public final int getLineBottom(int line) {
1447         return getLineTop(line + 1);
1448     }
1449
1450     /**
1451      * Return the vertical position of the baseline of the specified line.
1452      */
1453     public final int getLineBaseline(int line) {
1454         // getLineTop(line+1) == getLineTop(line)
1455         return getLineTop(line+1) - getLineDescent(line);
1456     }
1457
1458     /**
1459      * Get the ascent of the text on the specified line.
1460      * The return value is negative to match the Paint.ascent() convention.
1461      */
1462     public final int getLineAscent(int line) {
1463         // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1464         return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1465     }
1466
1467     public int getOffsetToLeftOf(int offset) {
1468         return getOffsetToLeftRightOf(offset, true);
1469     }
1470
1471     public int getOffsetToRightOf(int offset) {
1472         return getOffsetToLeftRightOf(offset, false);
1473     }
1474
1475     private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1476         int line = getLineForOffset(caret);
1477         int lineStart = getLineStart(line);
1478         int lineEnd = getLineEnd(line);
1479         int lineDir = getParagraphDirection(line);
1480
1481         boolean lineChanged = false;
1482         boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
1483         // if walking off line, look at the line we're headed to
1484         if (advance) {
1485             if (caret == lineEnd) {
1486                 if (line < getLineCount() - 1) {
1487                     lineChanged = true;
1488                     ++line;
1489                 } else {
1490                     return caret; // at very end, don't move
1491                 }
1492             }
1493         } else {
1494             if (caret == lineStart) {
1495                 if (line > 0) {
1496                     lineChanged = true;
1497                     --line;
1498                 } else {
1499                     return caret; // at very start, don't move
1500                 }
1501             }
1502         }
1503
1504         if (lineChanged) {
1505             lineStart = getLineStart(line);
1506             lineEnd = getLineEnd(line);
1507             int newDir = getParagraphDirection(line);
1508             if (newDir != lineDir) {
1509                 // unusual case.  we want to walk onto the line, but it runs
1510                 // in a different direction than this one, so we fake movement
1511                 // in the opposite direction.
1512                 toLeft = !toLeft;
1513                 lineDir = newDir;
1514             }
1515         }
1516
1517         Directions directions = getLineDirections(line);
1518
1519         TextLine tl = TextLine.obtain();
1520         // XXX: we don't care about tabs
1521         tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null);
1522         caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
1523         tl = TextLine.recycle(tl);
1524         return caret;
1525     }
1526
1527     private int getOffsetAtStartOf(int offset) {
1528         // XXX this probably should skip local reorderings and
1529         // zero-width characters, look at callers
1530         if (offset == 0)
1531             return 0;
1532
1533         CharSequence text = mText;
1534         char c = text.charAt(offset);
1535
1536         if (c >= '\uDC00' && c <= '\uDFFF') {
1537             char c1 = text.charAt(offset - 1);
1538
1539             if (c1 >= '\uD800' && c1 <= '\uDBFF')
1540                 offset -= 1;
1541         }
1542
1543         if (mSpannedText) {
1544             ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1545                                                        ReplacementSpan.class);
1546
1547             for (int i = 0; i < spans.length; i++) {
1548                 int start = ((Spanned) text).getSpanStart(spans[i]);
1549                 int end = ((Spanned) text).getSpanEnd(spans[i]);
1550
1551                 if (start < offset && end > offset)
1552                     offset = start;
1553             }
1554         }
1555
1556         return offset;
1557     }
1558
1559     /**
1560      * Determine whether we should clamp cursor position. Currently it's
1561      * only robust for left-aligned displays.
1562      * @hide
1563      */
1564     public boolean shouldClampCursor(int line) {
1565         // Only clamp cursor position in left-aligned displays.
1566         switch (getParagraphAlignment(line)) {
1567             case ALIGN_LEFT:
1568                 return true;
1569             case ALIGN_NORMAL:
1570                 return getParagraphDirection(line) > 0;
1571             default:
1572                 return false;
1573         }
1574
1575     }
1576     /**
1577      * Fills in the specified Path with a representation of a cursor
1578      * at the specified offset.  This will often be a vertical line
1579      * but can be multiple discontinuous lines in text with multiple
1580      * directionalities.
1581      */
1582     public void getCursorPath(int point, Path dest,
1583                               CharSequence editingBuffer) {
1584         dest.reset();
1585
1586         int line = getLineForOffset(point);
1587         int top = getLineTop(line);
1588         int bottom = getLineTop(line+1);
1589
1590         boolean clamped = shouldClampCursor(line);
1591         float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1592         float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
1593
1594         int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1595                    TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1596         int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
1597         int dist = 0;
1598
1599         if (caps != 0 || fn != 0) {
1600             dist = (bottom - top) >> 2;
1601
1602             if (fn != 0)
1603                 top += dist;
1604             if (caps != 0)
1605                 bottom -= dist;
1606         }
1607
1608         if (h1 < 0.5f)
1609             h1 = 0.5f;
1610         if (h2 < 0.5f)
1611             h2 = 0.5f;
1612
1613         if (Float.compare(h1, h2) == 0) {
1614             dest.moveTo(h1, top);
1615             dest.lineTo(h1, bottom);
1616         } else {
1617             dest.moveTo(h1, top);
1618             dest.lineTo(h1, (top + bottom) >> 1);
1619
1620             dest.moveTo(h2, (top + bottom) >> 1);
1621             dest.lineTo(h2, bottom);
1622         }
1623
1624         if (caps == 2) {
1625             dest.moveTo(h2, bottom);
1626             dest.lineTo(h2 - dist, bottom + dist);
1627             dest.lineTo(h2, bottom);
1628             dest.lineTo(h2 + dist, bottom + dist);
1629         } else if (caps == 1) {
1630             dest.moveTo(h2, bottom);
1631             dest.lineTo(h2 - dist, bottom + dist);
1632
1633             dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1634             dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1635
1636             dest.moveTo(h2 + dist, bottom + dist);
1637             dest.lineTo(h2, bottom);
1638         }
1639
1640         if (fn == 2) {
1641             dest.moveTo(h1, top);
1642             dest.lineTo(h1 - dist, top - dist);
1643             dest.lineTo(h1, top);
1644             dest.lineTo(h1 + dist, top - dist);
1645         } else if (fn == 1) {
1646             dest.moveTo(h1, top);
1647             dest.lineTo(h1 - dist, top - dist);
1648
1649             dest.moveTo(h1 - dist, top - dist + 0.5f);
1650             dest.lineTo(h1 + dist, top - dist + 0.5f);
1651
1652             dest.moveTo(h1 + dist, top - dist);
1653             dest.lineTo(h1, top);
1654         }
1655     }
1656
1657     private void addSelection(int line, int start, int end,
1658                               int top, int bottom, Path dest) {
1659         int linestart = getLineStart(line);
1660         int lineend = getLineEnd(line);
1661         Directions dirs = getLineDirections(line);
1662
1663         if (lineend > linestart && mText.charAt(lineend - 1) == '\n')
1664             lineend--;
1665
1666         for (int i = 0; i < dirs.mDirections.length; i += 2) {
1667             int here = linestart + dirs.mDirections[i];
1668             int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1669
1670             if (there > lineend)
1671                 there = lineend;
1672
1673             if (start <= there && end >= here) {
1674                 int st = Math.max(start, here);
1675                 int en = Math.min(end, there);
1676
1677                 if (st != en) {
1678                     float h1 = getHorizontal(st, false, line, false /* not clamped */);
1679                     float h2 = getHorizontal(en, true, line, false /* not clamped */);
1680
1681                     float left = Math.min(h1, h2);
1682                     float right = Math.max(h1, h2);
1683
1684                     dest.addRect(left, top, right, bottom, Path.Direction.CW);
1685                 }
1686             }
1687         }
1688     }
1689
1690     /**
1691      * Fills in the specified Path with a representation of a highlight
1692      * between the specified offsets.  This will often be a rectangle
1693      * or a potentially discontinuous set of rectangles.  If the start
1694      * and end are the same, the returned path is empty.
1695      */
1696     public void getSelectionPath(int start, int end, Path dest) {
1697         dest.reset();
1698
1699         if (start == end)
1700             return;
1701
1702         if (end < start) {
1703             int temp = end;
1704             end = start;
1705             start = temp;
1706         }
1707
1708         int startline = getLineForOffset(start);
1709         int endline = getLineForOffset(end);
1710
1711         int top = getLineTop(startline);
1712         int bottom = getLineBottom(endline);
1713
1714         if (startline == endline) {
1715             addSelection(startline, start, end, top, bottom, dest);
1716         } else {
1717             final float width = mWidth;
1718
1719             addSelection(startline, start, getLineEnd(startline),
1720                          top, getLineBottom(startline), dest);
1721
1722             if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT)
1723                 dest.addRect(getLineLeft(startline), top,
1724                               0, getLineBottom(startline), Path.Direction.CW);
1725             else
1726                 dest.addRect(getLineRight(startline), top,
1727                               width, getLineBottom(startline), Path.Direction.CW);
1728
1729             for (int i = startline + 1; i < endline; i++) {
1730                 top = getLineTop(i);
1731                 bottom = getLineBottom(i);
1732                 dest.addRect(0, top, width, bottom, Path.Direction.CW);
1733             }
1734
1735             top = getLineTop(endline);
1736             bottom = getLineBottom(endline);
1737
1738             addSelection(endline, getLineStart(endline), end,
1739                          top, bottom, dest);
1740
1741             if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT)
1742                 dest.addRect(width, top, getLineRight(endline), bottom, Path.Direction.CW);
1743             else
1744                 dest.addRect(0, top, getLineLeft(endline), bottom, Path.Direction.CW);
1745         }
1746     }
1747
1748     /**
1749      * Get the alignment of the specified paragraph, taking into account
1750      * markup attached to it.
1751      */
1752     public final Alignment getParagraphAlignment(int line) {
1753         Alignment align = mAlignment;
1754
1755         if (mSpannedText) {
1756             Spanned sp = (Spanned) mText;
1757             AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
1758                                                 getLineEnd(line),
1759                                                 AlignmentSpan.class);
1760
1761             int spanLength = spans.length;
1762             if (spanLength > 0) {
1763                 align = spans[spanLength-1].getAlignment();
1764             }
1765         }
1766
1767         return align;
1768     }
1769
1770     /**
1771      * Get the left edge of the specified paragraph, inset by left margins.
1772      */
1773     public final int getParagraphLeft(int line) {
1774         int left = 0;
1775         int dir = getParagraphDirection(line);
1776         if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
1777             return left; // leading margin has no impact, or no styles
1778         }
1779         return getParagraphLeadingMargin(line);
1780     }
1781
1782     /**
1783      * Get the right edge of the specified paragraph, inset by right margins.
1784      */
1785     public final int getParagraphRight(int line) {
1786         int right = mWidth;
1787         int dir = getParagraphDirection(line);
1788         if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
1789             return right; // leading margin has no impact, or no styles
1790         }
1791         return right - getParagraphLeadingMargin(line);
1792     }
1793
1794     /**
1795      * Returns the effective leading margin (unsigned) for this line,
1796      * taking into account LeadingMarginSpan and LeadingMarginSpan2.
1797      * @param line the line index
1798      * @return the leading margin of this line
1799      */
1800     private int getParagraphLeadingMargin(int line) {
1801         if (!mSpannedText) {
1802             return 0;
1803         }
1804         Spanned spanned = (Spanned) mText;
1805
1806         int lineStart = getLineStart(line);
1807         int lineEnd = getLineEnd(line);
1808         int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
1809                 LeadingMarginSpan.class);
1810         LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
1811                                                 LeadingMarginSpan.class);
1812         if (spans.length == 0) {
1813             return 0; // no leading margin span;
1814         }
1815
1816         int margin = 0;
1817
1818         boolean isFirstParaLine = lineStart == 0 ||
1819             spanned.charAt(lineStart - 1) == '\n';
1820
1821         boolean useFirstLineMargin = isFirstParaLine;
1822         for (int i = 0; i < spans.length; i++) {
1823             if (spans[i] instanceof LeadingMarginSpan2) {
1824                 int spStart = spanned.getSpanStart(spans[i]);
1825                 int spanLine = getLineForOffset(spStart);
1826                 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
1827                 // if there is more than one LeadingMarginSpan2, use the count that is greatest
1828                 useFirstLineMargin |= line < spanLine + count;
1829             }
1830         }
1831         for (int i = 0; i < spans.length; i++) {
1832             LeadingMarginSpan span = spans[i];
1833             margin += span.getLeadingMargin(useFirstLineMargin);
1834         }
1835
1836         return margin;
1837     }
1838
1839     /* package */
1840     static float measurePara(TextPaint paint, CharSequence text, int start, int end) {
1841
1842         MeasuredText mt = MeasuredText.obtain();
1843         TextLine tl = TextLine.obtain();
1844         try {
1845             mt.setPara(text, start, end, TextDirectionHeuristics.LTR, null);
1846             Directions directions;
1847             int dir;
1848             if (mt.mEasy) {
1849                 directions = DIRS_ALL_LEFT_TO_RIGHT;
1850                 dir = Layout.DIR_LEFT_TO_RIGHT;
1851             } else {
1852                 directions = AndroidBidi.directions(mt.mDir, mt.mLevels,
1853                     0, mt.mChars, 0, mt.mLen);
1854                 dir = mt.mDir;
1855             }
1856             char[] chars = mt.mChars;
1857             int len = mt.mLen;
1858             boolean hasTabs = false;
1859             TabStops tabStops = null;
1860             // leading margins should be taken into account when measuring a paragraph
1861             int margin = 0;
1862             if (text instanceof Spanned) {
1863                 Spanned spanned = (Spanned) text;
1864                 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
1865                         LeadingMarginSpan.class);
1866                 for (LeadingMarginSpan lms : spans) {
1867                     margin += lms.getLeadingMargin(true);
1868                 }
1869             }
1870             for (int i = 0; i < len; ++i) {
1871                 if (chars[i] == '\t') {
1872                     hasTabs = true;
1873                     if (text instanceof Spanned) {
1874                         Spanned spanned = (Spanned) text;
1875                         int spanEnd = spanned.nextSpanTransition(start, end,
1876                                 TabStopSpan.class);
1877                         TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
1878                                 TabStopSpan.class);
1879                         if (spans.length > 0) {
1880                             tabStops = new TabStops(TAB_INCREMENT, spans);
1881                         }
1882                     }
1883                     break;
1884                 }
1885             }
1886             tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops);
1887             return margin + tl.metrics(null);
1888         } finally {
1889             TextLine.recycle(tl);
1890             MeasuredText.recycle(mt);
1891         }
1892     }
1893
1894     /**
1895      * @hide
1896      */
1897     /* package */ static class TabStops {
1898         private int[] mStops;
1899         private int mNumStops;
1900         private int mIncrement;
1901
1902         TabStops(int increment, Object[] spans) {
1903             reset(increment, spans);
1904         }
1905
1906         void reset(int increment, Object[] spans) {
1907             this.mIncrement = increment;
1908
1909             int ns = 0;
1910             if (spans != null) {
1911                 int[] stops = this.mStops;
1912                 for (Object o : spans) {
1913                     if (o instanceof TabStopSpan) {
1914                         if (stops == null) {
1915                             stops = new int[10];
1916                         } else if (ns == stops.length) {
1917                             int[] nstops = new int[ns * 2];
1918                             for (int i = 0; i < ns; ++i) {
1919                                 nstops[i] = stops[i];
1920                             }
1921                             stops = nstops;
1922                         }
1923                         stops[ns++] = ((TabStopSpan) o).getTabStop();
1924                     }
1925                 }
1926                 if (ns > 1) {
1927                     Arrays.sort(stops, 0, ns);
1928                 }
1929                 if (stops != this.mStops) {
1930                     this.mStops = stops;
1931                 }
1932             }
1933             this.mNumStops = ns;
1934         }
1935
1936         float nextTab(float h) {
1937             int ns = this.mNumStops;
1938             if (ns > 0) {
1939                 int[] stops = this.mStops;
1940                 for (int i = 0; i < ns; ++i) {
1941                     int stop = stops[i];
1942                     if (stop > h) {
1943                         return stop;
1944                     }
1945                 }
1946             }
1947             return nextDefaultStop(h, mIncrement);
1948         }
1949
1950         public static float nextDefaultStop(float h, int inc) {
1951             return ((int) ((h + inc) / inc)) * inc;
1952         }
1953     }
1954
1955     /**
1956      * Returns the position of the next tab stop after h on the line.
1957      *
1958      * @param text the text
1959      * @param start start of the line
1960      * @param end limit of the line
1961      * @param h the current horizontal offset
1962      * @param tabs the tabs, can be null.  If it is null, any tabs in effect
1963      * on the line will be used.  If there are no tabs, a default offset
1964      * will be used to compute the tab stop.
1965      * @return the offset of the next tab stop.
1966      */
1967     /* package */ static float nextTab(CharSequence text, int start, int end,
1968                                        float h, Object[] tabs) {
1969         float nh = Float.MAX_VALUE;
1970         boolean alltabs = false;
1971
1972         if (text instanceof Spanned) {
1973             if (tabs == null) {
1974                 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
1975                 alltabs = true;
1976             }
1977
1978             for (int i = 0; i < tabs.length; i++) {
1979                 if (!alltabs) {
1980                     if (!(tabs[i] instanceof TabStopSpan))
1981                         continue;
1982                 }
1983
1984                 int where = ((TabStopSpan) tabs[i]).getTabStop();
1985
1986                 if (where < nh && where > h)
1987                     nh = where;
1988             }
1989
1990             if (nh != Float.MAX_VALUE)
1991                 return nh;
1992         }
1993
1994         return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
1995     }
1996
1997     protected final boolean isSpanned() {
1998         return mSpannedText;
1999     }
2000
2001     /**
2002      * Returns the same as <code>text.getSpans()</code>, except where
2003      * <code>start</code> and <code>end</code> are the same and are not
2004      * at the very beginning of the text, in which case an empty array
2005      * is returned instead.
2006      * <p>
2007      * This is needed because of the special case that <code>getSpans()</code>
2008      * on an empty range returns the spans adjacent to that range, which is
2009      * primarily for the sake of <code>TextWatchers</code> so they will get
2010      * notifications when text goes from empty to non-empty.  But it also
2011      * has the unfortunate side effect that if the text ends with an empty
2012      * paragraph, that paragraph accidentally picks up the styles of the
2013      * preceding paragraph (even though those styles will not be picked up
2014      * by new text that is inserted into the empty paragraph).
2015      * <p>
2016      * The reason it just checks whether <code>start</code> and <code>end</code>
2017      * is the same is that the only time a line can contain 0 characters
2018      * is if it is the final paragraph of the Layout; otherwise any line will
2019      * contain at least one printing or newline character.  The reason for the
2020      * additional check if <code>start</code> is greater than 0 is that
2021      * if the empty paragraph is the entire content of the buffer, paragraph
2022      * styles that are already applied to the buffer will apply to text that
2023      * is inserted into it.
2024      */
2025     /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
2026         if (start == end && start > 0) {
2027             return ArrayUtils.emptyArray(type);
2028         }
2029
2030         if(text instanceof SpannableStringBuilder) {
2031             return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2032         } else {
2033             return text.getSpans(start, end, type);
2034         }
2035     }
2036
2037     private char getEllipsisChar(TextUtils.TruncateAt method) {
2038         return (method == TextUtils.TruncateAt.END_SMALL) ?
2039                 TextUtils.ELLIPSIS_TWO_DOTS[0] :
2040                 TextUtils.ELLIPSIS_NORMAL[0];
2041     }
2042
2043     private void ellipsize(int start, int end, int line,
2044                            char[] dest, int destoff, TextUtils.TruncateAt method) {
2045         int ellipsisCount = getEllipsisCount(line);
2046
2047         if (ellipsisCount == 0) {
2048             return;
2049         }
2050
2051         int ellipsisStart = getEllipsisStart(line);
2052         int linestart = getLineStart(line);
2053
2054         for (int i = ellipsisStart; i < ellipsisStart + ellipsisCount; i++) {
2055             char c;
2056
2057             if (i == ellipsisStart) {
2058                 c = getEllipsisChar(method); // ellipsis
2059             } else {
2060                 c = '\uFEFF'; // 0-width space
2061             }
2062
2063             int a = i + linestart;
2064
2065             if (a >= start && a < end) {
2066                 dest[destoff + a - start] = c;
2067             }
2068         }
2069     }
2070
2071     /**
2072      * Stores information about bidirectional (left-to-right or right-to-left)
2073      * text within the layout of a line.
2074      */
2075     public static class Directions {
2076         // Directions represents directional runs within a line of text.
2077         // Runs are pairs of ints listed in visual order, starting from the
2078         // leading margin.  The first int of each pair is the offset from
2079         // the first character of the line to the start of the run.  The
2080         // second int represents both the length and level of the run.
2081         // The length is in the lower bits, accessed by masking with
2082         // DIR_LENGTH_MASK.  The level is in the higher bits, accessed
2083         // by shifting by DIR_LEVEL_SHIFT and masking by DIR_LEVEL_MASK.
2084         // To simply test for an RTL direction, test the bit using
2085         // DIR_RTL_FLAG, if set then the direction is rtl.
2086
2087         /* package */ int[] mDirections;
2088         /* package */ Directions(int[] dirs) {
2089             mDirections = dirs;
2090         }
2091     }
2092
2093     /**
2094      * Return the offset of the first character to be ellipsized away,
2095      * relative to the start of the line.  (So 0 if the beginning of the
2096      * line is ellipsized, not getLineStart().)
2097      */
2098     public abstract int getEllipsisStart(int line);
2099
2100     /**
2101      * Returns the number of characters to be ellipsized away, or 0 if
2102      * no ellipsis is to take place.
2103      */
2104     public abstract int getEllipsisCount(int line);
2105
2106     /* package */ static class Ellipsizer implements CharSequence, GetChars {
2107         /* package */ CharSequence mText;
2108         /* package */ Layout mLayout;
2109         /* package */ int mWidth;
2110         /* package */ TextUtils.TruncateAt mMethod;
2111
2112         public Ellipsizer(CharSequence s) {
2113             mText = s;
2114         }
2115
2116         public char charAt(int off) {
2117             char[] buf = TextUtils.obtain(1);
2118             getChars(off, off + 1, buf, 0);
2119             char ret = buf[0];
2120
2121             TextUtils.recycle(buf);
2122             return ret;
2123         }
2124
2125         public void getChars(int start, int end, char[] dest, int destoff) {
2126             int line1 = mLayout.getLineForOffset(start);
2127             int line2 = mLayout.getLineForOffset(end);
2128
2129             TextUtils.getChars(mText, start, end, dest, destoff);
2130
2131             for (int i = line1; i <= line2; i++) {
2132                 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
2133             }
2134         }
2135
2136         public int length() {
2137             return mText.length();
2138         }
2139
2140         public CharSequence subSequence(int start, int end) {
2141             char[] s = new char[end - start];
2142             getChars(start, end, s, 0);
2143             return new String(s);
2144         }
2145
2146         @Override
2147         public String toString() {
2148             char[] s = new char[length()];
2149             getChars(0, length(), s, 0);
2150             return new String(s);
2151         }
2152
2153     }
2154
2155     /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
2156         private Spanned mSpanned;
2157
2158         public SpannedEllipsizer(CharSequence display) {
2159             super(display);
2160             mSpanned = (Spanned) display;
2161         }
2162
2163         public <T> T[] getSpans(int start, int end, Class<T> type) {
2164             return mSpanned.getSpans(start, end, type);
2165         }
2166
2167         public int getSpanStart(Object tag) {
2168             return mSpanned.getSpanStart(tag);
2169         }
2170
2171         public int getSpanEnd(Object tag) {
2172             return mSpanned.getSpanEnd(tag);
2173         }
2174
2175         public int getSpanFlags(Object tag) {
2176             return mSpanned.getSpanFlags(tag);
2177         }
2178
2179         @SuppressWarnings("rawtypes")
2180         public int nextSpanTransition(int start, int limit, Class type) {
2181             return mSpanned.nextSpanTransition(start, limit, type);
2182         }
2183
2184         @Override
2185         public CharSequence subSequence(int start, int end) {
2186             char[] s = new char[end - start];
2187             getChars(start, end, s, 0);
2188
2189             SpannableString ss = new SpannableString(new String(s));
2190             TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2191             return ss;
2192         }
2193     }
2194
2195     private CharSequence mText;
2196     private TextPaint mPaint;
2197     private int mWidth;
2198     private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2199     private float mSpacingMult;
2200     private float mSpacingAdd;
2201     private static final Rect sTempRect = new Rect();
2202     private boolean mSpannedText;
2203     private TextDirectionHeuristic mTextDir;
2204     private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
2205
2206     public static final int DIR_LEFT_TO_RIGHT = 1;
2207     public static final int DIR_RIGHT_TO_LEFT = -1;
2208
2209     /* package */ static final int DIR_REQUEST_LTR = 1;
2210     /* package */ static final int DIR_REQUEST_RTL = -1;
2211     /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2212     /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
2213
2214     /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2215     /* package */ static final int RUN_LEVEL_SHIFT = 26;
2216     /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2217     /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2218
2219     public enum Alignment {
2220         ALIGN_NORMAL,
2221         ALIGN_OPPOSITE,
2222         ALIGN_CENTER,
2223         /** @hide */
2224         ALIGN_LEFT,
2225         /** @hide */
2226         ALIGN_RIGHT,
2227     }
2228
2229     private static final int TAB_INCREMENT = 20;
2230
2231     /* package */ static final Directions DIRS_ALL_LEFT_TO_RIGHT =
2232         new Directions(new int[] { 0, RUN_LENGTH_MASK });
2233     /* package */ static final Directions DIRS_ALL_RIGHT_TO_LEFT =
2234         new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });
2235
2236 }