blob: 3633808e9e6c3ebf9cb679d60267af814f7cf167 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.graphics.Canvas;
22import android.graphics.Paint;
Doug Felt9f7a4442010-03-01 12:45:56 -080023import android.graphics.Path;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.graphics.Rect;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.text.method.TextKeyListener;
Doug Felt9f7a4442010-03-01 12:45:56 -080026import android.text.style.AlignmentSpan;
27import android.text.style.LeadingMarginSpan;
Gilles Debunne162bf0f2010-11-16 16:23:53 -080028import android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
Doug Felt9f7a4442010-03-01 12:45:56 -080029import android.text.style.LineBackgroundSpan;
30import android.text.style.ParagraphStyle;
31import android.text.style.ReplacementSpan;
32import android.text.style.TabStopSpan;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033
Siyamed Sinired09ae12016-02-16 14:36:26 -080034import com.android.internal.annotations.VisibleForTesting;
Doug Feltcb3791202011-07-07 11:57:48 -070035import com.android.internal.util.ArrayUtils;
Adam Lesinski776abc22014-03-07 11:30:59 -050036import com.android.internal.util.GrowingArrayUtils;
Doug Feltcb3791202011-07-07 11:57:48 -070037
Raph Levien39b4db72015-03-25 13:18:20 -070038import java.lang.annotation.Retention;
39import java.lang.annotation.RetentionPolicy;
Doug Feltc982f602010-05-25 11:51:40 -070040import java.util.Arrays;
Doug Felt9f7a4442010-03-01 12:45:56 -080041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042/**
Doug Felt9f7a4442010-03-01 12:45:56 -080043 * A base class that manages text layout in visual elements on
44 * the screen.
45 * <p>For text that will be edited, use a {@link DynamicLayout},
46 * which will be updated as the text changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047 * For text that will not change, use a {@link StaticLayout}.
48 */
49public abstract class Layout {
Raph Levien39b4db72015-03-25 13:18:20 -070050 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -070051 @IntDef(prefix = { "BREAK_STRATEGY_" }, value = {
52 BREAK_STRATEGY_SIMPLE,
53 BREAK_STRATEGY_HIGH_QUALITY,
54 BREAK_STRATEGY_BALANCED
55 })
Raph Levien39b4db72015-03-25 13:18:20 -070056 @Retention(RetentionPolicy.SOURCE)
57 public @interface BreakStrategy {}
58
59 /**
60 * Value for break strategy indicating simple line breaking. Automatic hyphens are not added
61 * (though soft hyphens are respected), and modifying text generally doesn't affect the layout
62 * before it (which yields a more consistent user experience when editing), but layout may not
63 * be the highest quality.
64 */
65 public static final int BREAK_STRATEGY_SIMPLE = 0;
66
67 /**
68 * Value for break strategy indicating high quality line breaking, including automatic
69 * hyphenation and doing whole-paragraph optimization of line breaks.
70 */
71 public static final int BREAK_STRATEGY_HIGH_QUALITY = 1;
72
73 /**
74 * Value for break strategy indicating balanced line breaking. The breaks are chosen to
75 * make all lines as close to the same length as possible, including automatic hyphenation.
76 */
77 public static final int BREAK_STRATEGY_BALANCED = 2;
78
Roozbeh Pournader95c7a132015-05-12 12:01:06 -070079 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -070080 @IntDef(prefix = { "HYPHENATION_FREQUENCY_" }, value = {
81 HYPHENATION_FREQUENCY_NORMAL,
82 HYPHENATION_FREQUENCY_FULL,
83 HYPHENATION_FREQUENCY_NONE
84 })
Roozbeh Pournader95c7a132015-05-12 12:01:06 -070085 @Retention(RetentionPolicy.SOURCE)
86 public @interface HyphenationFrequency {}
87
88 /**
89 * Value for hyphenation frequency indicating no automatic hyphenation. Useful
90 * for backward compatibility, and for cases where the automatic hyphenation algorithm results
91 * in incorrect hyphenation. Mid-word breaks may still happen when a word is wider than the
92 * layout and there is otherwise no valid break. Soft hyphens are ignored and will not be used
93 * as suggestions for potential line breaks.
94 */
95 public static final int HYPHENATION_FREQUENCY_NONE = 0;
96
97 /**
98 * Value for hyphenation frequency indicating a light amount of automatic hyphenation, which
99 * is a conservative default. Useful for informal cases, such as short sentences or chat
100 * messages.
101 */
102 public static final int HYPHENATION_FREQUENCY_NORMAL = 1;
103
104 /**
105 * Value for hyphenation frequency indicating the full amount of automatic hyphenation, typical
106 * in typography. Useful for running text and where it's important to put the maximum amount of
107 * text in a screen with limited space.
108 */
109 public static final int HYPHENATION_FREQUENCY_FULL = 2;
110
Doug Felt71b8dd72010-02-16 17:27:09 -0800111 private static final ParagraphStyle[] NO_PARA_SPANS =
112 ArrayUtils.emptyArray(ParagraphStyle.class);
Dave Bort76c02262009-04-13 17:17:21 -0700113
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700114 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -0700115 @IntDef(prefix = { "JUSTIFICATION_MODE_" }, value = {
116 JUSTIFICATION_MODE_NONE,
117 JUSTIFICATION_MODE_INTER_WORD
118 })
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700119 @Retention(RetentionPolicy.SOURCE)
120 public @interface JustificationMode {}
121
122 /**
123 * Value for justification mode indicating no justification.
124 */
125 public static final int JUSTIFICATION_MODE_NONE = 0;
126
127 /**
128 * Value for justification mode indicating the text is justified by stretching word spacing.
129 */
130 public static final int JUSTIFICATION_MODE_INTER_WORD = 1;
131
Roozbeh Pournader22a167c2017-08-21 12:53:44 -0700132 /*
133 * Line spacing multiplier for default line spacing.
134 */
135 public static final float DEFAULT_LINESPACING_MULTIPLIER = 1.0f;
136
137 /*
138 * Line spacing addition for default line spacing.
139 */
140 public static final float DEFAULT_LINESPACING_ADDITION = 0.0f;
141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 /**
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700143 * Return how wide a layout must be in order to display the specified text with one line per
144 * paragraph.
145 *
146 * <p>As of O, Uses
147 * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
148 * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 */
150 public static float getDesiredWidth(CharSequence source,
151 TextPaint paint) {
152 return getDesiredWidth(source, 0, source.length(), paint);
153 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 /**
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700156 * Return how wide a layout must be in order to display the specified text slice with one
157 * line per paragraph.
158 *
159 * <p>As of O, Uses
160 * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
161 * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
162 */
163 public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint) {
164 return getDesiredWidth(source, start, end, paint, TextDirectionHeuristics.FIRSTSTRONG_LTR);
165 }
166
167 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800168 * Return how wide a layout must be in order to display the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 * specified text slice with one line per paragraph.
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700170 *
171 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 */
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700173 public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint,
174 TextDirectionHeuristic textDir) {
Seigo Nonaka917748e2017-08-03 17:42:28 -0700175 return getDesiredWidthWithLimit(source, start, end, paint, textDir, Float.MAX_VALUE);
176 }
177 /**
178 * Return how wide a layout must be in order to display the
179 * specified text slice with one line per paragraph.
180 *
181 * If the measured width exceeds given limit, returns limit value instead.
182 * @hide
183 */
184 public static float getDesiredWidthWithLimit(CharSequence source, int start, int end,
185 TextPaint paint, TextDirectionHeuristic textDir, float upperLimit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 float need = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
188 int next;
189 for (int i = start; i <= end; i = next) {
190 next = TextUtils.indexOf(source, '\n', i, end);
191
192 if (next < 0)
193 next = end;
194
Doug Felt71b8dd72010-02-16 17:27:09 -0800195 // note, omits trailing paragraph char
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700196 float w = measurePara(paint, source, i, next, textDir);
Seigo Nonaka917748e2017-08-03 17:42:28 -0700197 if (w > upperLimit) {
198 return upperLimit;
199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
201 if (w > need)
202 need = w;
203
204 next++;
205 }
206
207 return need;
208 }
209
210 /**
211 * Subclasses of Layout use this constructor to set the display text,
212 * width, and other standard properties.
Doug Felt71b8dd72010-02-16 17:27:09 -0800213 * @param text the text to render
214 * @param paint the default paint for the layout. Styles can override
215 * various attributes of the paint.
216 * @param width the wrapping width for the text.
217 * @param align whether to left, right, or center the text. Styles can
218 * override the alignment.
219 * @param spacingMult factor by which to scale the font size to get the
220 * default line spacing
221 * @param spacingAdd amount to add to the default line spacing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 */
223 protected Layout(CharSequence text, TextPaint paint,
224 int width, Alignment align,
Doug Felt71b8dd72010-02-16 17:27:09 -0800225 float spacingMult, float spacingAdd) {
Doug Feltcb3791202011-07-07 11:57:48 -0700226 this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
227 spacingMult, spacingAdd);
228 }
229
230 /**
231 * Subclasses of Layout use this constructor to set the display text,
232 * width, and other standard properties.
233 * @param text the text to render
234 * @param paint the default paint for the layout. Styles can override
235 * various attributes of the paint.
236 * @param width the wrapping width for the text.
237 * @param align whether to left, right, or center the text. Styles can
238 * override the alignment.
239 * @param spacingMult factor by which to scale the font size to get the
240 * default line spacing
241 * @param spacingAdd amount to add to the default line spacing
242 *
243 * @hide
244 */
245 protected Layout(CharSequence text, TextPaint paint,
246 int width, Alignment align, TextDirectionHeuristic textDir,
247 float spacingMult, float spacingAdd) {
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 if (width < 0)
250 throw new IllegalArgumentException("Layout: " + width + " < 0");
251
Doug Felte8e45f22010-03-29 14:58:40 -0700252 // Ensure paint doesn't have baselineShift set.
253 // While normally we don't modify the paint the user passed in,
254 // we were already doing this in Styled.drawUniformRun with both
255 // baselineShift and bgColor. We probably should reevaluate bgColor.
256 if (paint != null) {
257 paint.bgColor = 0;
258 paint.baselineShift = 0;
259 }
260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 mText = text;
262 mPaint = paint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 mWidth = width;
264 mAlignment = align;
Doug Felt71b8dd72010-02-16 17:27:09 -0800265 mSpacingMult = spacingMult;
266 mSpacingAdd = spacingAdd;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 mSpannedText = text instanceof Spanned;
Doug Feltcb3791202011-07-07 11:57:48 -0700268 mTextDir = textDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 }
270
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900271 /** @hide */
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700272 protected void setJustificationMode(@JustificationMode int justificationMode) {
273 mJustificationMode = justificationMode;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900274 }
275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 /**
277 * Replace constructor properties of this Layout with new ones. Be careful.
278 */
279 /* package */ void replaceWith(CharSequence text, TextPaint paint,
280 int width, Alignment align,
281 float spacingmult, float spacingadd) {
282 if (width < 0) {
283 throw new IllegalArgumentException("Layout: " + width + " < 0");
284 }
285
286 mText = text;
287 mPaint = paint;
288 mWidth = width;
289 mAlignment = align;
290 mSpacingMult = spacingmult;
291 mSpacingAdd = spacingadd;
292 mSpannedText = text instanceof Spanned;
293 }
294
295 /**
296 * Draw this Layout on the specified Canvas.
297 */
298 public void draw(Canvas c) {
299 draw(c, null, null, 0);
300 }
301
302 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800303 * Draw this Layout on the specified canvas, with the highlight path drawn
304 * between the background and the text.
305 *
Gilles Debunne6c488de2012-03-01 16:20:35 -0800306 * @param canvas the canvas
Doug Felt71b8dd72010-02-16 17:27:09 -0800307 * @param highlight the path of the highlight or cursor; can be null
308 * @param highlightPaint the paint for the highlight
309 * @param cursorOffsetVertical the amount to temporarily translate the
310 * canvas while rendering the highlight
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 */
Gilles Debunne6c488de2012-03-01 16:20:35 -0800312 public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
313 int cursorOffsetVertical) {
314 final long lineRange = getLineRangeForDraw(canvas);
315 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
316 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
317 if (lastLine < 0) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318
Gilles Debunne6c488de2012-03-01 16:20:35 -0800319 drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
320 firstLine, lastLine);
321 drawText(canvas, firstLine, lastLine);
322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900324 private boolean isJustificationRequired(int lineNum) {
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700325 if (mJustificationMode == JUSTIFICATION_MODE_NONE) return false;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900326 final int lineEnd = getLineEnd(lineNum);
327 return lineEnd < mText.length() && mText.charAt(lineEnd - 1) != '\n';
328 }
329
330 private float getJustifyWidth(int lineNum) {
331 Alignment paraAlign = mAlignment;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900332
333 int left = 0;
334 int right = mWidth;
335
336 final int dir = getParagraphDirection(lineNum);
337
338 ParagraphStyle[] spans = NO_PARA_SPANS;
339 if (mSpannedText) {
340 Spanned sp = (Spanned) mText;
341 final int start = getLineStart(lineNum);
342
343 final boolean isFirstParaLine = (start == 0 || mText.charAt(start - 1) == '\n');
344
345 if (isFirstParaLine) {
346 final int spanEnd = sp.nextSpanTransition(start, mText.length(),
347 ParagraphStyle.class);
348 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
349
350 for (int n = spans.length - 1; n >= 0; n--) {
351 if (spans[n] instanceof AlignmentSpan) {
352 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
353 break;
354 }
355 }
356 }
357
358 final int length = spans.length;
359 boolean useFirstLineMargin = isFirstParaLine;
360 for (int n = 0; n < length; n++) {
361 if (spans[n] instanceof LeadingMarginSpan2) {
362 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
363 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
364 if (lineNum < startLine + count) {
365 useFirstLineMargin = true;
366 break;
367 }
368 }
369 }
370 for (int n = 0; n < length; n++) {
371 if (spans[n] instanceof LeadingMarginSpan) {
372 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
373 if (dir == DIR_RIGHT_TO_LEFT) {
374 right -= margin.getLeadingMargin(useFirstLineMargin);
375 } else {
376 left += margin.getLeadingMargin(useFirstLineMargin);
377 }
378 }
379 }
380 }
381
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900382 final Alignment align;
383 if (paraAlign == Alignment.ALIGN_LEFT) {
384 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
385 } else if (paraAlign == Alignment.ALIGN_RIGHT) {
386 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
387 } else {
388 align = paraAlign;
389 }
390
391 final int indentWidth;
392 if (align == Alignment.ALIGN_NORMAL) {
393 if (dir == DIR_LEFT_TO_RIGHT) {
394 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
395 } else {
396 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
397 }
398 } else if (align == Alignment.ALIGN_OPPOSITE) {
399 if (dir == DIR_LEFT_TO_RIGHT) {
400 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
401 } else {
402 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
403 }
404 } else { // Alignment.ALIGN_CENTER
405 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
406 }
407
408 return right - left - indentWidth;
409 }
410
Gilles Debunne6c488de2012-03-01 16:20:35 -0800411 /**
412 * @hide
413 */
414 public void drawText(Canvas canvas, int firstLine, int lastLine) {
415 int previousLineBottom = getLineTop(firstLine);
416 int previousLineEnd = getLineStart(firstLine);
Doug Felt71b8dd72010-02-16 17:27:09 -0800417 ParagraphStyle[] spans = NO_PARA_SPANS;
Doug Feltc982f602010-05-25 11:51:40 -0700418 int spanEnd = 0;
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -0700419 final TextPaint paint = mWorkPaint;
420 paint.set(mPaint);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800421 CharSequence buf = mText;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700423 Alignment paraAlign = mAlignment;
Doug Feltc982f602010-05-25 11:51:40 -0700424 TabStops tabStops = null;
425 boolean tabStopsIsInitialized = false;
Doug Felt9f7a4442010-03-01 12:45:56 -0800426
Doug Felte8e45f22010-03-29 14:58:40 -0700427 TextLine tl = TextLine.obtain();
Doug Feltc982f602010-05-25 11:51:40 -0700428
Gilles Debunne6c488de2012-03-01 16:20:35 -0800429 // Draw the lines, one at a time.
430 // The baseline is the top of the following line minus the current line's descent.
Raph Levien26d443a2015-03-30 14:18:32 -0700431 for (int lineNum = firstLine; lineNum <= lastLine; lineNum++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 int start = previousLineEnd;
Raph Levien26d443a2015-03-30 14:18:32 -0700433 previousLineEnd = getLineStart(lineNum + 1);
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900434 final boolean justify = isJustificationRequired(lineNum);
Raph Levien26d443a2015-03-30 14:18:32 -0700435 int end = getLineVisibleEnd(lineNum, start, previousLineEnd);
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -0700436 paint.setHyphenEdit(getHyphen(lineNum));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437
438 int ltop = previousLineBottom;
Raph Levien26d443a2015-03-30 14:18:32 -0700439 int lbottom = getLineTop(lineNum + 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 previousLineBottom = lbottom;
Raph Levien26d443a2015-03-30 14:18:32 -0700441 int lbaseline = lbottom - getLineDescent(lineNum);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442
Raph Levien26d443a2015-03-30 14:18:32 -0700443 int dir = getParagraphDirection(lineNum);
Doug Feltc982f602010-05-25 11:51:40 -0700444 int left = 0;
445 int right = mWidth;
446
Gilles Debunne6c488de2012-03-01 16:20:35 -0800447 if (mSpannedText) {
Doug Feltc982f602010-05-25 11:51:40 -0700448 Spanned sp = (Spanned) buf;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800449 int textLength = buf.length();
450 boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
Doug Felt0c702b82010-05-14 10:55:42 -0700451
Doug Feltc982f602010-05-25 11:51:40 -0700452 // New batch of paragraph styles, collect into spans array.
453 // Compute the alignment, last alignment style wins.
454 // Reset tabStops, we'll rebuild if we encounter a line with
455 // tabs.
456 // We expect paragraph spans to be relatively infrequent, use
457 // spanEnd so that we can check less frequently. Since
458 // paragraph styles ought to apply to entire paragraphs, we can
459 // just collect the ones present at the start of the paragraph.
460 // If spanEnd is before the end of the paragraph, that's not
461 // our problem.
Raph Levien26d443a2015-03-30 14:18:32 -0700462 if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
Doug Feltc982f602010-05-25 11:51:40 -0700463 spanEnd = sp.nextSpanTransition(start, textLength,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 ParagraphStyle.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -0700465 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
Doug Felt9f7a4442010-03-01 12:45:56 -0800466
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700467 paraAlign = mAlignment;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800468 for (int n = spans.length - 1; n >= 0; n--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 if (spans[n] instanceof AlignmentSpan) {
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700470 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 break;
472 }
473 }
Doug Felt0c702b82010-05-14 10:55:42 -0700474
Doug Feltc982f602010-05-25 11:51:40 -0700475 tabStopsIsInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800477
Doug Feltc982f602010-05-25 11:51:40 -0700478 // Draw all leading margin spans. Adjust left or right according
479 // to the paragraph direction of the line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 final int length = spans.length;
Anish Athalyeab08c6d2014-08-08 12:09:58 -0700481 boolean useFirstLineMargin = isFirstParaLine;
482 for (int n = 0; n < length; n++) {
483 if (spans[n] instanceof LeadingMarginSpan2) {
484 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
485 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
486 // if there is more than one LeadingMarginSpan2, use
487 // the count that is greatest
Raph Levien26d443a2015-03-30 14:18:32 -0700488 if (lineNum < startLine + count) {
Anish Athalyeab08c6d2014-08-08 12:09:58 -0700489 useFirstLineMargin = true;
490 break;
491 }
492 }
493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 for (int n = 0; n < length; n++) {
495 if (spans[n] instanceof LeadingMarginSpan) {
496 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 if (dir == DIR_RIGHT_TO_LEFT) {
Gilles Debunne6c488de2012-03-01 16:20:35 -0800498 margin.drawLeadingMargin(canvas, paint, right, dir, ltop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 lbaseline, lbottom, buf,
Doug Felt71b8dd72010-02-16 17:27:09 -0800500 start, end, isFirstParaLine, this);
Doug Feltc982f602010-05-25 11:51:40 -0700501 right -= margin.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 } else {
Gilles Debunne6c488de2012-03-01 16:20:35 -0800503 margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 lbaseline, lbottom, buf,
Doug Felt71b8dd72010-02-16 17:27:09 -0800505 start, end, isFirstParaLine, this);
Doug Feltc982f602010-05-25 11:51:40 -0700506 left += margin.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
508 }
509 }
510 }
511
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700512 boolean hasTab = getLineContainsTab(lineNum);
Doug Feltc982f602010-05-25 11:51:40 -0700513 // Can't tell if we have tabs for sure, currently
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700514 if (hasTab && !tabStopsIsInitialized) {
Doug Feltc982f602010-05-25 11:51:40 -0700515 if (tabStops == null) {
516 tabStops = new TabStops(TAB_INCREMENT, spans);
517 } else {
518 tabStops.reset(TAB_INCREMENT, spans);
519 }
520 tabStopsIsInitialized = true;
521 }
522
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700523 // Determine whether the line aligns to normal, opposite, or center.
524 Alignment align = paraAlign;
525 if (align == Alignment.ALIGN_LEFT) {
526 align = (dir == DIR_LEFT_TO_RIGHT) ?
527 Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
528 } else if (align == Alignment.ALIGN_RIGHT) {
529 align = (dir == DIR_LEFT_TO_RIGHT) ?
530 Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
531 }
532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 int x;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900534 final int indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 if (align == Alignment.ALIGN_NORMAL) {
536 if (dir == DIR_LEFT_TO_RIGHT) {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900537 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
538 x = left + indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 } else {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900540 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
541 x = right - indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 }
543 } else {
Raph Levien26d443a2015-03-30 14:18:32 -0700544 int max = (int)getLineExtent(lineNum, tabStops, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 if (align == Alignment.ALIGN_OPPOSITE) {
Doug Feltc982f602010-05-25 11:51:40 -0700546 if (dir == DIR_LEFT_TO_RIGHT) {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900547 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
548 x = right - max - indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 } else {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900550 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
551 x = left - max + indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 }
Doug Feltc982f602010-05-25 11:51:40 -0700553 } else { // Alignment.ALIGN_CENTER
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900554 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
Doug Feltc982f602010-05-25 11:51:40 -0700555 max = max & ~1;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900556 x = ((right + left - max) >> 1) + indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 }
558 }
559
Raph Levien26d443a2015-03-30 14:18:32 -0700560 Directions directions = getLineDirections(lineNum);
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900561 if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTab && !justify) {
Doug Felt71b8dd72010-02-16 17:27:09 -0800562 // XXX: assumes there's nothing additional to be done
Gilles Debunne6c488de2012-03-01 16:20:35 -0800563 canvas.drawText(buf, start, end, x, lbaseline, paint);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 } else {
Mihai Popace642dc2018-05-24 14:25:11 +0100565 tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops,
566 getEllipsisStart(lineNum),
567 getEllipsisStart(lineNum) + getEllipsisCount(lineNum));
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900568 if (justify) {
569 tl.justify(right - left - indentWidth);
570 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800571 tl.draw(canvas, x, ltop, lbaseline, lbottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
573 }
Doug Feltc982f602010-05-25 11:51:40 -0700574
Doug Felte8e45f22010-03-29 14:58:40 -0700575 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 }
577
578 /**
Gilles Debunne6c488de2012-03-01 16:20:35 -0800579 * @hide
580 */
581 public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
582 int cursorOffsetVertical, int firstLine, int lastLine) {
583 // First, draw LineBackgroundSpans.
584 // LineBackgroundSpans know nothing about the alignment, margins, or
585 // direction of the layout or line. XXX: Should they?
586 // They are evaluated at each line.
587 if (mSpannedText) {
Gilles Debunneeca5b732012-04-25 18:48:42 -0700588 if (mLineBackgroundSpans == null) {
589 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700590 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800591
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700592 Spanned buffer = (Spanned) mText;
593 int textLength = buffer.length();
Gilles Debunneeca5b732012-04-25 18:48:42 -0700594 mLineBackgroundSpans.init(buffer, 0, textLength);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800595
Gilles Debunneeca5b732012-04-25 18:48:42 -0700596 if (mLineBackgroundSpans.numberOfSpans > 0) {
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700597 int previousLineBottom = getLineTop(firstLine);
598 int previousLineEnd = getLineStart(firstLine);
599 ParagraphStyle[] spans = NO_PARA_SPANS;
600 int spansLength = 0;
601 TextPaint paint = mPaint;
602 int spanEnd = 0;
603 final int width = mWidth;
604 for (int i = firstLine; i <= lastLine; i++) {
605 int start = previousLineEnd;
606 int end = getLineStart(i + 1);
607 previousLineEnd = end;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800608
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700609 int ltop = previousLineBottom;
610 int lbottom = getLineTop(i + 1);
611 previousLineBottom = lbottom;
612 int lbaseline = lbottom - getLineDescent(i);
613
614 if (start >= spanEnd) {
615 // These should be infrequent, so we'll use this so that
616 // we don't have to check as often.
Gilles Debunneeca5b732012-04-25 18:48:42 -0700617 spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700618 // All LineBackgroundSpans on a line contribute to its background.
619 spansLength = 0;
620 // Duplication of the logic of getParagraphSpans
621 if (start != end || start == 0) {
622 // Equivalent to a getSpans(start, end), but filling the 'spans' local
623 // array instead to reduce memory allocation
Gilles Debunneeca5b732012-04-25 18:48:42 -0700624 for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
625 // equal test is valid since both intervals are not empty by
626 // construction
627 if (mLineBackgroundSpans.spanStarts[j] >= end ||
628 mLineBackgroundSpans.spanEnds[j] <= start) continue;
Adam Lesinski776abc22014-03-07 11:30:59 -0500629 spans = GrowingArrayUtils.append(
630 spans, spansLength, mLineBackgroundSpans.spans[j]);
631 spansLength++;
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700632 }
633 }
634 }
635
636 for (int n = 0; n < spansLength; n++) {
637 LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
638 lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
639 ltop, lbaseline, lbottom,
640 buffer, start, end, i);
641 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800642 }
643 }
Gilles Debunneeca5b732012-04-25 18:48:42 -0700644 mLineBackgroundSpans.recycle();
Gilles Debunne6c488de2012-03-01 16:20:35 -0800645 }
646
647 // There can be a highlight even without spans if we are drawing
648 // a non-spanned transformation of a spanned editing buffer.
649 if (highlight != null) {
650 if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
651 canvas.drawPath(highlight, highlightPaint);
652 if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
653 }
654 }
655
656 /**
657 * @param canvas
658 * @return The range of lines that need to be drawn, possibly empty.
659 * @hide
660 */
661 public long getLineRangeForDraw(Canvas canvas) {
662 int dtop, dbottom;
663
664 synchronized (sTempRect) {
665 if (!canvas.getClipBounds(sTempRect)) {
666 // Negative range end used as a special flag
667 return TextUtils.packRangeInLong(0, -1);
668 }
669
670 dtop = sTempRect.top;
671 dbottom = sTempRect.bottom;
672 }
673
674 final int top = Math.max(dtop, 0);
675 final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
676
Gilles Debunne2fba3382012-06-11 17:46:24 -0700677 if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800678 return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
679 }
680
681 /**
Doug Feltc982f602010-05-25 11:51:40 -0700682 * Return the start position of the line, given the left and right bounds
683 * of the margins.
Doug Felt0c702b82010-05-14 10:55:42 -0700684 *
Doug Feltc982f602010-05-25 11:51:40 -0700685 * @param line the line index
686 * @param left the left bounds (0, or leading margin if ltr para)
687 * @param right the right bounds (width, minus leading margin if rtl para)
688 * @return the start position of the line (to right of line if rtl para)
689 */
690 private int getLineStartPos(int line, int left, int right) {
691 // Adjust the point at which to start rendering depending on the
692 // alignment of the paragraph.
693 Alignment align = getParagraphAlignment(line);
694 int dir = getParagraphDirection(line);
695
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700696 if (align == Alignment.ALIGN_LEFT) {
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700697 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
698 } else if (align == Alignment.ALIGN_RIGHT) {
699 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
700 }
701
702 int x;
703 if (align == Alignment.ALIGN_NORMAL) {
Doug Feltc982f602010-05-25 11:51:40 -0700704 if (dir == DIR_LEFT_TO_RIGHT) {
Raph Levien2ea52902015-07-01 14:39:31 -0700705 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
Doug Feltc982f602010-05-25 11:51:40 -0700706 } else {
Raph Levien2ea52902015-07-01 14:39:31 -0700707 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
Doug Feltc982f602010-05-25 11:51:40 -0700708 }
709 } else {
710 TabStops tabStops = null;
711 if (mSpannedText && getLineContainsTab(line)) {
712 Spanned spanned = (Spanned) mText;
713 int start = getLineStart(line);
714 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
715 TabStopSpan.class);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800716 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
717 TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -0700718 if (tabSpans.length > 0) {
719 tabStops = new TabStops(TAB_INCREMENT, tabSpans);
720 }
721 }
722 int max = (int)getLineExtent(line, tabStops, false);
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700723 if (align == Alignment.ALIGN_OPPOSITE) {
Doug Feltc982f602010-05-25 11:51:40 -0700724 if (dir == DIR_LEFT_TO_RIGHT) {
Raph Levien2ea52902015-07-01 14:39:31 -0700725 x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
Doug Feltc982f602010-05-25 11:51:40 -0700726 } else {
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700727 // max is negative here
Raph Levien2ea52902015-07-01 14:39:31 -0700728 x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
Doug Feltc982f602010-05-25 11:51:40 -0700729 }
730 } else { // Alignment.ALIGN_CENTER
731 max = max & ~1;
Raph Levien2ea52902015-07-01 14:39:31 -0700732 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
Doug Feltc982f602010-05-25 11:51:40 -0700733 }
734 }
735 return x;
736 }
737
738 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 * Return the text that is displayed by this Layout.
740 */
741 public final CharSequence getText() {
742 return mText;
743 }
744
745 /**
746 * Return the base Paint properties for this layout.
747 * Do NOT change the paint, which may result in funny
748 * drawing for this layout.
749 */
750 public final TextPaint getPaint() {
751 return mPaint;
752 }
753
754 /**
755 * Return the width of this layout.
756 */
757 public final int getWidth() {
758 return mWidth;
759 }
760
761 /**
762 * Return the width to which this Layout is ellipsizing, or
763 * {@link #getWidth} if it is not doing anything special.
764 */
765 public int getEllipsizedWidth() {
766 return mWidth;
767 }
768
769 /**
770 * Increase the width of this layout to the specified width.
Doug Felt71b8dd72010-02-16 17:27:09 -0800771 * Be careful to use this only when you know it is appropriate&mdash;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 * it does not cause the text to reflow to use the full new width.
773 */
774 public final void increaseWidthTo(int wid) {
775 if (wid < mWidth) {
776 throw new RuntimeException("attempted to reduce Layout width");
777 }
778
779 mWidth = wid;
780 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 /**
783 * Return the total height of this layout.
784 */
785 public int getHeight() {
Doug Felt71b8dd72010-02-16 17:27:09 -0800786 return getLineTop(getLineCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 }
788
789 /**
Siyamed Sinir0745c722016-05-31 20:39:33 -0700790 * Return the total height of this layout.
791 *
792 * @param cap if true and max lines is set, returns the height of the layout at the max lines.
793 *
794 * @hide
795 */
796 public int getHeight(boolean cap) {
797 return getHeight();
798 }
799
800 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 * Return the base alignment of this layout.
802 */
803 public final Alignment getAlignment() {
804 return mAlignment;
805 }
806
807 /**
808 * Return what the text height is multiplied by to get the line height.
809 */
810 public final float getSpacingMultiplier() {
811 return mSpacingMult;
812 }
813
814 /**
815 * Return the number of units of leading that are added to each line.
816 */
817 public final float getSpacingAdd() {
818 return mSpacingAdd;
819 }
820
821 /**
Doug Feltcb3791202011-07-07 11:57:48 -0700822 * Return the heuristic used to determine paragraph text direction.
823 * @hide
824 */
825 public final TextDirectionHeuristic getTextDirectionHeuristic() {
826 return mTextDir;
827 }
828
829 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 * Return the number of lines of text in this layout.
831 */
832 public abstract int getLineCount();
Doug Felt9f7a4442010-03-01 12:45:56 -0800833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 /**
835 * Return the baseline for the specified line (0&hellip;getLineCount() - 1)
836 * If bounds is not null, return the top, left, right, bottom extents
837 * of the specified line in it.
838 * @param line which line to examine (0..getLineCount() - 1)
839 * @param bounds Optional. If not null, it returns the extent of the line
840 * @return the Y-coordinate of the baseline
841 */
842 public int getLineBounds(int line, Rect bounds) {
843 if (bounds != null) {
844 bounds.left = 0; // ???
845 bounds.top = getLineTop(line);
846 bounds.right = mWidth; // ???
Doug Felt71b8dd72010-02-16 17:27:09 -0800847 bounds.bottom = getLineTop(line + 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
849 return getLineBaseline(line);
850 }
851
852 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800853 * Return the vertical position of the top of the specified line
854 * (0&hellip;getLineCount()).
855 * If the specified line is equal to the line count, returns the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 * bottom of the last line.
857 */
858 public abstract int getLineTop(int line);
859
860 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800861 * Return the descent of the specified line(0&hellip;getLineCount() - 1).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 */
863 public abstract int getLineDescent(int line);
864
865 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800866 * Return the text offset of the beginning of the specified line (
867 * 0&hellip;getLineCount()). If the specified line is equal to the line
868 * count, returns the length of the text.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 */
870 public abstract int getLineStart(int line);
871
872 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800873 * Returns the primary directionality of the paragraph containing the
874 * specified line, either 1 for left-to-right lines, or -1 for right-to-left
875 * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 */
877 public abstract int getParagraphDirection(int line);
878
879 /**
The Android Open Source Project10592532009-03-18 17:39:46 -0700880 * Returns whether the specified line contains one or more
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700881 * characters that need to be handled specially, like tabs.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 */
883 public abstract boolean getLineContainsTab(int line);
884
885 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800886 * Returns the directional run information for the specified line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 * The array alternates counts of characters in left-to-right
888 * and right-to-left segments of the line.
Doug Felt71b8dd72010-02-16 17:27:09 -0800889 *
890 * <p>NOTE: this is inadequate to support bidirectional text, and will change.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 */
892 public abstract Directions getLineDirections(int line);
893
894 /**
895 * Returns the (negative) number of extra pixels of ascent padding in the
896 * top line of the Layout.
897 */
898 public abstract int getTopPadding();
899
900 /**
901 * Returns the number of extra pixels of descent padding in the
902 * bottom line of the Layout.
903 */
904 public abstract int getBottomPadding();
905
Raph Levien26d443a2015-03-30 14:18:32 -0700906 /**
907 * Returns the hyphen edit for a line.
908 *
909 * @hide
910 */
911 public int getHyphen(int line) {
912 return 0;
913 }
914
Raph Levien2ea52902015-07-01 14:39:31 -0700915 /**
916 * Returns the left indent for a line.
917 *
918 * @hide
919 */
920 public int getIndentAdjust(int line, Alignment alignment) {
921 return 0;
922 }
Doug Felt4e0c5e52010-03-15 16:56:02 -0700923
924 /**
925 * Returns true if the character at offset and the preceding character
926 * are at different run levels (and thus there's a split caret).
927 * @param offset the offset
928 * @return true if at a level boundary
Gilles Debunnef75c97e2011-02-10 16:09:53 -0800929 * @hide
Doug Felt4e0c5e52010-03-15 16:56:02 -0700930 */
Gilles Debunnef75c97e2011-02-10 16:09:53 -0800931 public boolean isLevelBoundary(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -0800932 int line = getLineForOffset(offset);
Doug Felt4e0c5e52010-03-15 16:56:02 -0700933 Directions dirs = getLineDirections(line);
934 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
935 return false;
936 }
937
938 int[] runs = dirs.mDirections;
Doug Felt9f7a4442010-03-01 12:45:56 -0800939 int lineStart = getLineStart(line);
Doug Felt4e0c5e52010-03-15 16:56:02 -0700940 int lineEnd = getLineEnd(line);
941 if (offset == lineStart || offset == lineEnd) {
942 int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
943 int runIndex = offset == lineStart ? 0 : runs.length - 2;
944 return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
945 }
946
947 offset -= lineStart;
Doug Felt9f7a4442010-03-01 12:45:56 -0800948 for (int i = 0; i < runs.length; i += 2) {
Doug Felt4e0c5e52010-03-15 16:56:02 -0700949 if (offset == runs[i]) {
950 return true;
Doug Felt9f7a4442010-03-01 12:45:56 -0800951 }
952 }
Doug Felt4e0c5e52010-03-15 16:56:02 -0700953 return false;
Doug Felt9f7a4442010-03-01 12:45:56 -0800954 }
955
Fabrice Di Meglio34d2eba2011-08-31 19:46:15 -0700956 /**
957 * Returns true if the character at offset is right to left (RTL).
958 * @param offset the offset
959 * @return true if the character is RTL, false if it is LTR
960 */
961 public boolean isRtlCharAt(int offset) {
962 int line = getLineForOffset(offset);
963 Directions dirs = getLineDirections(line);
964 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
965 return false;
966 }
967 if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
968 return true;
969 }
970 int[] runs = dirs.mDirections;
971 int lineStart = getLineStart(line);
972 for (int i = 0; i < runs.length; i += 2) {
Raph Levien87506202014-09-04 12:47:03 -0700973 int start = lineStart + runs[i];
974 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
975 if (offset >= start && offset < limit) {
Fabrice Di Meglio34d2eba2011-08-31 19:46:15 -0700976 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
977 return ((level & 1) != 0);
978 }
979 }
980 // Should happen only if the offset is "out of bounds"
981 return false;
982 }
983
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +0900984 /**
985 * Returns the range of the run that the character at offset belongs to.
986 * @param offset the offset
987 * @return The range of the run
988 * @hide
989 */
990 public long getRunRange(int offset) {
991 int line = getLineForOffset(offset);
992 Directions dirs = getLineDirections(line);
993 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
994 return TextUtils.packRangeInLong(0, getLineEnd(line));
995 }
996 int[] runs = dirs.mDirections;
997 int lineStart = getLineStart(line);
998 for (int i = 0; i < runs.length; i += 2) {
999 int start = lineStart + runs[i];
1000 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1001 if (offset >= start && offset < limit) {
1002 return TextUtils.packRangeInLong(start, limit);
1003 }
1004 }
1005 // Should happen only if the offset is "out of bounds"
1006 return TextUtils.packRangeInLong(0, getLineEnd(line));
1007 }
1008
Mihai Popa7626c862018-05-09 17:31:48 +01001009 /**
1010 * Checks if the trailing BiDi level should be used for an offset
1011 *
1012 * This method is useful when the offset is at the BiDi level transition point and determine
1013 * which run need to be used. For example, let's think about following input: (L* denotes
1014 * Left-to-Right characters, R* denotes Right-to-Left characters.)
1015 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1016 * Input (Display Order): L1 L2 L3 R3 R2 R1 L4 L5 L6
1017 *
1018 * Then, think about selecting the range (3, 6). The offset=3 and offset=6 are ambiguous here
1019 * since they are at the BiDi transition point. In Android, the offset is considered to be
1020 * associated with the trailing run if the BiDi level of the trailing run is higher than of the
1021 * previous run. In this case, the BiDi level of the input text is as follows:
1022 *
1023 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1024 * BiDi Run: [ Run 0 ][ Run 1 ][ Run 2 ]
1025 * BiDi Level: 0 0 0 1 1 1 0 0 0
1026 *
1027 * Thus, offset = 3 is part of Run 1 and this method returns true for offset = 3, since the BiDi
1028 * level of Run 1 is higher than the level of Run 0. Similarly, the offset = 6 is a part of Run
1029 * 1 and this method returns false for the offset = 6 since the BiDi level of Run 1 is higher
1030 * than the level of Run 2.
1031 *
1032 * @returns true if offset is at the BiDi level transition point and trailing BiDi level is
1033 * higher than previous BiDi level. See above for the detail.
1034 * @hide
1035 */
Seigo Nonaka19e75a62018-05-16 16:57:33 -07001036 @VisibleForTesting
1037 public boolean primaryIsTrailingPrevious(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001038 int line = getLineForOffset(offset);
1039 int lineStart = getLineStart(line);
Doug Felt4e0c5e52010-03-15 16:56:02 -07001040 int lineEnd = getLineEnd(line);
Doug Felt9f7a4442010-03-01 12:45:56 -08001041 int[] runs = getLineDirections(line).mDirections;
1042
1043 int levelAt = -1;
1044 for (int i = 0; i < runs.length; i += 2) {
1045 int start = lineStart + runs[i];
1046 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1047 if (limit > lineEnd) {
1048 limit = lineEnd;
1049 }
1050 if (offset >= start && offset < limit) {
1051 if (offset > start) {
1052 // Previous character is at same level, so don't use trailing.
1053 return false;
1054 }
1055 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1056 break;
1057 }
1058 }
1059 if (levelAt == -1) {
1060 // Offset was limit of line.
1061 levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
1062 }
1063
1064 // At level boundary, check previous level.
1065 int levelBefore = -1;
1066 if (offset == lineStart) {
1067 levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
1068 } else {
1069 offset -= 1;
1070 for (int i = 0; i < runs.length; i += 2) {
1071 int start = lineStart + runs[i];
1072 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1073 if (limit > lineEnd) {
1074 limit = lineEnd;
1075 }
1076 if (offset >= start && offset < limit) {
1077 levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1078 break;
1079 }
1080 }
1081 }
1082
1083 return levelBefore < levelAt;
1084 }
1085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001087 * Computes in linear time the results of calling
1088 * #primaryIsTrailingPrevious for all offsets on a line.
1089 * @param line The line giving the offsets we compute the information for
1090 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1091 * @hide
1092 */
1093 @VisibleForTesting
1094 public boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
1095 int lineStart = getLineStart(line);
1096 int lineEnd = getLineEnd(line);
1097 int[] runs = getLineDirections(line).mDirections;
1098
1099 boolean[] trailing = new boolean[lineEnd - lineStart + 1];
1100
1101 byte[] level = new byte[lineEnd - lineStart + 1];
1102 for (int i = 0; i < runs.length; i += 2) {
1103 int start = lineStart + runs[i];
1104 int limit = start + (runs[i + 1] & RUN_LENGTH_MASK);
1105 if (limit > lineEnd) {
1106 limit = lineEnd;
1107 }
1108 level[limit - lineStart - 1] =
1109 (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1110 }
1111
1112 for (int i = 0; i < runs.length; i += 2) {
1113 int start = lineStart + runs[i];
1114 byte currentLevel = (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1115 trailing[start - lineStart] = currentLevel > (start == lineStart
1116 ? (getParagraphDirection(line) == 1 ? 0 : 1)
1117 : level[start - lineStart - 1]);
1118 }
1119
1120 return trailing;
1121 }
1122
1123 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 * Get the primary horizontal position for the specified text offset.
1125 * This is the location where a new character would be inserted in
1126 * the paragraph's primary direction.
1127 */
1128 public float getPrimaryHorizontal(int offset) {
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001129 return getPrimaryHorizontal(offset, false /* not clamped */);
Raph Levienafe8e9b2012-12-19 16:09:32 -08001130 }
1131
1132 /**
1133 * Get the primary horizontal position for the specified text offset, but
1134 * optionally clamp it so that it doesn't exceed the width of the layout.
1135 * @hide
1136 */
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001137 public float getPrimaryHorizontal(int offset, boolean clamped) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001138 boolean trailing = primaryIsTrailingPrevious(offset);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001139 return getHorizontal(offset, trailing, clamped);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
1141
1142 /**
1143 * Get the secondary horizontal position for the specified text offset.
1144 * This is the location where a new character would be inserted in
1145 * the direction other than the paragraph's primary direction.
1146 */
1147 public float getSecondaryHorizontal(int offset) {
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001148 return getSecondaryHorizontal(offset, false /* not clamped */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150
Raph Levienafe8e9b2012-12-19 16:09:32 -08001151 /**
1152 * Get the secondary horizontal position for the specified text offset, but
1153 * optionally clamp it so that it doesn't exceed the width of the layout.
1154 * @hide
1155 */
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001156 public float getSecondaryHorizontal(int offset, boolean clamped) {
Raph Levienafe8e9b2012-12-19 16:09:32 -08001157 boolean trailing = primaryIsTrailingPrevious(offset);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001158 return getHorizontal(offset, !trailing, clamped);
Raph Levienafe8e9b2012-12-19 16:09:32 -08001159 }
1160
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001161 private float getHorizontal(int offset, boolean primary) {
1162 return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09001163 }
1164
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001165 private float getHorizontal(int offset, boolean trailing, boolean clamped) {
1166 int line = getLineForOffset(offset);
1167
Raph Levienafe8e9b2012-12-19 16:09:32 -08001168 return getHorizontal(offset, trailing, line, clamped);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
1170
Raph Levienafe8e9b2012-12-19 16:09:32 -08001171 private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 int start = getLineStart(line);
Doug Felte8e45f22010-03-29 14:58:40 -07001173 int end = getLineEnd(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 int dir = getParagraphDirection(line);
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001175 boolean hasTab = getLineContainsTab(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 Directions directions = getLineDirections(line);
1177
Doug Feltc982f602010-05-25 11:51:40 -07001178 TabStops tabStops = null;
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001179 if (hasTab && mText instanceof Spanned) {
Doug Feltc982f602010-05-25 11:51:40 -07001180 // Just checking this line should be good enough, tabs should be
1181 // consistent across all lines in a paragraph.
Eric Fischer74d31ef2010-08-05 15:29:36 -07001182 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -07001183 if (tabs.length > 0) {
1184 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
1187
Doug Felte8e45f22010-03-29 14:58:40 -07001188 TextLine tl = TextLine.obtain();
Mihai Popace642dc2018-05-24 14:25:11 +01001189 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops,
1190 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Doug Felte8e45f22010-03-29 14:58:40 -07001191 float wid = tl.measure(offset - start, trailing, null);
1192 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193
Raph Levienafe8e9b2012-12-19 16:09:32 -08001194 if (clamped && wid > mWidth) {
1195 wid = mWidth;
1196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 int left = getParagraphLeft(line);
1198 int right = getParagraphRight(line);
1199
Doug Feltc982f602010-05-25 11:51:40 -07001200 return getLineStartPos(line, left, right) + wid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 }
1202
1203 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001204 * Computes in linear time the results of calling
1205 * #getHorizontal for all offsets on a line.
1206 * @param line The line giving the offsets we compute information for
1207 * @param clamped Whether to clamp the results to the width of the layout
1208 * @param primary Whether the results should be the primary or the secondary horizontal
1209 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1210 */
1211 private float[] getLineHorizontals(int line, boolean clamped, boolean primary) {
1212 int start = getLineStart(line);
1213 int end = getLineEnd(line);
1214 int dir = getParagraphDirection(line);
1215 boolean hasTab = getLineContainsTab(line);
1216 Directions directions = getLineDirections(line);
1217
1218 TabStops tabStops = null;
1219 if (hasTab && mText instanceof Spanned) {
1220 // Just checking this line should be good enough, tabs should be
1221 // consistent across all lines in a paragraph.
1222 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1223 if (tabs.length > 0) {
1224 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1225 }
1226 }
1227
1228 TextLine tl = TextLine.obtain();
Mihai Popace642dc2018-05-24 14:25:11 +01001229 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops,
1230 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Mihai Popa7626c862018-05-09 17:31:48 +01001231 boolean[] trailings = primaryIsTrailingPreviousAllLineOffsets(line);
1232 if (!primary) {
1233 for (int offset = 0; offset < trailings.length; ++offset) {
1234 trailings[offset] = !trailings[offset];
1235 }
1236 }
1237 float[] wid = tl.measureAllOffsets(trailings, null);
1238 TextLine.recycle(tl);
1239
1240 if (clamped) {
1241 for (int offset = 0; offset <= wid.length; ++offset) {
1242 if (wid[offset] > mWidth) {
1243 wid[offset] = mWidth;
1244 }
1245 }
1246 }
1247 int left = getParagraphLeft(line);
1248 int right = getParagraphRight(line);
1249
1250 int lineStartPos = getLineStartPos(line, left, right);
1251 float[] horizontal = new float[end - start + 1];
1252 for (int offset = 0; offset < horizontal.length; ++offset) {
1253 horizontal[offset] = lineStartPos + wid[offset];
1254 }
1255 return horizontal;
1256 }
1257
1258 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 * Get the leftmost position that should be exposed for horizontal
1260 * scrolling on the specified line.
1261 */
1262 public float getLineLeft(int line) {
1263 int dir = getParagraphDirection(line);
1264 Alignment align = getParagraphAlignment(line);
1265
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001266 if (align == Alignment.ALIGN_LEFT) {
1267 return 0;
1268 } else if (align == Alignment.ALIGN_NORMAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 if (dir == DIR_RIGHT_TO_LEFT)
1270 return getParagraphRight(line) - getLineMax(line);
1271 else
1272 return 0;
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001273 } else if (align == Alignment.ALIGN_RIGHT) {
1274 return mWidth - getLineMax(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 } else if (align == Alignment.ALIGN_OPPOSITE) {
1276 if (dir == DIR_RIGHT_TO_LEFT)
1277 return 0;
1278 else
1279 return mWidth - getLineMax(line);
1280 } else { /* align == Alignment.ALIGN_CENTER */
1281 int left = getParagraphLeft(line);
1282 int right = getParagraphRight(line);
1283 int max = ((int) getLineMax(line)) & ~1;
1284
1285 return left + ((right - left) - max) / 2;
1286 }
1287 }
1288
1289 /**
1290 * Get the rightmost position that should be exposed for horizontal
1291 * scrolling on the specified line.
1292 */
1293 public float getLineRight(int line) {
1294 int dir = getParagraphDirection(line);
1295 Alignment align = getParagraphAlignment(line);
1296
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001297 if (align == Alignment.ALIGN_LEFT) {
1298 return getParagraphLeft(line) + getLineMax(line);
1299 } else if (align == Alignment.ALIGN_NORMAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 if (dir == DIR_RIGHT_TO_LEFT)
1301 return mWidth;
1302 else
1303 return getParagraphLeft(line) + getLineMax(line);
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001304 } else if (align == Alignment.ALIGN_RIGHT) {
1305 return mWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 } else if (align == Alignment.ALIGN_OPPOSITE) {
1307 if (dir == DIR_RIGHT_TO_LEFT)
1308 return getLineMax(line);
1309 else
1310 return mWidth;
1311 } else { /* align == Alignment.ALIGN_CENTER */
1312 int left = getParagraphLeft(line);
1313 int right = getParagraphRight(line);
1314 int max = ((int) getLineMax(line)) & ~1;
1315
1316 return right - ((right - left) - max) / 2;
1317 }
1318 }
1319
1320 /**
Doug Felt0c702b82010-05-14 10:55:42 -07001321 * Gets the unsigned horizontal extent of the specified line, including
Doug Feltc982f602010-05-25 11:51:40 -07001322 * leading margin indent, but excluding trailing whitespace.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 */
1324 public float getLineMax(int line) {
Doug Feltc982f602010-05-25 11:51:40 -07001325 float margin = getParagraphLeadingMargin(line);
1326 float signedExtent = getLineExtent(line, false);
Anish Athalyec14b3ad2014-07-24 18:03:21 -07001327 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
1329
1330 /**
Doug Feltc982f602010-05-25 11:51:40 -07001331 * Gets the unsigned horizontal extent of the specified line, including
1332 * leading margin indent and trailing whitespace.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 */
1334 public float getLineWidth(int line) {
Doug Feltc982f602010-05-25 11:51:40 -07001335 float margin = getParagraphLeadingMargin(line);
1336 float signedExtent = getLineExtent(line, true);
Anish Athalyec14b3ad2014-07-24 18:03:21 -07001337 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 }
1339
Doug Feltc982f602010-05-25 11:51:40 -07001340 /**
1341 * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1342 * tab stops instead of using the ones passed in.
1343 * @param line the index of the line
1344 * @param full whether to include trailing whitespace
1345 * @return the extent of the line
1346 */
1347 private float getLineExtent(int line, boolean full) {
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001348 final int start = getLineStart(line);
1349 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
Doug Feltc982f602010-05-25 11:51:40 -07001350
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001351 final boolean hasTabs = getLineContainsTab(line);
Doug Feltc982f602010-05-25 11:51:40 -07001352 TabStops tabStops = null;
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001353 if (hasTabs && mText instanceof Spanned) {
Doug Feltc982f602010-05-25 11:51:40 -07001354 // Just checking this line should be good enough, tabs should be
1355 // consistent across all lines in a paragraph.
Eric Fischer74d31ef2010-08-05 15:29:36 -07001356 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -07001357 if (tabs.length > 0) {
1358 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1359 }
1360 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001361 final Directions directions = getLineDirections(line);
Fabrice Di Meglio8059e0902011-08-10 16:31:58 -07001362 // Returned directions can actually be null
1363 if (directions == null) {
1364 return 0f;
1365 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001366 final int dir = getParagraphDirection(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001368 final TextLine tl = TextLine.obtain();
1369 final TextPaint paint = mWorkPaint;
1370 paint.set(mPaint);
1371 paint.setHyphenEdit(getHyphen(line));
Mihai Popace642dc2018-05-24 14:25:11 +01001372 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops,
1373 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001374 if (isJustificationRequired(line)) {
1375 tl.justify(getJustifyWidth(line));
1376 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001377 final float width = tl.metrics(null);
Doug Feltc982f602010-05-25 11:51:40 -07001378 TextLine.recycle(tl);
1379 return width;
1380 }
1381
1382 /**
1383 * Returns the signed horizontal extent of the specified line, excluding
1384 * leading margin. If full is false, excludes trailing whitespace.
1385 * @param line the index of the line
1386 * @param tabStops the tab stops, can be null if we know they're not used.
1387 * @param full whether to include trailing whitespace
1388 * @return the extent of the text on this line
1389 */
1390 private float getLineExtent(int line, TabStops tabStops, boolean full) {
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001391 final int start = getLineStart(line);
1392 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1393 final boolean hasTabs = getLineContainsTab(line);
1394 final Directions directions = getLineDirections(line);
1395 final int dir = getParagraphDirection(line);
Doug Feltc982f602010-05-25 11:51:40 -07001396
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001397 final TextLine tl = TextLine.obtain();
1398 final TextPaint paint = mWorkPaint;
1399 paint.set(mPaint);
1400 paint.setHyphenEdit(getHyphen(line));
Mihai Popace642dc2018-05-24 14:25:11 +01001401 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops,
1402 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001403 if (isJustificationRequired(line)) {
1404 tl.justify(getJustifyWidth(line));
1405 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001406 final float width = tl.metrics(null);
Doug Felte8e45f22010-03-29 14:58:40 -07001407 TextLine.recycle(tl);
1408 return width;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 }
1410
1411 /**
1412 * Get the line number corresponding to the specified vertical position.
1413 * If you ask for a position above 0, you get 0; if you ask for a position
1414 * below the bottom of the text, you get the last line.
1415 */
1416 // FIXME: It may be faster to do a linear search for layouts without many lines.
1417 public int getLineForVertical(int vertical) {
1418 int high = getLineCount(), low = -1, guess;
1419
1420 while (high - low > 1) {
1421 guess = (high + low) / 2;
1422
1423 if (getLineTop(guess) > vertical)
1424 high = guess;
1425 else
1426 low = guess;
1427 }
1428
1429 if (low < 0)
1430 return 0;
1431 else
1432 return low;
1433 }
1434
1435 /**
1436 * Get the line number on which the specified text offset appears.
1437 * If you ask for a position before 0, you get 0; if you ask for a position
1438 * beyond the end of the text, you get the last line.
1439 */
1440 public int getLineForOffset(int offset) {
1441 int high = getLineCount(), low = -1, guess;
1442
1443 while (high - low > 1) {
1444 guess = (high + low) / 2;
1445
1446 if (getLineStart(guess) > offset)
1447 high = guess;
1448 else
1449 low = guess;
1450 }
1451
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001452 if (low < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 return 0;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001454 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 return low;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 }
1458
1459 /**
Doug Felt9f7a4442010-03-01 12:45:56 -08001460 * Get the character offset on the specified line whose position is
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 * closest to the specified horizontal position.
1462 */
1463 public int getOffsetForHorizontal(int line, float horiz) {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09001464 return getOffsetForHorizontal(line, horiz, true);
1465 }
1466
1467 /**
1468 * Get the character offset on the specified line whose position is
1469 * closest to the specified horizontal position.
1470 *
1471 * @param line the line used to find the closest offset
1472 * @param horiz the horizontal position used to find the closest offset
1473 * @param primary whether to use the primary position or secondary position to find the offset
1474 *
1475 * @hide
1476 */
1477 public int getOffsetForHorizontal(int line, float horiz, boolean primary) {
Raph Levienedb27f12015-06-01 14:34:47 -07001478 // TODO: use Paint.getOffsetForAdvance to avoid binary search
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001479 final int lineEndOffset = getLineEnd(line);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001480 final int lineStartOffset = getLineStart(line);
1481
1482 Directions dirs = getLineDirections(line);
1483
1484 TextLine tl = TextLine.obtain();
1485 // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1486 tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
Mihai Popace642dc2018-05-24 14:25:11 +01001487 false, null,
1488 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Mihai Popa7626c862018-05-09 17:31:48 +01001489 final HorizontalMeasurementProvider horizontal =
1490 new HorizontalMeasurementProvider(line, primary);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001491
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001492 final int max;
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001493 if (line == getLineCount() - 1) {
1494 max = lineEndOffset;
1495 } else {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001496 max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1497 !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001498 }
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001499 int best = lineStartOffset;
Mihai Popa7626c862018-05-09 17:31:48 +01001500 float bestdist = Math.abs(horizontal.get(lineStartOffset) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501
Doug Felt9f7a4442010-03-01 12:45:56 -08001502 for (int i = 0; i < dirs.mDirections.length; i += 2) {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001503 int here = lineStartOffset + dirs.mDirections[i];
Doug Felt9f7a4442010-03-01 12:45:56 -08001504 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001505 boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1506 int swap = isRtl ? -1 : 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507
1508 if (there > max)
1509 there = max;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 int high = there - 1 + 1, low = here + 1 - 1, guess;
1511
1512 while (high - low > 1) {
1513 guess = (high + low) / 2;
1514 int adguess = getOffsetAtStartOf(guess);
1515
Mihai Popa7626c862018-05-09 17:31:48 +01001516 if (horizontal.get(adguess) * swap >= horiz * swap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 high = guess;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001518 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 low = guess;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522
1523 if (low < here + 1)
1524 low = here + 1;
1525
1526 if (low < there) {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001527 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1528 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1529 if (low >= here && low < there) {
Mihai Popa7626c862018-05-09 17:31:48 +01001530 float dist = Math.abs(horizontal.get(low) - horiz);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001531 if (aft < there) {
Mihai Popa7626c862018-05-09 17:31:48 +01001532 float other = Math.abs(horizontal.get(aft) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001534 if (other < dist) {
1535 dist = other;
1536 low = aft;
1537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001540 if (dist < bestdist) {
1541 bestdist = dist;
1542 best = low;
1543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545 }
1546
Mihai Popa7626c862018-05-09 17:31:48 +01001547 float dist = Math.abs(horizontal.get(here) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548
1549 if (dist < bestdist) {
1550 bestdist = dist;
1551 best = here;
1552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
1554
Mihai Popa7626c862018-05-09 17:31:48 +01001555 float dist = Math.abs(horizontal.get(max) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556
Raph Levien373b7a82013-09-20 15:11:52 -07001557 if (dist <= bestdist) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 best = max;
1559 }
1560
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001561 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 return best;
1563 }
1564
1565 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001566 * Responds to #getHorizontal queries, by selecting the better strategy between:
1567 * - calling #getHorizontal explicitly for each query
1568 * - precomputing all #getHorizontal measurements, and responding to any query in constant time
1569 * The first strategy is used for LTR-only text, while the second is used for all other cases.
1570 * The class is currently only used in #getOffsetForHorizontal, so reuse with care in other
1571 * contexts.
1572 */
1573 private class HorizontalMeasurementProvider {
1574 private final int mLine;
1575 private final boolean mPrimary;
1576
1577 private float[] mHorizontals;
1578 private int mLineStartOffset;
1579
1580 HorizontalMeasurementProvider(final int line, final boolean primary) {
1581 mLine = line;
1582 mPrimary = primary;
1583 init();
1584 }
1585
1586 private void init() {
1587 final Directions dirs = getLineDirections(mLine);
1588 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1589 return;
1590 }
1591
1592 mHorizontals = getLineHorizontals(mLine, false, mPrimary);
1593 mLineStartOffset = getLineStart(mLine);
1594 }
1595
1596 float get(final int offset) {
Siyamed Sinir58df7952018-08-14 18:43:56 -07001597 final int index = offset - mLineStartOffset;
1598 if (mHorizontals == null || index < 0 || index >= mHorizontals.length) {
Mihai Popa7626c862018-05-09 17:31:48 +01001599 return getHorizontal(offset, mPrimary);
1600 } else {
Siyamed Sinir58df7952018-08-14 18:43:56 -07001601 return mHorizontals[index];
Mihai Popa7626c862018-05-09 17:31:48 +01001602 }
1603 }
1604 }
1605
1606 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 * Return the text offset after the last character on the specified line.
1608 */
1609 public final int getLineEnd(int line) {
1610 return getLineStart(line + 1);
1611 }
1612
Doug Felt9f7a4442010-03-01 12:45:56 -08001613 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 * Return the text offset after the last visible character (so whitespace
1615 * is not counted) on the specified line.
1616 */
1617 public int getLineVisibleEnd(int line) {
1618 return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1619 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 private int getLineVisibleEnd(int line, int start, int end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 CharSequence text = mText;
1623 char ch;
1624 if (line == getLineCount() - 1) {
1625 return end;
1626 }
1627
1628 for (; end > start; end--) {
1629 ch = text.charAt(end - 1);
1630
1631 if (ch == '\n') {
1632 return end - 1;
1633 }
1634
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001635 if (!TextLine.isLineEndSpace(ch)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 break;
1637 }
1638
1639 }
1640
1641 return end;
1642 }
1643
1644 /**
1645 * Return the vertical position of the bottom of the specified line.
1646 */
1647 public final int getLineBottom(int line) {
1648 return getLineTop(line + 1);
1649 }
1650
1651 /**
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001652 * Return the vertical position of the bottom of the specified line without the line spacing
1653 * added.
1654 *
1655 * @hide
1656 */
1657 public final int getLineBottomWithoutSpacing(int line) {
1658 return getLineTop(line + 1) - getLineExtra(line);
1659 }
1660
1661 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 * Return the vertical position of the baseline of the specified line.
1663 */
1664 public final int getLineBaseline(int line) {
1665 // getLineTop(line+1) == getLineTop(line)
1666 return getLineTop(line+1) - getLineDescent(line);
1667 }
1668
1669 /**
1670 * Get the ascent of the text on the specified line.
1671 * The return value is negative to match the Paint.ascent() convention.
1672 */
1673 public final int getLineAscent(int line) {
1674 // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1675 return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1676 }
1677
Siyamed Sinir0fa89d62017-07-24 20:46:41 -07001678 /**
1679 * Return the extra space added as a result of line spacing attributes
1680 * {@link #getSpacingAdd()} and {@link #getSpacingMultiplier()}. Default value is {@code zero}.
1681 *
1682 * @param line the index of the line, the value should be equal or greater than {@code zero}
1683 * @hide
1684 */
1685 public int getLineExtra(@IntRange(from = 0) int line) {
1686 return 0;
1687 }
1688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 public int getOffsetToLeftOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001690 return getOffsetToLeftRightOf(offset, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
1692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 public int getOffsetToRightOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001694 return getOffsetToLeftRightOf(offset, false);
1695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696
Doug Felt9f7a4442010-03-01 12:45:56 -08001697 private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1698 int line = getLineForOffset(caret);
1699 int lineStart = getLineStart(line);
1700 int lineEnd = getLineEnd(line);
Doug Felte8e45f22010-03-29 14:58:40 -07001701 int lineDir = getParagraphDirection(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001703 boolean lineChanged = false;
Doug Felte8e45f22010-03-29 14:58:40 -07001704 boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001705 // if walking off line, look at the line we're headed to
1706 if (advance) {
1707 if (caret == lineEnd) {
Doug Felte8e45f22010-03-29 14:58:40 -07001708 if (line < getLineCount() - 1) {
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001709 lineChanged = true;
Doug Felte8e45f22010-03-29 14:58:40 -07001710 ++line;
1711 } else {
1712 return caret; // at very end, don't move
1713 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001714 }
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001715 } else {
1716 if (caret == lineStart) {
1717 if (line > 0) {
1718 lineChanged = true;
1719 --line;
1720 } else {
1721 return caret; // at very start, don't move
1722 }
1723 }
1724 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001725
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001726 if (lineChanged) {
Doug Felte8e45f22010-03-29 14:58:40 -07001727 lineStart = getLineStart(line);
1728 lineEnd = getLineEnd(line);
1729 int newDir = getParagraphDirection(line);
1730 if (newDir != lineDir) {
1731 // unusual case. we want to walk onto the line, but it runs
1732 // in a different direction than this one, so we fake movement
1733 // in the opposite direction.
1734 toLeft = !toLeft;
1735 lineDir = newDir;
1736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001738
Doug Felte8e45f22010-03-29 14:58:40 -07001739 Directions directions = getLineDirections(line);
Doug Felt9f7a4442010-03-01 12:45:56 -08001740
Doug Felte8e45f22010-03-29 14:58:40 -07001741 TextLine tl = TextLine.obtain();
1742 // XXX: we don't care about tabs
Mihai Popace642dc2018-05-24 14:25:11 +01001743 tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null,
1744 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Doug Felte8e45f22010-03-29 14:58:40 -07001745 caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
Siyamed Sinira273a702017-10-05 11:22:12 -07001746 TextLine.recycle(tl);
Doug Felte8e45f22010-03-29 14:58:40 -07001747 return caret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
1749
1750 private int getOffsetAtStartOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001751 // XXX this probably should skip local reorderings and
1752 // zero-width characters, look at callers
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 if (offset == 0)
1754 return 0;
1755
1756 CharSequence text = mText;
1757 char c = text.charAt(offset);
1758
1759 if (c >= '\uDC00' && c <= '\uDFFF') {
1760 char c1 = text.charAt(offset - 1);
1761
1762 if (c1 >= '\uD800' && c1 <= '\uDBFF')
1763 offset -= 1;
1764 }
1765
1766 if (mSpannedText) {
1767 ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1768 ReplacementSpan.class);
1769
1770 for (int i = 0; i < spans.length; i++) {
1771 int start = ((Spanned) text).getSpanStart(spans[i]);
1772 int end = ((Spanned) text).getSpanEnd(spans[i]);
1773
1774 if (start < offset && end > offset)
1775 offset = start;
1776 }
1777 }
1778
1779 return offset;
1780 }
1781
1782 /**
Raph Levienafe8e9b2012-12-19 16:09:32 -08001783 * Determine whether we should clamp cursor position. Currently it's
1784 * only robust for left-aligned displays.
1785 * @hide
1786 */
1787 public boolean shouldClampCursor(int line) {
1788 // Only clamp cursor position in left-aligned displays.
1789 switch (getParagraphAlignment(line)) {
1790 case ALIGN_LEFT:
1791 return true;
1792 case ALIGN_NORMAL:
1793 return getParagraphDirection(line) > 0;
1794 default:
1795 return false;
1796 }
1797
1798 }
1799 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 * Fills in the specified Path with a representation of a cursor
1801 * at the specified offset. This will often be a vertical line
Doug Felt4e0c5e52010-03-15 16:56:02 -07001802 * but can be multiple discontinuous lines in text with multiple
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 * directionalities.
1804 */
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001805 public void getCursorPath(final int point, final Path dest, final CharSequence editingBuffer) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 dest.reset();
1807
1808 int line = getLineForOffset(point);
1809 int top = getLineTop(line);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001810 int bottom = getLineBottomWithoutSpacing(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811
Raph Levienafe8e9b2012-12-19 16:09:32 -08001812 boolean clamped = shouldClampCursor(line);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001813 float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1814 float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815
Jeff Brown497a92c2010-09-12 17:55:08 -07001816 int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1817 TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1818 int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 int dist = 0;
1820
1821 if (caps != 0 || fn != 0) {
1822 dist = (bottom - top) >> 2;
1823
1824 if (fn != 0)
1825 top += dist;
1826 if (caps != 0)
1827 bottom -= dist;
1828 }
1829
1830 if (h1 < 0.5f)
1831 h1 = 0.5f;
1832 if (h2 < 0.5f)
1833 h2 = 0.5f;
1834
Jozef BABJAK2fb503f2011-03-17 09:54:51 +01001835 if (Float.compare(h1, h2) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 dest.moveTo(h1, top);
1837 dest.lineTo(h1, bottom);
1838 } else {
1839 dest.moveTo(h1, top);
1840 dest.lineTo(h1, (top + bottom) >> 1);
1841
1842 dest.moveTo(h2, (top + bottom) >> 1);
1843 dest.lineTo(h2, bottom);
1844 }
1845
1846 if (caps == 2) {
1847 dest.moveTo(h2, bottom);
1848 dest.lineTo(h2 - dist, bottom + dist);
1849 dest.lineTo(h2, bottom);
1850 dest.lineTo(h2 + dist, bottom + dist);
1851 } else if (caps == 1) {
1852 dest.moveTo(h2, bottom);
1853 dest.lineTo(h2 - dist, bottom + dist);
1854
1855 dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1856 dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1857
1858 dest.moveTo(h2 + dist, bottom + dist);
1859 dest.lineTo(h2, bottom);
1860 }
1861
1862 if (fn == 2) {
1863 dest.moveTo(h1, top);
1864 dest.lineTo(h1 - dist, top - dist);
1865 dest.lineTo(h1, top);
1866 dest.lineTo(h1 + dist, top - dist);
1867 } else if (fn == 1) {
1868 dest.moveTo(h1, top);
1869 dest.lineTo(h1 - dist, top - dist);
1870
1871 dest.moveTo(h1 - dist, top - dist + 0.5f);
1872 dest.lineTo(h1 + dist, top - dist + 0.5f);
1873
1874 dest.moveTo(h1 + dist, top - dist);
1875 dest.lineTo(h1, top);
1876 }
1877 }
1878
1879 private void addSelection(int line, int start, int end,
Petar Šeginab92c5392017-09-06 15:25:05 +01001880 int top, int bottom, SelectionRectangleConsumer consumer) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 int linestart = getLineStart(line);
1882 int lineend = getLineEnd(line);
1883 Directions dirs = getLineDirections(line);
1884
Petar Šeginafb748b32017-08-07 12:37:52 +01001885 if (lineend > linestart && mText.charAt(lineend - 1) == '\n') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 lineend--;
Petar Šeginafb748b32017-08-07 12:37:52 +01001887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888
Doug Felt9f7a4442010-03-01 12:45:56 -08001889 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1890 int here = linestart + dirs.mDirections[i];
Petar Šeginafb748b32017-08-07 12:37:52 +01001891 int there = here + (dirs.mDirections[i + 1] & RUN_LENGTH_MASK);
Doug Felt9f7a4442010-03-01 12:45:56 -08001892
Petar Šeginafb748b32017-08-07 12:37:52 +01001893 if (there > lineend) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 there = lineend;
Petar Šeginafb748b32017-08-07 12:37:52 +01001895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896
1897 if (start <= there && end >= here) {
1898 int st = Math.max(start, here);
1899 int en = Math.min(end, there);
1900
1901 if (st != en) {
Raph Levienafe8e9b2012-12-19 16:09:32 -08001902 float h1 = getHorizontal(st, false, line, false /* not clamped */);
1903 float h2 = getHorizontal(en, true, line, false /* not clamped */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904
Fabrice Di Meglio37166012011-08-31 13:56:37 -07001905 float left = Math.min(h1, h2);
1906 float right = Math.max(h1, h2);
1907
Petar Šegina8f1f74e2017-09-07 14:26:28 +01001908 final @TextSelectionLayout int layout =
1909 ((dirs.mDirections[i + 1] & RUN_RTL_FLAG) != 0)
1910 ? TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT
1911 : TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT;
1912
1913 consumer.accept(left, top, right, bottom, layout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 }
1915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 }
1917 }
1918
1919 /**
1920 * Fills in the specified Path with a representation of a highlight
1921 * between the specified offsets. This will often be a rectangle
1922 * or a potentially discontinuous set of rectangles. If the start
1923 * and end are the same, the returned path is empty.
1924 */
1925 public void getSelectionPath(int start, int end, Path dest) {
1926 dest.reset();
Petar Šeginab92c5392017-09-06 15:25:05 +01001927 getSelection(start, end, (left, top, right, bottom, textSelectionLayout) ->
Petar Šeginafb748b32017-08-07 12:37:52 +01001928 dest.addRect(left, top, right, bottom, Path.Direction.CW));
1929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930
Petar Šeginafb748b32017-08-07 12:37:52 +01001931 /**
1932 * Calculates the rectangles which should be highlighted to indicate a selection between start
Petar Šeginab92c5392017-09-06 15:25:05 +01001933 * and end and feeds them into the given {@link SelectionRectangleConsumer}.
Petar Šeginafb748b32017-08-07 12:37:52 +01001934 *
1935 * @param start the starting index of the selection
1936 * @param end the ending index of the selection
Petar Šeginab92c5392017-09-06 15:25:05 +01001937 * @param consumer the {@link SelectionRectangleConsumer} which will receive the generated
1938 * rectangles. It will be called every time a rectangle is generated.
Petar Šeginafb748b32017-08-07 12:37:52 +01001939 * @hide
1940 * @see #getSelectionPath(int, int, Path)
1941 */
Petar Šeginab92c5392017-09-06 15:25:05 +01001942 public final void getSelection(int start, int end, final SelectionRectangleConsumer consumer) {
Petar Šeginafb748b32017-08-07 12:37:52 +01001943 if (start == end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 return;
Petar Šeginafb748b32017-08-07 12:37:52 +01001945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946
1947 if (end < start) {
1948 int temp = end;
1949 end = start;
1950 start = temp;
1951 }
1952
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001953 final int startline = getLineForOffset(start);
1954 final int endline = getLineForOffset(end);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 int top = getLineTop(startline);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001957 int bottom = getLineBottomWithoutSpacing(endline);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958
1959 if (startline == endline) {
Petar Šeginafb748b32017-08-07 12:37:52 +01001960 addSelection(startline, start, end, top, bottom, consumer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 } else {
1962 final float width = mWidth;
1963
1964 addSelection(startline, start, getLineEnd(startline),
Petar Šeginafb748b32017-08-07 12:37:52 +01001965 top, getLineBottom(startline), consumer);
Doug Felt9f7a4442010-03-01 12:45:56 -08001966
Petar Šeginafb748b32017-08-07 12:37:52 +01001967 if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT) {
Petar Šeginab92c5392017-09-06 15:25:05 +01001968 consumer.accept(getLineLeft(startline), top, 0, getLineBottom(startline),
Petar Šegina3a92fb62017-09-07 21:03:24 +01001969 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001970 } else {
Petar Šeginab92c5392017-09-06 15:25:05 +01001971 consumer.accept(getLineRight(startline), top, width, getLineBottom(startline),
Petar Šegina3a92fb62017-09-07 21:03:24 +01001972 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974
1975 for (int i = startline + 1; i < endline; i++) {
1976 top = getLineTop(i);
1977 bottom = getLineBottom(i);
Petar Šeginab92c5392017-09-06 15:25:05 +01001978 if (getParagraphDirection(i) == DIR_RIGHT_TO_LEFT) {
Petar Šegina3a92fb62017-09-07 21:03:24 +01001979 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginab92c5392017-09-06 15:25:05 +01001980 } else {
Petar Šegina3a92fb62017-09-07 21:03:24 +01001981 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginab92c5392017-09-06 15:25:05 +01001982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 }
1984
1985 top = getLineTop(endline);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001986 bottom = getLineBottomWithoutSpacing(endline);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987
Petar Šeginafb748b32017-08-07 12:37:52 +01001988 addSelection(endline, getLineStart(endline), end, top, bottom, consumer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989
Petar Šeginafb748b32017-08-07 12:37:52 +01001990 if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT) {
Petar Šeginab92c5392017-09-06 15:25:05 +01001991 consumer.accept(width, top, getLineRight(endline), bottom,
Petar Šegina3a92fb62017-09-07 21:03:24 +01001992 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001993 } else {
Petar Šeginab92c5392017-09-06 15:25:05 +01001994 consumer.accept(0, top, getLineLeft(endline), bottom,
Petar Šegina3a92fb62017-09-07 21:03:24 +01001995 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
1998 }
1999
2000 /**
2001 * Get the alignment of the specified paragraph, taking into account
2002 * markup attached to it.
2003 */
2004 public final Alignment getParagraphAlignment(int line) {
2005 Alignment align = mAlignment;
2006
2007 if (mSpannedText) {
2008 Spanned sp = (Spanned) mText;
Eric Fischer74d31ef2010-08-05 15:29:36 -07002009 AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 getLineEnd(line),
2011 AlignmentSpan.class);
2012
2013 int spanLength = spans.length;
2014 if (spanLength > 0) {
2015 align = spans[spanLength-1].getAlignment();
2016 }
2017 }
2018
2019 return align;
2020 }
2021
2022 /**
2023 * Get the left edge of the specified paragraph, inset by left margins.
2024 */
2025 public final int getParagraphLeft(int line) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 int left = 0;
Doug Feltc982f602010-05-25 11:51:40 -07002027 int dir = getParagraphDirection(line);
2028 if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
2029 return left; // leading margin has no impact, or no styles
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
Doug Feltc982f602010-05-25 11:51:40 -07002031 return getParagraphLeadingMargin(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033
2034 /**
2035 * Get the right edge of the specified paragraph, inset by right margins.
2036 */
2037 public final int getParagraphRight(int line) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 int right = mWidth;
Doug Feltc982f602010-05-25 11:51:40 -07002039 int dir = getParagraphDirection(line);
2040 if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
2041 return right; // leading margin has no impact, or no styles
2042 }
2043 return right - getParagraphLeadingMargin(line);
2044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045
Doug Feltc982f602010-05-25 11:51:40 -07002046 /**
2047 * Returns the effective leading margin (unsigned) for this line,
2048 * taking into account LeadingMarginSpan and LeadingMarginSpan2.
2049 * @param line the line index
2050 * @return the leading margin of this line
2051 */
2052 private int getParagraphLeadingMargin(int line) {
2053 if (!mSpannedText) {
2054 return 0;
2055 }
2056 Spanned spanned = (Spanned) mText;
Doug Felt0c702b82010-05-14 10:55:42 -07002057
Doug Feltc982f602010-05-25 11:51:40 -07002058 int lineStart = getLineStart(line);
2059 int lineEnd = getLineEnd(line);
Doug Felt0c702b82010-05-14 10:55:42 -07002060 int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002061 LeadingMarginSpan.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002062 LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002063 LeadingMarginSpan.class);
2064 if (spans.length == 0) {
2065 return 0; // no leading margin span;
2066 }
Doug Felt0c702b82010-05-14 10:55:42 -07002067
Doug Feltc982f602010-05-25 11:51:40 -07002068 int margin = 0;
Doug Felt0c702b82010-05-14 10:55:42 -07002069
Siyamed Sinira273a702017-10-05 11:22:12 -07002070 boolean useFirstLineMargin = lineStart == 0 || spanned.charAt(lineStart - 1) == '\n';
Anish Athalyeab08c6d2014-08-08 12:09:58 -07002071 for (int i = 0; i < spans.length; i++) {
2072 if (spans[i] instanceof LeadingMarginSpan2) {
2073 int spStart = spanned.getSpanStart(spans[i]);
2074 int spanLine = getLineForOffset(spStart);
2075 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
2076 // if there is more than one LeadingMarginSpan2, use the count that is greatest
2077 useFirstLineMargin |= line < spanLine + count;
2078 }
2079 }
Doug Feltc982f602010-05-25 11:51:40 -07002080 for (int i = 0; i < spans.length; i++) {
2081 LeadingMarginSpan span = spans[i];
Doug Feltc982f602010-05-25 11:51:40 -07002082 margin += span.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
2084
Doug Feltc982f602010-05-25 11:51:40 -07002085 return margin;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
2087
Roozbeh Pournader9a9179d2017-08-29 14:14:28 -07002088 private static float measurePara(TextPaint paint, CharSequence text, int start, int end,
Siyamed Sinir79bf9d12016-05-18 19:57:52 -07002089 TextDirectionHeuristic textDir) {
Seigo Nonaka9d3bd082018-01-11 10:02:12 -08002090 MeasuredParagraph mt = null;
Doug Felte8e45f22010-03-29 14:58:40 -07002091 TextLine tl = TextLine.obtain();
2092 try {
Seigo Nonaka9d3bd082018-01-11 10:02:12 -08002093 mt = MeasuredParagraph.buildForBidi(text, start, end, textDir, mt);
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002094 final char[] chars = mt.getChars();
2095 final int len = chars.length;
2096 final Directions directions = mt.getDirections(0, len);
2097 final int dir = mt.getParagraphDir();
Doug Feltc982f602010-05-25 11:51:40 -07002098 boolean hasTabs = false;
2099 TabStops tabStops = null;
Anish Athalyec14b3ad2014-07-24 18:03:21 -07002100 // leading margins should be taken into account when measuring a paragraph
2101 int margin = 0;
2102 if (text instanceof Spanned) {
2103 Spanned spanned = (Spanned) text;
2104 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
2105 LeadingMarginSpan.class);
2106 for (LeadingMarginSpan lms : spans) {
2107 margin += lms.getLeadingMargin(true);
2108 }
2109 }
Doug Feltc982f602010-05-25 11:51:40 -07002110 for (int i = 0; i < len; ++i) {
2111 if (chars[i] == '\t') {
2112 hasTabs = true;
2113 if (text instanceof Spanned) {
2114 Spanned spanned = (Spanned) text;
Doug Felt0c702b82010-05-14 10:55:42 -07002115 int spanEnd = spanned.nextSpanTransition(start, end,
Doug Feltc982f602010-05-25 11:51:40 -07002116 TabStopSpan.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002117 TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002118 TabStopSpan.class);
2119 if (spans.length > 0) {
2120 tabStops = new TabStops(TAB_INCREMENT, spans);
2121 }
2122 }
2123 break;
2124 }
2125 }
Mihai Popace642dc2018-05-24 14:25:11 +01002126 tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops,
2127 0 /* ellipsisStart */, 0 /* ellipsisEnd */);
Siyamed Sinir79bf9d12016-05-18 19:57:52 -07002128 return margin + Math.abs(tl.metrics(null));
Doug Felte8e45f22010-03-29 14:58:40 -07002129 } finally {
2130 TextLine.recycle(tl);
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002131 if (mt != null) {
2132 mt.recycle();
2133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136
Doug Felt71b8dd72010-02-16 17:27:09 -08002137 /**
Doug Feltc982f602010-05-25 11:51:40 -07002138 * @hide
2139 */
Seigo Nonaka32afe262018-05-16 22:05:27 -07002140 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2141 public static class TabStops {
Doug Feltc982f602010-05-25 11:51:40 -07002142 private int[] mStops;
2143 private int mNumStops;
2144 private int mIncrement;
Doug Felt0c702b82010-05-14 10:55:42 -07002145
Seigo Nonaka32afe262018-05-16 22:05:27 -07002146 public TabStops(int increment, Object[] spans) {
Doug Feltc982f602010-05-25 11:51:40 -07002147 reset(increment, spans);
2148 }
Doug Felt0c702b82010-05-14 10:55:42 -07002149
Doug Feltc982f602010-05-25 11:51:40 -07002150 void reset(int increment, Object[] spans) {
2151 this.mIncrement = increment;
2152
2153 int ns = 0;
2154 if (spans != null) {
2155 int[] stops = this.mStops;
2156 for (Object o : spans) {
2157 if (o instanceof TabStopSpan) {
2158 if (stops == null) {
2159 stops = new int[10];
2160 } else if (ns == stops.length) {
2161 int[] nstops = new int[ns * 2];
2162 for (int i = 0; i < ns; ++i) {
2163 nstops[i] = stops[i];
2164 }
2165 stops = nstops;
2166 }
2167 stops[ns++] = ((TabStopSpan) o).getTabStop();
2168 }
2169 }
2170 if (ns > 1) {
2171 Arrays.sort(stops, 0, ns);
2172 }
2173 if (stops != this.mStops) {
2174 this.mStops = stops;
2175 }
2176 }
2177 this.mNumStops = ns;
2178 }
Doug Felt0c702b82010-05-14 10:55:42 -07002179
Doug Feltc982f602010-05-25 11:51:40 -07002180 float nextTab(float h) {
2181 int ns = this.mNumStops;
2182 if (ns > 0) {
2183 int[] stops = this.mStops;
2184 for (int i = 0; i < ns; ++i) {
2185 int stop = stops[i];
2186 if (stop > h) {
2187 return stop;
2188 }
2189 }
2190 }
2191 return nextDefaultStop(h, mIncrement);
2192 }
2193
2194 public static float nextDefaultStop(float h, int inc) {
2195 return ((int) ((h + inc) / inc)) * inc;
2196 }
2197 }
Doug Felt0c702b82010-05-14 10:55:42 -07002198
Doug Feltc982f602010-05-25 11:51:40 -07002199 /**
Doug Felt71b8dd72010-02-16 17:27:09 -08002200 * Returns the position of the next tab stop after h on the line.
2201 *
2202 * @param text the text
2203 * @param start start of the line
2204 * @param end limit of the line
2205 * @param h the current horizontal offset
2206 * @param tabs the tabs, can be null. If it is null, any tabs in effect
2207 * on the line will be used. If there are no tabs, a default offset
2208 * will be used to compute the tab stop.
2209 * @return the offset of the next tab stop.
2210 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 /* package */ static float nextTab(CharSequence text, int start, int end,
2212 float h, Object[] tabs) {
2213 float nh = Float.MAX_VALUE;
2214 boolean alltabs = false;
2215
2216 if (text instanceof Spanned) {
2217 if (tabs == null) {
Eric Fischer74d31ef2010-08-05 15:29:36 -07002218 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 alltabs = true;
2220 }
2221
2222 for (int i = 0; i < tabs.length; i++) {
2223 if (!alltabs) {
2224 if (!(tabs[i] instanceof TabStopSpan))
2225 continue;
2226 }
2227
2228 int where = ((TabStopSpan) tabs[i]).getTabStop();
2229
2230 if (where < nh && where > h)
2231 nh = where;
2232 }
2233
2234 if (nh != Float.MAX_VALUE)
2235 return nh;
2236 }
2237
2238 return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
2239 }
2240
2241 protected final boolean isSpanned() {
2242 return mSpannedText;
2243 }
2244
Eric Fischer74d31ef2010-08-05 15:29:36 -07002245 /**
2246 * Returns the same as <code>text.getSpans()</code>, except where
2247 * <code>start</code> and <code>end</code> are the same and are not
2248 * at the very beginning of the text, in which case an empty array
2249 * is returned instead.
2250 * <p>
2251 * This is needed because of the special case that <code>getSpans()</code>
2252 * on an empty range returns the spans adjacent to that range, which is
2253 * primarily for the sake of <code>TextWatchers</code> so they will get
2254 * notifications when text goes from empty to non-empty. But it also
2255 * has the unfortunate side effect that if the text ends with an empty
2256 * paragraph, that paragraph accidentally picks up the styles of the
2257 * preceding paragraph (even though those styles will not be picked up
2258 * by new text that is inserted into the empty paragraph).
2259 * <p>
2260 * The reason it just checks whether <code>start</code> and <code>end</code>
2261 * is the same is that the only time a line can contain 0 characters
2262 * is if it is the final paragraph of the Layout; otherwise any line will
2263 * contain at least one printing or newline character. The reason for the
2264 * additional check if <code>start</code> is greater than 0 is that
2265 * if the empty paragraph is the entire content of the buffer, paragraph
2266 * styles that are already applied to the buffer will apply to text that
2267 * is inserted into it.
2268 */
Gilles Debunneeca5b732012-04-25 18:48:42 -07002269 /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
Eric Fischer74d31ef2010-08-05 15:29:36 -07002270 if (start == end && start > 0) {
Gilles Debunne6c488de2012-03-01 16:20:35 -08002271 return ArrayUtils.emptyArray(type);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002272 }
2273
Siyamed Sinirfa05ba02016-01-12 10:54:43 -08002274 if(text instanceof SpannableStringBuilder) {
2275 return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2276 } else {
2277 return text.getSpans(start, end, type);
2278 }
Eric Fischer74d31ef2010-08-05 15:29:36 -07002279 }
2280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 private void ellipsize(int start, int end, int line,
Fabrice Di Meglio8d44fff2012-06-13 15:45:38 -07002282 char[] dest, int destoff, TextUtils.TruncateAt method) {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002283 final int ellipsisCount = getEllipsisCount(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 if (ellipsisCount == 0) {
2285 return;
2286 }
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002287 final int ellipsisStart = getEllipsisStart(line);
2288 final int lineStart = getLineStart(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002290 final String ellipsisString = TextUtils.getEllipsisString(method);
2291 final int ellipsisStringLen = ellipsisString.length();
Roozbeh Pournader1051bbe2017-07-25 13:52:57 -07002292 // Use the ellipsis string only if there are that at least as many characters to replace.
2293 final boolean useEllipsisString = ellipsisCount >= ellipsisStringLen;
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002294 for (int i = 0; i < ellipsisCount; i++) {
2295 final char c;
Roozbeh Pournader1051bbe2017-07-25 13:52:57 -07002296 if (useEllipsisString && i < ellipsisStringLen) {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002297 c = ellipsisString.charAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 } else {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002299 c = TextUtils.ELLIPSIS_FILLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300 }
2301
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002302 final int a = i + ellipsisStart + lineStart;
2303 if (start <= a && a < end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 dest[destoff + a - start] = c;
2305 }
2306 }
2307 }
2308
2309 /**
2310 * Stores information about bidirectional (left-to-right or right-to-left)
Doug Felt9f7a4442010-03-01 12:45:56 -08002311 * text within the layout of a line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 */
2313 public static class Directions {
Siyamed Sinired09ae12016-02-16 14:36:26 -08002314 /**
Petar Šegina7c31d5c2017-09-25 12:19:28 +01002315 * Directions represents directional runs within a line of text. Runs are pairs of ints
2316 * listed in visual order, starting from the leading margin. The first int of each pair is
2317 * the offset from the first character of the line to the start of the run. The second int
2318 * represents both the length and level of the run. The length is in the lower bits,
2319 * accessed by masking with RUN_LENGTH_MASK. The level is in the higher bits, accessed by
2320 * shifting by RUN_LEVEL_SHIFT and masking by RUN_LEVEL_MASK. To simply test for an RTL
2321 * direction, test the bit using RUN_RTL_FLAG, if set then the direction is rtl.
Siyamed Sinired09ae12016-02-16 14:36:26 -08002322 * @hide
2323 */
2324 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2325 public int[] mDirections;
2326
2327 /**
2328 * @hide
2329 */
2330 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2331 public Directions(int[] dirs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 mDirections = dirs;
2333 }
2334 }
2335
2336 /**
2337 * Return the offset of the first character to be ellipsized away,
2338 * relative to the start of the line. (So 0 if the beginning of the
2339 * line is ellipsized, not getLineStart().)
2340 */
2341 public abstract int getEllipsisStart(int line);
Doug Felte8e45f22010-03-29 14:58:40 -07002342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 /**
2344 * Returns the number of characters to be ellipsized away, or 0 if
2345 * no ellipsis is to take place.
2346 */
2347 public abstract int getEllipsisCount(int line);
2348
2349 /* package */ static class Ellipsizer implements CharSequence, GetChars {
2350 /* package */ CharSequence mText;
2351 /* package */ Layout mLayout;
2352 /* package */ int mWidth;
2353 /* package */ TextUtils.TruncateAt mMethod;
2354
2355 public Ellipsizer(CharSequence s) {
2356 mText = s;
2357 }
2358
2359 public char charAt(int off) {
2360 char[] buf = TextUtils.obtain(1);
2361 getChars(off, off + 1, buf, 0);
2362 char ret = buf[0];
2363
2364 TextUtils.recycle(buf);
2365 return ret;
2366 }
2367
2368 public void getChars(int start, int end, char[] dest, int destoff) {
2369 int line1 = mLayout.getLineForOffset(start);
2370 int line2 = mLayout.getLineForOffset(end);
2371
2372 TextUtils.getChars(mText, start, end, dest, destoff);
2373
2374 for (int i = line1; i <= line2; i++) {
Fabrice Di Meglio8d44fff2012-06-13 15:45:38 -07002375 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 }
2377 }
2378
2379 public int length() {
2380 return mText.length();
2381 }
Doug Felt9f7a4442010-03-01 12:45:56 -08002382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 public CharSequence subSequence(int start, int end) {
2384 char[] s = new char[end - start];
2385 getChars(start, end, s, 0);
2386 return new String(s);
2387 }
2388
Gilles Debunne162bf0f2010-11-16 16:23:53 -08002389 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 public String toString() {
2391 char[] s = new char[length()];
2392 getChars(0, length(), s, 0);
2393 return new String(s);
2394 }
2395
2396 }
2397
Gilles Debunne6c488de2012-03-01 16:20:35 -08002398 /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 private Spanned mSpanned;
2400
2401 public SpannedEllipsizer(CharSequence display) {
2402 super(display);
2403 mSpanned = (Spanned) display;
2404 }
2405
2406 public <T> T[] getSpans(int start, int end, Class<T> type) {
2407 return mSpanned.getSpans(start, end, type);
2408 }
2409
2410 public int getSpanStart(Object tag) {
2411 return mSpanned.getSpanStart(tag);
2412 }
2413
2414 public int getSpanEnd(Object tag) {
2415 return mSpanned.getSpanEnd(tag);
2416 }
2417
2418 public int getSpanFlags(Object tag) {
2419 return mSpanned.getSpanFlags(tag);
2420 }
2421
Gilles Debunne6c488de2012-03-01 16:20:35 -08002422 @SuppressWarnings("rawtypes")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 public int nextSpanTransition(int start, int limit, Class type) {
2424 return mSpanned.nextSpanTransition(start, limit, type);
2425 }
2426
Gilles Debunne162bf0f2010-11-16 16:23:53 -08002427 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 public CharSequence subSequence(int start, int end) {
2429 char[] s = new char[end - start];
2430 getChars(start, end, s, 0);
2431
2432 SpannableString ss = new SpannableString(new String(s));
2433 TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2434 return ss;
2435 }
2436 }
2437
2438 private CharSequence mText;
2439 private TextPaint mPaint;
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07002440 private TextPaint mWorkPaint = new TextPaint();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 private int mWidth;
2442 private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2443 private float mSpacingMult;
2444 private float mSpacingAdd;
Romain Guyc4d8eb62010-08-18 20:48:33 -07002445 private static final Rect sTempRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 private boolean mSpannedText;
Doug Feltcb3791202011-07-07 11:57:48 -07002447 private TextDirectionHeuristic mTextDir;
Gilles Debunneeca5b732012-04-25 18:48:42 -07002448 private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
Seigo Nonaka4b4730d2017-03-31 09:42:16 -07002449 private int mJustificationMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002451 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -07002452 @IntDef(prefix = { "DIR_" }, value = {
2453 DIR_LEFT_TO_RIGHT,
2454 DIR_RIGHT_TO_LEFT
2455 })
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002456 @Retention(RetentionPolicy.SOURCE)
2457 public @interface Direction {}
2458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 public static final int DIR_LEFT_TO_RIGHT = 1;
2460 public static final int DIR_RIGHT_TO_LEFT = -1;
Doug Felt9f7a4442010-03-01 12:45:56 -08002461
Doug Felt20178d62010-02-22 13:39:01 -08002462 /* package */ static final int DIR_REQUEST_LTR = 1;
2463 /* package */ static final int DIR_REQUEST_RTL = -1;
2464 /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2465 /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466
Doug Felt9f7a4442010-03-01 12:45:56 -08002467 /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2468 /* package */ static final int RUN_LEVEL_SHIFT = 26;
2469 /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2470 /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 public enum Alignment {
2473 ALIGN_NORMAL,
2474 ALIGN_OPPOSITE,
2475 ALIGN_CENTER,
Doug Feltc0ccf0c2011-06-23 16:13:18 -07002476 /** @hide */
2477 ALIGN_LEFT,
2478 /** @hide */
2479 ALIGN_RIGHT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 }
2481
2482 private static final int TAB_INCREMENT = 20;
2483
Siyamed Sinired09ae12016-02-16 14:36:26 -08002484 /** @hide */
2485 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2486 public static final Directions DIRS_ALL_LEFT_TO_RIGHT =
Doug Felt9f7a4442010-03-01 12:45:56 -08002487 new Directions(new int[] { 0, RUN_LENGTH_MASK });
Siyamed Sinired09ae12016-02-16 14:36:26 -08002488
2489 /** @hide */
2490 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2491 public static final Directions DIRS_ALL_RIGHT_TO_LEFT =
Doug Felt9f7a4442010-03-01 12:45:56 -08002492 new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });
Gilles Debunne0a4db3c2011-01-14 12:12:04 -08002493
Petar Šeginafb748b32017-08-07 12:37:52 +01002494 /** @hide */
Petar Šeginab92c5392017-09-06 15:25:05 +01002495 @Retention(RetentionPolicy.SOURCE)
Jeff Sharkeyce8db992017-12-13 20:05:05 -07002496 @IntDef(prefix = { "TEXT_SELECTION_LAYOUT_" }, value = {
2497 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT,
2498 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT
2499 })
Petar Šegina3a92fb62017-09-07 21:03:24 +01002500 public @interface TextSelectionLayout {}
2501
2502 /** @hide */
2503 public static final int TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT = 0;
2504 /** @hide */
2505 public static final int TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT = 1;
Petar Šeginab92c5392017-09-06 15:25:05 +01002506
2507 /** @hide */
Petar Šeginafb748b32017-08-07 12:37:52 +01002508 @FunctionalInterface
Petar Šeginab92c5392017-09-06 15:25:05 +01002509 public interface SelectionRectangleConsumer {
Petar Šeginafb748b32017-08-07 12:37:52 +01002510 /**
2511 * Performs this operation on the given rectangle.
2512 *
2513 * @param left the left edge of the rectangle
2514 * @param top the top edge of the rectangle
2515 * @param right the right edge of the rectangle
2516 * @param bottom the bottom edge of the rectangle
Petar Šeginab92c5392017-09-06 15:25:05 +01002517 * @param textSelectionLayout the layout (RTL or LTR) of the text covered by this
2518 * selection rectangle
Petar Šeginafb748b32017-08-07 12:37:52 +01002519 */
Petar Šeginab92c5392017-09-06 15:25:05 +01002520 void accept(float left, float top, float right, float bottom,
2521 @TextSelectionLayout int textSelectionLayout);
Petar Šeginafb748b32017-08-07 12:37:52 +01002522 }
2523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524}