OSDN Git Service

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