OSDN Git Service

fix case issues with mGoingIdleWakeLock in DeviceIdleController
[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     private boolean primaryIsTrailingPrevious(int offset) {
818         int line = getLineForOffset(offset);
819         int lineStart = getLineStart(line);
820         int lineEnd = getLineEnd(line);
821         int[] runs = getLineDirections(line).mDirections;
822
823         int levelAt = -1;
824         for (int i = 0; i < runs.length; i += 2) {
825             int start = lineStart + runs[i];
826             int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
827             if (limit > lineEnd) {
828                 limit = lineEnd;
829             }
830             if (offset >= start && offset < limit) {
831                 if (offset > start) {
832                     // Previous character is at same level, so don't use trailing.
833                     return false;
834                 }
835                 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
836                 break;
837             }
838         }
839         if (levelAt == -1) {
840             // Offset was limit of line.
841             levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
842         }
843
844         // At level boundary, check previous level.
845         int levelBefore = -1;
846         if (offset == lineStart) {
847             levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
848         } else {
849             offset -= 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                     levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
858                     break;
859                 }
860             }
861         }
862
863         return levelBefore < levelAt;
864     }
865
866     /**
867      * Get the primary horizontal position for the specified text offset.
868      * This is the location where a new character would be inserted in
869      * the paragraph's primary direction.
870      */
871     public float getPrimaryHorizontal(int offset) {
872         return getPrimaryHorizontal(offset, false /* not clamped */);
873     }
874
875     /**
876      * Get the primary horizontal position for the specified text offset, but
877      * optionally clamp it so that it doesn't exceed the width of the layout.
878      * @hide
879      */
880     public float getPrimaryHorizontal(int offset, boolean clamped) {
881         boolean trailing = primaryIsTrailingPrevious(offset);
882         return getHorizontal(offset, trailing, clamped);
883     }
884
885     /**
886      * Get the secondary horizontal position for the specified text offset.
887      * This is the location where a new character would be inserted in
888      * the direction other than the paragraph's primary direction.
889      */
890     public float getSecondaryHorizontal(int offset) {
891         return getSecondaryHorizontal(offset, false /* not clamped */);
892     }
893
894     /**
895      * Get the secondary horizontal position for the specified text offset, but
896      * optionally clamp it so that it doesn't exceed the width of the layout.
897      * @hide
898      */
899     public float getSecondaryHorizontal(int offset, boolean clamped) {
900         boolean trailing = primaryIsTrailingPrevious(offset);
901         return getHorizontal(offset, !trailing, clamped);
902     }
903
904     private float getHorizontal(int offset, boolean trailing, boolean clamped) {
905         int line = getLineForOffset(offset);
906
907         return getHorizontal(offset, trailing, line, clamped);
908     }
909
910     private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
911         int start = getLineStart(line);
912         int end = getLineEnd(line);
913         int dir = getParagraphDirection(line);
914         boolean hasTabOrEmoji = getLineContainsTab(line);
915         Directions directions = getLineDirections(line);
916
917         TabStops tabStops = null;
918         if (hasTabOrEmoji && mText instanceof Spanned) {
919             // Just checking this line should be good enough, tabs should be
920             // consistent across all lines in a paragraph.
921             TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
922             if (tabs.length > 0) {
923                 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
924             }
925         }
926
927         TextLine tl = TextLine.obtain();
928         tl.set(mPaint, mText, start, end, dir, directions, hasTabOrEmoji, tabStops);
929         float wid = tl.measure(offset - start, trailing, null);
930         TextLine.recycle(tl);
931
932         if (clamped && wid > mWidth) {
933             wid = mWidth;
934         }
935         int left = getParagraphLeft(line);
936         int right = getParagraphRight(line);
937
938         return getLineStartPos(line, left, right) + wid;
939     }
940
941     /**
942      * Get the leftmost position that should be exposed for horizontal
943      * scrolling on the specified line.
944      */
945     public float getLineLeft(int line) {
946         int dir = getParagraphDirection(line);
947         Alignment align = getParagraphAlignment(line);
948
949         if (align == Alignment.ALIGN_LEFT) {
950             return 0;
951         } else if (align == Alignment.ALIGN_NORMAL) {
952             if (dir == DIR_RIGHT_TO_LEFT)
953                 return getParagraphRight(line) - getLineMax(line);
954             else
955                 return 0;
956         } else if (align == Alignment.ALIGN_RIGHT) {
957             return mWidth - getLineMax(line);
958         } else if (align == Alignment.ALIGN_OPPOSITE) {
959             if (dir == DIR_RIGHT_TO_LEFT)
960                 return 0;
961             else
962                 return mWidth - getLineMax(line);
963         } else { /* align == Alignment.ALIGN_CENTER */
964             int left = getParagraphLeft(line);
965             int right = getParagraphRight(line);
966             int max = ((int) getLineMax(line)) & ~1;
967
968             return left + ((right - left) - max) / 2;
969         }
970     }
971
972     /**
973      * Get the rightmost position that should be exposed for horizontal
974      * scrolling on the specified line.
975      */
976     public float getLineRight(int line) {
977         int dir = getParagraphDirection(line);
978         Alignment align = getParagraphAlignment(line);
979
980         if (align == Alignment.ALIGN_LEFT) {
981             return getParagraphLeft(line) + getLineMax(line);
982         } else if (align == Alignment.ALIGN_NORMAL) {
983             if (dir == DIR_RIGHT_TO_LEFT)
984                 return mWidth;
985             else
986                 return getParagraphLeft(line) + getLineMax(line);
987         } else if (align == Alignment.ALIGN_RIGHT) {
988             return mWidth;
989         } else if (align == Alignment.ALIGN_OPPOSITE) {
990             if (dir == DIR_RIGHT_TO_LEFT)
991                 return getLineMax(line);
992             else
993                 return mWidth;
994         } else { /* align == Alignment.ALIGN_CENTER */
995             int left = getParagraphLeft(line);
996             int right = getParagraphRight(line);
997             int max = ((int) getLineMax(line)) & ~1;
998
999             return right - ((right - left) - max) / 2;
1000         }
1001     }
1002
1003     /**
1004      * Gets the unsigned horizontal extent of the specified line, including
1005      * leading margin indent, but excluding trailing whitespace.
1006      */
1007     public float getLineMax(int line) {
1008         float margin = getParagraphLeadingMargin(line);
1009         float signedExtent = getLineExtent(line, false);
1010         return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1011     }
1012
1013     /**
1014      * Gets the unsigned horizontal extent of the specified line, including
1015      * leading margin indent and trailing whitespace.
1016      */
1017     public float getLineWidth(int line) {
1018         float margin = getParagraphLeadingMargin(line);
1019         float signedExtent = getLineExtent(line, true);
1020         return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1021     }
1022
1023     /**
1024      * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1025      * tab stops instead of using the ones passed in.
1026      * @param line the index of the line
1027      * @param full whether to include trailing whitespace
1028      * @return the extent of the line
1029      */
1030     private float getLineExtent(int line, boolean full) {
1031         int start = getLineStart(line);
1032         int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1033
1034         boolean hasTabsOrEmoji = getLineContainsTab(line);
1035         TabStops tabStops = null;
1036         if (hasTabsOrEmoji && mText instanceof Spanned) {
1037             // Just checking this line should be good enough, tabs should be
1038             // consistent across all lines in a paragraph.
1039             TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1040             if (tabs.length > 0) {
1041                 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1042             }
1043         }
1044         Directions directions = getLineDirections(line);
1045         // Returned directions can actually be null
1046         if (directions == null) {
1047             return 0f;
1048         }
1049         int dir = getParagraphDirection(line);
1050
1051         TextLine tl = TextLine.obtain();
1052         tl.set(mPaint, mText, start, end, dir, directions, hasTabsOrEmoji, tabStops);
1053         float width = tl.metrics(null);
1054         TextLine.recycle(tl);
1055         return width;
1056     }
1057
1058     /**
1059      * Returns the signed horizontal extent of the specified line, excluding
1060      * leading margin.  If full is false, excludes trailing whitespace.
1061      * @param line the index of the line
1062      * @param tabStops the tab stops, can be null if we know they're not used.
1063      * @param full whether to include trailing whitespace
1064      * @return the extent of the text on this line
1065      */
1066     private float getLineExtent(int line, TabStops tabStops, boolean full) {
1067         int start = getLineStart(line);
1068         int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1069         boolean hasTabsOrEmoji = getLineContainsTab(line);
1070         Directions directions = getLineDirections(line);
1071         int dir = getParagraphDirection(line);
1072
1073         TextLine tl = TextLine.obtain();
1074         tl.set(mPaint, mText, start, end, dir, directions, hasTabsOrEmoji, tabStops);
1075         float width = tl.metrics(null);
1076         TextLine.recycle(tl);
1077         return width;
1078     }
1079
1080     /**
1081      * Get the line number corresponding to the specified vertical position.
1082      * If you ask for a position above 0, you get 0; if you ask for a position
1083      * below the bottom of the text, you get the last line.
1084      */
1085     // FIXME: It may be faster to do a linear search for layouts without many lines.
1086     public int getLineForVertical(int vertical) {
1087         int high = getLineCount(), low = -1, guess;
1088
1089         while (high - low > 1) {
1090             guess = (high + low) / 2;
1091
1092             if (getLineTop(guess) > vertical)
1093                 high = guess;
1094             else
1095                 low = guess;
1096         }
1097
1098         if (low < 0)
1099             return 0;
1100         else
1101             return low;
1102     }
1103
1104     /**
1105      * Get the line number on which the specified text offset appears.
1106      * If you ask for a position before 0, you get 0; if you ask for a position
1107      * beyond the end of the text, you get the last line.
1108      */
1109     public int getLineForOffset(int offset) {
1110         int high = getLineCount(), low = -1, guess;
1111
1112         while (high - low > 1) {
1113             guess = (high + low) / 2;
1114
1115             if (getLineStart(guess) > offset)
1116                 high = guess;
1117             else
1118                 low = guess;
1119         }
1120
1121         if (low < 0)
1122             return 0;
1123         else
1124             return low;
1125     }
1126
1127     /**
1128      * Get the character offset on the specified line whose position is
1129      * closest to the specified horizontal position.
1130      */
1131     public int getOffsetForHorizontal(int line, float horiz) {
1132         // TODO: use Paint.getOffsetForAdvance to avoid binary search
1133         final int lineEndOffset = getLineEnd(line);
1134         final int lineStartOffset = getLineStart(line);
1135
1136         Directions dirs = getLineDirections(line);
1137
1138         TextLine tl = TextLine.obtain();
1139         // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1140         tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
1141                 false, null);
1142
1143         final int max;
1144         if (line == getLineCount() - 1) {
1145             max = lineEndOffset;
1146         } else {
1147             max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1148                     !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
1149         }
1150         int best = lineStartOffset;
1151         float bestdist = Math.abs(getPrimaryHorizontal(best) - horiz);
1152
1153         for (int i = 0; i < dirs.mDirections.length; i += 2) {
1154             int here = lineStartOffset + dirs.mDirections[i];
1155             int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1156             boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1157             int swap = isRtl ? -1 : 1;
1158
1159             if (there > max)
1160                 there = max;
1161             int high = there - 1 + 1, low = here + 1 - 1, guess;
1162
1163             while (high - low > 1) {
1164                 guess = (high + low) / 2;
1165                 int adguess = getOffsetAtStartOf(guess);
1166
1167                 if (getPrimaryHorizontal(adguess) * swap >= horiz * swap)
1168                     high = guess;
1169                 else
1170                     low = guess;
1171             }
1172
1173             if (low < here + 1)
1174                 low = here + 1;
1175
1176             if (low < there) {
1177                 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1178                 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1179                 if (low >= here && low < there) {
1180                     float dist = Math.abs(getPrimaryHorizontal(low) - horiz);
1181                     if (aft < there) {
1182                         float other = Math.abs(getPrimaryHorizontal(aft) - horiz);
1183
1184                         if (other < dist) {
1185                             dist = other;
1186                             low = aft;
1187                         }
1188                     }
1189
1190                     if (dist < bestdist) {
1191                         bestdist = dist;
1192                         best = low;
1193                     }
1194                 }
1195             }
1196
1197             float dist = Math.abs(getPrimaryHorizontal(here) - horiz);
1198
1199             if (dist < bestdist) {
1200                 bestdist = dist;
1201                 best = here;
1202             }
1203         }
1204
1205         float dist = Math.abs(getPrimaryHorizontal(max) - horiz);
1206
1207         if (dist <= bestdist) {
1208             bestdist = dist;
1209             best = max;
1210         }
1211
1212         TextLine.recycle(tl);
1213         return best;
1214     }
1215
1216     /**
1217      * Return the text offset after the last character on the specified line.
1218      */
1219     public final int getLineEnd(int line) {
1220         return getLineStart(line + 1);
1221     }
1222
1223     /**
1224      * Return the text offset after the last visible character (so whitespace
1225      * is not counted) on the specified line.
1226      */
1227     public int getLineVisibleEnd(int line) {
1228         return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1229     }
1230
1231     private int getLineVisibleEnd(int line, int start, int end) {
1232         CharSequence text = mText;
1233         char ch;
1234         if (line == getLineCount() - 1) {
1235             return end;
1236         }
1237
1238         for (; end > start; end--) {
1239             ch = text.charAt(end - 1);
1240
1241             if (ch == '\n') {
1242                 return end - 1;
1243             }
1244
1245             // Note: keep this in sync with Minikin LineBreaker::isLineEndSpace()
1246             if (!(ch == ' ' || ch == '\t' || ch == 0x1680 ||
1247                     (0x2000 <= ch && ch <= 0x200A && ch != 0x2007) ||
1248                     ch == 0x205F || ch == 0x3000)) {
1249                 break;
1250             }
1251
1252         }
1253
1254         return end;
1255     }
1256
1257     /**
1258      * Return the vertical position of the bottom of the specified line.
1259      */
1260     public final int getLineBottom(int line) {
1261         return getLineTop(line + 1);
1262     }
1263
1264     /**
1265      * Return the vertical position of the baseline of the specified line.
1266      */
1267     public final int getLineBaseline(int line) {
1268         // getLineTop(line+1) == getLineTop(line)
1269         return getLineTop(line+1) - getLineDescent(line);
1270     }
1271
1272     /**
1273      * Get the ascent of the text on the specified line.
1274      * The return value is negative to match the Paint.ascent() convention.
1275      */
1276     public final int getLineAscent(int line) {
1277         // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1278         return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1279     }
1280
1281     public int getOffsetToLeftOf(int offset) {
1282         return getOffsetToLeftRightOf(offset, true);
1283     }
1284
1285     public int getOffsetToRightOf(int offset) {
1286         return getOffsetToLeftRightOf(offset, false);
1287     }
1288
1289     private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1290         int line = getLineForOffset(caret);
1291         int lineStart = getLineStart(line);
1292         int lineEnd = getLineEnd(line);
1293         int lineDir = getParagraphDirection(line);
1294
1295         boolean lineChanged = false;
1296         boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
1297         // if walking off line, look at the line we're headed to
1298         if (advance) {
1299             if (caret == lineEnd) {
1300                 if (line < getLineCount() - 1) {
1301                     lineChanged = true;
1302                     ++line;
1303                 } else {
1304                     return caret; // at very end, don't move
1305                 }
1306             }
1307         } else {
1308             if (caret == lineStart) {
1309                 if (line > 0) {
1310                     lineChanged = true;
1311                     --line;
1312                 } else {
1313                     return caret; // at very start, don't move
1314                 }
1315             }
1316         }
1317
1318         if (lineChanged) {
1319             lineStart = getLineStart(line);
1320             lineEnd = getLineEnd(line);
1321             int newDir = getParagraphDirection(line);
1322             if (newDir != lineDir) {
1323                 // unusual case.  we want to walk onto the line, but it runs
1324                 // in a different direction than this one, so we fake movement
1325                 // in the opposite direction.
1326                 toLeft = !toLeft;
1327                 lineDir = newDir;
1328             }
1329         }
1330
1331         Directions directions = getLineDirections(line);
1332
1333         TextLine tl = TextLine.obtain();
1334         // XXX: we don't care about tabs
1335         tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null);
1336         caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
1337         tl = TextLine.recycle(tl);
1338         return caret;
1339     }
1340
1341     private int getOffsetAtStartOf(int offset) {
1342         // XXX this probably should skip local reorderings and
1343         // zero-width characters, look at callers
1344         if (offset == 0)
1345             return 0;
1346
1347         CharSequence text = mText;
1348         char c = text.charAt(offset);
1349
1350         if (c >= '\uDC00' && c <= '\uDFFF') {
1351             char c1 = text.charAt(offset - 1);
1352
1353             if (c1 >= '\uD800' && c1 <= '\uDBFF')
1354                 offset -= 1;
1355         }
1356
1357         if (mSpannedText) {
1358             ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1359                                                        ReplacementSpan.class);
1360
1361             for (int i = 0; i < spans.length; i++) {
1362                 int start = ((Spanned) text).getSpanStart(spans[i]);
1363                 int end = ((Spanned) text).getSpanEnd(spans[i]);
1364
1365                 if (start < offset && end > offset)
1366                     offset = start;
1367             }
1368         }
1369
1370         return offset;
1371     }
1372
1373     /**
1374      * Determine whether we should clamp cursor position. Currently it's
1375      * only robust for left-aligned displays.
1376      * @hide
1377      */
1378     public boolean shouldClampCursor(int line) {
1379         // Only clamp cursor position in left-aligned displays.
1380         switch (getParagraphAlignment(line)) {
1381             case ALIGN_LEFT:
1382                 return true;
1383             case ALIGN_NORMAL:
1384                 return getParagraphDirection(line) > 0;
1385             default:
1386                 return false;
1387         }
1388
1389     }
1390     /**
1391      * Fills in the specified Path with a representation of a cursor
1392      * at the specified offset.  This will often be a vertical line
1393      * but can be multiple discontinuous lines in text with multiple
1394      * directionalities.
1395      */
1396     public void getCursorPath(int point, Path dest,
1397                               CharSequence editingBuffer) {
1398         dest.reset();
1399
1400         int line = getLineForOffset(point);
1401         int top = getLineTop(line);
1402         int bottom = getLineTop(line+1);
1403
1404         boolean clamped = shouldClampCursor(line);
1405         float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1406         float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
1407
1408         int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1409                    TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1410         int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
1411         int dist = 0;
1412
1413         if (caps != 0 || fn != 0) {
1414             dist = (bottom - top) >> 2;
1415
1416             if (fn != 0)
1417                 top += dist;
1418             if (caps != 0)
1419                 bottom -= dist;
1420         }
1421
1422         if (h1 < 0.5f)
1423             h1 = 0.5f;
1424         if (h2 < 0.5f)
1425             h2 = 0.5f;
1426
1427         if (Float.compare(h1, h2) == 0) {
1428             dest.moveTo(h1, top);
1429             dest.lineTo(h1, bottom);
1430         } else {
1431             dest.moveTo(h1, top);
1432             dest.lineTo(h1, (top + bottom) >> 1);
1433
1434             dest.moveTo(h2, (top + bottom) >> 1);
1435             dest.lineTo(h2, bottom);
1436         }
1437
1438         if (caps == 2) {
1439             dest.moveTo(h2, bottom);
1440             dest.lineTo(h2 - dist, bottom + dist);
1441             dest.lineTo(h2, bottom);
1442             dest.lineTo(h2 + dist, bottom + dist);
1443         } else if (caps == 1) {
1444             dest.moveTo(h2, bottom);
1445             dest.lineTo(h2 - dist, bottom + dist);
1446
1447             dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1448             dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1449
1450             dest.moveTo(h2 + dist, bottom + dist);
1451             dest.lineTo(h2, bottom);
1452         }
1453
1454         if (fn == 2) {
1455             dest.moveTo(h1, top);
1456             dest.lineTo(h1 - dist, top - dist);
1457             dest.lineTo(h1, top);
1458             dest.lineTo(h1 + dist, top - dist);
1459         } else if (fn == 1) {
1460             dest.moveTo(h1, top);
1461             dest.lineTo(h1 - dist, top - dist);
1462
1463             dest.moveTo(h1 - dist, top - dist + 0.5f);
1464             dest.lineTo(h1 + dist, top - dist + 0.5f);
1465
1466             dest.moveTo(h1 + dist, top - dist);
1467             dest.lineTo(h1, top);
1468         }
1469     }
1470
1471     private void addSelection(int line, int start, int end,
1472                               int top, int bottom, Path dest) {
1473         int linestart = getLineStart(line);
1474         int lineend = getLineEnd(line);
1475         Directions dirs = getLineDirections(line);
1476
1477         if (lineend > linestart && mText.charAt(lineend - 1) == '\n')
1478             lineend--;
1479
1480         for (int i = 0; i < dirs.mDirections.length; i += 2) {
1481             int here = linestart + dirs.mDirections[i];
1482             int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1483
1484             if (there > lineend)
1485                 there = lineend;
1486
1487             if (start <= there && end >= here) {
1488                 int st = Math.max(start, here);
1489                 int en = Math.min(end, there);
1490
1491                 if (st != en) {
1492                     float h1 = getHorizontal(st, false, line, false /* not clamped */);
1493                     float h2 = getHorizontal(en, true, line, false /* not clamped */);
1494
1495                     float left = Math.min(h1, h2);
1496                     float right = Math.max(h1, h2);
1497
1498                     dest.addRect(left, top, right, bottom, Path.Direction.CW);
1499                 }
1500             }
1501         }
1502     }
1503
1504     /**
1505      * Fills in the specified Path with a representation of a highlight
1506      * between the specified offsets.  This will often be a rectangle
1507      * or a potentially discontinuous set of rectangles.  If the start
1508      * and end are the same, the returned path is empty.
1509      */
1510     public void getSelectionPath(int start, int end, Path dest) {
1511         dest.reset();
1512
1513         if (start == end)
1514             return;
1515
1516         if (end < start) {
1517             int temp = end;
1518             end = start;
1519             start = temp;
1520         }
1521
1522         int startline = getLineForOffset(start);
1523         int endline = getLineForOffset(end);
1524
1525         int top = getLineTop(startline);
1526         int bottom = getLineBottom(endline);
1527
1528         if (startline == endline) {
1529             addSelection(startline, start, end, top, bottom, dest);
1530         } else {
1531             final float width = mWidth;
1532
1533             addSelection(startline, start, getLineEnd(startline),
1534                          top, getLineBottom(startline), dest);
1535
1536             if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT)
1537                 dest.addRect(getLineLeft(startline), top,
1538                               0, getLineBottom(startline), Path.Direction.CW);
1539             else
1540                 dest.addRect(getLineRight(startline), top,
1541                               width, getLineBottom(startline), Path.Direction.CW);
1542
1543             for (int i = startline + 1; i < endline; i++) {
1544                 top = getLineTop(i);
1545                 bottom = getLineBottom(i);
1546                 dest.addRect(0, top, width, bottom, Path.Direction.CW);
1547             }
1548
1549             top = getLineTop(endline);
1550             bottom = getLineBottom(endline);
1551
1552             addSelection(endline, getLineStart(endline), end,
1553                          top, bottom, dest);
1554
1555             if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT)
1556                 dest.addRect(width, top, getLineRight(endline), bottom, Path.Direction.CW);
1557             else
1558                 dest.addRect(0, top, getLineLeft(endline), bottom, Path.Direction.CW);
1559         }
1560     }
1561
1562     /**
1563      * Get the alignment of the specified paragraph, taking into account
1564      * markup attached to it.
1565      */
1566     public final Alignment getParagraphAlignment(int line) {
1567         Alignment align = mAlignment;
1568
1569         if (mSpannedText) {
1570             Spanned sp = (Spanned) mText;
1571             AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
1572                                                 getLineEnd(line),
1573                                                 AlignmentSpan.class);
1574
1575             int spanLength = spans.length;
1576             if (spanLength > 0) {
1577                 align = spans[spanLength-1].getAlignment();
1578             }
1579         }
1580
1581         return align;
1582     }
1583
1584     /**
1585      * Get the left edge of the specified paragraph, inset by left margins.
1586      */
1587     public final int getParagraphLeft(int line) {
1588         int left = 0;
1589         int dir = getParagraphDirection(line);
1590         if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
1591             return left; // leading margin has no impact, or no styles
1592         }
1593         return getParagraphLeadingMargin(line);
1594     }
1595
1596     /**
1597      * Get the right edge of the specified paragraph, inset by right margins.
1598      */
1599     public final int getParagraphRight(int line) {
1600         int right = mWidth;
1601         int dir = getParagraphDirection(line);
1602         if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
1603             return right; // leading margin has no impact, or no styles
1604         }
1605         return right - getParagraphLeadingMargin(line);
1606     }
1607
1608     /**
1609      * Returns the effective leading margin (unsigned) for this line,
1610      * taking into account LeadingMarginSpan and LeadingMarginSpan2.
1611      * @param line the line index
1612      * @return the leading margin of this line
1613      */
1614     private int getParagraphLeadingMargin(int line) {
1615         if (!mSpannedText) {
1616             return 0;
1617         }
1618         Spanned spanned = (Spanned) mText;
1619
1620         int lineStart = getLineStart(line);
1621         int lineEnd = getLineEnd(line);
1622         int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
1623                 LeadingMarginSpan.class);
1624         LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
1625                                                 LeadingMarginSpan.class);
1626         if (spans.length == 0) {
1627             return 0; // no leading margin span;
1628         }
1629
1630         int margin = 0;
1631
1632         boolean isFirstParaLine = lineStart == 0 ||
1633             spanned.charAt(lineStart - 1) == '\n';
1634
1635         boolean useFirstLineMargin = isFirstParaLine;
1636         for (int i = 0; i < spans.length; i++) {
1637             if (spans[i] instanceof LeadingMarginSpan2) {
1638                 int spStart = spanned.getSpanStart(spans[i]);
1639                 int spanLine = getLineForOffset(spStart);
1640                 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
1641                 // if there is more than one LeadingMarginSpan2, use the count that is greatest
1642                 useFirstLineMargin |= line < spanLine + count;
1643             }
1644         }
1645         for (int i = 0; i < spans.length; i++) {
1646             LeadingMarginSpan span = spans[i];
1647             margin += span.getLeadingMargin(useFirstLineMargin);
1648         }
1649
1650         return margin;
1651     }
1652
1653     /* package */
1654     static float measurePara(TextPaint paint, CharSequence text, int start, int end) {
1655
1656         MeasuredText mt = MeasuredText.obtain();
1657         TextLine tl = TextLine.obtain();
1658         try {
1659             mt.setPara(text, start, end, TextDirectionHeuristics.LTR, null);
1660             Directions directions;
1661             int dir;
1662             if (mt.mEasy) {
1663                 directions = DIRS_ALL_LEFT_TO_RIGHT;
1664                 dir = Layout.DIR_LEFT_TO_RIGHT;
1665             } else {
1666                 directions = AndroidBidi.directions(mt.mDir, mt.mLevels,
1667                     0, mt.mChars, 0, mt.mLen);
1668                 dir = mt.mDir;
1669             }
1670             char[] chars = mt.mChars;
1671             int len = mt.mLen;
1672             boolean hasTabs = false;
1673             TabStops tabStops = null;
1674             // leading margins should be taken into account when measuring a paragraph
1675             int margin = 0;
1676             if (text instanceof Spanned) {
1677                 Spanned spanned = (Spanned) text;
1678                 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
1679                         LeadingMarginSpan.class);
1680                 for (LeadingMarginSpan lms : spans) {
1681                     margin += lms.getLeadingMargin(true);
1682                 }
1683             }
1684             for (int i = 0; i < len; ++i) {
1685                 if (chars[i] == '\t') {
1686                     hasTabs = true;
1687                     if (text instanceof Spanned) {
1688                         Spanned spanned = (Spanned) text;
1689                         int spanEnd = spanned.nextSpanTransition(start, end,
1690                                 TabStopSpan.class);
1691                         TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
1692                                 TabStopSpan.class);
1693                         if (spans.length > 0) {
1694                             tabStops = new TabStops(TAB_INCREMENT, spans);
1695                         }
1696                     }
1697                     break;
1698                 }
1699             }
1700             tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops);
1701             return margin + tl.metrics(null);
1702         } finally {
1703             TextLine.recycle(tl);
1704             MeasuredText.recycle(mt);
1705         }
1706     }
1707
1708     /**
1709      * @hide
1710      */
1711     /* package */ static class TabStops {
1712         private int[] mStops;
1713         private int mNumStops;
1714         private int mIncrement;
1715
1716         TabStops(int increment, Object[] spans) {
1717             reset(increment, spans);
1718         }
1719
1720         void reset(int increment, Object[] spans) {
1721             this.mIncrement = increment;
1722
1723             int ns = 0;
1724             if (spans != null) {
1725                 int[] stops = this.mStops;
1726                 for (Object o : spans) {
1727                     if (o instanceof TabStopSpan) {
1728                         if (stops == null) {
1729                             stops = new int[10];
1730                         } else if (ns == stops.length) {
1731                             int[] nstops = new int[ns * 2];
1732                             for (int i = 0; i < ns; ++i) {
1733                                 nstops[i] = stops[i];
1734                             }
1735                             stops = nstops;
1736                         }
1737                         stops[ns++] = ((TabStopSpan) o).getTabStop();
1738                     }
1739                 }
1740                 if (ns > 1) {
1741                     Arrays.sort(stops, 0, ns);
1742                 }
1743                 if (stops != this.mStops) {
1744                     this.mStops = stops;
1745                 }
1746             }
1747             this.mNumStops = ns;
1748         }
1749
1750         float nextTab(float h) {
1751             int ns = this.mNumStops;
1752             if (ns > 0) {
1753                 int[] stops = this.mStops;
1754                 for (int i = 0; i < ns; ++i) {
1755                     int stop = stops[i];
1756                     if (stop > h) {
1757                         return stop;
1758                     }
1759                 }
1760             }
1761             return nextDefaultStop(h, mIncrement);
1762         }
1763
1764         public static float nextDefaultStop(float h, int inc) {
1765             return ((int) ((h + inc) / inc)) * inc;
1766         }
1767     }
1768
1769     /**
1770      * Returns the position of the next tab stop after h on the line.
1771      *
1772      * @param text the text
1773      * @param start start of the line
1774      * @param end limit of the line
1775      * @param h the current horizontal offset
1776      * @param tabs the tabs, can be null.  If it is null, any tabs in effect
1777      * on the line will be used.  If there are no tabs, a default offset
1778      * will be used to compute the tab stop.
1779      * @return the offset of the next tab stop.
1780      */
1781     /* package */ static float nextTab(CharSequence text, int start, int end,
1782                                        float h, Object[] tabs) {
1783         float nh = Float.MAX_VALUE;
1784         boolean alltabs = false;
1785
1786         if (text instanceof Spanned) {
1787             if (tabs == null) {
1788                 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
1789                 alltabs = true;
1790             }
1791
1792             for (int i = 0; i < tabs.length; i++) {
1793                 if (!alltabs) {
1794                     if (!(tabs[i] instanceof TabStopSpan))
1795                         continue;
1796                 }
1797
1798                 int where = ((TabStopSpan) tabs[i]).getTabStop();
1799
1800                 if (where < nh && where > h)
1801                     nh = where;
1802             }
1803
1804             if (nh != Float.MAX_VALUE)
1805                 return nh;
1806         }
1807
1808         return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
1809     }
1810
1811     protected final boolean isSpanned() {
1812         return mSpannedText;
1813     }
1814
1815     /**
1816      * Returns the same as <code>text.getSpans()</code>, except where
1817      * <code>start</code> and <code>end</code> are the same and are not
1818      * at the very beginning of the text, in which case an empty array
1819      * is returned instead.
1820      * <p>
1821      * This is needed because of the special case that <code>getSpans()</code>
1822      * on an empty range returns the spans adjacent to that range, which is
1823      * primarily for the sake of <code>TextWatchers</code> so they will get
1824      * notifications when text goes from empty to non-empty.  But it also
1825      * has the unfortunate side effect that if the text ends with an empty
1826      * paragraph, that paragraph accidentally picks up the styles of the
1827      * preceding paragraph (even though those styles will not be picked up
1828      * by new text that is inserted into the empty paragraph).
1829      * <p>
1830      * The reason it just checks whether <code>start</code> and <code>end</code>
1831      * is the same is that the only time a line can contain 0 characters
1832      * is if it is the final paragraph of the Layout; otherwise any line will
1833      * contain at least one printing or newline character.  The reason for the
1834      * additional check if <code>start</code> is greater than 0 is that
1835      * if the empty paragraph is the entire content of the buffer, paragraph
1836      * styles that are already applied to the buffer will apply to text that
1837      * is inserted into it.
1838      */
1839     /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
1840         if (start == end && start > 0) {
1841             return ArrayUtils.emptyArray(type);
1842         }
1843
1844         return text.getSpans(start, end, type);
1845     }
1846
1847     private char getEllipsisChar(TextUtils.TruncateAt method) {
1848         return (method == TextUtils.TruncateAt.END_SMALL) ?
1849                 TextUtils.ELLIPSIS_TWO_DOTS[0] :
1850                 TextUtils.ELLIPSIS_NORMAL[0];
1851     }
1852
1853     private void ellipsize(int start, int end, int line,
1854                            char[] dest, int destoff, TextUtils.TruncateAt method) {
1855         int ellipsisCount = getEllipsisCount(line);
1856
1857         if (ellipsisCount == 0) {
1858             return;
1859         }
1860
1861         int ellipsisStart = getEllipsisStart(line);
1862         int linestart = getLineStart(line);
1863
1864         for (int i = ellipsisStart; i < ellipsisStart + ellipsisCount; i++) {
1865             char c;
1866
1867             if (i == ellipsisStart) {
1868                 c = getEllipsisChar(method); // ellipsis
1869             } else {
1870                 c = '\uFEFF'; // 0-width space
1871             }
1872
1873             int a = i + linestart;
1874
1875             if (a >= start && a < end) {
1876                 dest[destoff + a - start] = c;
1877             }
1878         }
1879     }
1880
1881     /**
1882      * Stores information about bidirectional (left-to-right or right-to-left)
1883      * text within the layout of a line.
1884      */
1885     public static class Directions {
1886         // Directions represents directional runs within a line of text.
1887         // Runs are pairs of ints listed in visual order, starting from the
1888         // leading margin.  The first int of each pair is the offset from
1889         // the first character of the line to the start of the run.  The
1890         // second int represents both the length and level of the run.
1891         // The length is in the lower bits, accessed by masking with
1892         // DIR_LENGTH_MASK.  The level is in the higher bits, accessed
1893         // by shifting by DIR_LEVEL_SHIFT and masking by DIR_LEVEL_MASK.
1894         // To simply test for an RTL direction, test the bit using
1895         // DIR_RTL_FLAG, if set then the direction is rtl.
1896
1897         /* package */ int[] mDirections;
1898         /* package */ Directions(int[] dirs) {
1899             mDirections = dirs;
1900         }
1901     }
1902
1903     /**
1904      * Return the offset of the first character to be ellipsized away,
1905      * relative to the start of the line.  (So 0 if the beginning of the
1906      * line is ellipsized, not getLineStart().)
1907      */
1908     public abstract int getEllipsisStart(int line);
1909
1910     /**
1911      * Returns the number of characters to be ellipsized away, or 0 if
1912      * no ellipsis is to take place.
1913      */
1914     public abstract int getEllipsisCount(int line);
1915
1916     /* package */ static class Ellipsizer implements CharSequence, GetChars {
1917         /* package */ CharSequence mText;
1918         /* package */ Layout mLayout;
1919         /* package */ int mWidth;
1920         /* package */ TextUtils.TruncateAt mMethod;
1921
1922         public Ellipsizer(CharSequence s) {
1923             mText = s;
1924         }
1925
1926         public char charAt(int off) {
1927             char[] buf = TextUtils.obtain(1);
1928             getChars(off, off + 1, buf, 0);
1929             char ret = buf[0];
1930
1931             TextUtils.recycle(buf);
1932             return ret;
1933         }
1934
1935         public void getChars(int start, int end, char[] dest, int destoff) {
1936             int line1 = mLayout.getLineForOffset(start);
1937             int line2 = mLayout.getLineForOffset(end);
1938
1939             TextUtils.getChars(mText, start, end, dest, destoff);
1940
1941             for (int i = line1; i <= line2; i++) {
1942                 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
1943             }
1944         }
1945
1946         public int length() {
1947             return mText.length();
1948         }
1949
1950         public CharSequence subSequence(int start, int end) {
1951             char[] s = new char[end - start];
1952             getChars(start, end, s, 0);
1953             return new String(s);
1954         }
1955
1956         @Override
1957         public String toString() {
1958             char[] s = new char[length()];
1959             getChars(0, length(), s, 0);
1960             return new String(s);
1961         }
1962
1963     }
1964
1965     /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
1966         private Spanned mSpanned;
1967
1968         public SpannedEllipsizer(CharSequence display) {
1969             super(display);
1970             mSpanned = (Spanned) display;
1971         }
1972
1973         public <T> T[] getSpans(int start, int end, Class<T> type) {
1974             return mSpanned.getSpans(start, end, type);
1975         }
1976
1977         public int getSpanStart(Object tag) {
1978             return mSpanned.getSpanStart(tag);
1979         }
1980
1981         public int getSpanEnd(Object tag) {
1982             return mSpanned.getSpanEnd(tag);
1983         }
1984
1985         public int getSpanFlags(Object tag) {
1986             return mSpanned.getSpanFlags(tag);
1987         }
1988
1989         @SuppressWarnings("rawtypes")
1990         public int nextSpanTransition(int start, int limit, Class type) {
1991             return mSpanned.nextSpanTransition(start, limit, type);
1992         }
1993
1994         @Override
1995         public CharSequence subSequence(int start, int end) {
1996             char[] s = new char[end - start];
1997             getChars(start, end, s, 0);
1998
1999             SpannableString ss = new SpannableString(new String(s));
2000             TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2001             return ss;
2002         }
2003     }
2004
2005     private CharSequence mText;
2006     private TextPaint mPaint;
2007     private int mWidth;
2008     private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2009     private float mSpacingMult;
2010     private float mSpacingAdd;
2011     private static final Rect sTempRect = new Rect();
2012     private boolean mSpannedText;
2013     private TextDirectionHeuristic mTextDir;
2014     private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
2015
2016     public static final int DIR_LEFT_TO_RIGHT = 1;
2017     public static final int DIR_RIGHT_TO_LEFT = -1;
2018
2019     /* package */ static final int DIR_REQUEST_LTR = 1;
2020     /* package */ static final int DIR_REQUEST_RTL = -1;
2021     /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2022     /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
2023
2024     /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2025     /* package */ static final int RUN_LEVEL_SHIFT = 26;
2026     /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2027     /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2028
2029     public enum Alignment {
2030         ALIGN_NORMAL,
2031         ALIGN_OPPOSITE,
2032         ALIGN_CENTER,
2033         /** @hide */
2034         ALIGN_LEFT,
2035         /** @hide */
2036         ALIGN_RIGHT,
2037     }
2038
2039     private static final int TAB_INCREMENT = 20;
2040
2041     /* package */ static final Directions DIRS_ALL_LEFT_TO_RIGHT =
2042         new Directions(new int[] { 0, RUN_LENGTH_MASK });
2043     /* package */ static final Directions DIRS_ALL_RIGHT_TO_LEFT =
2044         new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });
2045
2046 }