2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import android.annotation.IntDef;
20 import android.graphics.Canvas;
21 import android.graphics.Paint;
22 import android.graphics.Path;
23 import android.graphics.Rect;
24 import android.text.method.TextKeyListener;
25 import android.text.style.AlignmentSpan;
26 import android.text.style.LeadingMarginSpan;
27 import android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
28 import android.text.style.LineBackgroundSpan;
29 import android.text.style.ParagraphStyle;
30 import android.text.style.ReplacementSpan;
31 import android.text.style.TabStopSpan;
33 import com.android.internal.util.ArrayUtils;
34 import com.android.internal.util.GrowingArrayUtils;
36 import java.lang.annotation.Retention;
37 import java.lang.annotation.RetentionPolicy;
38 import java.util.Arrays;
41 * A base class that manages text layout in visual elements on
43 * <p>For text that will be edited, use a {@link DynamicLayout},
44 * which will be updated as the text changes.
45 * For text that will not change, use a {@link StaticLayout}.
47 public abstract class Layout {
49 @IntDef({BREAK_STRATEGY_SIMPLE, BREAK_STRATEGY_HIGH_QUALITY, BREAK_STRATEGY_BALANCED})
50 @Retention(RetentionPolicy.SOURCE)
51 public @interface BreakStrategy {}
54 * Value for break strategy indicating simple line breaking. Automatic hyphens are not added
55 * (though soft hyphens are respected), and modifying text generally doesn't affect the layout
56 * before it (which yields a more consistent user experience when editing), but layout may not
57 * be the highest quality.
59 public static final int BREAK_STRATEGY_SIMPLE = 0;
62 * Value for break strategy indicating high quality line breaking, including automatic
63 * hyphenation and doing whole-paragraph optimization of line breaks.
65 public static final int BREAK_STRATEGY_HIGH_QUALITY = 1;
68 * Value for break strategy indicating balanced line breaking. The breaks are chosen to
69 * make all lines as close to the same length as possible, including automatic hyphenation.
71 public static final int BREAK_STRATEGY_BALANCED = 2;
74 @IntDef({HYPHENATION_FREQUENCY_NORMAL, HYPHENATION_FREQUENCY_FULL,
75 HYPHENATION_FREQUENCY_NONE})
76 @Retention(RetentionPolicy.SOURCE)
77 public @interface HyphenationFrequency {}
80 * Value for hyphenation frequency indicating no automatic hyphenation. Useful
81 * for backward compatibility, and for cases where the automatic hyphenation algorithm results
82 * in incorrect hyphenation. Mid-word breaks may still happen when a word is wider than the
83 * layout and there is otherwise no valid break. Soft hyphens are ignored and will not be used
84 * as suggestions for potential line breaks.
86 public static final int HYPHENATION_FREQUENCY_NONE = 0;
89 * Value for hyphenation frequency indicating a light amount of automatic hyphenation, which
90 * is a conservative default. Useful for informal cases, such as short sentences or chat
93 public static final int HYPHENATION_FREQUENCY_NORMAL = 1;
96 * Value for hyphenation frequency indicating the full amount of automatic hyphenation, typical
97 * in typography. Useful for running text and where it's important to put the maximum amount of
98 * text in a screen with limited space.
100 public static final int HYPHENATION_FREQUENCY_FULL = 2;
102 private static final ParagraphStyle[] NO_PARA_SPANS =
103 ArrayUtils.emptyArray(ParagraphStyle.class);
106 * Return how wide a layout must be in order to display the
107 * specified text with one line per paragraph.
109 public static float getDesiredWidth(CharSequence source,
111 return getDesiredWidth(source, 0, source.length(), paint);
115 * Return how wide a layout must be in order to display the
116 * specified text slice with one line per paragraph.
118 public static float getDesiredWidth(CharSequence source,
124 for (int i = start; i <= end; i = next) {
125 next = TextUtils.indexOf(source, '\n', i, end);
130 // note, omits trailing paragraph char
131 float w = measurePara(paint, source, i, next);
143 * Subclasses of Layout use this constructor to set the display text,
144 * width, and other standard properties.
145 * @param text the text to render
146 * @param paint the default paint for the layout. Styles can override
147 * various attributes of the paint.
148 * @param width the wrapping width for the text.
149 * @param align whether to left, right, or center the text. Styles can
150 * override the alignment.
151 * @param spacingMult factor by which to scale the font size to get the
152 * default line spacing
153 * @param spacingAdd amount to add to the default line spacing
155 protected Layout(CharSequence text, TextPaint paint,
156 int width, Alignment align,
157 float spacingMult, float spacingAdd) {
158 this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
159 spacingMult, spacingAdd);
163 * Subclasses of Layout use this constructor to set the display text,
164 * width, and other standard properties.
165 * @param text the text to render
166 * @param paint the default paint for the layout. Styles can override
167 * various attributes of the paint.
168 * @param width the wrapping width for the text.
169 * @param align whether to left, right, or center the text. Styles can
170 * override the alignment.
171 * @param spacingMult factor by which to scale the font size to get the
172 * default line spacing
173 * @param spacingAdd amount to add to the default line spacing
177 protected Layout(CharSequence text, TextPaint paint,
178 int width, Alignment align, TextDirectionHeuristic textDir,
179 float spacingMult, float spacingAdd) {
182 throw new IllegalArgumentException("Layout: " + width + " < 0");
184 // Ensure paint doesn't have baselineShift set.
185 // While normally we don't modify the paint the user passed in,
186 // we were already doing this in Styled.drawUniformRun with both
187 // baselineShift and bgColor. We probably should reevaluate bgColor.
190 paint.baselineShift = 0;
197 mSpacingMult = spacingMult;
198 mSpacingAdd = spacingAdd;
199 mSpannedText = text instanceof Spanned;
204 * Replace constructor properties of this Layout with new ones. Be careful.
206 /* package */ void replaceWith(CharSequence text, TextPaint paint,
207 int width, Alignment align,
208 float spacingmult, float spacingadd) {
210 throw new IllegalArgumentException("Layout: " + width + " < 0");
217 mSpacingMult = spacingmult;
218 mSpacingAdd = spacingadd;
219 mSpannedText = text instanceof Spanned;
223 * Draw this Layout on the specified Canvas.
225 public void draw(Canvas c) {
226 draw(c, null, null, 0);
230 * Draw this Layout on the specified canvas, with the highlight path drawn
231 * between the background and the text.
233 * @param canvas the canvas
234 * @param highlight the path of the highlight or cursor; can be null
235 * @param highlightPaint the paint for the highlight
236 * @param cursorOffsetVertical the amount to temporarily translate the
237 * canvas while rendering the highlight
239 public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
240 int cursorOffsetVertical) {
241 final long lineRange = getLineRangeForDraw(canvas);
242 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
243 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
244 if (lastLine < 0) return;
246 drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
247 firstLine, lastLine);
248 drawText(canvas, firstLine, lastLine);
254 public void drawText(Canvas canvas, int firstLine, int lastLine) {
255 int previousLineBottom = getLineTop(firstLine);
256 int previousLineEnd = getLineStart(firstLine);
257 ParagraphStyle[] spans = NO_PARA_SPANS;
259 TextPaint paint = mPaint;
260 CharSequence buf = mText;
262 Alignment paraAlign = mAlignment;
263 TabStops tabStops = null;
264 boolean tabStopsIsInitialized = false;
266 TextLine tl = TextLine.obtain();
268 // Draw the lines, one at a time.
269 // The baseline is the top of the following line minus the current line's descent.
270 for (int lineNum = firstLine; lineNum <= lastLine; lineNum++) {
271 int start = previousLineEnd;
272 previousLineEnd = getLineStart(lineNum + 1);
273 int end = getLineVisibleEnd(lineNum, start, previousLineEnd);
275 int ltop = previousLineBottom;
276 int lbottom = getLineTop(lineNum + 1);
277 previousLineBottom = lbottom;
278 int lbaseline = lbottom - getLineDescent(lineNum);
280 int dir = getParagraphDirection(lineNum);
285 Spanned sp = (Spanned) buf;
286 int textLength = buf.length();
287 boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
289 // New batch of paragraph styles, collect into spans array.
290 // Compute the alignment, last alignment style wins.
291 // Reset tabStops, we'll rebuild if we encounter a line with
293 // We expect paragraph spans to be relatively infrequent, use
294 // spanEnd so that we can check less frequently. Since
295 // paragraph styles ought to apply to entire paragraphs, we can
296 // just collect the ones present at the start of the paragraph.
297 // If spanEnd is before the end of the paragraph, that's not
299 if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
300 spanEnd = sp.nextSpanTransition(start, textLength,
301 ParagraphStyle.class);
302 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
304 paraAlign = mAlignment;
305 for (int n = spans.length - 1; n >= 0; n--) {
306 if (spans[n] instanceof AlignmentSpan) {
307 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
312 tabStopsIsInitialized = false;
315 // Draw all leading margin spans. Adjust left or right according
316 // to the paragraph direction of the line.
317 final int length = spans.length;
318 boolean useFirstLineMargin = isFirstParaLine;
319 for (int n = 0; n < length; n++) {
320 if (spans[n] instanceof LeadingMarginSpan2) {
321 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
322 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
323 // if there is more than one LeadingMarginSpan2, use
324 // the count that is greatest
325 if (lineNum < startLine + count) {
326 useFirstLineMargin = true;
331 for (int n = 0; n < length; n++) {
332 if (spans[n] instanceof LeadingMarginSpan) {
333 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
334 if (dir == DIR_RIGHT_TO_LEFT) {
335 margin.drawLeadingMargin(canvas, paint, right, dir, ltop,
336 lbaseline, lbottom, buf,
337 start, end, isFirstParaLine, this);
338 right -= margin.getLeadingMargin(useFirstLineMargin);
340 margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
341 lbaseline, lbottom, buf,
342 start, end, isFirstParaLine, this);
343 left += margin.getLeadingMargin(useFirstLineMargin);
349 boolean hasTab = getLineContainsTab(lineNum);
350 // Can't tell if we have tabs for sure, currently
351 if (hasTab && !tabStopsIsInitialized) {
352 if (tabStops == null) {
353 tabStops = new TabStops(TAB_INCREMENT, spans);
355 tabStops.reset(TAB_INCREMENT, spans);
357 tabStopsIsInitialized = true;
360 // Determine whether the line aligns to normal, opposite, or center.
361 Alignment align = paraAlign;
362 if (align == Alignment.ALIGN_LEFT) {
363 align = (dir == DIR_LEFT_TO_RIGHT) ?
364 Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
365 } else if (align == Alignment.ALIGN_RIGHT) {
366 align = (dir == DIR_LEFT_TO_RIGHT) ?
367 Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
371 if (align == Alignment.ALIGN_NORMAL) {
372 if (dir == DIR_LEFT_TO_RIGHT) {
373 x = left + getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
375 x = right + getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
378 int max = (int)getLineExtent(lineNum, tabStops, false);
379 if (align == Alignment.ALIGN_OPPOSITE) {
380 if (dir == DIR_LEFT_TO_RIGHT) {
381 x = right - max + getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
383 x = left - max + getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
385 } else { // Alignment.ALIGN_CENTER
387 x = ((right + left - max) >> 1) +
388 getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
392 paint.setHyphenEdit(getHyphen(lineNum));
393 Directions directions = getLineDirections(lineNum);
394 if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTab) {
395 // XXX: assumes there's nothing additional to be done
396 canvas.drawText(buf, start, end, x, lbaseline, paint);
398 tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops);
399 tl.draw(canvas, x, ltop, lbaseline, lbottom);
401 paint.setHyphenEdit(0);
404 TextLine.recycle(tl);
410 public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
411 int cursorOffsetVertical, int firstLine, int lastLine) {
412 // First, draw LineBackgroundSpans.
413 // LineBackgroundSpans know nothing about the alignment, margins, or
414 // direction of the layout or line. XXX: Should they?
415 // They are evaluated at each line.
417 if (mLineBackgroundSpans == null) {
418 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
421 Spanned buffer = (Spanned) mText;
422 int textLength = buffer.length();
423 mLineBackgroundSpans.init(buffer, 0, textLength);
425 if (mLineBackgroundSpans.numberOfSpans > 0) {
426 int previousLineBottom = getLineTop(firstLine);
427 int previousLineEnd = getLineStart(firstLine);
428 ParagraphStyle[] spans = NO_PARA_SPANS;
430 TextPaint paint = mPaint;
432 final int width = mWidth;
433 for (int i = firstLine; i <= lastLine; i++) {
434 int start = previousLineEnd;
435 int end = getLineStart(i + 1);
436 previousLineEnd = end;
438 int ltop = previousLineBottom;
439 int lbottom = getLineTop(i + 1);
440 previousLineBottom = lbottom;
441 int lbaseline = lbottom - getLineDescent(i);
443 if (start >= spanEnd) {
444 // These should be infrequent, so we'll use this so that
445 // we don't have to check as often.
446 spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
447 // All LineBackgroundSpans on a line contribute to its background.
449 // Duplication of the logic of getParagraphSpans
450 if (start != end || start == 0) {
451 // Equivalent to a getSpans(start, end), but filling the 'spans' local
452 // array instead to reduce memory allocation
453 for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
454 // equal test is valid since both intervals are not empty by
456 if (mLineBackgroundSpans.spanStarts[j] >= end ||
457 mLineBackgroundSpans.spanEnds[j] <= start) continue;
458 spans = GrowingArrayUtils.append(
459 spans, spansLength, mLineBackgroundSpans.spans[j]);
465 for (int n = 0; n < spansLength; n++) {
466 LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
467 lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
468 ltop, lbaseline, lbottom,
469 buffer, start, end, i);
473 mLineBackgroundSpans.recycle();
476 // There can be a highlight even without spans if we are drawing
477 // a non-spanned transformation of a spanned editing buffer.
478 if (highlight != null) {
479 if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
480 canvas.drawPath(highlight, highlightPaint);
481 if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
487 * @return The range of lines that need to be drawn, possibly empty.
490 public long getLineRangeForDraw(Canvas canvas) {
493 synchronized (sTempRect) {
494 if (!canvas.getClipBounds(sTempRect)) {
495 // Negative range end used as a special flag
496 return TextUtils.packRangeInLong(0, -1);
499 dtop = sTempRect.top;
500 dbottom = sTempRect.bottom;
503 final int top = Math.max(dtop, 0);
504 final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
506 if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
507 return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
511 * Return the start position of the line, given the left and right bounds
514 * @param line the line index
515 * @param left the left bounds (0, or leading margin if ltr para)
516 * @param right the right bounds (width, minus leading margin if rtl para)
517 * @return the start position of the line (to right of line if rtl para)
519 private int getLineStartPos(int line, int left, int right) {
520 // Adjust the point at which to start rendering depending on the
521 // alignment of the paragraph.
522 Alignment align = getParagraphAlignment(line);
523 int dir = getParagraphDirection(line);
525 if (align == Alignment.ALIGN_LEFT) {
526 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
527 } else if (align == Alignment.ALIGN_RIGHT) {
528 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
532 if (align == Alignment.ALIGN_NORMAL) {
533 if (dir == DIR_LEFT_TO_RIGHT) {
534 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
536 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
539 TabStops tabStops = null;
540 if (mSpannedText && getLineContainsTab(line)) {
541 Spanned spanned = (Spanned) mText;
542 int start = getLineStart(line);
543 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
545 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
547 if (tabSpans.length > 0) {
548 tabStops = new TabStops(TAB_INCREMENT, tabSpans);
551 int max = (int)getLineExtent(line, tabStops, false);
552 if (align == Alignment.ALIGN_OPPOSITE) {
553 if (dir == DIR_LEFT_TO_RIGHT) {
554 x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
556 // max is negative here
557 x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
559 } else { // Alignment.ALIGN_CENTER
561 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
568 * Return the text that is displayed by this Layout.
570 public final CharSequence getText() {
575 * Return the base Paint properties for this layout.
576 * Do NOT change the paint, which may result in funny
577 * drawing for this layout.
579 public final TextPaint getPaint() {
584 * Return the width of this layout.
586 public final int getWidth() {
591 * Return the width to which this Layout is ellipsizing, or
592 * {@link #getWidth} if it is not doing anything special.
594 public int getEllipsizedWidth() {
599 * Increase the width of this layout to the specified width.
600 * Be careful to use this only when you know it is appropriate—
601 * it does not cause the text to reflow to use the full new width.
603 public final void increaseWidthTo(int wid) {
605 throw new RuntimeException("attempted to reduce Layout width");
612 * Return the total height of this layout.
614 public int getHeight() {
615 return getLineTop(getLineCount());
619 * Return the base alignment of this layout.
621 public final Alignment getAlignment() {
626 * Return what the text height is multiplied by to get the line height.
628 public final float getSpacingMultiplier() {
633 * Return the number of units of leading that are added to each line.
635 public final float getSpacingAdd() {
640 * Return the heuristic used to determine paragraph text direction.
643 public final TextDirectionHeuristic getTextDirectionHeuristic() {
648 * Return the number of lines of text in this layout.
650 public abstract int getLineCount();
653 * Return the baseline for the specified line (0…getLineCount() - 1)
654 * If bounds is not null, return the top, left, right, bottom extents
655 * of the specified line in it.
656 * @param line which line to examine (0..getLineCount() - 1)
657 * @param bounds Optional. If not null, it returns the extent of the line
658 * @return the Y-coordinate of the baseline
660 public int getLineBounds(int line, Rect bounds) {
661 if (bounds != null) {
662 bounds.left = 0; // ???
663 bounds.top = getLineTop(line);
664 bounds.right = mWidth; // ???
665 bounds.bottom = getLineTop(line + 1);
667 return getLineBaseline(line);
671 * Return the vertical position of the top of the specified line
672 * (0…getLineCount()).
673 * If the specified line is equal to the line count, returns the
674 * bottom of the last line.
676 public abstract int getLineTop(int line);
679 * Return the descent of the specified line(0…getLineCount() - 1).
681 public abstract int getLineDescent(int line);
684 * Return the text offset of the beginning of the specified line (
685 * 0…getLineCount()). If the specified line is equal to the line
686 * count, returns the length of the text.
688 public abstract int getLineStart(int line);
691 * Returns the primary directionality of the paragraph containing the
692 * specified line, either 1 for left-to-right lines, or -1 for right-to-left
693 * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
695 public abstract int getParagraphDirection(int line);
698 * Returns whether the specified line contains one or more
699 * characters that need to be handled specially, like tabs.
701 public abstract boolean getLineContainsTab(int line);
704 * Returns the directional run information for the specified line.
705 * The array alternates counts of characters in left-to-right
706 * and right-to-left segments of the line.
708 * <p>NOTE: this is inadequate to support bidirectional text, and will change.
710 public abstract Directions getLineDirections(int line);
713 * Returns the (negative) number of extra pixels of ascent padding in the
714 * top line of the Layout.
716 public abstract int getTopPadding();
719 * Returns the number of extra pixels of descent padding in the
720 * bottom line of the Layout.
722 public abstract int getBottomPadding();
725 * Returns the hyphen edit for a line.
729 public int getHyphen(int line) {
734 * Returns the left indent for a line.
738 public int getIndentAdjust(int line, Alignment alignment) {
743 * Returns true if the character at offset and the preceding character
744 * are at different run levels (and thus there's a split caret).
745 * @param offset the offset
746 * @return true if at a level boundary
749 public boolean isLevelBoundary(int offset) {
750 int line = getLineForOffset(offset);
751 Directions dirs = getLineDirections(line);
752 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
756 int[] runs = dirs.mDirections;
757 int lineStart = getLineStart(line);
758 int lineEnd = getLineEnd(line);
759 if (offset == lineStart || offset == lineEnd) {
760 int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
761 int runIndex = offset == lineStart ? 0 : runs.length - 2;
762 return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
766 for (int i = 0; i < runs.length; i += 2) {
767 if (offset == runs[i]) {
775 * Returns true if the character at offset is right to left (RTL).
776 * @param offset the offset
777 * @return true if the character is RTL, false if it is LTR
779 public boolean isRtlCharAt(int offset) {
780 int line = getLineForOffset(offset);
781 Directions dirs = getLineDirections(line);
782 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
785 if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
788 int[] runs = dirs.mDirections;
789 int lineStart = getLineStart(line);
790 for (int i = 0; i < runs.length; i += 2) {
791 int start = lineStart + runs[i];
792 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
793 if (offset >= start && offset < limit) {
794 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
795 return ((level & 1) != 0);
798 // Should happen only if the offset is "out of bounds"
803 * Returns the range of the run that the character at offset belongs to.
804 * @param offset the offset
805 * @return The range of the run
808 public long getRunRange(int offset) {
809 int line = getLineForOffset(offset);
810 Directions dirs = getLineDirections(line);
811 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
812 return TextUtils.packRangeInLong(0, getLineEnd(line));
814 int[] runs = dirs.mDirections;
815 int lineStart = getLineStart(line);
816 for (int i = 0; i < runs.length; i += 2) {
817 int start = lineStart + runs[i];
818 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
819 if (offset >= start && offset < limit) {
820 return TextUtils.packRangeInLong(start, limit);
823 // Should happen only if the offset is "out of bounds"
824 return TextUtils.packRangeInLong(0, getLineEnd(line));
828 * Checks if the trailing BiDi level should be used for an offset
830 * This method is useful when the offset is at the BiDi level transition point and determine
831 * which run need to be used. For example, let's think about following input: (L* denotes
832 * Left-to-Right characters, R* denotes Right-to-Left characters.)
833 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
834 * Input (Display Order): L1 L2 L3 R3 R2 R1 L4 L5 L6
836 * Then, think about selecting the range (3, 6). The offset=3 and offset=6 are ambiguous here
837 * since they are at the BiDi transition point. In Android, the offset is considered to be
838 * associated with the trailing run if the BiDi level of the trailing run is higher than of the
839 * previous run. In this case, the BiDi level of the input text is as follows:
841 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
842 * BiDi Run: [ Run 0 ][ Run 1 ][ Run 2 ]
843 * BiDi Level: 0 0 0 1 1 1 0 0 0
845 * Thus, offset = 3 is part of Run 1 and this method returns true for offset = 3, since the BiDi
846 * level of Run 1 is higher than the level of Run 0. Similarly, the offset = 6 is a part of Run
847 * 1 and this method returns false for the offset = 6 since the BiDi level of Run 1 is higher
848 * than the level of Run 2.
850 * @returns true if offset is at the BiDi level transition point and trailing BiDi level is
851 * higher than previous BiDi level. See above for the detail.
853 private boolean primaryIsTrailingPrevious(int offset) {
854 int line = getLineForOffset(offset);
855 int lineStart = getLineStart(line);
856 int lineEnd = getLineEnd(line);
857 int[] runs = getLineDirections(line).mDirections;
860 for (int i = 0; i < runs.length; i += 2) {
861 int start = lineStart + runs[i];
862 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
863 if (limit > lineEnd) {
866 if (offset >= start && offset < limit) {
867 if (offset > start) {
868 // Previous character is at same level, so don't use trailing.
871 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
876 // Offset was limit of line.
877 levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
880 // At level boundary, check previous level.
881 int levelBefore = -1;
882 if (offset == lineStart) {
883 levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
886 for (int i = 0; i < runs.length; i += 2) {
887 int start = lineStart + runs[i];
888 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
889 if (limit > lineEnd) {
892 if (offset >= start && offset < limit) {
893 levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
899 return levelBefore < levelAt;
903 * Computes in linear time the results of calling
904 * #primaryIsTrailingPrevious for all offsets on a line.
905 * @param line The line giving the offsets we compute the information for
906 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
908 private boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
909 int lineStart = getLineStart(line);
910 int lineEnd = getLineEnd(line);
911 int[] runs = getLineDirections(line).mDirections;
913 boolean[] trailing = new boolean[lineEnd - lineStart + 1];
915 byte[] level = new byte[lineEnd - lineStart + 1];
916 for (int i = 0; i < runs.length; i += 2) {
917 int start = lineStart + runs[i];
918 int limit = start + (runs[i + 1] & RUN_LENGTH_MASK);
919 if (limit > lineEnd) {
922 level[limit - lineStart - 1] =
923 (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
926 for (int i = 0; i < runs.length; i += 2) {
927 int start = lineStart + runs[i];
928 byte currentLevel = (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
929 trailing[start - lineStart] = currentLevel > (start == lineStart
930 ? (getParagraphDirection(line) == 1 ? 0 : 1)
931 : level[start - lineStart - 1]);
938 * Get the primary horizontal position for the specified text offset.
939 * This is the location where a new character would be inserted in
940 * the paragraph's primary direction.
942 public float getPrimaryHorizontal(int offset) {
943 return getPrimaryHorizontal(offset, false /* not clamped */);
947 * Get the primary horizontal position for the specified text offset, but
948 * optionally clamp it so that it doesn't exceed the width of the layout.
951 public float getPrimaryHorizontal(int offset, boolean clamped) {
952 boolean trailing = primaryIsTrailingPrevious(offset);
953 return getHorizontal(offset, trailing, clamped);
957 * Get the secondary horizontal position for the specified text offset.
958 * This is the location where a new character would be inserted in
959 * the direction other than the paragraph's primary direction.
961 public float getSecondaryHorizontal(int offset) {
962 return getSecondaryHorizontal(offset, false /* not clamped */);
966 * Get the secondary horizontal position for the specified text offset, but
967 * optionally clamp it so that it doesn't exceed the width of the layout.
970 public float getSecondaryHorizontal(int offset, boolean clamped) {
971 boolean trailing = primaryIsTrailingPrevious(offset);
972 return getHorizontal(offset, !trailing, clamped);
975 private float getHorizontal(int offset, boolean primary) {
976 return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
979 private float getHorizontal(int offset, boolean trailing, boolean clamped) {
980 int line = getLineForOffset(offset);
982 return getHorizontal(offset, trailing, line, clamped);
985 private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
986 int start = getLineStart(line);
987 int end = getLineEnd(line);
988 int dir = getParagraphDirection(line);
989 boolean hasTab = getLineContainsTab(line);
990 Directions directions = getLineDirections(line);
992 TabStops tabStops = null;
993 if (hasTab && mText instanceof Spanned) {
994 // Just checking this line should be good enough, tabs should be
995 // consistent across all lines in a paragraph.
996 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
997 if (tabs.length > 0) {
998 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1002 TextLine tl = TextLine.obtain();
1003 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
1004 float wid = tl.measure(offset - start, trailing, null);
1005 TextLine.recycle(tl);
1007 if (clamped && wid > mWidth) {
1010 int left = getParagraphLeft(line);
1011 int right = getParagraphRight(line);
1013 return getLineStartPos(line, left, right) + wid;
1017 * Computes in linear time the results of calling
1018 * #getHorizontal for all offsets on a line.
1019 * @param line The line giving the offsets we compute information for
1020 * @param clamped Whether to clamp the results to the width of the layout
1021 * @param primary Whether the results should be the primary or the secondary horizontal
1022 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1024 private float[] getLineHorizontals(int line, boolean clamped, boolean primary) {
1025 int start = getLineStart(line);
1026 int end = getLineEnd(line);
1027 int dir = getParagraphDirection(line);
1028 boolean hasTab = getLineContainsTab(line);
1029 Directions directions = getLineDirections(line);
1031 TabStops tabStops = null;
1032 if (hasTab && mText instanceof Spanned) {
1033 // Just checking this line should be good enough, tabs should be
1034 // consistent across all lines in a paragraph.
1035 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1036 if (tabs.length > 0) {
1037 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1041 TextLine tl = TextLine.obtain();
1042 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
1043 boolean[] trailings = primaryIsTrailingPreviousAllLineOffsets(line);
1045 for (int offset = 0; offset < trailings.length; ++offset) {
1046 trailings[offset] = !trailings[offset];
1049 float[] wid = tl.measureAllOffsets(trailings, null);
1050 TextLine.recycle(tl);
1053 for (int offset = 0; offset <= wid.length; ++offset) {
1054 if (wid[offset] > mWidth) {
1055 wid[offset] = mWidth;
1059 int left = getParagraphLeft(line);
1060 int right = getParagraphRight(line);
1062 int lineStartPos = getLineStartPos(line, left, right);
1063 float[] horizontal = new float[end - start + 1];
1064 for (int offset = 0; offset < horizontal.length; ++offset) {
1065 horizontal[offset] = lineStartPos + wid[offset];
1071 * Get the leftmost position that should be exposed for horizontal
1072 * scrolling on the specified line.
1074 public float getLineLeft(int line) {
1075 int dir = getParagraphDirection(line);
1076 Alignment align = getParagraphAlignment(line);
1078 if (align == Alignment.ALIGN_LEFT) {
1080 } else if (align == Alignment.ALIGN_NORMAL) {
1081 if (dir == DIR_RIGHT_TO_LEFT)
1082 return getParagraphRight(line) - getLineMax(line);
1085 } else if (align == Alignment.ALIGN_RIGHT) {
1086 return mWidth - getLineMax(line);
1087 } else if (align == Alignment.ALIGN_OPPOSITE) {
1088 if (dir == DIR_RIGHT_TO_LEFT)
1091 return mWidth - getLineMax(line);
1092 } else { /* align == Alignment.ALIGN_CENTER */
1093 int left = getParagraphLeft(line);
1094 int right = getParagraphRight(line);
1095 int max = ((int) getLineMax(line)) & ~1;
1097 return left + ((right - left) - max) / 2;
1102 * Get the rightmost position that should be exposed for horizontal
1103 * scrolling on the specified line.
1105 public float getLineRight(int line) {
1106 int dir = getParagraphDirection(line);
1107 Alignment align = getParagraphAlignment(line);
1109 if (align == Alignment.ALIGN_LEFT) {
1110 return getParagraphLeft(line) + getLineMax(line);
1111 } else if (align == Alignment.ALIGN_NORMAL) {
1112 if (dir == DIR_RIGHT_TO_LEFT)
1115 return getParagraphLeft(line) + getLineMax(line);
1116 } else if (align == Alignment.ALIGN_RIGHT) {
1118 } else if (align == Alignment.ALIGN_OPPOSITE) {
1119 if (dir == DIR_RIGHT_TO_LEFT)
1120 return getLineMax(line);
1123 } else { /* align == Alignment.ALIGN_CENTER */
1124 int left = getParagraphLeft(line);
1125 int right = getParagraphRight(line);
1126 int max = ((int) getLineMax(line)) & ~1;
1128 return right - ((right - left) - max) / 2;
1133 * Gets the unsigned horizontal extent of the specified line, including
1134 * leading margin indent, but excluding trailing whitespace.
1136 public float getLineMax(int line) {
1137 float margin = getParagraphLeadingMargin(line);
1138 float signedExtent = getLineExtent(line, false);
1139 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1143 * Gets the unsigned horizontal extent of the specified line, including
1144 * leading margin indent and trailing whitespace.
1146 public float getLineWidth(int line) {
1147 float margin = getParagraphLeadingMargin(line);
1148 float signedExtent = getLineExtent(line, true);
1149 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
1153 * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1154 * tab stops instead of using the ones passed in.
1155 * @param line the index of the line
1156 * @param full whether to include trailing whitespace
1157 * @return the extent of the line
1159 private float getLineExtent(int line, boolean full) {
1160 int start = getLineStart(line);
1161 int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1163 boolean hasTabs = getLineContainsTab(line);
1164 TabStops tabStops = null;
1165 if (hasTabs && mText instanceof Spanned) {
1166 // Just checking this line should be good enough, tabs should be
1167 // consistent across all lines in a paragraph.
1168 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1169 if (tabs.length > 0) {
1170 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1173 Directions directions = getLineDirections(line);
1174 // Returned directions can actually be null
1175 if (directions == null) {
1178 int dir = getParagraphDirection(line);
1180 TextLine tl = TextLine.obtain();
1181 tl.set(mPaint, mText, start, end, dir, directions, hasTabs, tabStops);
1182 float width = tl.metrics(null);
1183 TextLine.recycle(tl);
1188 * Returns the signed horizontal extent of the specified line, excluding
1189 * leading margin. If full is false, excludes trailing whitespace.
1190 * @param line the index of the line
1191 * @param tabStops the tab stops, can be null if we know they're not used.
1192 * @param full whether to include trailing whitespace
1193 * @return the extent of the text on this line
1195 private float getLineExtent(int line, TabStops tabStops, boolean full) {
1196 int start = getLineStart(line);
1197 int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1198 boolean hasTabs = getLineContainsTab(line);
1199 Directions directions = getLineDirections(line);
1200 int dir = getParagraphDirection(line);
1202 TextLine tl = TextLine.obtain();
1203 tl.set(mPaint, mText, start, end, dir, directions, hasTabs, tabStops);
1204 float width = tl.metrics(null);
1205 TextLine.recycle(tl);
1210 * Get the line number corresponding to the specified vertical position.
1211 * If you ask for a position above 0, you get 0; if you ask for a position
1212 * below the bottom of the text, you get the last line.
1214 // FIXME: It may be faster to do a linear search for layouts without many lines.
1215 public int getLineForVertical(int vertical) {
1216 int high = getLineCount(), low = -1, guess;
1218 while (high - low > 1) {
1219 guess = (high + low) / 2;
1221 if (getLineTop(guess) > vertical)
1234 * Get the line number on which the specified text offset appears.
1235 * If you ask for a position before 0, you get 0; if you ask for a position
1236 * beyond the end of the text, you get the last line.
1238 public int getLineForOffset(int offset) {
1239 int high = getLineCount(), low = -1, guess;
1241 while (high - low > 1) {
1242 guess = (high + low) / 2;
1244 if (getLineStart(guess) > offset)
1257 * Get the character offset on the specified line whose position is
1258 * closest to the specified horizontal position.
1260 public int getOffsetForHorizontal(int line, float horiz) {
1261 return getOffsetForHorizontal(line, horiz, true);
1265 * Get the character offset on the specified line whose position is
1266 * closest to the specified horizontal position.
1268 * @param line the line used to find the closest offset
1269 * @param horiz the horizontal position used to find the closest offset
1270 * @param primary whether to use the primary position or secondary position to find the offset
1274 public int getOffsetForHorizontal(int line, float horiz, boolean primary) {
1275 // TODO: use Paint.getOffsetForAdvance to avoid binary search
1276 final int lineEndOffset = getLineEnd(line);
1277 final int lineStartOffset = getLineStart(line);
1279 Directions dirs = getLineDirections(line);
1281 TextLine tl = TextLine.obtain();
1282 // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1283 tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
1285 final HorizontalMeasurementProvider horizontal =
1286 new HorizontalMeasurementProvider(line, primary);
1289 if (line == getLineCount() - 1) {
1290 max = lineEndOffset;
1292 max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1293 !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
1295 int best = lineStartOffset;
1296 float bestdist = Math.abs(horizontal.get(lineStartOffset) - horiz);
1298 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1299 int here = lineStartOffset + dirs.mDirections[i];
1300 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1301 boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1302 int swap = isRtl ? -1 : 1;
1306 int high = there - 1 + 1, low = here + 1 - 1, guess;
1308 while (high - low > 1) {
1309 guess = (high + low) / 2;
1310 int adguess = getOffsetAtStartOf(guess);
1312 if (horizontal.get(adguess) * swap >= horiz * swap)
1322 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1323 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1324 if (low >= here && low < there) {
1325 float dist = Math.abs(horizontal.get(low) - horiz);
1327 float other = Math.abs(horizontal.get(aft) - horiz);
1335 if (dist < bestdist) {
1342 float dist = Math.abs(horizontal.get(here) - horiz);
1344 if (dist < bestdist) {
1350 float dist = Math.abs(horizontal.get(max) - horiz);
1352 if (dist <= bestdist) {
1357 TextLine.recycle(tl);
1362 * Responds to #getHorizontal queries, by selecting the better strategy between:
1363 * - calling #getHorizontal explicitly for each query
1364 * - precomputing all #getHorizontal measurements, and responding to any query in constant time
1365 * The first strategy is used for LTR-only text, while the second is used for all other cases.
1366 * The class is currently only used in #getOffsetForHorizontal, so reuse with care in other
1369 private class HorizontalMeasurementProvider {
1370 private final int mLine;
1371 private final boolean mPrimary;
1373 private float[] mHorizontals;
1374 private int mLineStartOffset;
1376 HorizontalMeasurementProvider(final int line, final boolean primary) {
1382 private void init() {
1383 final Directions dirs = getLineDirections(mLine);
1384 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1388 mHorizontals = getLineHorizontals(mLine, false, mPrimary);
1389 mLineStartOffset = getLineStart(mLine);
1392 float get(final int offset) {
1393 if (mHorizontals == null) {
1394 return getHorizontal(offset, mPrimary);
1396 return mHorizontals[offset - mLineStartOffset];
1402 * Return the text offset after the last character on the specified line.
1404 public final int getLineEnd(int line) {
1405 return getLineStart(line + 1);
1409 * Return the text offset after the last visible character (so whitespace
1410 * is not counted) on the specified line.
1412 public int getLineVisibleEnd(int line) {
1413 return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1416 private int getLineVisibleEnd(int line, int start, int end) {
1417 CharSequence text = mText;
1419 if (line == getLineCount() - 1) {
1423 for (; end > start; end--) {
1424 ch = text.charAt(end - 1);
1430 // Note: keep this in sync with Minikin LineBreaker::isLineEndSpace()
1431 if (!(ch == ' ' || ch == '\t' || ch == 0x1680 ||
1432 (0x2000 <= ch && ch <= 0x200A && ch != 0x2007) ||
1433 ch == 0x205F || ch == 0x3000)) {
1443 * Return the vertical position of the bottom of the specified line.
1445 public final int getLineBottom(int line) {
1446 return getLineTop(line + 1);
1450 * Return the vertical position of the baseline of the specified line.
1452 public final int getLineBaseline(int line) {
1453 // getLineTop(line+1) == getLineTop(line)
1454 return getLineTop(line+1) - getLineDescent(line);
1458 * Get the ascent of the text on the specified line.
1459 * The return value is negative to match the Paint.ascent() convention.
1461 public final int getLineAscent(int line) {
1462 // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1463 return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1466 public int getOffsetToLeftOf(int offset) {
1467 return getOffsetToLeftRightOf(offset, true);
1470 public int getOffsetToRightOf(int offset) {
1471 return getOffsetToLeftRightOf(offset, false);
1474 private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1475 int line = getLineForOffset(caret);
1476 int lineStart = getLineStart(line);
1477 int lineEnd = getLineEnd(line);
1478 int lineDir = getParagraphDirection(line);
1480 boolean lineChanged = false;
1481 boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
1482 // if walking off line, look at the line we're headed to
1484 if (caret == lineEnd) {
1485 if (line < getLineCount() - 1) {
1489 return caret; // at very end, don't move
1493 if (caret == lineStart) {
1498 return caret; // at very start, don't move
1504 lineStart = getLineStart(line);
1505 lineEnd = getLineEnd(line);
1506 int newDir = getParagraphDirection(line);
1507 if (newDir != lineDir) {
1508 // unusual case. we want to walk onto the line, but it runs
1509 // in a different direction than this one, so we fake movement
1510 // in the opposite direction.
1516 Directions directions = getLineDirections(line);
1518 TextLine tl = TextLine.obtain();
1519 // XXX: we don't care about tabs
1520 tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null);
1521 caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
1522 tl = TextLine.recycle(tl);
1526 private int getOffsetAtStartOf(int offset) {
1527 // XXX this probably should skip local reorderings and
1528 // zero-width characters, look at callers
1532 CharSequence text = mText;
1533 char c = text.charAt(offset);
1535 if (c >= '\uDC00' && c <= '\uDFFF') {
1536 char c1 = text.charAt(offset - 1);
1538 if (c1 >= '\uD800' && c1 <= '\uDBFF')
1543 ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1544 ReplacementSpan.class);
1546 for (int i = 0; i < spans.length; i++) {
1547 int start = ((Spanned) text).getSpanStart(spans[i]);
1548 int end = ((Spanned) text).getSpanEnd(spans[i]);
1550 if (start < offset && end > offset)
1559 * Determine whether we should clamp cursor position. Currently it's
1560 * only robust for left-aligned displays.
1563 public boolean shouldClampCursor(int line) {
1564 // Only clamp cursor position in left-aligned displays.
1565 switch (getParagraphAlignment(line)) {
1569 return getParagraphDirection(line) > 0;
1576 * Fills in the specified Path with a representation of a cursor
1577 * at the specified offset. This will often be a vertical line
1578 * but can be multiple discontinuous lines in text with multiple
1581 public void getCursorPath(int point, Path dest,
1582 CharSequence editingBuffer) {
1585 int line = getLineForOffset(point);
1586 int top = getLineTop(line);
1587 int bottom = getLineTop(line+1);
1589 boolean clamped = shouldClampCursor(line);
1590 float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1591 float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
1593 int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1594 TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1595 int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
1598 if (caps != 0 || fn != 0) {
1599 dist = (bottom - top) >> 2;
1612 if (Float.compare(h1, h2) == 0) {
1613 dest.moveTo(h1, top);
1614 dest.lineTo(h1, bottom);
1616 dest.moveTo(h1, top);
1617 dest.lineTo(h1, (top + bottom) >> 1);
1619 dest.moveTo(h2, (top + bottom) >> 1);
1620 dest.lineTo(h2, bottom);
1624 dest.moveTo(h2, bottom);
1625 dest.lineTo(h2 - dist, bottom + dist);
1626 dest.lineTo(h2, bottom);
1627 dest.lineTo(h2 + dist, bottom + dist);
1628 } else if (caps == 1) {
1629 dest.moveTo(h2, bottom);
1630 dest.lineTo(h2 - dist, bottom + dist);
1632 dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1633 dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1635 dest.moveTo(h2 + dist, bottom + dist);
1636 dest.lineTo(h2, bottom);
1640 dest.moveTo(h1, top);
1641 dest.lineTo(h1 - dist, top - dist);
1642 dest.lineTo(h1, top);
1643 dest.lineTo(h1 + dist, top - dist);
1644 } else if (fn == 1) {
1645 dest.moveTo(h1, top);
1646 dest.lineTo(h1 - dist, top - dist);
1648 dest.moveTo(h1 - dist, top - dist + 0.5f);
1649 dest.lineTo(h1 + dist, top - dist + 0.5f);
1651 dest.moveTo(h1 + dist, top - dist);
1652 dest.lineTo(h1, top);
1656 private void addSelection(int line, int start, int end,
1657 int top, int bottom, Path dest) {
1658 int linestart = getLineStart(line);
1659 int lineend = getLineEnd(line);
1660 Directions dirs = getLineDirections(line);
1662 if (lineend > linestart && mText.charAt(lineend - 1) == '\n')
1665 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1666 int here = linestart + dirs.mDirections[i];
1667 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
1669 if (there > lineend)
1672 if (start <= there && end >= here) {
1673 int st = Math.max(start, here);
1674 int en = Math.min(end, there);
1677 float h1 = getHorizontal(st, false, line, false /* not clamped */);
1678 float h2 = getHorizontal(en, true, line, false /* not clamped */);
1680 float left = Math.min(h1, h2);
1681 float right = Math.max(h1, h2);
1683 dest.addRect(left, top, right, bottom, Path.Direction.CW);
1690 * Fills in the specified Path with a representation of a highlight
1691 * between the specified offsets. This will often be a rectangle
1692 * or a potentially discontinuous set of rectangles. If the start
1693 * and end are the same, the returned path is empty.
1695 public void getSelectionPath(int start, int end, Path dest) {
1707 int startline = getLineForOffset(start);
1708 int endline = getLineForOffset(end);
1710 int top = getLineTop(startline);
1711 int bottom = getLineBottom(endline);
1713 if (startline == endline) {
1714 addSelection(startline, start, end, top, bottom, dest);
1716 final float width = mWidth;
1718 addSelection(startline, start, getLineEnd(startline),
1719 top, getLineBottom(startline), dest);
1721 if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT)
1722 dest.addRect(getLineLeft(startline), top,
1723 0, getLineBottom(startline), Path.Direction.CW);
1725 dest.addRect(getLineRight(startline), top,
1726 width, getLineBottom(startline), Path.Direction.CW);
1728 for (int i = startline + 1; i < endline; i++) {
1729 top = getLineTop(i);
1730 bottom = getLineBottom(i);
1731 dest.addRect(0, top, width, bottom, Path.Direction.CW);
1734 top = getLineTop(endline);
1735 bottom = getLineBottom(endline);
1737 addSelection(endline, getLineStart(endline), end,
1740 if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT)
1741 dest.addRect(width, top, getLineRight(endline), bottom, Path.Direction.CW);
1743 dest.addRect(0, top, getLineLeft(endline), bottom, Path.Direction.CW);
1748 * Get the alignment of the specified paragraph, taking into account
1749 * markup attached to it.
1751 public final Alignment getParagraphAlignment(int line) {
1752 Alignment align = mAlignment;
1755 Spanned sp = (Spanned) mText;
1756 AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
1758 AlignmentSpan.class);
1760 int spanLength = spans.length;
1761 if (spanLength > 0) {
1762 align = spans[spanLength-1].getAlignment();
1770 * Get the left edge of the specified paragraph, inset by left margins.
1772 public final int getParagraphLeft(int line) {
1774 int dir = getParagraphDirection(line);
1775 if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
1776 return left; // leading margin has no impact, or no styles
1778 return getParagraphLeadingMargin(line);
1782 * Get the right edge of the specified paragraph, inset by right margins.
1784 public final int getParagraphRight(int line) {
1786 int dir = getParagraphDirection(line);
1787 if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
1788 return right; // leading margin has no impact, or no styles
1790 return right - getParagraphLeadingMargin(line);
1794 * Returns the effective leading margin (unsigned) for this line,
1795 * taking into account LeadingMarginSpan and LeadingMarginSpan2.
1796 * @param line the line index
1797 * @return the leading margin of this line
1799 private int getParagraphLeadingMargin(int line) {
1800 if (!mSpannedText) {
1803 Spanned spanned = (Spanned) mText;
1805 int lineStart = getLineStart(line);
1806 int lineEnd = getLineEnd(line);
1807 int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
1808 LeadingMarginSpan.class);
1809 LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
1810 LeadingMarginSpan.class);
1811 if (spans.length == 0) {
1812 return 0; // no leading margin span;
1817 boolean isFirstParaLine = lineStart == 0 ||
1818 spanned.charAt(lineStart - 1) == '\n';
1820 boolean useFirstLineMargin = isFirstParaLine;
1821 for (int i = 0; i < spans.length; i++) {
1822 if (spans[i] instanceof LeadingMarginSpan2) {
1823 int spStart = spanned.getSpanStart(spans[i]);
1824 int spanLine = getLineForOffset(spStart);
1825 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
1826 // if there is more than one LeadingMarginSpan2, use the count that is greatest
1827 useFirstLineMargin |= line < spanLine + count;
1830 for (int i = 0; i < spans.length; i++) {
1831 LeadingMarginSpan span = spans[i];
1832 margin += span.getLeadingMargin(useFirstLineMargin);
1839 static float measurePara(TextPaint paint, CharSequence text, int start, int end) {
1841 MeasuredText mt = MeasuredText.obtain();
1842 TextLine tl = TextLine.obtain();
1844 mt.setPara(text, start, end, TextDirectionHeuristics.LTR, null);
1845 Directions directions;
1848 directions = DIRS_ALL_LEFT_TO_RIGHT;
1849 dir = Layout.DIR_LEFT_TO_RIGHT;
1851 directions = AndroidBidi.directions(mt.mDir, mt.mLevels,
1852 0, mt.mChars, 0, mt.mLen);
1855 char[] chars = mt.mChars;
1857 boolean hasTabs = false;
1858 TabStops tabStops = null;
1859 // leading margins should be taken into account when measuring a paragraph
1861 if (text instanceof Spanned) {
1862 Spanned spanned = (Spanned) text;
1863 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
1864 LeadingMarginSpan.class);
1865 for (LeadingMarginSpan lms : spans) {
1866 margin += lms.getLeadingMargin(true);
1869 for (int i = 0; i < len; ++i) {
1870 if (chars[i] == '\t') {
1872 if (text instanceof Spanned) {
1873 Spanned spanned = (Spanned) text;
1874 int spanEnd = spanned.nextSpanTransition(start, end,
1876 TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
1878 if (spans.length > 0) {
1879 tabStops = new TabStops(TAB_INCREMENT, spans);
1885 tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops);
1886 return margin + tl.metrics(null);
1888 TextLine.recycle(tl);
1889 MeasuredText.recycle(mt);
1896 /* package */ static class TabStops {
1897 private int[] mStops;
1898 private int mNumStops;
1899 private int mIncrement;
1901 TabStops(int increment, Object[] spans) {
1902 reset(increment, spans);
1905 void reset(int increment, Object[] spans) {
1906 this.mIncrement = increment;
1909 if (spans != null) {
1910 int[] stops = this.mStops;
1911 for (Object o : spans) {
1912 if (o instanceof TabStopSpan) {
1913 if (stops == null) {
1914 stops = new int[10];
1915 } else if (ns == stops.length) {
1916 int[] nstops = new int[ns * 2];
1917 for (int i = 0; i < ns; ++i) {
1918 nstops[i] = stops[i];
1922 stops[ns++] = ((TabStopSpan) o).getTabStop();
1926 Arrays.sort(stops, 0, ns);
1928 if (stops != this.mStops) {
1929 this.mStops = stops;
1932 this.mNumStops = ns;
1935 float nextTab(float h) {
1936 int ns = this.mNumStops;
1938 int[] stops = this.mStops;
1939 for (int i = 0; i < ns; ++i) {
1940 int stop = stops[i];
1946 return nextDefaultStop(h, mIncrement);
1949 public static float nextDefaultStop(float h, int inc) {
1950 return ((int) ((h + inc) / inc)) * inc;
1955 * Returns the position of the next tab stop after h on the line.
1957 * @param text the text
1958 * @param start start of the line
1959 * @param end limit of the line
1960 * @param h the current horizontal offset
1961 * @param tabs the tabs, can be null. If it is null, any tabs in effect
1962 * on the line will be used. If there are no tabs, a default offset
1963 * will be used to compute the tab stop.
1964 * @return the offset of the next tab stop.
1966 /* package */ static float nextTab(CharSequence text, int start, int end,
1967 float h, Object[] tabs) {
1968 float nh = Float.MAX_VALUE;
1969 boolean alltabs = false;
1971 if (text instanceof Spanned) {
1973 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
1977 for (int i = 0; i < tabs.length; i++) {
1979 if (!(tabs[i] instanceof TabStopSpan))
1983 int where = ((TabStopSpan) tabs[i]).getTabStop();
1985 if (where < nh && where > h)
1989 if (nh != Float.MAX_VALUE)
1993 return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
1996 protected final boolean isSpanned() {
1997 return mSpannedText;
2001 * Returns the same as <code>text.getSpans()</code>, except where
2002 * <code>start</code> and <code>end</code> are the same and are not
2003 * at the very beginning of the text, in which case an empty array
2004 * is returned instead.
2006 * This is needed because of the special case that <code>getSpans()</code>
2007 * on an empty range returns the spans adjacent to that range, which is
2008 * primarily for the sake of <code>TextWatchers</code> so they will get
2009 * notifications when text goes from empty to non-empty. But it also
2010 * has the unfortunate side effect that if the text ends with an empty
2011 * paragraph, that paragraph accidentally picks up the styles of the
2012 * preceding paragraph (even though those styles will not be picked up
2013 * by new text that is inserted into the empty paragraph).
2015 * The reason it just checks whether <code>start</code> and <code>end</code>
2016 * is the same is that the only time a line can contain 0 characters
2017 * is if it is the final paragraph of the Layout; otherwise any line will
2018 * contain at least one printing or newline character. The reason for the
2019 * additional check if <code>start</code> is greater than 0 is that
2020 * if the empty paragraph is the entire content of the buffer, paragraph
2021 * styles that are already applied to the buffer will apply to text that
2022 * is inserted into it.
2024 /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
2025 if (start == end && start > 0) {
2026 return ArrayUtils.emptyArray(type);
2029 if(text instanceof SpannableStringBuilder) {
2030 return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2032 return text.getSpans(start, end, type);
2036 private char getEllipsisChar(TextUtils.TruncateAt method) {
2037 return (method == TextUtils.TruncateAt.END_SMALL) ?
2038 TextUtils.ELLIPSIS_TWO_DOTS[0] :
2039 TextUtils.ELLIPSIS_NORMAL[0];
2042 private void ellipsize(int start, int end, int line,
2043 char[] dest, int destoff, TextUtils.TruncateAt method) {
2044 int ellipsisCount = getEllipsisCount(line);
2046 if (ellipsisCount == 0) {
2050 int ellipsisStart = getEllipsisStart(line);
2051 int linestart = getLineStart(line);
2053 for (int i = ellipsisStart; i < ellipsisStart + ellipsisCount; i++) {
2056 if (i == ellipsisStart) {
2057 c = getEllipsisChar(method); // ellipsis
2059 c = '\uFEFF'; // 0-width space
2062 int a = i + linestart;
2064 if (a >= start && a < end) {
2065 dest[destoff + a - start] = c;
2071 * Stores information about bidirectional (left-to-right or right-to-left)
2072 * text within the layout of a line.
2074 public static class Directions {
2075 // Directions represents directional runs within a line of text.
2076 // Runs are pairs of ints listed in visual order, starting from the
2077 // leading margin. The first int of each pair is the offset from
2078 // the first character of the line to the start of the run. The
2079 // second int represents both the length and level of the run.
2080 // The length is in the lower bits, accessed by masking with
2081 // DIR_LENGTH_MASK. The level is in the higher bits, accessed
2082 // by shifting by DIR_LEVEL_SHIFT and masking by DIR_LEVEL_MASK.
2083 // To simply test for an RTL direction, test the bit using
2084 // DIR_RTL_FLAG, if set then the direction is rtl.
2086 /* package */ int[] mDirections;
2087 /* package */ Directions(int[] dirs) {
2093 * Return the offset of the first character to be ellipsized away,
2094 * relative to the start of the line. (So 0 if the beginning of the
2095 * line is ellipsized, not getLineStart().)
2097 public abstract int getEllipsisStart(int line);
2100 * Returns the number of characters to be ellipsized away, or 0 if
2101 * no ellipsis is to take place.
2103 public abstract int getEllipsisCount(int line);
2105 /* package */ static class Ellipsizer implements CharSequence, GetChars {
2106 /* package */ CharSequence mText;
2107 /* package */ Layout mLayout;
2108 /* package */ int mWidth;
2109 /* package */ TextUtils.TruncateAt mMethod;
2111 public Ellipsizer(CharSequence s) {
2115 public char charAt(int off) {
2116 char[] buf = TextUtils.obtain(1);
2117 getChars(off, off + 1, buf, 0);
2120 TextUtils.recycle(buf);
2124 public void getChars(int start, int end, char[] dest, int destoff) {
2125 int line1 = mLayout.getLineForOffset(start);
2126 int line2 = mLayout.getLineForOffset(end);
2128 TextUtils.getChars(mText, start, end, dest, destoff);
2130 for (int i = line1; i <= line2; i++) {
2131 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
2135 public int length() {
2136 return mText.length();
2139 public CharSequence subSequence(int start, int end) {
2140 char[] s = new char[end - start];
2141 getChars(start, end, s, 0);
2142 return new String(s);
2146 public String toString() {
2147 char[] s = new char[length()];
2148 getChars(0, length(), s, 0);
2149 return new String(s);
2154 /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
2155 private Spanned mSpanned;
2157 public SpannedEllipsizer(CharSequence display) {
2159 mSpanned = (Spanned) display;
2162 public <T> T[] getSpans(int start, int end, Class<T> type) {
2163 return mSpanned.getSpans(start, end, type);
2166 public int getSpanStart(Object tag) {
2167 return mSpanned.getSpanStart(tag);
2170 public int getSpanEnd(Object tag) {
2171 return mSpanned.getSpanEnd(tag);
2174 public int getSpanFlags(Object tag) {
2175 return mSpanned.getSpanFlags(tag);
2178 @SuppressWarnings("rawtypes")
2179 public int nextSpanTransition(int start, int limit, Class type) {
2180 return mSpanned.nextSpanTransition(start, limit, type);
2184 public CharSequence subSequence(int start, int end) {
2185 char[] s = new char[end - start];
2186 getChars(start, end, s, 0);
2188 SpannableString ss = new SpannableString(new String(s));
2189 TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2194 private CharSequence mText;
2195 private TextPaint mPaint;
2197 private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2198 private float mSpacingMult;
2199 private float mSpacingAdd;
2200 private static final Rect sTempRect = new Rect();
2201 private boolean mSpannedText;
2202 private TextDirectionHeuristic mTextDir;
2203 private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
2205 public static final int DIR_LEFT_TO_RIGHT = 1;
2206 public static final int DIR_RIGHT_TO_LEFT = -1;
2208 /* package */ static final int DIR_REQUEST_LTR = 1;
2209 /* package */ static final int DIR_REQUEST_RTL = -1;
2210 /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2211 /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
2213 /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2214 /* package */ static final int RUN_LEVEL_SHIFT = 26;
2215 /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2216 /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2218 public enum Alignment {
2228 private static final int TAB_INCREMENT = 20;
2230 /* package */ static final Directions DIRS_ALL_LEFT_TO_RIGHT =
2231 new Directions(new int[] { 0, RUN_LENGTH_MASK });
2232 /* package */ static final Directions DIRS_ALL_RIGHT_TO_LEFT =
2233 new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });