blob: 98d6e955dde2e1037e9c27311cf224c4ff374f3d [file] [log] [blame]
Gilles Debunne60e3b3f2012-03-13 11:26:05 -07001/*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002 * 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
17package android.text;
18
Raph Levien39b4db72015-03-25 13:18:20 -070019import android.annotation.IntDef;
Siyamed Sinir0fa89d62017-07-24 20:46:41 -070020import android.annotation.IntRange;
Mathew Inwoodefeab842018-08-14 15:21:30 +010021import android.annotation.UnsupportedAppUsage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.graphics.Canvas;
23import android.graphics.Paint;
Doug Felt9f7a4442010-03-01 12:45:56 -080024import android.graphics.Path;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.graphics.Rect;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.text.method.TextKeyListener;
Doug Felt9f7a4442010-03-01 12:45:56 -080027import android.text.style.AlignmentSpan;
28import android.text.style.LeadingMarginSpan;
Gilles Debunne162bf0f2010-11-16 16:23:53 -080029import android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
Doug Felt9f7a4442010-03-01 12:45:56 -080030import android.text.style.LineBackgroundSpan;
31import android.text.style.ParagraphStyle;
32import android.text.style.ReplacementSpan;
33import android.text.style.TabStopSpan;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034
Siyamed Sinired09ae12016-02-16 14:36:26 -080035import com.android.internal.annotations.VisibleForTesting;
Doug Feltcb3791202011-07-07 11:57:48 -070036import com.android.internal.util.ArrayUtils;
Adam Lesinski776abc22014-03-07 11:30:59 -050037import com.android.internal.util.GrowingArrayUtils;
Doug Feltcb3791202011-07-07 11:57:48 -070038
Raph Levien39b4db72015-03-25 13:18:20 -070039import java.lang.annotation.Retention;
40import java.lang.annotation.RetentionPolicy;
Doug Feltc982f602010-05-25 11:51:40 -070041import java.util.Arrays;
Doug Felt9f7a4442010-03-01 12:45:56 -080042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043/**
Doug Felt9f7a4442010-03-01 12:45:56 -080044 * A base class that manages text layout in visual elements on
45 * the screen.
46 * <p>For text that will be edited, use a {@link DynamicLayout},
47 * which will be updated as the text changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048 * For text that will not change, use a {@link StaticLayout}.
49 */
50public abstract class Layout {
Raph Levien39b4db72015-03-25 13:18:20 -070051 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -070052 @IntDef(prefix = { "BREAK_STRATEGY_" }, value = {
53 BREAK_STRATEGY_SIMPLE,
54 BREAK_STRATEGY_HIGH_QUALITY,
55 BREAK_STRATEGY_BALANCED
56 })
Raph Levien39b4db72015-03-25 13:18:20 -070057 @Retention(RetentionPolicy.SOURCE)
58 public @interface BreakStrategy {}
59
60 /**
61 * Value for break strategy indicating simple line breaking. Automatic hyphens are not added
62 * (though soft hyphens are respected), and modifying text generally doesn't affect the layout
63 * before it (which yields a more consistent user experience when editing), but layout may not
64 * be the highest quality.
65 */
66 public static final int BREAK_STRATEGY_SIMPLE = 0;
67
68 /**
69 * Value for break strategy indicating high quality line breaking, including automatic
70 * hyphenation and doing whole-paragraph optimization of line breaks.
71 */
72 public static final int BREAK_STRATEGY_HIGH_QUALITY = 1;
73
74 /**
75 * Value for break strategy indicating balanced line breaking. The breaks are chosen to
76 * make all lines as close to the same length as possible, including automatic hyphenation.
77 */
78 public static final int BREAK_STRATEGY_BALANCED = 2;
79
Roozbeh Pournader95c7a132015-05-12 12:01:06 -070080 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -070081 @IntDef(prefix = { "HYPHENATION_FREQUENCY_" }, value = {
82 HYPHENATION_FREQUENCY_NORMAL,
83 HYPHENATION_FREQUENCY_FULL,
84 HYPHENATION_FREQUENCY_NONE
85 })
Roozbeh Pournader95c7a132015-05-12 12:01:06 -070086 @Retention(RetentionPolicy.SOURCE)
87 public @interface HyphenationFrequency {}
88
89 /**
90 * Value for hyphenation frequency indicating no automatic hyphenation. Useful
91 * for backward compatibility, and for cases where the automatic hyphenation algorithm results
92 * in incorrect hyphenation. Mid-word breaks may still happen when a word is wider than the
93 * layout and there is otherwise no valid break. Soft hyphens are ignored and will not be used
94 * as suggestions for potential line breaks.
95 */
96 public static final int HYPHENATION_FREQUENCY_NONE = 0;
97
98 /**
99 * Value for hyphenation frequency indicating a light amount of automatic hyphenation, which
100 * is a conservative default. Useful for informal cases, such as short sentences or chat
101 * messages.
102 */
103 public static final int HYPHENATION_FREQUENCY_NORMAL = 1;
104
105 /**
106 * Value for hyphenation frequency indicating the full amount of automatic hyphenation, typical
107 * in typography. Useful for running text and where it's important to put the maximum amount of
108 * text in a screen with limited space.
109 */
110 public static final int HYPHENATION_FREQUENCY_FULL = 2;
111
Doug Felt71b8dd72010-02-16 17:27:09 -0800112 private static final ParagraphStyle[] NO_PARA_SPANS =
113 ArrayUtils.emptyArray(ParagraphStyle.class);
Dave Bort76c02262009-04-13 17:17:21 -0700114
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700115 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -0700116 @IntDef(prefix = { "JUSTIFICATION_MODE_" }, value = {
117 JUSTIFICATION_MODE_NONE,
118 JUSTIFICATION_MODE_INTER_WORD
119 })
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700120 @Retention(RetentionPolicy.SOURCE)
121 public @interface JustificationMode {}
122
123 /**
124 * Value for justification mode indicating no justification.
125 */
126 public static final int JUSTIFICATION_MODE_NONE = 0;
127
128 /**
129 * Value for justification mode indicating the text is justified by stretching word spacing.
130 */
131 public static final int JUSTIFICATION_MODE_INTER_WORD = 1;
132
Roozbeh Pournader22a167c2017-08-21 12:53:44 -0700133 /*
134 * Line spacing multiplier for default line spacing.
135 */
136 public static final float DEFAULT_LINESPACING_MULTIPLIER = 1.0f;
137
138 /*
139 * Line spacing addition for default line spacing.
140 */
141 public static final float DEFAULT_LINESPACING_ADDITION = 0.0f;
142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 /**
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700144 * Return how wide a layout must be in order to display the specified text with one line per
145 * paragraph.
146 *
147 * <p>As of O, Uses
148 * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
149 * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 */
151 public static float getDesiredWidth(CharSequence source,
152 TextPaint paint) {
153 return getDesiredWidth(source, 0, source.length(), paint);
154 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 /**
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700157 * Return how wide a layout must be in order to display the specified text slice with one
158 * line per paragraph.
159 *
160 * <p>As of O, Uses
161 * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
162 * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
163 */
164 public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint) {
165 return getDesiredWidth(source, start, end, paint, TextDirectionHeuristics.FIRSTSTRONG_LTR);
166 }
167
168 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800169 * Return how wide a layout must be in order to display the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 * specified text slice with one line per paragraph.
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700171 *
172 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 */
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700174 public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint,
175 TextDirectionHeuristic textDir) {
Seigo Nonaka917748e2017-08-03 17:42:28 -0700176 return getDesiredWidthWithLimit(source, start, end, paint, textDir, Float.MAX_VALUE);
177 }
178 /**
179 * Return how wide a layout must be in order to display the
180 * specified text slice with one line per paragraph.
181 *
182 * If the measured width exceeds given limit, returns limit value instead.
183 * @hide
184 */
185 public static float getDesiredWidthWithLimit(CharSequence source, int start, int end,
186 TextPaint paint, TextDirectionHeuristic textDir, float upperLimit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 float need = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
189 int next;
190 for (int i = start; i <= end; i = next) {
191 next = TextUtils.indexOf(source, '\n', i, end);
192
193 if (next < 0)
194 next = end;
195
Doug Felt71b8dd72010-02-16 17:27:09 -0800196 // note, omits trailing paragraph char
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700197 float w = measurePara(paint, source, i, next, textDir);
Seigo Nonaka917748e2017-08-03 17:42:28 -0700198 if (w > upperLimit) {
199 return upperLimit;
200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
202 if (w > need)
203 need = w;
204
205 next++;
206 }
207
208 return need;
209 }
210
211 /**
212 * Subclasses of Layout use this constructor to set the display text,
213 * width, and other standard properties.
Doug Felt71b8dd72010-02-16 17:27:09 -0800214 * @param text the text to render
215 * @param paint the default paint for the layout. Styles can override
216 * various attributes of the paint.
217 * @param width the wrapping width for the text.
218 * @param align whether to left, right, or center the text. Styles can
219 * override the alignment.
220 * @param spacingMult factor by which to scale the font size to get the
221 * default line spacing
222 * @param spacingAdd amount to add to the default line spacing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 */
224 protected Layout(CharSequence text, TextPaint paint,
225 int width, Alignment align,
Doug Felt71b8dd72010-02-16 17:27:09 -0800226 float spacingMult, float spacingAdd) {
Doug Feltcb3791202011-07-07 11:57:48 -0700227 this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
228 spacingMult, spacingAdd);
229 }
230
231 /**
232 * Subclasses of Layout use this constructor to set the display text,
233 * width, and other standard properties.
234 * @param text the text to render
235 * @param paint the default paint for the layout. Styles can override
236 * various attributes of the paint.
237 * @param width the wrapping width for the text.
238 * @param align whether to left, right, or center the text. Styles can
239 * override the alignment.
240 * @param spacingMult factor by which to scale the font size to get the
241 * default line spacing
242 * @param spacingAdd amount to add to the default line spacing
243 *
244 * @hide
245 */
246 protected Layout(CharSequence text, TextPaint paint,
247 int width, Alignment align, TextDirectionHeuristic textDir,
248 float spacingMult, float spacingAdd) {
249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 if (width < 0)
251 throw new IllegalArgumentException("Layout: " + width + " < 0");
252
Doug Felte8e45f22010-03-29 14:58:40 -0700253 // Ensure paint doesn't have baselineShift set.
254 // While normally we don't modify the paint the user passed in,
255 // we were already doing this in Styled.drawUniformRun with both
256 // baselineShift and bgColor. We probably should reevaluate bgColor.
257 if (paint != null) {
258 paint.bgColor = 0;
259 paint.baselineShift = 0;
260 }
261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 mText = text;
263 mPaint = paint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 mWidth = width;
265 mAlignment = align;
Doug Felt71b8dd72010-02-16 17:27:09 -0800266 mSpacingMult = spacingMult;
267 mSpacingAdd = spacingAdd;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 mSpannedText = text instanceof Spanned;
Doug Feltcb3791202011-07-07 11:57:48 -0700269 mTextDir = textDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 }
271
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900272 /** @hide */
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700273 protected void setJustificationMode(@JustificationMode int justificationMode) {
274 mJustificationMode = justificationMode;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900275 }
276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 /**
278 * Replace constructor properties of this Layout with new ones. Be careful.
279 */
280 /* package */ void replaceWith(CharSequence text, TextPaint paint,
281 int width, Alignment align,
282 float spacingmult, float spacingadd) {
283 if (width < 0) {
284 throw new IllegalArgumentException("Layout: " + width + " < 0");
285 }
286
287 mText = text;
288 mPaint = paint;
289 mWidth = width;
290 mAlignment = align;
291 mSpacingMult = spacingmult;
292 mSpacingAdd = spacingadd;
293 mSpannedText = text instanceof Spanned;
294 }
295
296 /**
297 * Draw this Layout on the specified Canvas.
298 */
299 public void draw(Canvas c) {
300 draw(c, null, null, 0);
301 }
302
303 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800304 * Draw this Layout on the specified canvas, with the highlight path drawn
305 * between the background and the text.
306 *
Gilles Debunne6c488de2012-03-01 16:20:35 -0800307 * @param canvas the canvas
Doug Felt71b8dd72010-02-16 17:27:09 -0800308 * @param highlight the path of the highlight or cursor; can be null
309 * @param highlightPaint the paint for the highlight
310 * @param cursorOffsetVertical the amount to temporarily translate the
311 * canvas while rendering the highlight
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 */
Gilles Debunne6c488de2012-03-01 16:20:35 -0800313 public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
314 int cursorOffsetVertical) {
315 final long lineRange = getLineRangeForDraw(canvas);
316 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
317 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
318 if (lastLine < 0) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319
Gilles Debunne6c488de2012-03-01 16:20:35 -0800320 drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
321 firstLine, lastLine);
322 drawText(canvas, firstLine, lastLine);
323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900325 private boolean isJustificationRequired(int lineNum) {
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700326 if (mJustificationMode == JUSTIFICATION_MODE_NONE) return false;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900327 final int lineEnd = getLineEnd(lineNum);
328 return lineEnd < mText.length() && mText.charAt(lineEnd - 1) != '\n';
329 }
330
331 private float getJustifyWidth(int lineNum) {
332 Alignment paraAlign = mAlignment;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900333
334 int left = 0;
335 int right = mWidth;
336
337 final int dir = getParagraphDirection(lineNum);
338
339 ParagraphStyle[] spans = NO_PARA_SPANS;
340 if (mSpannedText) {
341 Spanned sp = (Spanned) mText;
342 final int start = getLineStart(lineNum);
343
344 final boolean isFirstParaLine = (start == 0 || mText.charAt(start - 1) == '\n');
345
346 if (isFirstParaLine) {
347 final int spanEnd = sp.nextSpanTransition(start, mText.length(),
348 ParagraphStyle.class);
349 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
350
351 for (int n = spans.length - 1; n >= 0; n--) {
352 if (spans[n] instanceof AlignmentSpan) {
353 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
354 break;
355 }
356 }
357 }
358
359 final int length = spans.length;
360 boolean useFirstLineMargin = isFirstParaLine;
361 for (int n = 0; n < length; n++) {
362 if (spans[n] instanceof LeadingMarginSpan2) {
363 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
364 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
365 if (lineNum < startLine + count) {
366 useFirstLineMargin = true;
367 break;
368 }
369 }
370 }
371 for (int n = 0; n < length; n++) {
372 if (spans[n] instanceof LeadingMarginSpan) {
373 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
374 if (dir == DIR_RIGHT_TO_LEFT) {
375 right -= margin.getLeadingMargin(useFirstLineMargin);
376 } else {
377 left += margin.getLeadingMargin(useFirstLineMargin);
378 }
379 }
380 }
381 }
382
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900383 final Alignment align;
384 if (paraAlign == Alignment.ALIGN_LEFT) {
385 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
386 } else if (paraAlign == Alignment.ALIGN_RIGHT) {
387 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
388 } else {
389 align = paraAlign;
390 }
391
392 final int indentWidth;
393 if (align == Alignment.ALIGN_NORMAL) {
394 if (dir == DIR_LEFT_TO_RIGHT) {
395 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
396 } else {
397 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
398 }
399 } else if (align == Alignment.ALIGN_OPPOSITE) {
400 if (dir == DIR_LEFT_TO_RIGHT) {
401 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
402 } else {
403 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
404 }
405 } else { // Alignment.ALIGN_CENTER
406 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
407 }
408
409 return right - left - indentWidth;
410 }
411
Gilles Debunne6c488de2012-03-01 16:20:35 -0800412 /**
413 * @hide
414 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100415 @UnsupportedAppUsage
Gilles Debunne6c488de2012-03-01 16:20:35 -0800416 public void drawText(Canvas canvas, int firstLine, int lastLine) {
417 int previousLineBottom = getLineTop(firstLine);
418 int previousLineEnd = getLineStart(firstLine);
Doug Felt71b8dd72010-02-16 17:27:09 -0800419 ParagraphStyle[] spans = NO_PARA_SPANS;
Doug Feltc982f602010-05-25 11:51:40 -0700420 int spanEnd = 0;
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -0700421 final TextPaint paint = mWorkPaint;
422 paint.set(mPaint);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800423 CharSequence buf = mText;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700425 Alignment paraAlign = mAlignment;
Doug Feltc982f602010-05-25 11:51:40 -0700426 TabStops tabStops = null;
427 boolean tabStopsIsInitialized = false;
Doug Felt9f7a4442010-03-01 12:45:56 -0800428
Doug Felte8e45f22010-03-29 14:58:40 -0700429 TextLine tl = TextLine.obtain();
Doug Feltc982f602010-05-25 11:51:40 -0700430
Gilles Debunne6c488de2012-03-01 16:20:35 -0800431 // Draw the lines, one at a time.
432 // The baseline is the top of the following line minus the current line's descent.
Raph Levien26d443a2015-03-30 14:18:32 -0700433 for (int lineNum = firstLine; lineNum <= lastLine; lineNum++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 int start = previousLineEnd;
Raph Levien26d443a2015-03-30 14:18:32 -0700435 previousLineEnd = getLineStart(lineNum + 1);
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900436 final boolean justify = isJustificationRequired(lineNum);
Raph Levien26d443a2015-03-30 14:18:32 -0700437 int end = getLineVisibleEnd(lineNum, start, previousLineEnd);
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -0700438 paint.setHyphenEdit(getHyphen(lineNum));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439
440 int ltop = previousLineBottom;
Raph Levien26d443a2015-03-30 14:18:32 -0700441 int lbottom = getLineTop(lineNum + 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 previousLineBottom = lbottom;
Raph Levien26d443a2015-03-30 14:18:32 -0700443 int lbaseline = lbottom - getLineDescent(lineNum);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444
Raph Levien26d443a2015-03-30 14:18:32 -0700445 int dir = getParagraphDirection(lineNum);
Doug Feltc982f602010-05-25 11:51:40 -0700446 int left = 0;
447 int right = mWidth;
448
Gilles Debunne6c488de2012-03-01 16:20:35 -0800449 if (mSpannedText) {
Doug Feltc982f602010-05-25 11:51:40 -0700450 Spanned sp = (Spanned) buf;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800451 int textLength = buf.length();
452 boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
Doug Felt0c702b82010-05-14 10:55:42 -0700453
Doug Feltc982f602010-05-25 11:51:40 -0700454 // New batch of paragraph styles, collect into spans array.
455 // Compute the alignment, last alignment style wins.
456 // Reset tabStops, we'll rebuild if we encounter a line with
457 // tabs.
458 // We expect paragraph spans to be relatively infrequent, use
459 // spanEnd so that we can check less frequently. Since
460 // paragraph styles ought to apply to entire paragraphs, we can
461 // just collect the ones present at the start of the paragraph.
462 // If spanEnd is before the end of the paragraph, that's not
463 // our problem.
Raph Levien26d443a2015-03-30 14:18:32 -0700464 if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
Doug Feltc982f602010-05-25 11:51:40 -0700465 spanEnd = sp.nextSpanTransition(start, textLength,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 ParagraphStyle.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -0700467 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
Doug Felt9f7a4442010-03-01 12:45:56 -0800468
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700469 paraAlign = mAlignment;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800470 for (int n = spans.length - 1; n >= 0; n--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 if (spans[n] instanceof AlignmentSpan) {
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700472 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 break;
474 }
475 }
Doug Felt0c702b82010-05-14 10:55:42 -0700476
Doug Feltc982f602010-05-25 11:51:40 -0700477 tabStopsIsInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800479
Doug Feltc982f602010-05-25 11:51:40 -0700480 // Draw all leading margin spans. Adjust left or right according
481 // to the paragraph direction of the line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 final int length = spans.length;
Anish Athalyeab08c6d2014-08-08 12:09:58 -0700483 boolean useFirstLineMargin = isFirstParaLine;
484 for (int n = 0; n < length; n++) {
485 if (spans[n] instanceof LeadingMarginSpan2) {
486 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
487 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
488 // if there is more than one LeadingMarginSpan2, use
489 // the count that is greatest
Raph Levien26d443a2015-03-30 14:18:32 -0700490 if (lineNum < startLine + count) {
Anish Athalyeab08c6d2014-08-08 12:09:58 -0700491 useFirstLineMargin = true;
492 break;
493 }
494 }
495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 for (int n = 0; n < length; n++) {
497 if (spans[n] instanceof LeadingMarginSpan) {
498 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 if (dir == DIR_RIGHT_TO_LEFT) {
Gilles Debunne6c488de2012-03-01 16:20:35 -0800500 margin.drawLeadingMargin(canvas, paint, right, dir, ltop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 lbaseline, lbottom, buf,
Doug Felt71b8dd72010-02-16 17:27:09 -0800502 start, end, isFirstParaLine, this);
Doug Feltc982f602010-05-25 11:51:40 -0700503 right -= margin.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 } else {
Gilles Debunne6c488de2012-03-01 16:20:35 -0800505 margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 lbaseline, lbottom, buf,
Doug Felt71b8dd72010-02-16 17:27:09 -0800507 start, end, isFirstParaLine, this);
Doug Feltc982f602010-05-25 11:51:40 -0700508 left += margin.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 }
510 }
511 }
512 }
513
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700514 boolean hasTab = getLineContainsTab(lineNum);
Doug Feltc982f602010-05-25 11:51:40 -0700515 // Can't tell if we have tabs for sure, currently
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700516 if (hasTab && !tabStopsIsInitialized) {
Doug Feltc982f602010-05-25 11:51:40 -0700517 if (tabStops == null) {
518 tabStops = new TabStops(TAB_INCREMENT, spans);
519 } else {
520 tabStops.reset(TAB_INCREMENT, spans);
521 }
522 tabStopsIsInitialized = true;
523 }
524
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700525 // Determine whether the line aligns to normal, opposite, or center.
526 Alignment align = paraAlign;
527 if (align == Alignment.ALIGN_LEFT) {
528 align = (dir == DIR_LEFT_TO_RIGHT) ?
529 Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
530 } else if (align == Alignment.ALIGN_RIGHT) {
531 align = (dir == DIR_LEFT_TO_RIGHT) ?
532 Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
533 }
534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 int x;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900536 final int indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 if (align == Alignment.ALIGN_NORMAL) {
538 if (dir == DIR_LEFT_TO_RIGHT) {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900539 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
540 x = left + indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 } else {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900542 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
543 x = right - indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 }
545 } else {
Raph Levien26d443a2015-03-30 14:18:32 -0700546 int max = (int)getLineExtent(lineNum, tabStops, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 if (align == Alignment.ALIGN_OPPOSITE) {
Doug Feltc982f602010-05-25 11:51:40 -0700548 if (dir == DIR_LEFT_TO_RIGHT) {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900549 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
550 x = right - max - indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 } else {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900552 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
553 x = left - max + indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 }
Doug Feltc982f602010-05-25 11:51:40 -0700555 } else { // Alignment.ALIGN_CENTER
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900556 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
Doug Feltc982f602010-05-25 11:51:40 -0700557 max = max & ~1;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900558 x = ((right + left - max) >> 1) + indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 }
560 }
561
Raph Levien26d443a2015-03-30 14:18:32 -0700562 Directions directions = getLineDirections(lineNum);
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900563 if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTab && !justify) {
Doug Felt71b8dd72010-02-16 17:27:09 -0800564 // XXX: assumes there's nothing additional to be done
Gilles Debunne6c488de2012-03-01 16:20:35 -0800565 canvas.drawText(buf, start, end, x, lbaseline, paint);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 } else {
Mihai Popace642dc2018-05-24 14:25:11 +0100567 tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops,
568 getEllipsisStart(lineNum),
569 getEllipsisStart(lineNum) + getEllipsisCount(lineNum));
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900570 if (justify) {
571 tl.justify(right - left - indentWidth);
572 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800573 tl.draw(canvas, x, ltop, lbaseline, lbottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 }
575 }
Doug Feltc982f602010-05-25 11:51:40 -0700576
Doug Felte8e45f22010-03-29 14:58:40 -0700577 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 }
579
580 /**
Gilles Debunne6c488de2012-03-01 16:20:35 -0800581 * @hide
582 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100583 @UnsupportedAppUsage
Gilles Debunne6c488de2012-03-01 16:20:35 -0800584 public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
585 int cursorOffsetVertical, int firstLine, int lastLine) {
586 // First, draw LineBackgroundSpans.
587 // LineBackgroundSpans know nothing about the alignment, margins, or
588 // direction of the layout or line. XXX: Should they?
589 // They are evaluated at each line.
590 if (mSpannedText) {
Gilles Debunneeca5b732012-04-25 18:48:42 -0700591 if (mLineBackgroundSpans == null) {
592 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700593 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800594
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700595 Spanned buffer = (Spanned) mText;
596 int textLength = buffer.length();
Gilles Debunneeca5b732012-04-25 18:48:42 -0700597 mLineBackgroundSpans.init(buffer, 0, textLength);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800598
Gilles Debunneeca5b732012-04-25 18:48:42 -0700599 if (mLineBackgroundSpans.numberOfSpans > 0) {
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700600 int previousLineBottom = getLineTop(firstLine);
601 int previousLineEnd = getLineStart(firstLine);
602 ParagraphStyle[] spans = NO_PARA_SPANS;
603 int spansLength = 0;
604 TextPaint paint = mPaint;
605 int spanEnd = 0;
606 final int width = mWidth;
607 for (int i = firstLine; i <= lastLine; i++) {
608 int start = previousLineEnd;
609 int end = getLineStart(i + 1);
610 previousLineEnd = end;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800611
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700612 int ltop = previousLineBottom;
613 int lbottom = getLineTop(i + 1);
614 previousLineBottom = lbottom;
615 int lbaseline = lbottom - getLineDescent(i);
616
617 if (start >= spanEnd) {
618 // These should be infrequent, so we'll use this so that
619 // we don't have to check as often.
Gilles Debunneeca5b732012-04-25 18:48:42 -0700620 spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700621 // All LineBackgroundSpans on a line contribute to its background.
622 spansLength = 0;
623 // Duplication of the logic of getParagraphSpans
624 if (start != end || start == 0) {
625 // Equivalent to a getSpans(start, end), but filling the 'spans' local
626 // array instead to reduce memory allocation
Gilles Debunneeca5b732012-04-25 18:48:42 -0700627 for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
628 // equal test is valid since both intervals are not empty by
629 // construction
630 if (mLineBackgroundSpans.spanStarts[j] >= end ||
631 mLineBackgroundSpans.spanEnds[j] <= start) continue;
Adam Lesinski776abc22014-03-07 11:30:59 -0500632 spans = GrowingArrayUtils.append(
633 spans, spansLength, mLineBackgroundSpans.spans[j]);
634 spansLength++;
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700635 }
636 }
637 }
638
639 for (int n = 0; n < spansLength; n++) {
640 LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
641 lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
642 ltop, lbaseline, lbottom,
643 buffer, start, end, i);
644 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800645 }
646 }
Gilles Debunneeca5b732012-04-25 18:48:42 -0700647 mLineBackgroundSpans.recycle();
Gilles Debunne6c488de2012-03-01 16:20:35 -0800648 }
649
650 // There can be a highlight even without spans if we are drawing
651 // a non-spanned transformation of a spanned editing buffer.
652 if (highlight != null) {
653 if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
654 canvas.drawPath(highlight, highlightPaint);
655 if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
656 }
657 }
658
659 /**
660 * @param canvas
661 * @return The range of lines that need to be drawn, possibly empty.
662 * @hide
663 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100664 @UnsupportedAppUsage
Gilles Debunne6c488de2012-03-01 16:20:35 -0800665 public long getLineRangeForDraw(Canvas canvas) {
666 int dtop, dbottom;
667
668 synchronized (sTempRect) {
669 if (!canvas.getClipBounds(sTempRect)) {
670 // Negative range end used as a special flag
671 return TextUtils.packRangeInLong(0, -1);
672 }
673
674 dtop = sTempRect.top;
675 dbottom = sTempRect.bottom;
676 }
677
678 final int top = Math.max(dtop, 0);
679 final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
680
Gilles Debunne2fba3382012-06-11 17:46:24 -0700681 if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800682 return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
683 }
684
685 /**
Doug Feltc982f602010-05-25 11:51:40 -0700686 * Return the start position of the line, given the left and right bounds
687 * of the margins.
Doug Felt0c702b82010-05-14 10:55:42 -0700688 *
Doug Feltc982f602010-05-25 11:51:40 -0700689 * @param line the line index
690 * @param left the left bounds (0, or leading margin if ltr para)
691 * @param right the right bounds (width, minus leading margin if rtl para)
692 * @return the start position of the line (to right of line if rtl para)
693 */
694 private int getLineStartPos(int line, int left, int right) {
695 // Adjust the point at which to start rendering depending on the
696 // alignment of the paragraph.
697 Alignment align = getParagraphAlignment(line);
698 int dir = getParagraphDirection(line);
699
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700700 if (align == Alignment.ALIGN_LEFT) {
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700701 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
702 } else if (align == Alignment.ALIGN_RIGHT) {
703 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
704 }
705
706 int x;
707 if (align == Alignment.ALIGN_NORMAL) {
Doug Feltc982f602010-05-25 11:51:40 -0700708 if (dir == DIR_LEFT_TO_RIGHT) {
Raph Levien2ea52902015-07-01 14:39:31 -0700709 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
Doug Feltc982f602010-05-25 11:51:40 -0700710 } else {
Raph Levien2ea52902015-07-01 14:39:31 -0700711 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
Doug Feltc982f602010-05-25 11:51:40 -0700712 }
713 } else {
714 TabStops tabStops = null;
715 if (mSpannedText && getLineContainsTab(line)) {
716 Spanned spanned = (Spanned) mText;
717 int start = getLineStart(line);
718 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
719 TabStopSpan.class);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800720 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
721 TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -0700722 if (tabSpans.length > 0) {
723 tabStops = new TabStops(TAB_INCREMENT, tabSpans);
724 }
725 }
726 int max = (int)getLineExtent(line, tabStops, false);
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700727 if (align == Alignment.ALIGN_OPPOSITE) {
Doug Feltc982f602010-05-25 11:51:40 -0700728 if (dir == DIR_LEFT_TO_RIGHT) {
Raph Levien2ea52902015-07-01 14:39:31 -0700729 x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
Doug Feltc982f602010-05-25 11:51:40 -0700730 } else {
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700731 // max is negative here
Raph Levien2ea52902015-07-01 14:39:31 -0700732 x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
Doug Feltc982f602010-05-25 11:51:40 -0700733 }
734 } else { // Alignment.ALIGN_CENTER
735 max = max & ~1;
Raph Levien2ea52902015-07-01 14:39:31 -0700736 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
Doug Feltc982f602010-05-25 11:51:40 -0700737 }
738 }
739 return x;
740 }
741
742 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 * Return the text that is displayed by this Layout.
744 */
745 public final CharSequence getText() {
746 return mText;
747 }
748
749 /**
750 * Return the base Paint properties for this layout.
751 * Do NOT change the paint, which may result in funny
752 * drawing for this layout.
753 */
754 public final TextPaint getPaint() {
755 return mPaint;
756 }
757
758 /**
759 * Return the width of this layout.
760 */
761 public final int getWidth() {
762 return mWidth;
763 }
764
765 /**
766 * Return the width to which this Layout is ellipsizing, or
767 * {@link #getWidth} if it is not doing anything special.
768 */
769 public int getEllipsizedWidth() {
770 return mWidth;
771 }
772
773 /**
774 * Increase the width of this layout to the specified width.
Doug Felt71b8dd72010-02-16 17:27:09 -0800775 * Be careful to use this only when you know it is appropriate&mdash;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 * it does not cause the text to reflow to use the full new width.
777 */
778 public final void increaseWidthTo(int wid) {
779 if (wid < mWidth) {
780 throw new RuntimeException("attempted to reduce Layout width");
781 }
782
783 mWidth = wid;
784 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 /**
787 * Return the total height of this layout.
788 */
789 public int getHeight() {
Doug Felt71b8dd72010-02-16 17:27:09 -0800790 return getLineTop(getLineCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792
793 /**
Siyamed Sinir0745c722016-05-31 20:39:33 -0700794 * Return the total height of this layout.
795 *
796 * @param cap if true and max lines is set, returns the height of the layout at the max lines.
797 *
798 * @hide
799 */
800 public int getHeight(boolean cap) {
801 return getHeight();
802 }
803
804 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 * Return the base alignment of this layout.
806 */
807 public final Alignment getAlignment() {
808 return mAlignment;
809 }
810
811 /**
812 * Return what the text height is multiplied by to get the line height.
813 */
814 public final float getSpacingMultiplier() {
815 return mSpacingMult;
816 }
817
818 /**
819 * Return the number of units of leading that are added to each line.
820 */
821 public final float getSpacingAdd() {
822 return mSpacingAdd;
823 }
824
825 /**
Doug Feltcb3791202011-07-07 11:57:48 -0700826 * Return the heuristic used to determine paragraph text direction.
827 * @hide
828 */
829 public final TextDirectionHeuristic getTextDirectionHeuristic() {
830 return mTextDir;
831 }
832
833 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 * Return the number of lines of text in this layout.
835 */
836 public abstract int getLineCount();
Doug Felt9f7a4442010-03-01 12:45:56 -0800837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 /**
839 * Return the baseline for the specified line (0&hellip;getLineCount() - 1)
840 * If bounds is not null, return the top, left, right, bottom extents
841 * of the specified line in it.
842 * @param line which line to examine (0..getLineCount() - 1)
843 * @param bounds Optional. If not null, it returns the extent of the line
844 * @return the Y-coordinate of the baseline
845 */
846 public int getLineBounds(int line, Rect bounds) {
847 if (bounds != null) {
848 bounds.left = 0; // ???
849 bounds.top = getLineTop(line);
850 bounds.right = mWidth; // ???
Doug Felt71b8dd72010-02-16 17:27:09 -0800851 bounds.bottom = getLineTop(line + 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 }
853 return getLineBaseline(line);
854 }
855
856 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800857 * Return the vertical position of the top of the specified line
858 * (0&hellip;getLineCount()).
859 * If the specified line is equal to the line count, returns the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 * bottom of the last line.
861 */
862 public abstract int getLineTop(int line);
863
864 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800865 * Return the descent of the specified line(0&hellip;getLineCount() - 1).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 */
867 public abstract int getLineDescent(int line);
868
869 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800870 * Return the text offset of the beginning of the specified line (
871 * 0&hellip;getLineCount()). If the specified line is equal to the line
872 * count, returns the length of the text.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 */
874 public abstract int getLineStart(int line);
875
876 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800877 * Returns the primary directionality of the paragraph containing the
878 * specified line, either 1 for left-to-right lines, or -1 for right-to-left
879 * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 */
881 public abstract int getParagraphDirection(int line);
882
883 /**
The Android Open Source Project10592532009-03-18 17:39:46 -0700884 * Returns whether the specified line contains one or more
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700885 * characters that need to be handled specially, like tabs.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 */
887 public abstract boolean getLineContainsTab(int line);
888
889 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800890 * Returns the directional run information for the specified line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 * The array alternates counts of characters in left-to-right
892 * and right-to-left segments of the line.
Doug Felt71b8dd72010-02-16 17:27:09 -0800893 *
894 * <p>NOTE: this is inadequate to support bidirectional text, and will change.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 */
896 public abstract Directions getLineDirections(int line);
897
898 /**
899 * Returns the (negative) number of extra pixels of ascent padding in the
900 * top line of the Layout.
901 */
902 public abstract int getTopPadding();
903
904 /**
905 * Returns the number of extra pixels of descent padding in the
906 * bottom line of the Layout.
907 */
908 public abstract int getBottomPadding();
909
Raph Levien26d443a2015-03-30 14:18:32 -0700910 /**
911 * Returns the hyphen edit for a line.
912 *
913 * @hide
914 */
915 public int getHyphen(int line) {
916 return 0;
917 }
918
Raph Levien2ea52902015-07-01 14:39:31 -0700919 /**
920 * Returns the left indent for a line.
921 *
922 * @hide
923 */
924 public int getIndentAdjust(int line, Alignment alignment) {
925 return 0;
926 }
Doug Felt4e0c5e52010-03-15 16:56:02 -0700927
928 /**
929 * Returns true if the character at offset and the preceding character
930 * are at different run levels (and thus there's a split caret).
931 * @param offset the offset
932 * @return true if at a level boundary
Gilles Debunnef75c97e2011-02-10 16:09:53 -0800933 * @hide
Doug Felt4e0c5e52010-03-15 16:56:02 -0700934 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100935 @UnsupportedAppUsage
Gilles Debunnef75c97e2011-02-10 16:09:53 -0800936 public boolean isLevelBoundary(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -0800937 int line = getLineForOffset(offset);
Doug Felt4e0c5e52010-03-15 16:56:02 -0700938 Directions dirs = getLineDirections(line);
939 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
940 return false;
941 }
942
943 int[] runs = dirs.mDirections;
Doug Felt9f7a4442010-03-01 12:45:56 -0800944 int lineStart = getLineStart(line);
Doug Felt4e0c5e52010-03-15 16:56:02 -0700945 int lineEnd = getLineEnd(line);
946 if (offset == lineStart || offset == lineEnd) {
947 int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
948 int runIndex = offset == lineStart ? 0 : runs.length - 2;
949 return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
950 }
951
952 offset -= lineStart;
Doug Felt9f7a4442010-03-01 12:45:56 -0800953 for (int i = 0; i < runs.length; i += 2) {
Doug Felt4e0c5e52010-03-15 16:56:02 -0700954 if (offset == runs[i]) {
955 return true;
Doug Felt9f7a4442010-03-01 12:45:56 -0800956 }
957 }
Doug Felt4e0c5e52010-03-15 16:56:02 -0700958 return false;
Doug Felt9f7a4442010-03-01 12:45:56 -0800959 }
960
Fabrice Di Meglio34d2eba2011-08-31 19:46:15 -0700961 /**
962 * Returns true if the character at offset is right to left (RTL).
963 * @param offset the offset
964 * @return true if the character is RTL, false if it is LTR
965 */
966 public boolean isRtlCharAt(int offset) {
967 int line = getLineForOffset(offset);
968 Directions dirs = getLineDirections(line);
969 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
970 return false;
971 }
972 if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
973 return true;
974 }
975 int[] runs = dirs.mDirections;
976 int lineStart = getLineStart(line);
977 for (int i = 0; i < runs.length; i += 2) {
Raph Levien87506202014-09-04 12:47:03 -0700978 int start = lineStart + runs[i];
979 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
980 if (offset >= start && offset < limit) {
Fabrice Di Meglio34d2eba2011-08-31 19:46:15 -0700981 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
982 return ((level & 1) != 0);
983 }
984 }
985 // Should happen only if the offset is "out of bounds"
986 return false;
987 }
988
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +0900989 /**
990 * Returns the range of the run that the character at offset belongs to.
991 * @param offset the offset
992 * @return The range of the run
993 * @hide
994 */
995 public long getRunRange(int offset) {
996 int line = getLineForOffset(offset);
997 Directions dirs = getLineDirections(line);
998 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
999 return TextUtils.packRangeInLong(0, getLineEnd(line));
1000 }
1001 int[] runs = dirs.mDirections;
1002 int lineStart = getLineStart(line);
1003 for (int i = 0; i < runs.length; i += 2) {
1004 int start = lineStart + runs[i];
1005 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1006 if (offset >= start && offset < limit) {
1007 return TextUtils.packRangeInLong(start, limit);
1008 }
1009 }
1010 // Should happen only if the offset is "out of bounds"
1011 return TextUtils.packRangeInLong(0, getLineEnd(line));
1012 }
1013
Mihai Popa7626c862018-05-09 17:31:48 +01001014 /**
1015 * Checks if the trailing BiDi level should be used for an offset
1016 *
1017 * This method is useful when the offset is at the BiDi level transition point and determine
1018 * which run need to be used. For example, let's think about following input: (L* denotes
1019 * Left-to-Right characters, R* denotes Right-to-Left characters.)
1020 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1021 * Input (Display Order): L1 L2 L3 R3 R2 R1 L4 L5 L6
1022 *
1023 * Then, think about selecting the range (3, 6). The offset=3 and offset=6 are ambiguous here
1024 * since they are at the BiDi transition point. In Android, the offset is considered to be
1025 * associated with the trailing run if the BiDi level of the trailing run is higher than of the
1026 * previous run. In this case, the BiDi level of the input text is as follows:
1027 *
1028 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1029 * BiDi Run: [ Run 0 ][ Run 1 ][ Run 2 ]
1030 * BiDi Level: 0 0 0 1 1 1 0 0 0
1031 *
1032 * Thus, offset = 3 is part of Run 1 and this method returns true for offset = 3, since the BiDi
1033 * level of Run 1 is higher than the level of Run 0. Similarly, the offset = 6 is a part of Run
1034 * 1 and this method returns false for the offset = 6 since the BiDi level of Run 1 is higher
1035 * than the level of Run 2.
1036 *
1037 * @returns true if offset is at the BiDi level transition point and trailing BiDi level is
1038 * higher than previous BiDi level. See above for the detail.
1039 * @hide
1040 */
Seigo Nonaka19e75a62018-05-16 16:57:33 -07001041 @VisibleForTesting
1042 public boolean primaryIsTrailingPrevious(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001043 int line = getLineForOffset(offset);
1044 int lineStart = getLineStart(line);
Doug Felt4e0c5e52010-03-15 16:56:02 -07001045 int lineEnd = getLineEnd(line);
Doug Felt9f7a4442010-03-01 12:45:56 -08001046 int[] runs = getLineDirections(line).mDirections;
1047
1048 int levelAt = -1;
1049 for (int i = 0; i < runs.length; i += 2) {
1050 int start = lineStart + runs[i];
1051 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1052 if (limit > lineEnd) {
1053 limit = lineEnd;
1054 }
1055 if (offset >= start && offset < limit) {
1056 if (offset > start) {
1057 // Previous character is at same level, so don't use trailing.
1058 return false;
1059 }
1060 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1061 break;
1062 }
1063 }
1064 if (levelAt == -1) {
1065 // Offset was limit of line.
1066 levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
1067 }
1068
1069 // At level boundary, check previous level.
1070 int levelBefore = -1;
1071 if (offset == lineStart) {
1072 levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
1073 } else {
1074 offset -= 1;
1075 for (int i = 0; i < runs.length; i += 2) {
1076 int start = lineStart + runs[i];
1077 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1078 if (limit > lineEnd) {
1079 limit = lineEnd;
1080 }
1081 if (offset >= start && offset < limit) {
1082 levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1083 break;
1084 }
1085 }
1086 }
1087
1088 return levelBefore < levelAt;
1089 }
1090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001092 * Computes in linear time the results of calling
1093 * #primaryIsTrailingPrevious for all offsets on a line.
1094 * @param line The line giving the offsets we compute the information for
1095 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1096 * @hide
1097 */
1098 @VisibleForTesting
1099 public boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
1100 int lineStart = getLineStart(line);
1101 int lineEnd = getLineEnd(line);
1102 int[] runs = getLineDirections(line).mDirections;
1103
1104 boolean[] trailing = new boolean[lineEnd - lineStart + 1];
1105
1106 byte[] level = new byte[lineEnd - lineStart + 1];
1107 for (int i = 0; i < runs.length; i += 2) {
1108 int start = lineStart + runs[i];
1109 int limit = start + (runs[i + 1] & RUN_LENGTH_MASK);
1110 if (limit > lineEnd) {
1111 limit = lineEnd;
1112 }
1113 level[limit - lineStart - 1] =
1114 (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1115 }
1116
1117 for (int i = 0; i < runs.length; i += 2) {
1118 int start = lineStart + runs[i];
1119 byte currentLevel = (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1120 trailing[start - lineStart] = currentLevel > (start == lineStart
1121 ? (getParagraphDirection(line) == 1 ? 0 : 1)
1122 : level[start - lineStart - 1]);
1123 }
1124
1125 return trailing;
1126 }
1127
1128 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 * Get the primary horizontal position for the specified text offset.
1130 * This is the location where a new character would be inserted in
1131 * the paragraph's primary direction.
1132 */
1133 public float getPrimaryHorizontal(int offset) {
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001134 return getPrimaryHorizontal(offset, false /* not clamped */);
Raph Levienafe8e9b2012-12-19 16:09:32 -08001135 }
1136
1137 /**
1138 * Get the primary horizontal position for the specified text offset, but
1139 * optionally clamp it so that it doesn't exceed the width of the layout.
1140 * @hide
1141 */
Mathew Inwoodefeab842018-08-14 15:21:30 +01001142 @UnsupportedAppUsage
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001143 public float getPrimaryHorizontal(int offset, boolean clamped) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001144 boolean trailing = primaryIsTrailingPrevious(offset);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001145 return getHorizontal(offset, trailing, clamped);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147
1148 /**
1149 * Get the secondary horizontal position for the specified text offset.
1150 * This is the location where a new character would be inserted in
1151 * the direction other than the paragraph's primary direction.
1152 */
1153 public float getSecondaryHorizontal(int offset) {
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001154 return getSecondaryHorizontal(offset, false /* not clamped */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
1156
Raph Levienafe8e9b2012-12-19 16:09:32 -08001157 /**
1158 * Get the secondary horizontal position for the specified text offset, but
1159 * optionally clamp it so that it doesn't exceed the width of the layout.
1160 * @hide
1161 */
Mathew Inwoodefeab842018-08-14 15:21:30 +01001162 @UnsupportedAppUsage
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001163 public float getSecondaryHorizontal(int offset, boolean clamped) {
Raph Levienafe8e9b2012-12-19 16:09:32 -08001164 boolean trailing = primaryIsTrailingPrevious(offset);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001165 return getHorizontal(offset, !trailing, clamped);
Raph Levienafe8e9b2012-12-19 16:09:32 -08001166 }
1167
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001168 private float getHorizontal(int offset, boolean primary) {
1169 return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09001170 }
1171
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001172 private float getHorizontal(int offset, boolean trailing, boolean clamped) {
1173 int line = getLineForOffset(offset);
1174
Raph Levienafe8e9b2012-12-19 16:09:32 -08001175 return getHorizontal(offset, trailing, line, clamped);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
1177
Raph Levienafe8e9b2012-12-19 16:09:32 -08001178 private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 int start = getLineStart(line);
Doug Felte8e45f22010-03-29 14:58:40 -07001180 int end = getLineEnd(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 int dir = getParagraphDirection(line);
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001182 boolean hasTab = getLineContainsTab(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 Directions directions = getLineDirections(line);
1184
Doug Feltc982f602010-05-25 11:51:40 -07001185 TabStops tabStops = null;
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001186 if (hasTab && mText instanceof Spanned) {
Doug Feltc982f602010-05-25 11:51:40 -07001187 // Just checking this line should be good enough, tabs should be
1188 // consistent across all lines in a paragraph.
Eric Fischer74d31ef2010-08-05 15:29:36 -07001189 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -07001190 if (tabs.length > 0) {
1191 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
1194
Doug Felte8e45f22010-03-29 14:58:40 -07001195 TextLine tl = TextLine.obtain();
Mihai Popace642dc2018-05-24 14:25:11 +01001196 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops,
1197 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Doug Felte8e45f22010-03-29 14:58:40 -07001198 float wid = tl.measure(offset - start, trailing, null);
1199 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200
Raph Levienafe8e9b2012-12-19 16:09:32 -08001201 if (clamped && wid > mWidth) {
1202 wid = mWidth;
1203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 int left = getParagraphLeft(line);
1205 int right = getParagraphRight(line);
1206
Doug Feltc982f602010-05-25 11:51:40 -07001207 return getLineStartPos(line, left, right) + wid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209
1210 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001211 * Computes in linear time the results of calling
1212 * #getHorizontal for all offsets on a line.
1213 * @param line The line giving the offsets we compute information for
1214 * @param clamped Whether to clamp the results to the width of the layout
1215 * @param primary Whether the results should be the primary or the secondary horizontal
1216 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1217 */
1218 private float[] getLineHorizontals(int line, boolean clamped, boolean primary) {
1219 int start = getLineStart(line);
1220 int end = getLineEnd(line);
1221 int dir = getParagraphDirection(line);
1222 boolean hasTab = getLineContainsTab(line);
1223 Directions directions = getLineDirections(line);
1224
1225 TabStops tabStops = null;
1226 if (hasTab && mText instanceof Spanned) {
1227 // Just checking this line should be good enough, tabs should be
1228 // consistent across all lines in a paragraph.
1229 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1230 if (tabs.length > 0) {
1231 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1232 }
1233 }
1234
1235 TextLine tl = TextLine.obtain();
Mihai Popace642dc2018-05-24 14:25:11 +01001236 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops,
1237 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Mihai Popa7626c862018-05-09 17:31:48 +01001238 boolean[] trailings = primaryIsTrailingPreviousAllLineOffsets(line);
1239 if (!primary) {
1240 for (int offset = 0; offset < trailings.length; ++offset) {
1241 trailings[offset] = !trailings[offset];
1242 }
1243 }
1244 float[] wid = tl.measureAllOffsets(trailings, null);
1245 TextLine.recycle(tl);
1246
1247 if (clamped) {
1248 for (int offset = 0; offset <= wid.length; ++offset) {
1249 if (wid[offset] > mWidth) {
1250 wid[offset] = mWidth;
1251 }
1252 }
1253 }
1254 int left = getParagraphLeft(line);
1255 int right = getParagraphRight(line);
1256
1257 int lineStartPos = getLineStartPos(line, left, right);
1258 float[] horizontal = new float[end - start + 1];
1259 for (int offset = 0; offset < horizontal.length; ++offset) {
1260 horizontal[offset] = lineStartPos + wid[offset];
1261 }
1262 return horizontal;
1263 }
1264
1265 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 * Get the leftmost position that should be exposed for horizontal
1267 * scrolling on the specified line.
1268 */
1269 public float getLineLeft(int line) {
1270 int dir = getParagraphDirection(line);
1271 Alignment align = getParagraphAlignment(line);
1272
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001273 if (align == Alignment.ALIGN_LEFT) {
1274 return 0;
1275 } else if (align == Alignment.ALIGN_NORMAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 if (dir == DIR_RIGHT_TO_LEFT)
1277 return getParagraphRight(line) - getLineMax(line);
1278 else
1279 return 0;
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001280 } else if (align == Alignment.ALIGN_RIGHT) {
1281 return mWidth - getLineMax(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 } else if (align == Alignment.ALIGN_OPPOSITE) {
1283 if (dir == DIR_RIGHT_TO_LEFT)
1284 return 0;
1285 else
1286 return mWidth - getLineMax(line);
1287 } else { /* align == Alignment.ALIGN_CENTER */
1288 int left = getParagraphLeft(line);
1289 int right = getParagraphRight(line);
1290 int max = ((int) getLineMax(line)) & ~1;
1291
1292 return left + ((right - left) - max) / 2;
1293 }
1294 }
1295
1296 /**
1297 * Get the rightmost position that should be exposed for horizontal
1298 * scrolling on the specified line.
1299 */
1300 public float getLineRight(int line) {
1301 int dir = getParagraphDirection(line);
1302 Alignment align = getParagraphAlignment(line);
1303
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001304 if (align == Alignment.ALIGN_LEFT) {
1305 return getParagraphLeft(line) + getLineMax(line);
1306 } else if (align == Alignment.ALIGN_NORMAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 if (dir == DIR_RIGHT_TO_LEFT)
1308 return mWidth;
1309 else
1310 return getParagraphLeft(line) + getLineMax(line);
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001311 } else if (align == Alignment.ALIGN_RIGHT) {
1312 return mWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 } else if (align == Alignment.ALIGN_OPPOSITE) {
1314 if (dir == DIR_RIGHT_TO_LEFT)
1315 return getLineMax(line);
1316 else
1317 return mWidth;
1318 } else { /* align == Alignment.ALIGN_CENTER */
1319 int left = getParagraphLeft(line);
1320 int right = getParagraphRight(line);
1321 int max = ((int) getLineMax(line)) & ~1;
1322
1323 return right - ((right - left) - max) / 2;
1324 }
1325 }
1326
1327 /**
Doug Felt0c702b82010-05-14 10:55:42 -07001328 * Gets the unsigned horizontal extent of the specified line, including
Doug Feltc982f602010-05-25 11:51:40 -07001329 * leading margin indent, but excluding trailing whitespace.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 */
1331 public float getLineMax(int line) {
Doug Feltc982f602010-05-25 11:51:40 -07001332 float margin = getParagraphLeadingMargin(line);
1333 float signedExtent = getLineExtent(line, false);
Anish Athalyec14b3ad2014-07-24 18:03:21 -07001334 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336
1337 /**
Doug Feltc982f602010-05-25 11:51:40 -07001338 * Gets the unsigned horizontal extent of the specified line, including
1339 * leading margin indent and trailing whitespace.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 */
1341 public float getLineWidth(int line) {
Doug Feltc982f602010-05-25 11:51:40 -07001342 float margin = getParagraphLeadingMargin(line);
1343 float signedExtent = getLineExtent(line, true);
Anish Athalyec14b3ad2014-07-24 18:03:21 -07001344 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
1346
Doug Feltc982f602010-05-25 11:51:40 -07001347 /**
1348 * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1349 * tab stops instead of using the ones passed in.
1350 * @param line the index of the line
1351 * @param full whether to include trailing whitespace
1352 * @return the extent of the line
1353 */
1354 private float getLineExtent(int line, boolean full) {
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001355 final int start = getLineStart(line);
1356 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
Doug Feltc982f602010-05-25 11:51:40 -07001357
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001358 final boolean hasTabs = getLineContainsTab(line);
Doug Feltc982f602010-05-25 11:51:40 -07001359 TabStops tabStops = null;
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001360 if (hasTabs && mText instanceof Spanned) {
Doug Feltc982f602010-05-25 11:51:40 -07001361 // Just checking this line should be good enough, tabs should be
1362 // consistent across all lines in a paragraph.
Eric Fischer74d31ef2010-08-05 15:29:36 -07001363 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -07001364 if (tabs.length > 0) {
1365 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1366 }
1367 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001368 final Directions directions = getLineDirections(line);
Fabrice Di Meglio8059e0902011-08-10 16:31:58 -07001369 // Returned directions can actually be null
1370 if (directions == null) {
1371 return 0f;
1372 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001373 final int dir = getParagraphDirection(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001375 final TextLine tl = TextLine.obtain();
1376 final TextPaint paint = mWorkPaint;
1377 paint.set(mPaint);
1378 paint.setHyphenEdit(getHyphen(line));
Mihai Popace642dc2018-05-24 14:25:11 +01001379 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops,
1380 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001381 if (isJustificationRequired(line)) {
1382 tl.justify(getJustifyWidth(line));
1383 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001384 final float width = tl.metrics(null);
Doug Feltc982f602010-05-25 11:51:40 -07001385 TextLine.recycle(tl);
1386 return width;
1387 }
1388
1389 /**
1390 * Returns the signed horizontal extent of the specified line, excluding
1391 * leading margin. If full is false, excludes trailing whitespace.
1392 * @param line the index of the line
1393 * @param tabStops the tab stops, can be null if we know they're not used.
1394 * @param full whether to include trailing whitespace
1395 * @return the extent of the text on this line
1396 */
1397 private float getLineExtent(int line, TabStops tabStops, boolean full) {
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001398 final int start = getLineStart(line);
1399 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1400 final boolean hasTabs = getLineContainsTab(line);
1401 final Directions directions = getLineDirections(line);
1402 final int dir = getParagraphDirection(line);
Doug Feltc982f602010-05-25 11:51:40 -07001403
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001404 final TextLine tl = TextLine.obtain();
1405 final TextPaint paint = mWorkPaint;
1406 paint.set(mPaint);
1407 paint.setHyphenEdit(getHyphen(line));
Mihai Popace642dc2018-05-24 14:25:11 +01001408 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops,
1409 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001410 if (isJustificationRequired(line)) {
1411 tl.justify(getJustifyWidth(line));
1412 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001413 final float width = tl.metrics(null);
Doug Felte8e45f22010-03-29 14:58:40 -07001414 TextLine.recycle(tl);
1415 return width;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417
1418 /**
1419 * Get the line number corresponding to the specified vertical position.
1420 * If you ask for a position above 0, you get 0; if you ask for a position
1421 * below the bottom of the text, you get the last line.
1422 */
1423 // FIXME: It may be faster to do a linear search for layouts without many lines.
1424 public int getLineForVertical(int vertical) {
1425 int high = getLineCount(), low = -1, guess;
1426
1427 while (high - low > 1) {
1428 guess = (high + low) / 2;
1429
1430 if (getLineTop(guess) > vertical)
1431 high = guess;
1432 else
1433 low = guess;
1434 }
1435
1436 if (low < 0)
1437 return 0;
1438 else
1439 return low;
1440 }
1441
1442 /**
1443 * Get the line number on which the specified text offset appears.
1444 * If you ask for a position before 0, you get 0; if you ask for a position
1445 * beyond the end of the text, you get the last line.
1446 */
1447 public int getLineForOffset(int offset) {
1448 int high = getLineCount(), low = -1, guess;
1449
1450 while (high - low > 1) {
1451 guess = (high + low) / 2;
1452
1453 if (getLineStart(guess) > offset)
1454 high = guess;
1455 else
1456 low = guess;
1457 }
1458
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001459 if (low < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 return 0;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001461 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 return low;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
1465
1466 /**
Doug Felt9f7a4442010-03-01 12:45:56 -08001467 * Get the character offset on the specified line whose position is
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 * closest to the specified horizontal position.
1469 */
1470 public int getOffsetForHorizontal(int line, float horiz) {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09001471 return getOffsetForHorizontal(line, horiz, true);
1472 }
1473
1474 /**
1475 * Get the character offset on the specified line whose position is
1476 * closest to the specified horizontal position.
1477 *
1478 * @param line the line used to find the closest offset
1479 * @param horiz the horizontal position used to find the closest offset
1480 * @param primary whether to use the primary position or secondary position to find the offset
1481 *
1482 * @hide
1483 */
1484 public int getOffsetForHorizontal(int line, float horiz, boolean primary) {
Raph Levienedb27f12015-06-01 14:34:47 -07001485 // TODO: use Paint.getOffsetForAdvance to avoid binary search
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001486 final int lineEndOffset = getLineEnd(line);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001487 final int lineStartOffset = getLineStart(line);
1488
1489 Directions dirs = getLineDirections(line);
1490
1491 TextLine tl = TextLine.obtain();
1492 // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1493 tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
Mihai Popace642dc2018-05-24 14:25:11 +01001494 false, null,
1495 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Mihai Popa7626c862018-05-09 17:31:48 +01001496 final HorizontalMeasurementProvider horizontal =
1497 new HorizontalMeasurementProvider(line, primary);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001498
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001499 final int max;
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001500 if (line == getLineCount() - 1) {
1501 max = lineEndOffset;
1502 } else {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001503 max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1504 !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001505 }
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001506 int best = lineStartOffset;
Mihai Popa7626c862018-05-09 17:31:48 +01001507 float bestdist = Math.abs(horizontal.get(lineStartOffset) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508
Doug Felt9f7a4442010-03-01 12:45:56 -08001509 for (int i = 0; i < dirs.mDirections.length; i += 2) {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001510 int here = lineStartOffset + dirs.mDirections[i];
Doug Felt9f7a4442010-03-01 12:45:56 -08001511 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001512 boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1513 int swap = isRtl ? -1 : 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514
1515 if (there > max)
1516 there = max;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 int high = there - 1 + 1, low = here + 1 - 1, guess;
1518
1519 while (high - low > 1) {
1520 guess = (high + low) / 2;
1521 int adguess = getOffsetAtStartOf(guess);
1522
Mihai Popa7626c862018-05-09 17:31:48 +01001523 if (horizontal.get(adguess) * swap >= horiz * swap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 high = guess;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001525 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 low = guess;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
1529
1530 if (low < here + 1)
1531 low = here + 1;
1532
1533 if (low < there) {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001534 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1535 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1536 if (low >= here && low < there) {
Mihai Popa7626c862018-05-09 17:31:48 +01001537 float dist = Math.abs(horizontal.get(low) - horiz);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001538 if (aft < there) {
Mihai Popa7626c862018-05-09 17:31:48 +01001539 float other = Math.abs(horizontal.get(aft) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001541 if (other < dist) {
1542 dist = other;
1543 low = aft;
1544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001547 if (dist < bestdist) {
1548 bestdist = dist;
1549 best = low;
1550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
1552 }
1553
Mihai Popa7626c862018-05-09 17:31:48 +01001554 float dist = Math.abs(horizontal.get(here) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555
1556 if (dist < bestdist) {
1557 bestdist = dist;
1558 best = here;
1559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561
Mihai Popa7626c862018-05-09 17:31:48 +01001562 float dist = Math.abs(horizontal.get(max) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563
Raph Levien373b7a82013-09-20 15:11:52 -07001564 if (dist <= bestdist) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 best = max;
1566 }
1567
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001568 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 return best;
1570 }
1571
1572 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001573 * Responds to #getHorizontal queries, by selecting the better strategy between:
1574 * - calling #getHorizontal explicitly for each query
1575 * - precomputing all #getHorizontal measurements, and responding to any query in constant time
1576 * The first strategy is used for LTR-only text, while the second is used for all other cases.
1577 * The class is currently only used in #getOffsetForHorizontal, so reuse with care in other
1578 * contexts.
1579 */
1580 private class HorizontalMeasurementProvider {
1581 private final int mLine;
1582 private final boolean mPrimary;
1583
1584 private float[] mHorizontals;
1585 private int mLineStartOffset;
1586
1587 HorizontalMeasurementProvider(final int line, final boolean primary) {
1588 mLine = line;
1589 mPrimary = primary;
1590 init();
1591 }
1592
1593 private void init() {
1594 final Directions dirs = getLineDirections(mLine);
1595 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1596 return;
1597 }
1598
1599 mHorizontals = getLineHorizontals(mLine, false, mPrimary);
1600 mLineStartOffset = getLineStart(mLine);
1601 }
1602
1603 float get(final int offset) {
Seigo Nonaka960647d2018-07-19 16:22:02 -07001604 if (mHorizontals == null || offset < 0 || offset >= mHorizontals.length) {
Mihai Popa7626c862018-05-09 17:31:48 +01001605 return getHorizontal(offset, mPrimary);
1606 } else {
1607 return mHorizontals[offset - mLineStartOffset];
1608 }
1609 }
1610 }
1611
1612 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 * Return the text offset after the last character on the specified line.
1614 */
1615 public final int getLineEnd(int line) {
1616 return getLineStart(line + 1);
1617 }
1618
Doug Felt9f7a4442010-03-01 12:45:56 -08001619 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 * Return the text offset after the last visible character (so whitespace
1621 * is not counted) on the specified line.
1622 */
1623 public int getLineVisibleEnd(int line) {
1624 return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1625 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 private int getLineVisibleEnd(int line, int start, int end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 CharSequence text = mText;
1629 char ch;
1630 if (line == getLineCount() - 1) {
1631 return end;
1632 }
1633
1634 for (; end > start; end--) {
1635 ch = text.charAt(end - 1);
1636
1637 if (ch == '\n') {
1638 return end - 1;
1639 }
1640
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001641 if (!TextLine.isLineEndSpace(ch)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 break;
1643 }
1644
1645 }
1646
1647 return end;
1648 }
1649
1650 /**
1651 * Return the vertical position of the bottom of the specified line.
1652 */
1653 public final int getLineBottom(int line) {
1654 return getLineTop(line + 1);
1655 }
1656
1657 /**
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001658 * Return the vertical position of the bottom of the specified line without the line spacing
1659 * added.
1660 *
1661 * @hide
1662 */
1663 public final int getLineBottomWithoutSpacing(int line) {
1664 return getLineTop(line + 1) - getLineExtra(line);
1665 }
1666
1667 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 * Return the vertical position of the baseline of the specified line.
1669 */
1670 public final int getLineBaseline(int line) {
1671 // getLineTop(line+1) == getLineTop(line)
1672 return getLineTop(line+1) - getLineDescent(line);
1673 }
1674
1675 /**
1676 * Get the ascent of the text on the specified line.
1677 * The return value is negative to match the Paint.ascent() convention.
1678 */
1679 public final int getLineAscent(int line) {
1680 // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1681 return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1682 }
1683
Siyamed Sinir0fa89d62017-07-24 20:46:41 -07001684 /**
1685 * Return the extra space added as a result of line spacing attributes
1686 * {@link #getSpacingAdd()} and {@link #getSpacingMultiplier()}. Default value is {@code zero}.
1687 *
1688 * @param line the index of the line, the value should be equal or greater than {@code zero}
1689 * @hide
1690 */
1691 public int getLineExtra(@IntRange(from = 0) int line) {
1692 return 0;
1693 }
1694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 public int getOffsetToLeftOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001696 return getOffsetToLeftRightOf(offset, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 public int getOffsetToRightOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001700 return getOffsetToLeftRightOf(offset, false);
1701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702
Doug Felt9f7a4442010-03-01 12:45:56 -08001703 private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1704 int line = getLineForOffset(caret);
1705 int lineStart = getLineStart(line);
1706 int lineEnd = getLineEnd(line);
Doug Felte8e45f22010-03-29 14:58:40 -07001707 int lineDir = getParagraphDirection(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001709 boolean lineChanged = false;
Doug Felte8e45f22010-03-29 14:58:40 -07001710 boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001711 // if walking off line, look at the line we're headed to
1712 if (advance) {
1713 if (caret == lineEnd) {
Doug Felte8e45f22010-03-29 14:58:40 -07001714 if (line < getLineCount() - 1) {
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001715 lineChanged = true;
Doug Felte8e45f22010-03-29 14:58:40 -07001716 ++line;
1717 } else {
1718 return caret; // at very end, don't move
1719 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001720 }
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001721 } else {
1722 if (caret == lineStart) {
1723 if (line > 0) {
1724 lineChanged = true;
1725 --line;
1726 } else {
1727 return caret; // at very start, don't move
1728 }
1729 }
1730 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001731
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001732 if (lineChanged) {
Doug Felte8e45f22010-03-29 14:58:40 -07001733 lineStart = getLineStart(line);
1734 lineEnd = getLineEnd(line);
1735 int newDir = getParagraphDirection(line);
1736 if (newDir != lineDir) {
1737 // unusual case. we want to walk onto the line, but it runs
1738 // in a different direction than this one, so we fake movement
1739 // in the opposite direction.
1740 toLeft = !toLeft;
1741 lineDir = newDir;
1742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001744
Doug Felte8e45f22010-03-29 14:58:40 -07001745 Directions directions = getLineDirections(line);
Doug Felt9f7a4442010-03-01 12:45:56 -08001746
Doug Felte8e45f22010-03-29 14:58:40 -07001747 TextLine tl = TextLine.obtain();
1748 // XXX: we don't care about tabs
Mihai Popace642dc2018-05-24 14:25:11 +01001749 tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null,
1750 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Doug Felte8e45f22010-03-29 14:58:40 -07001751 caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
Siyamed Sinira273a702017-10-05 11:22:12 -07001752 TextLine.recycle(tl);
Doug Felte8e45f22010-03-29 14:58:40 -07001753 return caret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
1755
1756 private int getOffsetAtStartOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001757 // XXX this probably should skip local reorderings and
1758 // zero-width characters, look at callers
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 if (offset == 0)
1760 return 0;
1761
1762 CharSequence text = mText;
1763 char c = text.charAt(offset);
1764
1765 if (c >= '\uDC00' && c <= '\uDFFF') {
1766 char c1 = text.charAt(offset - 1);
1767
1768 if (c1 >= '\uD800' && c1 <= '\uDBFF')
1769 offset -= 1;
1770 }
1771
1772 if (mSpannedText) {
1773 ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1774 ReplacementSpan.class);
1775
1776 for (int i = 0; i < spans.length; i++) {
1777 int start = ((Spanned) text).getSpanStart(spans[i]);
1778 int end = ((Spanned) text).getSpanEnd(spans[i]);
1779
1780 if (start < offset && end > offset)
1781 offset = start;
1782 }
1783 }
1784
1785 return offset;
1786 }
1787
1788 /**
Raph Levienafe8e9b2012-12-19 16:09:32 -08001789 * Determine whether we should clamp cursor position. Currently it's
1790 * only robust for left-aligned displays.
1791 * @hide
1792 */
Mathew Inwoodefeab842018-08-14 15:21:30 +01001793 @UnsupportedAppUsage
Raph Levienafe8e9b2012-12-19 16:09:32 -08001794 public boolean shouldClampCursor(int line) {
1795 // Only clamp cursor position in left-aligned displays.
1796 switch (getParagraphAlignment(line)) {
1797 case ALIGN_LEFT:
1798 return true;
1799 case ALIGN_NORMAL:
1800 return getParagraphDirection(line) > 0;
1801 default:
1802 return false;
1803 }
1804
1805 }
1806 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 * Fills in the specified Path with a representation of a cursor
1808 * at the specified offset. This will often be a vertical line
Doug Felt4e0c5e52010-03-15 16:56:02 -07001809 * but can be multiple discontinuous lines in text with multiple
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 * directionalities.
1811 */
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001812 public void getCursorPath(final int point, final Path dest, final CharSequence editingBuffer) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 dest.reset();
1814
1815 int line = getLineForOffset(point);
1816 int top = getLineTop(line);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001817 int bottom = getLineBottomWithoutSpacing(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818
Raph Levienafe8e9b2012-12-19 16:09:32 -08001819 boolean clamped = shouldClampCursor(line);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001820 float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1821 float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822
Jeff Brown497a92c2010-09-12 17:55:08 -07001823 int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1824 TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1825 int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 int dist = 0;
1827
1828 if (caps != 0 || fn != 0) {
1829 dist = (bottom - top) >> 2;
1830
1831 if (fn != 0)
1832 top += dist;
1833 if (caps != 0)
1834 bottom -= dist;
1835 }
1836
1837 if (h1 < 0.5f)
1838 h1 = 0.5f;
1839 if (h2 < 0.5f)
1840 h2 = 0.5f;
1841
Jozef BABJAK2fb503f2011-03-17 09:54:51 +01001842 if (Float.compare(h1, h2) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 dest.moveTo(h1, top);
1844 dest.lineTo(h1, bottom);
1845 } else {
1846 dest.moveTo(h1, top);
1847 dest.lineTo(h1, (top + bottom) >> 1);
1848
1849 dest.moveTo(h2, (top + bottom) >> 1);
1850 dest.lineTo(h2, bottom);
1851 }
1852
1853 if (caps == 2) {
1854 dest.moveTo(h2, bottom);
1855 dest.lineTo(h2 - dist, bottom + dist);
1856 dest.lineTo(h2, bottom);
1857 dest.lineTo(h2 + dist, bottom + dist);
1858 } else if (caps == 1) {
1859 dest.moveTo(h2, bottom);
1860 dest.lineTo(h2 - dist, bottom + dist);
1861
1862 dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1863 dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1864
1865 dest.moveTo(h2 + dist, bottom + dist);
1866 dest.lineTo(h2, bottom);
1867 }
1868
1869 if (fn == 2) {
1870 dest.moveTo(h1, top);
1871 dest.lineTo(h1 - dist, top - dist);
1872 dest.lineTo(h1, top);
1873 dest.lineTo(h1 + dist, top - dist);
1874 } else if (fn == 1) {
1875 dest.moveTo(h1, top);
1876 dest.lineTo(h1 - dist, top - dist);
1877
1878 dest.moveTo(h1 - dist, top - dist + 0.5f);
1879 dest.lineTo(h1 + dist, top - dist + 0.5f);
1880
1881 dest.moveTo(h1 + dist, top - dist);
1882 dest.lineTo(h1, top);
1883 }
1884 }
1885
1886 private void addSelection(int line, int start, int end,
Petar Šeginab92c5392017-09-06 15:25:05 +01001887 int top, int bottom, SelectionRectangleConsumer consumer) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 int linestart = getLineStart(line);
1889 int lineend = getLineEnd(line);
1890 Directions dirs = getLineDirections(line);
1891
Petar Šeginafb748b32017-08-07 12:37:52 +01001892 if (lineend > linestart && mText.charAt(lineend - 1) == '\n') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 lineend--;
Petar Šeginafb748b32017-08-07 12:37:52 +01001894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895
Doug Felt9f7a4442010-03-01 12:45:56 -08001896 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1897 int here = linestart + dirs.mDirections[i];
Petar Šeginafb748b32017-08-07 12:37:52 +01001898 int there = here + (dirs.mDirections[i + 1] & RUN_LENGTH_MASK);
Doug Felt9f7a4442010-03-01 12:45:56 -08001899
Petar Šeginafb748b32017-08-07 12:37:52 +01001900 if (there > lineend) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 there = lineend;
Petar Šeginafb748b32017-08-07 12:37:52 +01001902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903
1904 if (start <= there && end >= here) {
1905 int st = Math.max(start, here);
1906 int en = Math.min(end, there);
1907
1908 if (st != en) {
Raph Levienafe8e9b2012-12-19 16:09:32 -08001909 float h1 = getHorizontal(st, false, line, false /* not clamped */);
1910 float h2 = getHorizontal(en, true, line, false /* not clamped */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911
Fabrice Di Meglio37166012011-08-31 13:56:37 -07001912 float left = Math.min(h1, h2);
1913 float right = Math.max(h1, h2);
1914
Petar Šegina8f1f74e2017-09-07 14:26:28 +01001915 final @TextSelectionLayout int layout =
1916 ((dirs.mDirections[i + 1] & RUN_RTL_FLAG) != 0)
1917 ? TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT
1918 : TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT;
1919
1920 consumer.accept(left, top, right, bottom, layout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 }
1922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 }
1924 }
1925
1926 /**
1927 * Fills in the specified Path with a representation of a highlight
1928 * between the specified offsets. This will often be a rectangle
1929 * or a potentially discontinuous set of rectangles. If the start
1930 * and end are the same, the returned path is empty.
1931 */
1932 public void getSelectionPath(int start, int end, Path dest) {
1933 dest.reset();
Petar Šeginab92c5392017-09-06 15:25:05 +01001934 getSelection(start, end, (left, top, right, bottom, textSelectionLayout) ->
Petar Šeginafb748b32017-08-07 12:37:52 +01001935 dest.addRect(left, top, right, bottom, Path.Direction.CW));
1936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937
Petar Šeginafb748b32017-08-07 12:37:52 +01001938 /**
1939 * Calculates the rectangles which should be highlighted to indicate a selection between start
Petar Šeginab92c5392017-09-06 15:25:05 +01001940 * and end and feeds them into the given {@link SelectionRectangleConsumer}.
Petar Šeginafb748b32017-08-07 12:37:52 +01001941 *
1942 * @param start the starting index of the selection
1943 * @param end the ending index of the selection
Petar Šeginab92c5392017-09-06 15:25:05 +01001944 * @param consumer the {@link SelectionRectangleConsumer} which will receive the generated
1945 * rectangles. It will be called every time a rectangle is generated.
Petar Šeginafb748b32017-08-07 12:37:52 +01001946 * @hide
1947 * @see #getSelectionPath(int, int, Path)
1948 */
Petar Šeginab92c5392017-09-06 15:25:05 +01001949 public final void getSelection(int start, int end, final SelectionRectangleConsumer consumer) {
Petar Šeginafb748b32017-08-07 12:37:52 +01001950 if (start == end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 return;
Petar Šeginafb748b32017-08-07 12:37:52 +01001952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953
1954 if (end < start) {
1955 int temp = end;
1956 end = start;
1957 start = temp;
1958 }
1959
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001960 final int startline = getLineForOffset(start);
1961 final int endline = getLineForOffset(end);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 int top = getLineTop(startline);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001964 int bottom = getLineBottomWithoutSpacing(endline);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965
1966 if (startline == endline) {
Petar Šeginafb748b32017-08-07 12:37:52 +01001967 addSelection(startline, start, end, top, bottom, consumer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 } else {
1969 final float width = mWidth;
1970
1971 addSelection(startline, start, getLineEnd(startline),
Petar Šeginafb748b32017-08-07 12:37:52 +01001972 top, getLineBottom(startline), consumer);
Doug Felt9f7a4442010-03-01 12:45:56 -08001973
Petar Šeginafb748b32017-08-07 12:37:52 +01001974 if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT) {
Petar Šeginab92c5392017-09-06 15:25:05 +01001975 consumer.accept(getLineLeft(startline), top, 0, getLineBottom(startline),
Petar Šegina3a92fb62017-09-07 21:03:24 +01001976 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001977 } else {
Petar Šeginab92c5392017-09-06 15:25:05 +01001978 consumer.accept(getLineRight(startline), top, width, getLineBottom(startline),
Petar Šegina3a92fb62017-09-07 21:03:24 +01001979 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981
1982 for (int i = startline + 1; i < endline; i++) {
1983 top = getLineTop(i);
1984 bottom = getLineBottom(i);
Petar Šeginab92c5392017-09-06 15:25:05 +01001985 if (getParagraphDirection(i) == DIR_RIGHT_TO_LEFT) {
Petar Šegina3a92fb62017-09-07 21:03:24 +01001986 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginab92c5392017-09-06 15:25:05 +01001987 } else {
Petar Šegina3a92fb62017-09-07 21:03:24 +01001988 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginab92c5392017-09-06 15:25:05 +01001989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
1991
1992 top = getLineTop(endline);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001993 bottom = getLineBottomWithoutSpacing(endline);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994
Petar Šeginafb748b32017-08-07 12:37:52 +01001995 addSelection(endline, getLineStart(endline), end, top, bottom, consumer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996
Petar Šeginafb748b32017-08-07 12:37:52 +01001997 if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT) {
Petar Šeginab92c5392017-09-06 15:25:05 +01001998 consumer.accept(width, top, getLineRight(endline), bottom,
Petar Šegina3a92fb62017-09-07 21:03:24 +01001999 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginafb748b32017-08-07 12:37:52 +01002000 } else {
Petar Šeginab92c5392017-09-06 15:25:05 +01002001 consumer.accept(0, top, getLineLeft(endline), bottom,
Petar Šegina3a92fb62017-09-07 21:03:24 +01002002 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginafb748b32017-08-07 12:37:52 +01002003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
2005 }
2006
2007 /**
2008 * Get the alignment of the specified paragraph, taking into account
2009 * markup attached to it.
2010 */
2011 public final Alignment getParagraphAlignment(int line) {
2012 Alignment align = mAlignment;
2013
2014 if (mSpannedText) {
2015 Spanned sp = (Spanned) mText;
Eric Fischer74d31ef2010-08-05 15:29:36 -07002016 AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 getLineEnd(line),
2018 AlignmentSpan.class);
2019
2020 int spanLength = spans.length;
2021 if (spanLength > 0) {
2022 align = spans[spanLength-1].getAlignment();
2023 }
2024 }
2025
2026 return align;
2027 }
2028
2029 /**
2030 * Get the left edge of the specified paragraph, inset by left margins.
2031 */
2032 public final int getParagraphLeft(int line) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 int left = 0;
Doug Feltc982f602010-05-25 11:51:40 -07002034 int dir = getParagraphDirection(line);
2035 if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
2036 return left; // leading margin has no impact, or no styles
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 }
Doug Feltc982f602010-05-25 11:51:40 -07002038 return getParagraphLeadingMargin(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 }
2040
2041 /**
2042 * Get the right edge of the specified paragraph, inset by right margins.
2043 */
2044 public final int getParagraphRight(int line) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 int right = mWidth;
Doug Feltc982f602010-05-25 11:51:40 -07002046 int dir = getParagraphDirection(line);
2047 if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
2048 return right; // leading margin has no impact, or no styles
2049 }
2050 return right - getParagraphLeadingMargin(line);
2051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052
Doug Feltc982f602010-05-25 11:51:40 -07002053 /**
2054 * Returns the effective leading margin (unsigned) for this line,
2055 * taking into account LeadingMarginSpan and LeadingMarginSpan2.
2056 * @param line the line index
2057 * @return the leading margin of this line
2058 */
2059 private int getParagraphLeadingMargin(int line) {
2060 if (!mSpannedText) {
2061 return 0;
2062 }
2063 Spanned spanned = (Spanned) mText;
Doug Felt0c702b82010-05-14 10:55:42 -07002064
Doug Feltc982f602010-05-25 11:51:40 -07002065 int lineStart = getLineStart(line);
2066 int lineEnd = getLineEnd(line);
Doug Felt0c702b82010-05-14 10:55:42 -07002067 int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002068 LeadingMarginSpan.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002069 LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002070 LeadingMarginSpan.class);
2071 if (spans.length == 0) {
2072 return 0; // no leading margin span;
2073 }
Doug Felt0c702b82010-05-14 10:55:42 -07002074
Doug Feltc982f602010-05-25 11:51:40 -07002075 int margin = 0;
Doug Felt0c702b82010-05-14 10:55:42 -07002076
Siyamed Sinira273a702017-10-05 11:22:12 -07002077 boolean useFirstLineMargin = lineStart == 0 || spanned.charAt(lineStart - 1) == '\n';
Anish Athalyeab08c6d2014-08-08 12:09:58 -07002078 for (int i = 0; i < spans.length; i++) {
2079 if (spans[i] instanceof LeadingMarginSpan2) {
2080 int spStart = spanned.getSpanStart(spans[i]);
2081 int spanLine = getLineForOffset(spStart);
2082 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
2083 // if there is more than one LeadingMarginSpan2, use the count that is greatest
2084 useFirstLineMargin |= line < spanLine + count;
2085 }
2086 }
Doug Feltc982f602010-05-25 11:51:40 -07002087 for (int i = 0; i < spans.length; i++) {
2088 LeadingMarginSpan span = spans[i];
Doug Feltc982f602010-05-25 11:51:40 -07002089 margin += span.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
2091
Doug Feltc982f602010-05-25 11:51:40 -07002092 return margin;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 }
2094
Roozbeh Pournader9a9179d2017-08-29 14:14:28 -07002095 private static float measurePara(TextPaint paint, CharSequence text, int start, int end,
Siyamed Sinir79bf9d12016-05-18 19:57:52 -07002096 TextDirectionHeuristic textDir) {
Seigo Nonaka9d3bd082018-01-11 10:02:12 -08002097 MeasuredParagraph mt = null;
Doug Felte8e45f22010-03-29 14:58:40 -07002098 TextLine tl = TextLine.obtain();
2099 try {
Seigo Nonaka9d3bd082018-01-11 10:02:12 -08002100 mt = MeasuredParagraph.buildForBidi(text, start, end, textDir, mt);
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002101 final char[] chars = mt.getChars();
2102 final int len = chars.length;
2103 final Directions directions = mt.getDirections(0, len);
2104 final int dir = mt.getParagraphDir();
Doug Feltc982f602010-05-25 11:51:40 -07002105 boolean hasTabs = false;
2106 TabStops tabStops = null;
Anish Athalyec14b3ad2014-07-24 18:03:21 -07002107 // leading margins should be taken into account when measuring a paragraph
2108 int margin = 0;
2109 if (text instanceof Spanned) {
2110 Spanned spanned = (Spanned) text;
2111 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
2112 LeadingMarginSpan.class);
2113 for (LeadingMarginSpan lms : spans) {
2114 margin += lms.getLeadingMargin(true);
2115 }
2116 }
Doug Feltc982f602010-05-25 11:51:40 -07002117 for (int i = 0; i < len; ++i) {
2118 if (chars[i] == '\t') {
2119 hasTabs = true;
2120 if (text instanceof Spanned) {
2121 Spanned spanned = (Spanned) text;
Doug Felt0c702b82010-05-14 10:55:42 -07002122 int spanEnd = spanned.nextSpanTransition(start, end,
Doug Feltc982f602010-05-25 11:51:40 -07002123 TabStopSpan.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002124 TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002125 TabStopSpan.class);
2126 if (spans.length > 0) {
2127 tabStops = new TabStops(TAB_INCREMENT, spans);
2128 }
2129 }
2130 break;
2131 }
2132 }
Mihai Popace642dc2018-05-24 14:25:11 +01002133 tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops,
2134 0 /* ellipsisStart */, 0 /* ellipsisEnd */);
Siyamed Sinir79bf9d12016-05-18 19:57:52 -07002135 return margin + Math.abs(tl.metrics(null));
Doug Felte8e45f22010-03-29 14:58:40 -07002136 } finally {
2137 TextLine.recycle(tl);
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002138 if (mt != null) {
2139 mt.recycle();
2140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143
Doug Felt71b8dd72010-02-16 17:27:09 -08002144 /**
Doug Feltc982f602010-05-25 11:51:40 -07002145 * @hide
2146 */
Seigo Nonaka32afe262018-05-16 22:05:27 -07002147 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2148 public static class TabStops {
Doug Feltc982f602010-05-25 11:51:40 -07002149 private int[] mStops;
2150 private int mNumStops;
2151 private int mIncrement;
Doug Felt0c702b82010-05-14 10:55:42 -07002152
Seigo Nonaka32afe262018-05-16 22:05:27 -07002153 public TabStops(int increment, Object[] spans) {
Doug Feltc982f602010-05-25 11:51:40 -07002154 reset(increment, spans);
2155 }
Doug Felt0c702b82010-05-14 10:55:42 -07002156
Doug Feltc982f602010-05-25 11:51:40 -07002157 void reset(int increment, Object[] spans) {
2158 this.mIncrement = increment;
2159
2160 int ns = 0;
2161 if (spans != null) {
2162 int[] stops = this.mStops;
2163 for (Object o : spans) {
2164 if (o instanceof TabStopSpan) {
2165 if (stops == null) {
2166 stops = new int[10];
2167 } else if (ns == stops.length) {
2168 int[] nstops = new int[ns * 2];
2169 for (int i = 0; i < ns; ++i) {
2170 nstops[i] = stops[i];
2171 }
2172 stops = nstops;
2173 }
2174 stops[ns++] = ((TabStopSpan) o).getTabStop();
2175 }
2176 }
2177 if (ns > 1) {
2178 Arrays.sort(stops, 0, ns);
2179 }
2180 if (stops != this.mStops) {
2181 this.mStops = stops;
2182 }
2183 }
2184 this.mNumStops = ns;
2185 }
Doug Felt0c702b82010-05-14 10:55:42 -07002186
Doug Feltc982f602010-05-25 11:51:40 -07002187 float nextTab(float h) {
2188 int ns = this.mNumStops;
2189 if (ns > 0) {
2190 int[] stops = this.mStops;
2191 for (int i = 0; i < ns; ++i) {
2192 int stop = stops[i];
2193 if (stop > h) {
2194 return stop;
2195 }
2196 }
2197 }
2198 return nextDefaultStop(h, mIncrement);
2199 }
2200
2201 public static float nextDefaultStop(float h, int inc) {
2202 return ((int) ((h + inc) / inc)) * inc;
2203 }
2204 }
Doug Felt0c702b82010-05-14 10:55:42 -07002205
Doug Feltc982f602010-05-25 11:51:40 -07002206 /**
Doug Felt71b8dd72010-02-16 17:27:09 -08002207 * Returns the position of the next tab stop after h on the line.
2208 *
2209 * @param text the text
2210 * @param start start of the line
2211 * @param end limit of the line
2212 * @param h the current horizontal offset
2213 * @param tabs the tabs, can be null. If it is null, any tabs in effect
2214 * on the line will be used. If there are no tabs, a default offset
2215 * will be used to compute the tab stop.
2216 * @return the offset of the next tab stop.
2217 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 /* package */ static float nextTab(CharSequence text, int start, int end,
2219 float h, Object[] tabs) {
2220 float nh = Float.MAX_VALUE;
2221 boolean alltabs = false;
2222
2223 if (text instanceof Spanned) {
2224 if (tabs == null) {
Eric Fischer74d31ef2010-08-05 15:29:36 -07002225 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 alltabs = true;
2227 }
2228
2229 for (int i = 0; i < tabs.length; i++) {
2230 if (!alltabs) {
2231 if (!(tabs[i] instanceof TabStopSpan))
2232 continue;
2233 }
2234
2235 int where = ((TabStopSpan) tabs[i]).getTabStop();
2236
2237 if (where < nh && where > h)
2238 nh = where;
2239 }
2240
2241 if (nh != Float.MAX_VALUE)
2242 return nh;
2243 }
2244
2245 return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
2246 }
2247
2248 protected final boolean isSpanned() {
2249 return mSpannedText;
2250 }
2251
Eric Fischer74d31ef2010-08-05 15:29:36 -07002252 /**
2253 * Returns the same as <code>text.getSpans()</code>, except where
2254 * <code>start</code> and <code>end</code> are the same and are not
2255 * at the very beginning of the text, in which case an empty array
2256 * is returned instead.
2257 * <p>
2258 * This is needed because of the special case that <code>getSpans()</code>
2259 * on an empty range returns the spans adjacent to that range, which is
2260 * primarily for the sake of <code>TextWatchers</code> so they will get
2261 * notifications when text goes from empty to non-empty. But it also
2262 * has the unfortunate side effect that if the text ends with an empty
2263 * paragraph, that paragraph accidentally picks up the styles of the
2264 * preceding paragraph (even though those styles will not be picked up
2265 * by new text that is inserted into the empty paragraph).
2266 * <p>
2267 * The reason it just checks whether <code>start</code> and <code>end</code>
2268 * is the same is that the only time a line can contain 0 characters
2269 * is if it is the final paragraph of the Layout; otherwise any line will
2270 * contain at least one printing or newline character. The reason for the
2271 * additional check if <code>start</code> is greater than 0 is that
2272 * if the empty paragraph is the entire content of the buffer, paragraph
2273 * styles that are already applied to the buffer will apply to text that
2274 * is inserted into it.
2275 */
Gilles Debunneeca5b732012-04-25 18:48:42 -07002276 /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
Eric Fischer74d31ef2010-08-05 15:29:36 -07002277 if (start == end && start > 0) {
Gilles Debunne6c488de2012-03-01 16:20:35 -08002278 return ArrayUtils.emptyArray(type);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002279 }
2280
Siyamed Sinirfa05ba02016-01-12 10:54:43 -08002281 if(text instanceof SpannableStringBuilder) {
2282 return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2283 } else {
2284 return text.getSpans(start, end, type);
2285 }
Eric Fischer74d31ef2010-08-05 15:29:36 -07002286 }
2287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 private void ellipsize(int start, int end, int line,
Fabrice Di Meglio8d44fff2012-06-13 15:45:38 -07002289 char[] dest, int destoff, TextUtils.TruncateAt method) {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002290 final int ellipsisCount = getEllipsisCount(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 if (ellipsisCount == 0) {
2292 return;
2293 }
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002294 final int ellipsisStart = getEllipsisStart(line);
2295 final int lineStart = getLineStart(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002297 final String ellipsisString = TextUtils.getEllipsisString(method);
2298 final int ellipsisStringLen = ellipsisString.length();
Roozbeh Pournader1051bbe2017-07-25 13:52:57 -07002299 // Use the ellipsis string only if there are that at least as many characters to replace.
2300 final boolean useEllipsisString = ellipsisCount >= ellipsisStringLen;
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002301 for (int i = 0; i < ellipsisCount; i++) {
2302 final char c;
Roozbeh Pournader1051bbe2017-07-25 13:52:57 -07002303 if (useEllipsisString && i < ellipsisStringLen) {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002304 c = ellipsisString.charAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 } else {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002306 c = TextUtils.ELLIPSIS_FILLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 }
2308
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002309 final int a = i + ellipsisStart + lineStart;
2310 if (start <= a && a < end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 dest[destoff + a - start] = c;
2312 }
2313 }
2314 }
2315
2316 /**
2317 * Stores information about bidirectional (left-to-right or right-to-left)
Doug Felt9f7a4442010-03-01 12:45:56 -08002318 * text within the layout of a line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 */
2320 public static class Directions {
Siyamed Sinired09ae12016-02-16 14:36:26 -08002321 /**
Petar Šegina7c31d5c2017-09-25 12:19:28 +01002322 * Directions represents directional runs within a line of text. Runs are pairs of ints
2323 * listed in visual order, starting from the leading margin. The first int of each pair is
2324 * the offset from the first character of the line to the start of the run. The second int
2325 * represents both the length and level of the run. The length is in the lower bits,
2326 * accessed by masking with RUN_LENGTH_MASK. The level is in the higher bits, accessed by
2327 * shifting by RUN_LEVEL_SHIFT and masking by RUN_LEVEL_MASK. To simply test for an RTL
2328 * direction, test the bit using RUN_RTL_FLAG, if set then the direction is rtl.
Siyamed Sinired09ae12016-02-16 14:36:26 -08002329 * @hide
2330 */
2331 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2332 public int[] mDirections;
2333
2334 /**
2335 * @hide
2336 */
2337 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2338 public Directions(int[] dirs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 mDirections = dirs;
2340 }
2341 }
2342
2343 /**
2344 * Return the offset of the first character to be ellipsized away,
2345 * relative to the start of the line. (So 0 if the beginning of the
2346 * line is ellipsized, not getLineStart().)
2347 */
2348 public abstract int getEllipsisStart(int line);
Doug Felte8e45f22010-03-29 14:58:40 -07002349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 /**
2351 * Returns the number of characters to be ellipsized away, or 0 if
2352 * no ellipsis is to take place.
2353 */
2354 public abstract int getEllipsisCount(int line);
2355
2356 /* package */ static class Ellipsizer implements CharSequence, GetChars {
2357 /* package */ CharSequence mText;
2358 /* package */ Layout mLayout;
2359 /* package */ int mWidth;
2360 /* package */ TextUtils.TruncateAt mMethod;
2361
2362 public Ellipsizer(CharSequence s) {
2363 mText = s;
2364 }
2365
2366 public char charAt(int off) {
2367 char[] buf = TextUtils.obtain(1);
2368 getChars(off, off + 1, buf, 0);
2369 char ret = buf[0];
2370
2371 TextUtils.recycle(buf);
2372 return ret;
2373 }
2374
2375 public void getChars(int start, int end, char[] dest, int destoff) {
2376 int line1 = mLayout.getLineForOffset(start);
2377 int line2 = mLayout.getLineForOffset(end);
2378
2379 TextUtils.getChars(mText, start, end, dest, destoff);
2380
2381 for (int i = line1; i <= line2; i++) {
Fabrice Di Meglio8d44fff2012-06-13 15:45:38 -07002382 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 }
2384 }
2385
2386 public int length() {
2387 return mText.length();
2388 }
Doug Felt9f7a4442010-03-01 12:45:56 -08002389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 public CharSequence subSequence(int start, int end) {
2391 char[] s = new char[end - start];
2392 getChars(start, end, s, 0);
2393 return new String(s);
2394 }
2395
Gilles Debunne162bf0f2010-11-16 16:23:53 -08002396 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 public String toString() {
2398 char[] s = new char[length()];
2399 getChars(0, length(), s, 0);
2400 return new String(s);
2401 }
2402
2403 }
2404
Gilles Debunne6c488de2012-03-01 16:20:35 -08002405 /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 private Spanned mSpanned;
2407
2408 public SpannedEllipsizer(CharSequence display) {
2409 super(display);
2410 mSpanned = (Spanned) display;
2411 }
2412
2413 public <T> T[] getSpans(int start, int end, Class<T> type) {
2414 return mSpanned.getSpans(start, end, type);
2415 }
2416
2417 public int getSpanStart(Object tag) {
2418 return mSpanned.getSpanStart(tag);
2419 }
2420
2421 public int getSpanEnd(Object tag) {
2422 return mSpanned.getSpanEnd(tag);
2423 }
2424
2425 public int getSpanFlags(Object tag) {
2426 return mSpanned.getSpanFlags(tag);
2427 }
2428
Gilles Debunne6c488de2012-03-01 16:20:35 -08002429 @SuppressWarnings("rawtypes")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 public int nextSpanTransition(int start, int limit, Class type) {
2431 return mSpanned.nextSpanTransition(start, limit, type);
2432 }
2433
Gilles Debunne162bf0f2010-11-16 16:23:53 -08002434 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 public CharSequence subSequence(int start, int end) {
2436 char[] s = new char[end - start];
2437 getChars(start, end, s, 0);
2438
2439 SpannableString ss = new SpannableString(new String(s));
2440 TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2441 return ss;
2442 }
2443 }
2444
2445 private CharSequence mText;
Mathew Inwoodefeab842018-08-14 15:21:30 +01002446 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 private TextPaint mPaint;
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07002448 private TextPaint mWorkPaint = new TextPaint();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 private int mWidth;
2450 private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2451 private float mSpacingMult;
2452 private float mSpacingAdd;
Romain Guyc4d8eb62010-08-18 20:48:33 -07002453 private static final Rect sTempRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 private boolean mSpannedText;
Doug Feltcb3791202011-07-07 11:57:48 -07002455 private TextDirectionHeuristic mTextDir;
Gilles Debunneeca5b732012-04-25 18:48:42 -07002456 private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
Seigo Nonaka4b4730d2017-03-31 09:42:16 -07002457 private int mJustificationMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002459 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -07002460 @IntDef(prefix = { "DIR_" }, value = {
2461 DIR_LEFT_TO_RIGHT,
2462 DIR_RIGHT_TO_LEFT
2463 })
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002464 @Retention(RetentionPolicy.SOURCE)
2465 public @interface Direction {}
2466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 public static final int DIR_LEFT_TO_RIGHT = 1;
2468 public static final int DIR_RIGHT_TO_LEFT = -1;
Doug Felt9f7a4442010-03-01 12:45:56 -08002469
Doug Felt20178d62010-02-22 13:39:01 -08002470 /* package */ static final int DIR_REQUEST_LTR = 1;
2471 /* package */ static final int DIR_REQUEST_RTL = -1;
Mathew Inwoodefeab842018-08-14 15:21:30 +01002472 @UnsupportedAppUsage
Doug Felt20178d62010-02-22 13:39:01 -08002473 /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2474 /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475
Doug Felt9f7a4442010-03-01 12:45:56 -08002476 /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2477 /* package */ static final int RUN_LEVEL_SHIFT = 26;
2478 /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2479 /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 public enum Alignment {
2482 ALIGN_NORMAL,
2483 ALIGN_OPPOSITE,
2484 ALIGN_CENTER,
Doug Feltc0ccf0c2011-06-23 16:13:18 -07002485 /** @hide */
Mathew Inwoodefeab842018-08-14 15:21:30 +01002486 @UnsupportedAppUsage
Doug Feltc0ccf0c2011-06-23 16:13:18 -07002487 ALIGN_LEFT,
2488 /** @hide */
Mathew Inwoodefeab842018-08-14 15:21:30 +01002489 @UnsupportedAppUsage
Doug Feltc0ccf0c2011-06-23 16:13:18 -07002490 ALIGN_RIGHT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 }
2492
2493 private static final int TAB_INCREMENT = 20;
2494
Siyamed Sinired09ae12016-02-16 14:36:26 -08002495 /** @hide */
2496 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Mathew Inwoodefeab842018-08-14 15:21:30 +01002497 @UnsupportedAppUsage
Siyamed Sinired09ae12016-02-16 14:36:26 -08002498 public static final Directions DIRS_ALL_LEFT_TO_RIGHT =
Doug Felt9f7a4442010-03-01 12:45:56 -08002499 new Directions(new int[] { 0, RUN_LENGTH_MASK });
Siyamed Sinired09ae12016-02-16 14:36:26 -08002500
2501 /** @hide */
2502 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Mathew Inwoodefeab842018-08-14 15:21:30 +01002503 @UnsupportedAppUsage
Siyamed Sinired09ae12016-02-16 14:36:26 -08002504 public static final Directions DIRS_ALL_RIGHT_TO_LEFT =
Doug Felt9f7a4442010-03-01 12:45:56 -08002505 new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });
Gilles Debunne0a4db3c2011-01-14 12:12:04 -08002506
Petar Šeginafb748b32017-08-07 12:37:52 +01002507 /** @hide */
Petar Šeginab92c5392017-09-06 15:25:05 +01002508 @Retention(RetentionPolicy.SOURCE)
Jeff Sharkeyce8db992017-12-13 20:05:05 -07002509 @IntDef(prefix = { "TEXT_SELECTION_LAYOUT_" }, value = {
2510 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT,
2511 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT
2512 })
Petar Šegina3a92fb62017-09-07 21:03:24 +01002513 public @interface TextSelectionLayout {}
2514
2515 /** @hide */
2516 public static final int TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT = 0;
2517 /** @hide */
2518 public static final int TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT = 1;
Petar Šeginab92c5392017-09-06 15:25:05 +01002519
2520 /** @hide */
Petar Šeginafb748b32017-08-07 12:37:52 +01002521 @FunctionalInterface
Petar Šeginab92c5392017-09-06 15:25:05 +01002522 public interface SelectionRectangleConsumer {
Petar Šeginafb748b32017-08-07 12:37:52 +01002523 /**
2524 * Performs this operation on the given rectangle.
2525 *
2526 * @param left the left edge of the rectangle
2527 * @param top the top edge of the rectangle
2528 * @param right the right edge of the rectangle
2529 * @param bottom the bottom edge of the rectangle
Petar Šeginab92c5392017-09-06 15:25:05 +01002530 * @param textSelectionLayout the layout (RTL or LTR) of the text covered by this
2531 * selection rectangle
Petar Šeginafb748b32017-08-07 12:37:52 +01002532 */
Petar Šeginab92c5392017-09-06 15:25:05 +01002533 void accept(float left, float top, float right, float bottom,
2534 @TextSelectionLayout int textSelectionLayout);
Petar Šeginafb748b32017-08-07 12:37:52 +01002535 }
2536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537}