blob: 92f7a47a1e60740ec60d38f87fd449e2aa1d49dd [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 {
Seigo Nonaka4e90fa22018-02-13 21:40:01 +0000565 tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops);
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900566 if (justify) {
567 tl.justify(right - left - indentWidth);
568 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800569 tl.draw(canvas, x, ltop, lbaseline, lbottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 }
571 }
Doug Feltc982f602010-05-25 11:51:40 -0700572
Doug Felte8e45f22010-03-29 14:58:40 -0700573 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 }
575
576 /**
Gilles Debunne6c488de2012-03-01 16:20:35 -0800577 * @hide
578 */
579 public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
580 int cursorOffsetVertical, int firstLine, int lastLine) {
581 // First, draw LineBackgroundSpans.
582 // LineBackgroundSpans know nothing about the alignment, margins, or
583 // direction of the layout or line. XXX: Should they?
584 // They are evaluated at each line.
585 if (mSpannedText) {
Gilles Debunneeca5b732012-04-25 18:48:42 -0700586 if (mLineBackgroundSpans == null) {
587 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700588 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800589
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700590 Spanned buffer = (Spanned) mText;
591 int textLength = buffer.length();
Gilles Debunneeca5b732012-04-25 18:48:42 -0700592 mLineBackgroundSpans.init(buffer, 0, textLength);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800593
Gilles Debunneeca5b732012-04-25 18:48:42 -0700594 if (mLineBackgroundSpans.numberOfSpans > 0) {
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700595 int previousLineBottom = getLineTop(firstLine);
596 int previousLineEnd = getLineStart(firstLine);
597 ParagraphStyle[] spans = NO_PARA_SPANS;
598 int spansLength = 0;
599 TextPaint paint = mPaint;
600 int spanEnd = 0;
601 final int width = mWidth;
602 for (int i = firstLine; i <= lastLine; i++) {
603 int start = previousLineEnd;
604 int end = getLineStart(i + 1);
605 previousLineEnd = end;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800606
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700607 int ltop = previousLineBottom;
608 int lbottom = getLineTop(i + 1);
609 previousLineBottom = lbottom;
610 int lbaseline = lbottom - getLineDescent(i);
611
612 if (start >= spanEnd) {
613 // These should be infrequent, so we'll use this so that
614 // we don't have to check as often.
Gilles Debunneeca5b732012-04-25 18:48:42 -0700615 spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700616 // All LineBackgroundSpans on a line contribute to its background.
617 spansLength = 0;
618 // Duplication of the logic of getParagraphSpans
619 if (start != end || start == 0) {
620 // Equivalent to a getSpans(start, end), but filling the 'spans' local
621 // array instead to reduce memory allocation
Gilles Debunneeca5b732012-04-25 18:48:42 -0700622 for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
623 // equal test is valid since both intervals are not empty by
624 // construction
625 if (mLineBackgroundSpans.spanStarts[j] >= end ||
626 mLineBackgroundSpans.spanEnds[j] <= start) continue;
Adam Lesinski776abc22014-03-07 11:30:59 -0500627 spans = GrowingArrayUtils.append(
628 spans, spansLength, mLineBackgroundSpans.spans[j]);
629 spansLength++;
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700630 }
631 }
632 }
633
634 for (int n = 0; n < spansLength; n++) {
635 LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
636 lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
637 ltop, lbaseline, lbottom,
638 buffer, start, end, i);
639 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800640 }
641 }
Gilles Debunneeca5b732012-04-25 18:48:42 -0700642 mLineBackgroundSpans.recycle();
Gilles Debunne6c488de2012-03-01 16:20:35 -0800643 }
644
645 // There can be a highlight even without spans if we are drawing
646 // a non-spanned transformation of a spanned editing buffer.
647 if (highlight != null) {
648 if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
649 canvas.drawPath(highlight, highlightPaint);
650 if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
651 }
652 }
653
654 /**
655 * @param canvas
656 * @return The range of lines that need to be drawn, possibly empty.
657 * @hide
658 */
659 public long getLineRangeForDraw(Canvas canvas) {
660 int dtop, dbottom;
661
662 synchronized (sTempRect) {
663 if (!canvas.getClipBounds(sTempRect)) {
664 // Negative range end used as a special flag
665 return TextUtils.packRangeInLong(0, -1);
666 }
667
668 dtop = sTempRect.top;
669 dbottom = sTempRect.bottom;
670 }
671
672 final int top = Math.max(dtop, 0);
673 final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
674
Gilles Debunne2fba3382012-06-11 17:46:24 -0700675 if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800676 return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
677 }
678
679 /**
Doug Feltc982f602010-05-25 11:51:40 -0700680 * Return the start position of the line, given the left and right bounds
681 * of the margins.
Doug Felt0c702b82010-05-14 10:55:42 -0700682 *
Doug Feltc982f602010-05-25 11:51:40 -0700683 * @param line the line index
684 * @param left the left bounds (0, or leading margin if ltr para)
685 * @param right the right bounds (width, minus leading margin if rtl para)
686 * @return the start position of the line (to right of line if rtl para)
687 */
688 private int getLineStartPos(int line, int left, int right) {
689 // Adjust the point at which to start rendering depending on the
690 // alignment of the paragraph.
691 Alignment align = getParagraphAlignment(line);
692 int dir = getParagraphDirection(line);
693
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700694 if (align == Alignment.ALIGN_LEFT) {
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700695 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
696 } else if (align == Alignment.ALIGN_RIGHT) {
697 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
698 }
699
700 int x;
701 if (align == Alignment.ALIGN_NORMAL) {
Doug Feltc982f602010-05-25 11:51:40 -0700702 if (dir == DIR_LEFT_TO_RIGHT) {
Raph Levien2ea52902015-07-01 14:39:31 -0700703 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
Doug Feltc982f602010-05-25 11:51:40 -0700704 } else {
Raph Levien2ea52902015-07-01 14:39:31 -0700705 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
Doug Feltc982f602010-05-25 11:51:40 -0700706 }
707 } else {
708 TabStops tabStops = null;
709 if (mSpannedText && getLineContainsTab(line)) {
710 Spanned spanned = (Spanned) mText;
711 int start = getLineStart(line);
712 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
713 TabStopSpan.class);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800714 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
715 TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -0700716 if (tabSpans.length > 0) {
717 tabStops = new TabStops(TAB_INCREMENT, tabSpans);
718 }
719 }
720 int max = (int)getLineExtent(line, tabStops, false);
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700721 if (align == Alignment.ALIGN_OPPOSITE) {
Doug Feltc982f602010-05-25 11:51:40 -0700722 if (dir == DIR_LEFT_TO_RIGHT) {
Raph Levien2ea52902015-07-01 14:39:31 -0700723 x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
Doug Feltc982f602010-05-25 11:51:40 -0700724 } else {
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700725 // max is negative here
Raph Levien2ea52902015-07-01 14:39:31 -0700726 x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
Doug Feltc982f602010-05-25 11:51:40 -0700727 }
728 } else { // Alignment.ALIGN_CENTER
729 max = max & ~1;
Raph Levien2ea52902015-07-01 14:39:31 -0700730 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
Doug Feltc982f602010-05-25 11:51:40 -0700731 }
732 }
733 return x;
734 }
735
736 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 * Return the text that is displayed by this Layout.
738 */
739 public final CharSequence getText() {
740 return mText;
741 }
742
743 /**
744 * Return the base Paint properties for this layout.
745 * Do NOT change the paint, which may result in funny
746 * drawing for this layout.
747 */
748 public final TextPaint getPaint() {
749 return mPaint;
750 }
751
752 /**
753 * Return the width of this layout.
754 */
755 public final int getWidth() {
756 return mWidth;
757 }
758
759 /**
760 * Return the width to which this Layout is ellipsizing, or
761 * {@link #getWidth} if it is not doing anything special.
762 */
763 public int getEllipsizedWidth() {
764 return mWidth;
765 }
766
767 /**
768 * Increase the width of this layout to the specified width.
Doug Felt71b8dd72010-02-16 17:27:09 -0800769 * Be careful to use this only when you know it is appropriate&mdash;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 * it does not cause the text to reflow to use the full new width.
771 */
772 public final void increaseWidthTo(int wid) {
773 if (wid < mWidth) {
774 throw new RuntimeException("attempted to reduce Layout width");
775 }
776
777 mWidth = wid;
778 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 /**
781 * Return the total height of this layout.
782 */
783 public int getHeight() {
Doug Felt71b8dd72010-02-16 17:27:09 -0800784 return getLineTop(getLineCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 }
786
787 /**
Siyamed Sinir0745c722016-05-31 20:39:33 -0700788 * Return the total height of this layout.
789 *
790 * @param cap if true and max lines is set, returns the height of the layout at the max lines.
791 *
792 * @hide
793 */
794 public int getHeight(boolean cap) {
795 return getHeight();
796 }
797
798 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 * Return the base alignment of this layout.
800 */
801 public final Alignment getAlignment() {
802 return mAlignment;
803 }
804
805 /**
806 * Return what the text height is multiplied by to get the line height.
807 */
808 public final float getSpacingMultiplier() {
809 return mSpacingMult;
810 }
811
812 /**
813 * Return the number of units of leading that are added to each line.
814 */
815 public final float getSpacingAdd() {
816 return mSpacingAdd;
817 }
818
819 /**
Doug Feltcb3791202011-07-07 11:57:48 -0700820 * Return the heuristic used to determine paragraph text direction.
821 * @hide
822 */
823 public final TextDirectionHeuristic getTextDirectionHeuristic() {
824 return mTextDir;
825 }
826
827 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 * Return the number of lines of text in this layout.
829 */
830 public abstract int getLineCount();
Doug Felt9f7a4442010-03-01 12:45:56 -0800831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 /**
833 * Return the baseline for the specified line (0&hellip;getLineCount() - 1)
834 * If bounds is not null, return the top, left, right, bottom extents
835 * of the specified line in it.
836 * @param line which line to examine (0..getLineCount() - 1)
837 * @param bounds Optional. If not null, it returns the extent of the line
838 * @return the Y-coordinate of the baseline
839 */
840 public int getLineBounds(int line, Rect bounds) {
841 if (bounds != null) {
842 bounds.left = 0; // ???
843 bounds.top = getLineTop(line);
844 bounds.right = mWidth; // ???
Doug Felt71b8dd72010-02-16 17:27:09 -0800845 bounds.bottom = getLineTop(line + 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 }
847 return getLineBaseline(line);
848 }
849
850 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800851 * Return the vertical position of the top of the specified line
852 * (0&hellip;getLineCount()).
853 * If the specified line is equal to the line count, returns the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 * bottom of the last line.
855 */
856 public abstract int getLineTop(int line);
857
858 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800859 * Return the descent of the specified line(0&hellip;getLineCount() - 1).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 */
861 public abstract int getLineDescent(int line);
862
863 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800864 * Return the text offset of the beginning of the specified line (
865 * 0&hellip;getLineCount()). If the specified line is equal to the line
866 * count, returns the length of the text.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 */
868 public abstract int getLineStart(int line);
869
870 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800871 * Returns the primary directionality of the paragraph containing the
872 * specified line, either 1 for left-to-right lines, or -1 for right-to-left
873 * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 */
875 public abstract int getParagraphDirection(int line);
876
877 /**
The Android Open Source Project10592532009-03-18 17:39:46 -0700878 * Returns whether the specified line contains one or more
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700879 * characters that need to be handled specially, like tabs.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 */
881 public abstract boolean getLineContainsTab(int line);
882
883 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800884 * Returns the directional run information for the specified line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 * The array alternates counts of characters in left-to-right
886 * and right-to-left segments of the line.
Doug Felt71b8dd72010-02-16 17:27:09 -0800887 *
888 * <p>NOTE: this is inadequate to support bidirectional text, and will change.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 */
890 public abstract Directions getLineDirections(int line);
891
892 /**
893 * Returns the (negative) number of extra pixels of ascent padding in the
894 * top line of the Layout.
895 */
896 public abstract int getTopPadding();
897
898 /**
899 * Returns the number of extra pixels of descent padding in the
900 * bottom line of the Layout.
901 */
902 public abstract int getBottomPadding();
903
Raph Levien26d443a2015-03-30 14:18:32 -0700904 /**
905 * Returns the hyphen edit for a line.
906 *
907 * @hide
908 */
909 public int getHyphen(int line) {
910 return 0;
911 }
912
Raph Levien2ea52902015-07-01 14:39:31 -0700913 /**
914 * Returns the left indent for a line.
915 *
916 * @hide
917 */
918 public int getIndentAdjust(int line, Alignment alignment) {
919 return 0;
920 }
Doug Felt4e0c5e52010-03-15 16:56:02 -0700921
922 /**
923 * Returns true if the character at offset and the preceding character
924 * are at different run levels (and thus there's a split caret).
925 * @param offset the offset
926 * @return true if at a level boundary
Gilles Debunnef75c97e2011-02-10 16:09:53 -0800927 * @hide
Doug Felt4e0c5e52010-03-15 16:56:02 -0700928 */
Gilles Debunnef75c97e2011-02-10 16:09:53 -0800929 public boolean isLevelBoundary(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -0800930 int line = getLineForOffset(offset);
Doug Felt4e0c5e52010-03-15 16:56:02 -0700931 Directions dirs = getLineDirections(line);
932 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
933 return false;
934 }
935
936 int[] runs = dirs.mDirections;
Doug Felt9f7a4442010-03-01 12:45:56 -0800937 int lineStart = getLineStart(line);
Doug Felt4e0c5e52010-03-15 16:56:02 -0700938 int lineEnd = getLineEnd(line);
939 if (offset == lineStart || offset == lineEnd) {
940 int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
941 int runIndex = offset == lineStart ? 0 : runs.length - 2;
942 return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
943 }
944
945 offset -= lineStart;
Doug Felt9f7a4442010-03-01 12:45:56 -0800946 for (int i = 0; i < runs.length; i += 2) {
Doug Felt4e0c5e52010-03-15 16:56:02 -0700947 if (offset == runs[i]) {
948 return true;
Doug Felt9f7a4442010-03-01 12:45:56 -0800949 }
950 }
Doug Felt4e0c5e52010-03-15 16:56:02 -0700951 return false;
Doug Felt9f7a4442010-03-01 12:45:56 -0800952 }
953
Fabrice Di Meglio34d2eba2011-08-31 19:46:15 -0700954 /**
955 * Returns true if the character at offset is right to left (RTL).
956 * @param offset the offset
957 * @return true if the character is RTL, false if it is LTR
958 */
959 public boolean isRtlCharAt(int offset) {
960 int line = getLineForOffset(offset);
961 Directions dirs = getLineDirections(line);
962 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
963 return false;
964 }
965 if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
966 return true;
967 }
968 int[] runs = dirs.mDirections;
969 int lineStart = getLineStart(line);
970 for (int i = 0; i < runs.length; i += 2) {
Raph Levien87506202014-09-04 12:47:03 -0700971 int start = lineStart + runs[i];
972 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
973 if (offset >= start && offset < limit) {
Fabrice Di Meglio34d2eba2011-08-31 19:46:15 -0700974 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
975 return ((level & 1) != 0);
976 }
977 }
978 // Should happen only if the offset is "out of bounds"
979 return false;
980 }
981
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +0900982 /**
983 * Returns the range of the run that the character at offset belongs to.
984 * @param offset the offset
985 * @return The range of the run
986 * @hide
987 */
988 public long getRunRange(int offset) {
989 int line = getLineForOffset(offset);
990 Directions dirs = getLineDirections(line);
991 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
992 return TextUtils.packRangeInLong(0, getLineEnd(line));
993 }
994 int[] runs = dirs.mDirections;
995 int lineStart = getLineStart(line);
996 for (int i = 0; i < runs.length; i += 2) {
997 int start = lineStart + runs[i];
998 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
999 if (offset >= start && offset < limit) {
1000 return TextUtils.packRangeInLong(start, limit);
1001 }
1002 }
1003 // Should happen only if the offset is "out of bounds"
1004 return TextUtils.packRangeInLong(0, getLineEnd(line));
1005 }
1006
Mihai Popa7626c862018-05-09 17:31:48 +01001007 /**
1008 * Checks if the trailing BiDi level should be used for an offset
1009 *
1010 * This method is useful when the offset is at the BiDi level transition point and determine
1011 * which run need to be used. For example, let's think about following input: (L* denotes
1012 * Left-to-Right characters, R* denotes Right-to-Left characters.)
1013 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1014 * Input (Display Order): L1 L2 L3 R3 R2 R1 L4 L5 L6
1015 *
1016 * Then, think about selecting the range (3, 6). The offset=3 and offset=6 are ambiguous here
1017 * since they are at the BiDi transition point. In Android, the offset is considered to be
1018 * associated with the trailing run if the BiDi level of the trailing run is higher than of the
1019 * previous run. In this case, the BiDi level of the input text is as follows:
1020 *
1021 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1022 * BiDi Run: [ Run 0 ][ Run 1 ][ Run 2 ]
1023 * BiDi Level: 0 0 0 1 1 1 0 0 0
1024 *
1025 * Thus, offset = 3 is part of Run 1 and this method returns true for offset = 3, since the BiDi
1026 * level of Run 1 is higher than the level of Run 0. Similarly, the offset = 6 is a part of Run
1027 * 1 and this method returns false for the offset = 6 since the BiDi level of Run 1 is higher
1028 * than the level of Run 2.
1029 *
1030 * @returns true if offset is at the BiDi level transition point and trailing BiDi level is
1031 * higher than previous BiDi level. See above for the detail.
1032 * @hide
1033 */
Seigo Nonaka19e75a62018-05-16 16:57:33 -07001034 @VisibleForTesting
1035 public boolean primaryIsTrailingPrevious(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001036 int line = getLineForOffset(offset);
1037 int lineStart = getLineStart(line);
Doug Felt4e0c5e52010-03-15 16:56:02 -07001038 int lineEnd = getLineEnd(line);
Doug Felt9f7a4442010-03-01 12:45:56 -08001039 int[] runs = getLineDirections(line).mDirections;
1040
1041 int levelAt = -1;
1042 for (int i = 0; i < runs.length; i += 2) {
1043 int start = lineStart + runs[i];
1044 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1045 if (limit > lineEnd) {
1046 limit = lineEnd;
1047 }
1048 if (offset >= start && offset < limit) {
1049 if (offset > start) {
1050 // Previous character is at same level, so don't use trailing.
1051 return false;
1052 }
1053 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1054 break;
1055 }
1056 }
1057 if (levelAt == -1) {
1058 // Offset was limit of line.
1059 levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
1060 }
1061
1062 // At level boundary, check previous level.
1063 int levelBefore = -1;
1064 if (offset == lineStart) {
1065 levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
1066 } else {
1067 offset -= 1;
1068 for (int i = 0; i < runs.length; i += 2) {
1069 int start = lineStart + runs[i];
1070 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1071 if (limit > lineEnd) {
1072 limit = lineEnd;
1073 }
1074 if (offset >= start && offset < limit) {
1075 levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1076 break;
1077 }
1078 }
1079 }
1080
1081 return levelBefore < levelAt;
1082 }
1083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001085 * Computes in linear time the results of calling
1086 * #primaryIsTrailingPrevious for all offsets on a line.
1087 * @param line The line giving the offsets we compute the information for
1088 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1089 * @hide
1090 */
1091 @VisibleForTesting
1092 public boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
1093 int lineStart = getLineStart(line);
1094 int lineEnd = getLineEnd(line);
1095 int[] runs = getLineDirections(line).mDirections;
1096
1097 boolean[] trailing = new boolean[lineEnd - lineStart + 1];
1098
1099 byte[] level = new byte[lineEnd - lineStart + 1];
1100 for (int i = 0; i < runs.length; i += 2) {
1101 int start = lineStart + runs[i];
1102 int limit = start + (runs[i + 1] & RUN_LENGTH_MASK);
1103 if (limit > lineEnd) {
1104 limit = lineEnd;
1105 }
1106 level[limit - lineStart - 1] =
1107 (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1108 }
1109
1110 for (int i = 0; i < runs.length; i += 2) {
1111 int start = lineStart + runs[i];
1112 byte currentLevel = (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1113 trailing[start - lineStart] = currentLevel > (start == lineStart
1114 ? (getParagraphDirection(line) == 1 ? 0 : 1)
1115 : level[start - lineStart - 1]);
1116 }
1117
1118 return trailing;
1119 }
1120
1121 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 * Get the primary horizontal position for the specified text offset.
1123 * This is the location where a new character would be inserted in
1124 * the paragraph's primary direction.
1125 */
1126 public float getPrimaryHorizontal(int offset) {
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001127 return getPrimaryHorizontal(offset, false /* not clamped */);
Raph Levienafe8e9b2012-12-19 16:09:32 -08001128 }
1129
1130 /**
1131 * Get the primary horizontal position for the specified text offset, but
1132 * optionally clamp it so that it doesn't exceed the width of the layout.
1133 * @hide
1134 */
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001135 public float getPrimaryHorizontal(int offset, boolean clamped) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001136 boolean trailing = primaryIsTrailingPrevious(offset);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001137 return getHorizontal(offset, trailing, clamped);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139
1140 /**
1141 * Get the secondary horizontal position for the specified text offset.
1142 * This is the location where a new character would be inserted in
1143 * the direction other than the paragraph's primary direction.
1144 */
1145 public float getSecondaryHorizontal(int offset) {
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001146 return getSecondaryHorizontal(offset, false /* not clamped */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
1148
Raph Levienafe8e9b2012-12-19 16:09:32 -08001149 /**
1150 * Get the secondary horizontal position for the specified text offset, but
1151 * optionally clamp it so that it doesn't exceed the width of the layout.
1152 * @hide
1153 */
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001154 public float getSecondaryHorizontal(int offset, boolean clamped) {
Raph Levienafe8e9b2012-12-19 16:09:32 -08001155 boolean trailing = primaryIsTrailingPrevious(offset);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001156 return getHorizontal(offset, !trailing, clamped);
Raph Levienafe8e9b2012-12-19 16:09:32 -08001157 }
1158
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001159 private float getHorizontal(int offset, boolean primary) {
1160 return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09001161 }
1162
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001163 private float getHorizontal(int offset, boolean trailing, boolean clamped) {
1164 int line = getLineForOffset(offset);
1165
Raph Levienafe8e9b2012-12-19 16:09:32 -08001166 return getHorizontal(offset, trailing, line, clamped);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
1168
Raph Levienafe8e9b2012-12-19 16:09:32 -08001169 private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 int start = getLineStart(line);
Doug Felte8e45f22010-03-29 14:58:40 -07001171 int end = getLineEnd(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 int dir = getParagraphDirection(line);
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001173 boolean hasTab = getLineContainsTab(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 Directions directions = getLineDirections(line);
1175
Doug Feltc982f602010-05-25 11:51:40 -07001176 TabStops tabStops = null;
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001177 if (hasTab && mText instanceof Spanned) {
Doug Feltc982f602010-05-25 11:51:40 -07001178 // Just checking this line should be good enough, tabs should be
1179 // consistent across all lines in a paragraph.
Eric Fischer74d31ef2010-08-05 15:29:36 -07001180 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -07001181 if (tabs.length > 0) {
1182 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185
Doug Felte8e45f22010-03-29 14:58:40 -07001186 TextLine tl = TextLine.obtain();
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001187 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
Doug Felte8e45f22010-03-29 14:58:40 -07001188 float wid = tl.measure(offset - start, trailing, null);
1189 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190
Raph Levienafe8e9b2012-12-19 16:09:32 -08001191 if (clamped && wid > mWidth) {
1192 wid = mWidth;
1193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 int left = getParagraphLeft(line);
1195 int right = getParagraphRight(line);
1196
Doug Feltc982f602010-05-25 11:51:40 -07001197 return getLineStartPos(line, left, right) + wid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
1199
1200 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001201 * Computes in linear time the results of calling
1202 * #getHorizontal for all offsets on a line.
1203 * @param line The line giving the offsets we compute information for
1204 * @param clamped Whether to clamp the results to the width of the layout
1205 * @param primary Whether the results should be the primary or the secondary horizontal
1206 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1207 */
1208 private float[] getLineHorizontals(int line, boolean clamped, boolean primary) {
1209 int start = getLineStart(line);
1210 int end = getLineEnd(line);
1211 int dir = getParagraphDirection(line);
1212 boolean hasTab = getLineContainsTab(line);
1213 Directions directions = getLineDirections(line);
1214
1215 TabStops tabStops = null;
1216 if (hasTab && mText instanceof Spanned) {
1217 // Just checking this line should be good enough, tabs should be
1218 // consistent across all lines in a paragraph.
1219 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1220 if (tabs.length > 0) {
1221 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1222 }
1223 }
1224
1225 TextLine tl = TextLine.obtain();
1226 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops);
1227 boolean[] trailings = primaryIsTrailingPreviousAllLineOffsets(line);
1228 if (!primary) {
1229 for (int offset = 0; offset < trailings.length; ++offset) {
1230 trailings[offset] = !trailings[offset];
1231 }
1232 }
1233 float[] wid = tl.measureAllOffsets(trailings, null);
1234 TextLine.recycle(tl);
1235
1236 if (clamped) {
1237 for (int offset = 0; offset <= wid.length; ++offset) {
1238 if (wid[offset] > mWidth) {
1239 wid[offset] = mWidth;
1240 }
1241 }
1242 }
1243 int left = getParagraphLeft(line);
1244 int right = getParagraphRight(line);
1245
1246 int lineStartPos = getLineStartPos(line, left, right);
1247 float[] horizontal = new float[end - start + 1];
1248 for (int offset = 0; offset < horizontal.length; ++offset) {
1249 horizontal[offset] = lineStartPos + wid[offset];
1250 }
1251 return horizontal;
1252 }
1253
1254 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 * Get the leftmost position that should be exposed for horizontal
1256 * scrolling on the specified line.
1257 */
1258 public float getLineLeft(int line) {
1259 int dir = getParagraphDirection(line);
1260 Alignment align = getParagraphAlignment(line);
1261
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001262 if (align == Alignment.ALIGN_LEFT) {
1263 return 0;
1264 } else if (align == Alignment.ALIGN_NORMAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 if (dir == DIR_RIGHT_TO_LEFT)
1266 return getParagraphRight(line) - getLineMax(line);
1267 else
1268 return 0;
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001269 } else if (align == Alignment.ALIGN_RIGHT) {
1270 return mWidth - getLineMax(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 } else if (align == Alignment.ALIGN_OPPOSITE) {
1272 if (dir == DIR_RIGHT_TO_LEFT)
1273 return 0;
1274 else
1275 return mWidth - getLineMax(line);
1276 } else { /* align == Alignment.ALIGN_CENTER */
1277 int left = getParagraphLeft(line);
1278 int right = getParagraphRight(line);
1279 int max = ((int) getLineMax(line)) & ~1;
1280
1281 return left + ((right - left) - max) / 2;
1282 }
1283 }
1284
1285 /**
1286 * Get the rightmost position that should be exposed for horizontal
1287 * scrolling on the specified line.
1288 */
1289 public float getLineRight(int line) {
1290 int dir = getParagraphDirection(line);
1291 Alignment align = getParagraphAlignment(line);
1292
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001293 if (align == Alignment.ALIGN_LEFT) {
1294 return getParagraphLeft(line) + getLineMax(line);
1295 } else if (align == Alignment.ALIGN_NORMAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 if (dir == DIR_RIGHT_TO_LEFT)
1297 return mWidth;
1298 else
1299 return getParagraphLeft(line) + getLineMax(line);
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001300 } else if (align == Alignment.ALIGN_RIGHT) {
1301 return mWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 } else if (align == Alignment.ALIGN_OPPOSITE) {
1303 if (dir == DIR_RIGHT_TO_LEFT)
1304 return getLineMax(line);
1305 else
1306 return mWidth;
1307 } else { /* align == Alignment.ALIGN_CENTER */
1308 int left = getParagraphLeft(line);
1309 int right = getParagraphRight(line);
1310 int max = ((int) getLineMax(line)) & ~1;
1311
1312 return right - ((right - left) - max) / 2;
1313 }
1314 }
1315
1316 /**
Doug Felt0c702b82010-05-14 10:55:42 -07001317 * Gets the unsigned horizontal extent of the specified line, including
Doug Feltc982f602010-05-25 11:51:40 -07001318 * leading margin indent, but excluding trailing whitespace.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 */
1320 public float getLineMax(int line) {
Doug Feltc982f602010-05-25 11:51:40 -07001321 float margin = getParagraphLeadingMargin(line);
1322 float signedExtent = getLineExtent(line, false);
Anish Athalyec14b3ad2014-07-24 18:03:21 -07001323 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325
1326 /**
Doug Feltc982f602010-05-25 11:51:40 -07001327 * Gets the unsigned horizontal extent of the specified line, including
1328 * leading margin indent and trailing whitespace.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 */
1330 public float getLineWidth(int line) {
Doug Feltc982f602010-05-25 11:51:40 -07001331 float margin = getParagraphLeadingMargin(line);
1332 float signedExtent = getLineExtent(line, true);
Anish Athalyec14b3ad2014-07-24 18:03:21 -07001333 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 }
1335
Doug Feltc982f602010-05-25 11:51:40 -07001336 /**
1337 * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1338 * tab stops instead of using the ones passed in.
1339 * @param line the index of the line
1340 * @param full whether to include trailing whitespace
1341 * @return the extent of the line
1342 */
1343 private float getLineExtent(int line, boolean full) {
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001344 final int start = getLineStart(line);
1345 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
Doug Feltc982f602010-05-25 11:51:40 -07001346
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001347 final boolean hasTabs = getLineContainsTab(line);
Doug Feltc982f602010-05-25 11:51:40 -07001348 TabStops tabStops = null;
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001349 if (hasTabs && mText instanceof Spanned) {
Doug Feltc982f602010-05-25 11:51:40 -07001350 // Just checking this line should be good enough, tabs should be
1351 // consistent across all lines in a paragraph.
Eric Fischer74d31ef2010-08-05 15:29:36 -07001352 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -07001353 if (tabs.length > 0) {
1354 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1355 }
1356 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001357 final Directions directions = getLineDirections(line);
Fabrice Di Meglio8059e0902011-08-10 16:31:58 -07001358 // Returned directions can actually be null
1359 if (directions == null) {
1360 return 0f;
1361 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001362 final int dir = getParagraphDirection(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001364 final TextLine tl = TextLine.obtain();
1365 final TextPaint paint = mWorkPaint;
1366 paint.set(mPaint);
1367 paint.setHyphenEdit(getHyphen(line));
Roozbeh Pournader53aba292017-08-25 15:53:33 -07001368 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops);
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001369 if (isJustificationRequired(line)) {
1370 tl.justify(getJustifyWidth(line));
1371 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001372 final float width = tl.metrics(null);
Doug Feltc982f602010-05-25 11:51:40 -07001373 TextLine.recycle(tl);
1374 return width;
1375 }
1376
1377 /**
1378 * Returns the signed horizontal extent of the specified line, excluding
1379 * leading margin. If full is false, excludes trailing whitespace.
1380 * @param line the index of the line
1381 * @param tabStops the tab stops, can be null if we know they're not used.
1382 * @param full whether to include trailing whitespace
1383 * @return the extent of the text on this line
1384 */
1385 private float getLineExtent(int line, TabStops tabStops, boolean full) {
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001386 final int start = getLineStart(line);
1387 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1388 final boolean hasTabs = getLineContainsTab(line);
1389 final Directions directions = getLineDirections(line);
1390 final int dir = getParagraphDirection(line);
Doug Feltc982f602010-05-25 11:51:40 -07001391
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001392 final TextLine tl = TextLine.obtain();
1393 final TextPaint paint = mWorkPaint;
1394 paint.set(mPaint);
1395 paint.setHyphenEdit(getHyphen(line));
Roozbeh Pournader53aba292017-08-25 15:53:33 -07001396 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops);
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001397 if (isJustificationRequired(line)) {
1398 tl.justify(getJustifyWidth(line));
1399 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001400 final float width = tl.metrics(null);
Doug Felte8e45f22010-03-29 14:58:40 -07001401 TextLine.recycle(tl);
1402 return width;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404
1405 /**
1406 * Get the line number corresponding to the specified vertical position.
1407 * If you ask for a position above 0, you get 0; if you ask for a position
1408 * below the bottom of the text, you get the last line.
1409 */
1410 // FIXME: It may be faster to do a linear search for layouts without many lines.
1411 public int getLineForVertical(int vertical) {
1412 int high = getLineCount(), low = -1, guess;
1413
1414 while (high - low > 1) {
1415 guess = (high + low) / 2;
1416
1417 if (getLineTop(guess) > vertical)
1418 high = guess;
1419 else
1420 low = guess;
1421 }
1422
1423 if (low < 0)
1424 return 0;
1425 else
1426 return low;
1427 }
1428
1429 /**
1430 * Get the line number on which the specified text offset appears.
1431 * If you ask for a position before 0, you get 0; if you ask for a position
1432 * beyond the end of the text, you get the last line.
1433 */
1434 public int getLineForOffset(int offset) {
1435 int high = getLineCount(), low = -1, guess;
1436
1437 while (high - low > 1) {
1438 guess = (high + low) / 2;
1439
1440 if (getLineStart(guess) > offset)
1441 high = guess;
1442 else
1443 low = guess;
1444 }
1445
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001446 if (low < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 return 0;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001448 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 return low;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 }
1452
1453 /**
Doug Felt9f7a4442010-03-01 12:45:56 -08001454 * Get the character offset on the specified line whose position is
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 * closest to the specified horizontal position.
1456 */
1457 public int getOffsetForHorizontal(int line, float horiz) {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09001458 return getOffsetForHorizontal(line, horiz, true);
1459 }
1460
1461 /**
1462 * Get the character offset on the specified line whose position is
1463 * closest to the specified horizontal position.
1464 *
1465 * @param line the line used to find the closest offset
1466 * @param horiz the horizontal position used to find the closest offset
1467 * @param primary whether to use the primary position or secondary position to find the offset
1468 *
1469 * @hide
1470 */
1471 public int getOffsetForHorizontal(int line, float horiz, boolean primary) {
Raph Levienedb27f12015-06-01 14:34:47 -07001472 // TODO: use Paint.getOffsetForAdvance to avoid binary search
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001473 final int lineEndOffset = getLineEnd(line);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001474 final int lineStartOffset = getLineStart(line);
1475
1476 Directions dirs = getLineDirections(line);
1477
1478 TextLine tl = TextLine.obtain();
1479 // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1480 tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
1481 false, null);
Mihai Popa7626c862018-05-09 17:31:48 +01001482 final HorizontalMeasurementProvider horizontal =
1483 new HorizontalMeasurementProvider(line, primary);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001484
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001485 final int max;
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001486 if (line == getLineCount() - 1) {
1487 max = lineEndOffset;
1488 } else {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001489 max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1490 !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001491 }
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001492 int best = lineStartOffset;
Mihai Popa7626c862018-05-09 17:31:48 +01001493 float bestdist = Math.abs(horizontal.get(lineStartOffset) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494
Doug Felt9f7a4442010-03-01 12:45:56 -08001495 for (int i = 0; i < dirs.mDirections.length; i += 2) {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001496 int here = lineStartOffset + dirs.mDirections[i];
Doug Felt9f7a4442010-03-01 12:45:56 -08001497 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001498 boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1499 int swap = isRtl ? -1 : 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500
1501 if (there > max)
1502 there = max;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 int high = there - 1 + 1, low = here + 1 - 1, guess;
1504
1505 while (high - low > 1) {
1506 guess = (high + low) / 2;
1507 int adguess = getOffsetAtStartOf(guess);
1508
Mihai Popa7626c862018-05-09 17:31:48 +01001509 if (horizontal.get(adguess) * swap >= horiz * swap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 high = guess;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001511 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 low = guess;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515
1516 if (low < here + 1)
1517 low = here + 1;
1518
1519 if (low < there) {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001520 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1521 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1522 if (low >= here && low < there) {
Mihai Popa7626c862018-05-09 17:31:48 +01001523 float dist = Math.abs(horizontal.get(low) - horiz);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001524 if (aft < there) {
Mihai Popa7626c862018-05-09 17:31:48 +01001525 float other = Math.abs(horizontal.get(aft) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001527 if (other < dist) {
1528 dist = other;
1529 low = aft;
1530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001533 if (dist < bestdist) {
1534 bestdist = dist;
1535 best = low;
1536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538 }
1539
Mihai Popa7626c862018-05-09 17:31:48 +01001540 float dist = Math.abs(horizontal.get(here) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541
1542 if (dist < bestdist) {
1543 bestdist = dist;
1544 best = here;
1545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547
Mihai Popa7626c862018-05-09 17:31:48 +01001548 float dist = Math.abs(horizontal.get(max) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549
Raph Levien373b7a82013-09-20 15:11:52 -07001550 if (dist <= bestdist) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 best = max;
1552 }
1553
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001554 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 return best;
1556 }
1557
1558 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001559 * Responds to #getHorizontal queries, by selecting the better strategy between:
1560 * - calling #getHorizontal explicitly for each query
1561 * - precomputing all #getHorizontal measurements, and responding to any query in constant time
1562 * The first strategy is used for LTR-only text, while the second is used for all other cases.
1563 * The class is currently only used in #getOffsetForHorizontal, so reuse with care in other
1564 * contexts.
1565 */
1566 private class HorizontalMeasurementProvider {
1567 private final int mLine;
1568 private final boolean mPrimary;
1569
1570 private float[] mHorizontals;
1571 private int mLineStartOffset;
1572
1573 HorizontalMeasurementProvider(final int line, final boolean primary) {
1574 mLine = line;
1575 mPrimary = primary;
1576 init();
1577 }
1578
1579 private void init() {
1580 final Directions dirs = getLineDirections(mLine);
1581 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1582 return;
1583 }
1584
1585 mHorizontals = getLineHorizontals(mLine, false, mPrimary);
1586 mLineStartOffset = getLineStart(mLine);
1587 }
1588
1589 float get(final int offset) {
1590 if (mHorizontals == null) {
1591 return getHorizontal(offset, mPrimary);
1592 } else {
1593 return mHorizontals[offset - mLineStartOffset];
1594 }
1595 }
1596 }
1597
1598 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 * Return the text offset after the last character on the specified line.
1600 */
1601 public final int getLineEnd(int line) {
1602 return getLineStart(line + 1);
1603 }
1604
Doug Felt9f7a4442010-03-01 12:45:56 -08001605 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 * Return the text offset after the last visible character (so whitespace
1607 * is not counted) on the specified line.
1608 */
1609 public int getLineVisibleEnd(int line) {
1610 return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1611 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 private int getLineVisibleEnd(int line, int start, int end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 CharSequence text = mText;
1615 char ch;
1616 if (line == getLineCount() - 1) {
1617 return end;
1618 }
1619
1620 for (; end > start; end--) {
1621 ch = text.charAt(end - 1);
1622
1623 if (ch == '\n') {
1624 return end - 1;
1625 }
1626
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001627 if (!TextLine.isLineEndSpace(ch)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 break;
1629 }
1630
1631 }
1632
1633 return end;
1634 }
1635
1636 /**
1637 * Return the vertical position of the bottom of the specified line.
1638 */
1639 public final int getLineBottom(int line) {
1640 return getLineTop(line + 1);
1641 }
1642
1643 /**
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001644 * Return the vertical position of the bottom of the specified line without the line spacing
1645 * added.
1646 *
1647 * @hide
1648 */
1649 public final int getLineBottomWithoutSpacing(int line) {
1650 return getLineTop(line + 1) - getLineExtra(line);
1651 }
1652
1653 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 * Return the vertical position of the baseline of the specified line.
1655 */
1656 public final int getLineBaseline(int line) {
1657 // getLineTop(line+1) == getLineTop(line)
1658 return getLineTop(line+1) - getLineDescent(line);
1659 }
1660
1661 /**
1662 * Get the ascent of the text on the specified line.
1663 * The return value is negative to match the Paint.ascent() convention.
1664 */
1665 public final int getLineAscent(int line) {
1666 // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1667 return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1668 }
1669
Siyamed Sinir0fa89d62017-07-24 20:46:41 -07001670 /**
1671 * Return the extra space added as a result of line spacing attributes
1672 * {@link #getSpacingAdd()} and {@link #getSpacingMultiplier()}. Default value is {@code zero}.
1673 *
1674 * @param line the index of the line, the value should be equal or greater than {@code zero}
1675 * @hide
1676 */
1677 public int getLineExtra(@IntRange(from = 0) int line) {
1678 return 0;
1679 }
1680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 public int getOffsetToLeftOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001682 return getOffsetToLeftRightOf(offset, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 }
1684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 public int getOffsetToRightOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001686 return getOffsetToLeftRightOf(offset, false);
1687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688
Doug Felt9f7a4442010-03-01 12:45:56 -08001689 private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1690 int line = getLineForOffset(caret);
1691 int lineStart = getLineStart(line);
1692 int lineEnd = getLineEnd(line);
Doug Felte8e45f22010-03-29 14:58:40 -07001693 int lineDir = getParagraphDirection(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001695 boolean lineChanged = false;
Doug Felte8e45f22010-03-29 14:58:40 -07001696 boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001697 // if walking off line, look at the line we're headed to
1698 if (advance) {
1699 if (caret == lineEnd) {
Doug Felte8e45f22010-03-29 14:58:40 -07001700 if (line < getLineCount() - 1) {
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001701 lineChanged = true;
Doug Felte8e45f22010-03-29 14:58:40 -07001702 ++line;
1703 } else {
1704 return caret; // at very end, don't move
1705 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001706 }
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001707 } else {
1708 if (caret == lineStart) {
1709 if (line > 0) {
1710 lineChanged = true;
1711 --line;
1712 } else {
1713 return caret; // at very start, don't move
1714 }
1715 }
1716 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001717
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001718 if (lineChanged) {
Doug Felte8e45f22010-03-29 14:58:40 -07001719 lineStart = getLineStart(line);
1720 lineEnd = getLineEnd(line);
1721 int newDir = getParagraphDirection(line);
1722 if (newDir != lineDir) {
1723 // unusual case. we want to walk onto the line, but it runs
1724 // in a different direction than this one, so we fake movement
1725 // in the opposite direction.
1726 toLeft = !toLeft;
1727 lineDir = newDir;
1728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001730
Doug Felte8e45f22010-03-29 14:58:40 -07001731 Directions directions = getLineDirections(line);
Doug Felt9f7a4442010-03-01 12:45:56 -08001732
Doug Felte8e45f22010-03-29 14:58:40 -07001733 TextLine tl = TextLine.obtain();
1734 // XXX: we don't care about tabs
1735 tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null);
1736 caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
Siyamed Sinira273a702017-10-05 11:22:12 -07001737 TextLine.recycle(tl);
Doug Felte8e45f22010-03-29 14:58:40 -07001738 return caret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740
1741 private int getOffsetAtStartOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001742 // XXX this probably should skip local reorderings and
1743 // zero-width characters, look at callers
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 if (offset == 0)
1745 return 0;
1746
1747 CharSequence text = mText;
1748 char c = text.charAt(offset);
1749
1750 if (c >= '\uDC00' && c <= '\uDFFF') {
1751 char c1 = text.charAt(offset - 1);
1752
1753 if (c1 >= '\uD800' && c1 <= '\uDBFF')
1754 offset -= 1;
1755 }
1756
1757 if (mSpannedText) {
1758 ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1759 ReplacementSpan.class);
1760
1761 for (int i = 0; i < spans.length; i++) {
1762 int start = ((Spanned) text).getSpanStart(spans[i]);
1763 int end = ((Spanned) text).getSpanEnd(spans[i]);
1764
1765 if (start < offset && end > offset)
1766 offset = start;
1767 }
1768 }
1769
1770 return offset;
1771 }
1772
1773 /**
Raph Levienafe8e9b2012-12-19 16:09:32 -08001774 * Determine whether we should clamp cursor position. Currently it's
1775 * only robust for left-aligned displays.
1776 * @hide
1777 */
1778 public boolean shouldClampCursor(int line) {
1779 // Only clamp cursor position in left-aligned displays.
1780 switch (getParagraphAlignment(line)) {
1781 case ALIGN_LEFT:
1782 return true;
1783 case ALIGN_NORMAL:
1784 return getParagraphDirection(line) > 0;
1785 default:
1786 return false;
1787 }
1788
1789 }
1790 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 * Fills in the specified Path with a representation of a cursor
1792 * at the specified offset. This will often be a vertical line
Doug Felt4e0c5e52010-03-15 16:56:02 -07001793 * but can be multiple discontinuous lines in text with multiple
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 * directionalities.
1795 */
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001796 public void getCursorPath(final int point, final Path dest, final CharSequence editingBuffer) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 dest.reset();
1798
1799 int line = getLineForOffset(point);
1800 int top = getLineTop(line);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001801 int bottom = getLineBottomWithoutSpacing(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802
Raph Levienafe8e9b2012-12-19 16:09:32 -08001803 boolean clamped = shouldClampCursor(line);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001804 float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1805 float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806
Jeff Brown497a92c2010-09-12 17:55:08 -07001807 int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1808 TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1809 int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 int dist = 0;
1811
1812 if (caps != 0 || fn != 0) {
1813 dist = (bottom - top) >> 2;
1814
1815 if (fn != 0)
1816 top += dist;
1817 if (caps != 0)
1818 bottom -= dist;
1819 }
1820
1821 if (h1 < 0.5f)
1822 h1 = 0.5f;
1823 if (h2 < 0.5f)
1824 h2 = 0.5f;
1825
Jozef BABJAK2fb503f2011-03-17 09:54:51 +01001826 if (Float.compare(h1, h2) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 dest.moveTo(h1, top);
1828 dest.lineTo(h1, bottom);
1829 } else {
1830 dest.moveTo(h1, top);
1831 dest.lineTo(h1, (top + bottom) >> 1);
1832
1833 dest.moveTo(h2, (top + bottom) >> 1);
1834 dest.lineTo(h2, bottom);
1835 }
1836
1837 if (caps == 2) {
1838 dest.moveTo(h2, bottom);
1839 dest.lineTo(h2 - dist, bottom + dist);
1840 dest.lineTo(h2, bottom);
1841 dest.lineTo(h2 + dist, bottom + dist);
1842 } else if (caps == 1) {
1843 dest.moveTo(h2, bottom);
1844 dest.lineTo(h2 - dist, bottom + dist);
1845
1846 dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1847 dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1848
1849 dest.moveTo(h2 + dist, bottom + dist);
1850 dest.lineTo(h2, bottom);
1851 }
1852
1853 if (fn == 2) {
1854 dest.moveTo(h1, top);
1855 dest.lineTo(h1 - dist, top - dist);
1856 dest.lineTo(h1, top);
1857 dest.lineTo(h1 + dist, top - dist);
1858 } else if (fn == 1) {
1859 dest.moveTo(h1, top);
1860 dest.lineTo(h1 - dist, top - dist);
1861
1862 dest.moveTo(h1 - dist, top - dist + 0.5f);
1863 dest.lineTo(h1 + dist, top - dist + 0.5f);
1864
1865 dest.moveTo(h1 + dist, top - dist);
1866 dest.lineTo(h1, top);
1867 }
1868 }
1869
1870 private void addSelection(int line, int start, int end,
Petar Šeginab92c5392017-09-06 15:25:05 +01001871 int top, int bottom, SelectionRectangleConsumer consumer) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 int linestart = getLineStart(line);
1873 int lineend = getLineEnd(line);
1874 Directions dirs = getLineDirections(line);
1875
Petar Šeginafb748b32017-08-07 12:37:52 +01001876 if (lineend > linestart && mText.charAt(lineend - 1) == '\n') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 lineend--;
Petar Šeginafb748b32017-08-07 12:37:52 +01001878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879
Doug Felt9f7a4442010-03-01 12:45:56 -08001880 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1881 int here = linestart + dirs.mDirections[i];
Petar Šeginafb748b32017-08-07 12:37:52 +01001882 int there = here + (dirs.mDirections[i + 1] & RUN_LENGTH_MASK);
Doug Felt9f7a4442010-03-01 12:45:56 -08001883
Petar Šeginafb748b32017-08-07 12:37:52 +01001884 if (there > lineend) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 there = lineend;
Petar Šeginafb748b32017-08-07 12:37:52 +01001886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887
1888 if (start <= there && end >= here) {
1889 int st = Math.max(start, here);
1890 int en = Math.min(end, there);
1891
1892 if (st != en) {
Raph Levienafe8e9b2012-12-19 16:09:32 -08001893 float h1 = getHorizontal(st, false, line, false /* not clamped */);
1894 float h2 = getHorizontal(en, true, line, false /* not clamped */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895
Fabrice Di Meglio37166012011-08-31 13:56:37 -07001896 float left = Math.min(h1, h2);
1897 float right = Math.max(h1, h2);
1898
Petar Šegina8f1f74e2017-09-07 14:26:28 +01001899 final @TextSelectionLayout int layout =
1900 ((dirs.mDirections[i + 1] & RUN_RTL_FLAG) != 0)
1901 ? TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT
1902 : TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT;
1903
1904 consumer.accept(left, top, right, bottom, layout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 }
1906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
1908 }
1909
1910 /**
1911 * Fills in the specified Path with a representation of a highlight
1912 * between the specified offsets. This will often be a rectangle
1913 * or a potentially discontinuous set of rectangles. If the start
1914 * and end are the same, the returned path is empty.
1915 */
1916 public void getSelectionPath(int start, int end, Path dest) {
1917 dest.reset();
Petar Šeginab92c5392017-09-06 15:25:05 +01001918 getSelection(start, end, (left, top, right, bottom, textSelectionLayout) ->
Petar Šeginafb748b32017-08-07 12:37:52 +01001919 dest.addRect(left, top, right, bottom, Path.Direction.CW));
1920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921
Petar Šeginafb748b32017-08-07 12:37:52 +01001922 /**
1923 * Calculates the rectangles which should be highlighted to indicate a selection between start
Petar Šeginab92c5392017-09-06 15:25:05 +01001924 * and end and feeds them into the given {@link SelectionRectangleConsumer}.
Petar Šeginafb748b32017-08-07 12:37:52 +01001925 *
1926 * @param start the starting index of the selection
1927 * @param end the ending index of the selection
Petar Šeginab92c5392017-09-06 15:25:05 +01001928 * @param consumer the {@link SelectionRectangleConsumer} which will receive the generated
1929 * rectangles. It will be called every time a rectangle is generated.
Petar Šeginafb748b32017-08-07 12:37:52 +01001930 * @hide
1931 * @see #getSelectionPath(int, int, Path)
1932 */
Petar Šeginab92c5392017-09-06 15:25:05 +01001933 public final void getSelection(int start, int end, final SelectionRectangleConsumer consumer) {
Petar Šeginafb748b32017-08-07 12:37:52 +01001934 if (start == end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 return;
Petar Šeginafb748b32017-08-07 12:37:52 +01001936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937
1938 if (end < start) {
1939 int temp = end;
1940 end = start;
1941 start = temp;
1942 }
1943
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001944 final int startline = getLineForOffset(start);
1945 final int endline = getLineForOffset(end);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 int top = getLineTop(startline);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001948 int bottom = getLineBottomWithoutSpacing(endline);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949
1950 if (startline == endline) {
Petar Šeginafb748b32017-08-07 12:37:52 +01001951 addSelection(startline, start, end, top, bottom, consumer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 } else {
1953 final float width = mWidth;
1954
1955 addSelection(startline, start, getLineEnd(startline),
Petar Šeginafb748b32017-08-07 12:37:52 +01001956 top, getLineBottom(startline), consumer);
Doug Felt9f7a4442010-03-01 12:45:56 -08001957
Petar Šeginafb748b32017-08-07 12:37:52 +01001958 if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT) {
Petar Šeginab92c5392017-09-06 15:25:05 +01001959 consumer.accept(getLineLeft(startline), top, 0, getLineBottom(startline),
Petar Šegina3a92fb62017-09-07 21:03:24 +01001960 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001961 } else {
Petar Šeginab92c5392017-09-06 15:25:05 +01001962 consumer.accept(getLineRight(startline), top, width, getLineBottom(startline),
Petar Šegina3a92fb62017-09-07 21:03:24 +01001963 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965
1966 for (int i = startline + 1; i < endline; i++) {
1967 top = getLineTop(i);
1968 bottom = getLineBottom(i);
Petar Šeginab92c5392017-09-06 15:25:05 +01001969 if (getParagraphDirection(i) == DIR_RIGHT_TO_LEFT) {
Petar Šegina3a92fb62017-09-07 21:03:24 +01001970 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginab92c5392017-09-06 15:25:05 +01001971 } else {
Petar Šegina3a92fb62017-09-07 21:03:24 +01001972 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginab92c5392017-09-06 15:25:05 +01001973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
1975
1976 top = getLineTop(endline);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001977 bottom = getLineBottomWithoutSpacing(endline);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978
Petar Šeginafb748b32017-08-07 12:37:52 +01001979 addSelection(endline, getLineStart(endline), end, top, bottom, consumer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980
Petar Šeginafb748b32017-08-07 12:37:52 +01001981 if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT) {
Petar Šeginab92c5392017-09-06 15:25:05 +01001982 consumer.accept(width, top, getLineRight(endline), bottom,
Petar Šegina3a92fb62017-09-07 21:03:24 +01001983 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001984 } else {
Petar Šeginab92c5392017-09-06 15:25:05 +01001985 consumer.accept(0, top, getLineLeft(endline), bottom,
Petar Šegina3a92fb62017-09-07 21:03:24 +01001986 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 }
1989 }
1990
1991 /**
1992 * Get the alignment of the specified paragraph, taking into account
1993 * markup attached to it.
1994 */
1995 public final Alignment getParagraphAlignment(int line) {
1996 Alignment align = mAlignment;
1997
1998 if (mSpannedText) {
1999 Spanned sp = (Spanned) mText;
Eric Fischer74d31ef2010-08-05 15:29:36 -07002000 AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 getLineEnd(line),
2002 AlignmentSpan.class);
2003
2004 int spanLength = spans.length;
2005 if (spanLength > 0) {
2006 align = spans[spanLength-1].getAlignment();
2007 }
2008 }
2009
2010 return align;
2011 }
2012
2013 /**
2014 * Get the left edge of the specified paragraph, inset by left margins.
2015 */
2016 public final int getParagraphLeft(int line) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 int left = 0;
Doug Feltc982f602010-05-25 11:51:40 -07002018 int dir = getParagraphDirection(line);
2019 if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
2020 return left; // leading margin has no impact, or no styles
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 }
Doug Feltc982f602010-05-25 11:51:40 -07002022 return getParagraphLeadingMargin(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 }
2024
2025 /**
2026 * Get the right edge of the specified paragraph, inset by right margins.
2027 */
2028 public final int getParagraphRight(int line) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 int right = mWidth;
Doug Feltc982f602010-05-25 11:51:40 -07002030 int dir = getParagraphDirection(line);
2031 if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
2032 return right; // leading margin has no impact, or no styles
2033 }
2034 return right - getParagraphLeadingMargin(line);
2035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036
Doug Feltc982f602010-05-25 11:51:40 -07002037 /**
2038 * Returns the effective leading margin (unsigned) for this line,
2039 * taking into account LeadingMarginSpan and LeadingMarginSpan2.
2040 * @param line the line index
2041 * @return the leading margin of this line
2042 */
2043 private int getParagraphLeadingMargin(int line) {
2044 if (!mSpannedText) {
2045 return 0;
2046 }
2047 Spanned spanned = (Spanned) mText;
Doug Felt0c702b82010-05-14 10:55:42 -07002048
Doug Feltc982f602010-05-25 11:51:40 -07002049 int lineStart = getLineStart(line);
2050 int lineEnd = getLineEnd(line);
Doug Felt0c702b82010-05-14 10:55:42 -07002051 int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002052 LeadingMarginSpan.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002053 LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002054 LeadingMarginSpan.class);
2055 if (spans.length == 0) {
2056 return 0; // no leading margin span;
2057 }
Doug Felt0c702b82010-05-14 10:55:42 -07002058
Doug Feltc982f602010-05-25 11:51:40 -07002059 int margin = 0;
Doug Felt0c702b82010-05-14 10:55:42 -07002060
Siyamed Sinira273a702017-10-05 11:22:12 -07002061 boolean useFirstLineMargin = lineStart == 0 || spanned.charAt(lineStart - 1) == '\n';
Anish Athalyeab08c6d2014-08-08 12:09:58 -07002062 for (int i = 0; i < spans.length; i++) {
2063 if (spans[i] instanceof LeadingMarginSpan2) {
2064 int spStart = spanned.getSpanStart(spans[i]);
2065 int spanLine = getLineForOffset(spStart);
2066 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
2067 // if there is more than one LeadingMarginSpan2, use the count that is greatest
2068 useFirstLineMargin |= line < spanLine + count;
2069 }
2070 }
Doug Feltc982f602010-05-25 11:51:40 -07002071 for (int i = 0; i < spans.length; i++) {
2072 LeadingMarginSpan span = spans[i];
Doug Feltc982f602010-05-25 11:51:40 -07002073 margin += span.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 }
2075
Doug Feltc982f602010-05-25 11:51:40 -07002076 return margin;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 }
2078
Roozbeh Pournader9a9179d2017-08-29 14:14:28 -07002079 private static float measurePara(TextPaint paint, CharSequence text, int start, int end,
Siyamed Sinir79bf9d12016-05-18 19:57:52 -07002080 TextDirectionHeuristic textDir) {
Seigo Nonaka9d3bd082018-01-11 10:02:12 -08002081 MeasuredParagraph mt = null;
Doug Felte8e45f22010-03-29 14:58:40 -07002082 TextLine tl = TextLine.obtain();
2083 try {
Seigo Nonaka9d3bd082018-01-11 10:02:12 -08002084 mt = MeasuredParagraph.buildForBidi(text, start, end, textDir, mt);
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002085 final char[] chars = mt.getChars();
2086 final int len = chars.length;
2087 final Directions directions = mt.getDirections(0, len);
2088 final int dir = mt.getParagraphDir();
Doug Feltc982f602010-05-25 11:51:40 -07002089 boolean hasTabs = false;
2090 TabStops tabStops = null;
Anish Athalyec14b3ad2014-07-24 18:03:21 -07002091 // leading margins should be taken into account when measuring a paragraph
2092 int margin = 0;
2093 if (text instanceof Spanned) {
2094 Spanned spanned = (Spanned) text;
2095 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
2096 LeadingMarginSpan.class);
2097 for (LeadingMarginSpan lms : spans) {
2098 margin += lms.getLeadingMargin(true);
2099 }
2100 }
Doug Feltc982f602010-05-25 11:51:40 -07002101 for (int i = 0; i < len; ++i) {
2102 if (chars[i] == '\t') {
2103 hasTabs = true;
2104 if (text instanceof Spanned) {
2105 Spanned spanned = (Spanned) text;
Doug Felt0c702b82010-05-14 10:55:42 -07002106 int spanEnd = spanned.nextSpanTransition(start, end,
Doug Feltc982f602010-05-25 11:51:40 -07002107 TabStopSpan.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002108 TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002109 TabStopSpan.class);
2110 if (spans.length > 0) {
2111 tabStops = new TabStops(TAB_INCREMENT, spans);
2112 }
2113 }
2114 break;
2115 }
2116 }
2117 tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops);
Siyamed Sinir79bf9d12016-05-18 19:57:52 -07002118 return margin + Math.abs(tl.metrics(null));
Doug Felte8e45f22010-03-29 14:58:40 -07002119 } finally {
2120 TextLine.recycle(tl);
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002121 if (mt != null) {
2122 mt.recycle();
2123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 }
2126
Doug Felt71b8dd72010-02-16 17:27:09 -08002127 /**
Doug Feltc982f602010-05-25 11:51:40 -07002128 * @hide
2129 */
Seigo Nonaka32afe262018-05-16 22:05:27 -07002130 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2131 public static class TabStops {
Doug Feltc982f602010-05-25 11:51:40 -07002132 private int[] mStops;
2133 private int mNumStops;
2134 private int mIncrement;
Doug Felt0c702b82010-05-14 10:55:42 -07002135
Seigo Nonaka32afe262018-05-16 22:05:27 -07002136 public TabStops(int increment, Object[] spans) {
Doug Feltc982f602010-05-25 11:51:40 -07002137 reset(increment, spans);
2138 }
Doug Felt0c702b82010-05-14 10:55:42 -07002139
Doug Feltc982f602010-05-25 11:51:40 -07002140 void reset(int increment, Object[] spans) {
2141 this.mIncrement = increment;
2142
2143 int ns = 0;
2144 if (spans != null) {
2145 int[] stops = this.mStops;
2146 for (Object o : spans) {
2147 if (o instanceof TabStopSpan) {
2148 if (stops == null) {
2149 stops = new int[10];
2150 } else if (ns == stops.length) {
2151 int[] nstops = new int[ns * 2];
2152 for (int i = 0; i < ns; ++i) {
2153 nstops[i] = stops[i];
2154 }
2155 stops = nstops;
2156 }
2157 stops[ns++] = ((TabStopSpan) o).getTabStop();
2158 }
2159 }
2160 if (ns > 1) {
2161 Arrays.sort(stops, 0, ns);
2162 }
2163 if (stops != this.mStops) {
2164 this.mStops = stops;
2165 }
2166 }
2167 this.mNumStops = ns;
2168 }
Doug Felt0c702b82010-05-14 10:55:42 -07002169
Doug Feltc982f602010-05-25 11:51:40 -07002170 float nextTab(float h) {
2171 int ns = this.mNumStops;
2172 if (ns > 0) {
2173 int[] stops = this.mStops;
2174 for (int i = 0; i < ns; ++i) {
2175 int stop = stops[i];
2176 if (stop > h) {
2177 return stop;
2178 }
2179 }
2180 }
2181 return nextDefaultStop(h, mIncrement);
2182 }
2183
2184 public static float nextDefaultStop(float h, int inc) {
2185 return ((int) ((h + inc) / inc)) * inc;
2186 }
2187 }
Doug Felt0c702b82010-05-14 10:55:42 -07002188
Doug Feltc982f602010-05-25 11:51:40 -07002189 /**
Doug Felt71b8dd72010-02-16 17:27:09 -08002190 * Returns the position of the next tab stop after h on the line.
2191 *
2192 * @param text the text
2193 * @param start start of the line
2194 * @param end limit of the line
2195 * @param h the current horizontal offset
2196 * @param tabs the tabs, can be null. If it is null, any tabs in effect
2197 * on the line will be used. If there are no tabs, a default offset
2198 * will be used to compute the tab stop.
2199 * @return the offset of the next tab stop.
2200 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 /* package */ static float nextTab(CharSequence text, int start, int end,
2202 float h, Object[] tabs) {
2203 float nh = Float.MAX_VALUE;
2204 boolean alltabs = false;
2205
2206 if (text instanceof Spanned) {
2207 if (tabs == null) {
Eric Fischer74d31ef2010-08-05 15:29:36 -07002208 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 alltabs = true;
2210 }
2211
2212 for (int i = 0; i < tabs.length; i++) {
2213 if (!alltabs) {
2214 if (!(tabs[i] instanceof TabStopSpan))
2215 continue;
2216 }
2217
2218 int where = ((TabStopSpan) tabs[i]).getTabStop();
2219
2220 if (where < nh && where > h)
2221 nh = where;
2222 }
2223
2224 if (nh != Float.MAX_VALUE)
2225 return nh;
2226 }
2227
2228 return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
2229 }
2230
2231 protected final boolean isSpanned() {
2232 return mSpannedText;
2233 }
2234
Eric Fischer74d31ef2010-08-05 15:29:36 -07002235 /**
2236 * Returns the same as <code>text.getSpans()</code>, except where
2237 * <code>start</code> and <code>end</code> are the same and are not
2238 * at the very beginning of the text, in which case an empty array
2239 * is returned instead.
2240 * <p>
2241 * This is needed because of the special case that <code>getSpans()</code>
2242 * on an empty range returns the spans adjacent to that range, which is
2243 * primarily for the sake of <code>TextWatchers</code> so they will get
2244 * notifications when text goes from empty to non-empty. But it also
2245 * has the unfortunate side effect that if the text ends with an empty
2246 * paragraph, that paragraph accidentally picks up the styles of the
2247 * preceding paragraph (even though those styles will not be picked up
2248 * by new text that is inserted into the empty paragraph).
2249 * <p>
2250 * The reason it just checks whether <code>start</code> and <code>end</code>
2251 * is the same is that the only time a line can contain 0 characters
2252 * is if it is the final paragraph of the Layout; otherwise any line will
2253 * contain at least one printing or newline character. The reason for the
2254 * additional check if <code>start</code> is greater than 0 is that
2255 * if the empty paragraph is the entire content of the buffer, paragraph
2256 * styles that are already applied to the buffer will apply to text that
2257 * is inserted into it.
2258 */
Gilles Debunneeca5b732012-04-25 18:48:42 -07002259 /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
Eric Fischer74d31ef2010-08-05 15:29:36 -07002260 if (start == end && start > 0) {
Gilles Debunne6c488de2012-03-01 16:20:35 -08002261 return ArrayUtils.emptyArray(type);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002262 }
2263
Siyamed Sinirfa05ba02016-01-12 10:54:43 -08002264 if(text instanceof SpannableStringBuilder) {
2265 return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2266 } else {
2267 return text.getSpans(start, end, type);
2268 }
Eric Fischer74d31ef2010-08-05 15:29:36 -07002269 }
2270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 private void ellipsize(int start, int end, int line,
Fabrice Di Meglio8d44fff2012-06-13 15:45:38 -07002272 char[] dest, int destoff, TextUtils.TruncateAt method) {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002273 final int ellipsisCount = getEllipsisCount(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 if (ellipsisCount == 0) {
2275 return;
2276 }
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002277 final int ellipsisStart = getEllipsisStart(line);
2278 final int lineStart = getLineStart(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002280 final String ellipsisString = TextUtils.getEllipsisString(method);
2281 final int ellipsisStringLen = ellipsisString.length();
Roozbeh Pournader1051bbe2017-07-25 13:52:57 -07002282 // Use the ellipsis string only if there are that at least as many characters to replace.
2283 final boolean useEllipsisString = ellipsisCount >= ellipsisStringLen;
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002284 for (int i = 0; i < ellipsisCount; i++) {
2285 final char c;
Roozbeh Pournader1051bbe2017-07-25 13:52:57 -07002286 if (useEllipsisString && i < ellipsisStringLen) {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002287 c = ellipsisString.charAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 } else {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002289 c = TextUtils.ELLIPSIS_FILLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 }
2291
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002292 final int a = i + ellipsisStart + lineStart;
2293 if (start <= a && a < end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 dest[destoff + a - start] = c;
2295 }
2296 }
2297 }
2298
2299 /**
2300 * Stores information about bidirectional (left-to-right or right-to-left)
Doug Felt9f7a4442010-03-01 12:45:56 -08002301 * text within the layout of a line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 */
2303 public static class Directions {
Siyamed Sinired09ae12016-02-16 14:36:26 -08002304 /**
Petar Šegina7c31d5c2017-09-25 12:19:28 +01002305 * Directions represents directional runs within a line of text. Runs are pairs of ints
2306 * listed in visual order, starting from the leading margin. The first int of each pair is
2307 * the offset from the first character of the line to the start of the run. The second int
2308 * represents both the length and level of the run. The length is in the lower bits,
2309 * accessed by masking with RUN_LENGTH_MASK. The level is in the higher bits, accessed by
2310 * shifting by RUN_LEVEL_SHIFT and masking by RUN_LEVEL_MASK. To simply test for an RTL
2311 * direction, test the bit using RUN_RTL_FLAG, if set then the direction is rtl.
Siyamed Sinired09ae12016-02-16 14:36:26 -08002312 * @hide
2313 */
2314 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2315 public int[] mDirections;
2316
2317 /**
2318 * @hide
2319 */
2320 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2321 public Directions(int[] dirs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 mDirections = dirs;
2323 }
2324 }
2325
2326 /**
2327 * Return the offset of the first character to be ellipsized away,
2328 * relative to the start of the line. (So 0 if the beginning of the
2329 * line is ellipsized, not getLineStart().)
2330 */
2331 public abstract int getEllipsisStart(int line);
Doug Felte8e45f22010-03-29 14:58:40 -07002332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 /**
2334 * Returns the number of characters to be ellipsized away, or 0 if
2335 * no ellipsis is to take place.
2336 */
2337 public abstract int getEllipsisCount(int line);
2338
2339 /* package */ static class Ellipsizer implements CharSequence, GetChars {
2340 /* package */ CharSequence mText;
2341 /* package */ Layout mLayout;
2342 /* package */ int mWidth;
2343 /* package */ TextUtils.TruncateAt mMethod;
2344
2345 public Ellipsizer(CharSequence s) {
2346 mText = s;
2347 }
2348
2349 public char charAt(int off) {
2350 char[] buf = TextUtils.obtain(1);
2351 getChars(off, off + 1, buf, 0);
2352 char ret = buf[0];
2353
2354 TextUtils.recycle(buf);
2355 return ret;
2356 }
2357
2358 public void getChars(int start, int end, char[] dest, int destoff) {
2359 int line1 = mLayout.getLineForOffset(start);
2360 int line2 = mLayout.getLineForOffset(end);
2361
2362 TextUtils.getChars(mText, start, end, dest, destoff);
2363
2364 for (int i = line1; i <= line2; i++) {
Fabrice Di Meglio8d44fff2012-06-13 15:45:38 -07002365 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 }
2367 }
2368
2369 public int length() {
2370 return mText.length();
2371 }
Doug Felt9f7a4442010-03-01 12:45:56 -08002372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 public CharSequence subSequence(int start, int end) {
2374 char[] s = new char[end - start];
2375 getChars(start, end, s, 0);
2376 return new String(s);
2377 }
2378
Gilles Debunne162bf0f2010-11-16 16:23:53 -08002379 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 public String toString() {
2381 char[] s = new char[length()];
2382 getChars(0, length(), s, 0);
2383 return new String(s);
2384 }
2385
2386 }
2387
Gilles Debunne6c488de2012-03-01 16:20:35 -08002388 /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 private Spanned mSpanned;
2390
2391 public SpannedEllipsizer(CharSequence display) {
2392 super(display);
2393 mSpanned = (Spanned) display;
2394 }
2395
2396 public <T> T[] getSpans(int start, int end, Class<T> type) {
2397 return mSpanned.getSpans(start, end, type);
2398 }
2399
2400 public int getSpanStart(Object tag) {
2401 return mSpanned.getSpanStart(tag);
2402 }
2403
2404 public int getSpanEnd(Object tag) {
2405 return mSpanned.getSpanEnd(tag);
2406 }
2407
2408 public int getSpanFlags(Object tag) {
2409 return mSpanned.getSpanFlags(tag);
2410 }
2411
Gilles Debunne6c488de2012-03-01 16:20:35 -08002412 @SuppressWarnings("rawtypes")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 public int nextSpanTransition(int start, int limit, Class type) {
2414 return mSpanned.nextSpanTransition(start, limit, type);
2415 }
2416
Gilles Debunne162bf0f2010-11-16 16:23:53 -08002417 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 public CharSequence subSequence(int start, int end) {
2419 char[] s = new char[end - start];
2420 getChars(start, end, s, 0);
2421
2422 SpannableString ss = new SpannableString(new String(s));
2423 TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2424 return ss;
2425 }
2426 }
2427
2428 private CharSequence mText;
2429 private TextPaint mPaint;
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07002430 private TextPaint mWorkPaint = new TextPaint();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 private int mWidth;
2432 private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2433 private float mSpacingMult;
2434 private float mSpacingAdd;
Romain Guyc4d8eb62010-08-18 20:48:33 -07002435 private static final Rect sTempRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 private boolean mSpannedText;
Doug Feltcb3791202011-07-07 11:57:48 -07002437 private TextDirectionHeuristic mTextDir;
Gilles Debunneeca5b732012-04-25 18:48:42 -07002438 private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
Seigo Nonaka4b4730d2017-03-31 09:42:16 -07002439 private int mJustificationMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002441 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -07002442 @IntDef(prefix = { "DIR_" }, value = {
2443 DIR_LEFT_TO_RIGHT,
2444 DIR_RIGHT_TO_LEFT
2445 })
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002446 @Retention(RetentionPolicy.SOURCE)
2447 public @interface Direction {}
2448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 public static final int DIR_LEFT_TO_RIGHT = 1;
2450 public static final int DIR_RIGHT_TO_LEFT = -1;
Doug Felt9f7a4442010-03-01 12:45:56 -08002451
Doug Felt20178d62010-02-22 13:39:01 -08002452 /* package */ static final int DIR_REQUEST_LTR = 1;
2453 /* package */ static final int DIR_REQUEST_RTL = -1;
2454 /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2455 /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456
Doug Felt9f7a4442010-03-01 12:45:56 -08002457 /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2458 /* package */ static final int RUN_LEVEL_SHIFT = 26;
2459 /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2460 /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 public enum Alignment {
2463 ALIGN_NORMAL,
2464 ALIGN_OPPOSITE,
2465 ALIGN_CENTER,
Doug Feltc0ccf0c2011-06-23 16:13:18 -07002466 /** @hide */
2467 ALIGN_LEFT,
2468 /** @hide */
2469 ALIGN_RIGHT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 }
2471
2472 private static final int TAB_INCREMENT = 20;
2473
Siyamed Sinired09ae12016-02-16 14:36:26 -08002474 /** @hide */
2475 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2476 public static final Directions DIRS_ALL_LEFT_TO_RIGHT =
Doug Felt9f7a4442010-03-01 12:45:56 -08002477 new Directions(new int[] { 0, RUN_LENGTH_MASK });
Siyamed Sinired09ae12016-02-16 14:36:26 -08002478
2479 /** @hide */
2480 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2481 public static final Directions DIRS_ALL_RIGHT_TO_LEFT =
Doug Felt9f7a4442010-03-01 12:45:56 -08002482 new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });
Gilles Debunne0a4db3c2011-01-14 12:12:04 -08002483
Petar Šeginafb748b32017-08-07 12:37:52 +01002484 /** @hide */
Petar Šeginab92c5392017-09-06 15:25:05 +01002485 @Retention(RetentionPolicy.SOURCE)
Jeff Sharkeyce8db992017-12-13 20:05:05 -07002486 @IntDef(prefix = { "TEXT_SELECTION_LAYOUT_" }, value = {
2487 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT,
2488 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT
2489 })
Petar Šegina3a92fb62017-09-07 21:03:24 +01002490 public @interface TextSelectionLayout {}
2491
2492 /** @hide */
2493 public static final int TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT = 0;
2494 /** @hide */
2495 public static final int TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT = 1;
Petar Šeginab92c5392017-09-06 15:25:05 +01002496
2497 /** @hide */
Petar Šeginafb748b32017-08-07 12:37:52 +01002498 @FunctionalInterface
Petar Šeginab92c5392017-09-06 15:25:05 +01002499 public interface SelectionRectangleConsumer {
Petar Šeginafb748b32017-08-07 12:37:52 +01002500 /**
2501 * Performs this operation on the given rectangle.
2502 *
2503 * @param left the left edge of the rectangle
2504 * @param top the top edge of the rectangle
2505 * @param right the right edge of the rectangle
2506 * @param bottom the bottom edge of the rectangle
Petar Šeginab92c5392017-09-06 15:25:05 +01002507 * @param textSelectionLayout the layout (RTL or LTR) of the text covered by this
2508 * selection rectangle
Petar Šeginafb748b32017-08-07 12:37:52 +01002509 */
Petar Šeginab92c5392017-09-06 15:25:05 +01002510 void accept(float left, float top, float right, float bottom,
2511 @TextSelectionLayout int textSelectionLayout);
Petar Šeginafb748b32017-08-07 12:37:52 +01002512 }
2513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514}