blob: c89617fefec5f0a71a7c79af57f4d3a1722046ce [file] [log] [blame]
Gilles Debunne60e3b3f2012-03-13 11:26:05 -07001/*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.text;
18
Raph Levien39b4db72015-03-25 13:18:20 -070019import android.annotation.IntDef;
Siyamed Sinir0fa89d62017-07-24 20:46:41 -070020import android.annotation.IntRange;
Mathew Inwoodefeab842018-08-14 15:21:30 +010021import android.annotation.UnsupportedAppUsage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.graphics.Canvas;
23import android.graphics.Paint;
Doug Felt9f7a4442010-03-01 12:45:56 -080024import android.graphics.Path;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.graphics.Rect;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.text.method.TextKeyListener;
Doug Felt9f7a4442010-03-01 12:45:56 -080027import android.text.style.AlignmentSpan;
28import android.text.style.LeadingMarginSpan;
Gilles Debunne162bf0f2010-11-16 16:23:53 -080029import android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
Doug Felt9f7a4442010-03-01 12:45:56 -080030import android.text.style.LineBackgroundSpan;
31import android.text.style.ParagraphStyle;
32import android.text.style.ReplacementSpan;
33import android.text.style.TabStopSpan;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034
Siyamed Sinired09ae12016-02-16 14:36:26 -080035import com.android.internal.annotations.VisibleForTesting;
Doug Feltcb3791202011-07-07 11:57:48 -070036import com.android.internal.util.ArrayUtils;
Adam Lesinski776abc22014-03-07 11:30:59 -050037import com.android.internal.util.GrowingArrayUtils;
Doug Feltcb3791202011-07-07 11:57:48 -070038
Raph Levien39b4db72015-03-25 13:18:20 -070039import java.lang.annotation.Retention;
40import java.lang.annotation.RetentionPolicy;
Doug Feltc982f602010-05-25 11:51:40 -070041import java.util.Arrays;
Doug Felt9f7a4442010-03-01 12:45:56 -080042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043/**
Doug Felt9f7a4442010-03-01 12:45:56 -080044 * A base class that manages text layout in visual elements on
45 * the screen.
46 * <p>For text that will be edited, use a {@link DynamicLayout},
47 * which will be updated as the text changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048 * For text that will not change, use a {@link StaticLayout}.
49 */
50public abstract class Layout {
Raph Levien39b4db72015-03-25 13:18:20 -070051 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -070052 @IntDef(prefix = { "BREAK_STRATEGY_" }, value = {
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -070053 NativeLineBreaker.BREAK_STRATEGY_SIMPLE,
54 NativeLineBreaker.BREAK_STRATEGY_HIGH_QUALITY,
55 NativeLineBreaker.BREAK_STRATEGY_BALANCED
Jeff Sharkeyce8db992017-12-13 20:05:05 -070056 })
Raph Levien39b4db72015-03-25 13:18:20 -070057 @Retention(RetentionPolicy.SOURCE)
58 public @interface BreakStrategy {}
59
60 /**
61 * Value for break strategy indicating simple line breaking. Automatic hyphens are not added
62 * (though soft hyphens are respected), and modifying text generally doesn't affect the layout
63 * before it (which yields a more consistent user experience when editing), but layout may not
64 * be the highest quality.
65 */
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -070066 public static final int BREAK_STRATEGY_SIMPLE = NativeLineBreaker.BREAK_STRATEGY_SIMPLE;
Raph Levien39b4db72015-03-25 13:18:20 -070067
68 /**
69 * Value for break strategy indicating high quality line breaking, including automatic
70 * hyphenation and doing whole-paragraph optimization of line breaks.
71 */
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -070072 public static final int BREAK_STRATEGY_HIGH_QUALITY =
73 NativeLineBreaker.BREAK_STRATEGY_HIGH_QUALITY;
Raph Levien39b4db72015-03-25 13:18:20 -070074
75 /**
76 * Value for break strategy indicating balanced line breaking. The breaks are chosen to
77 * make all lines as close to the same length as possible, including automatic hyphenation.
78 */
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -070079 public static final int BREAK_STRATEGY_BALANCED = NativeLineBreaker.BREAK_STRATEGY_BALANCED;
Raph Levien39b4db72015-03-25 13:18:20 -070080
Roozbeh Pournader95c7a132015-05-12 12:01:06 -070081 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -070082 @IntDef(prefix = { "HYPHENATION_FREQUENCY_" }, value = {
83 HYPHENATION_FREQUENCY_NORMAL,
84 HYPHENATION_FREQUENCY_FULL,
85 HYPHENATION_FREQUENCY_NONE
86 })
Roozbeh Pournader95c7a132015-05-12 12:01:06 -070087 @Retention(RetentionPolicy.SOURCE)
88 public @interface HyphenationFrequency {}
89
90 /**
91 * Value for hyphenation frequency indicating no automatic hyphenation. Useful
92 * for backward compatibility, and for cases where the automatic hyphenation algorithm results
93 * in incorrect hyphenation. Mid-word breaks may still happen when a word is wider than the
94 * layout and there is otherwise no valid break. Soft hyphens are ignored and will not be used
95 * as suggestions for potential line breaks.
96 */
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -070097 public static final int HYPHENATION_FREQUENCY_NONE =
98 NativeLineBreaker.HYPHENATION_FREQUENCY_NONE;
Roozbeh Pournader95c7a132015-05-12 12:01:06 -070099
100 /**
101 * Value for hyphenation frequency indicating a light amount of automatic hyphenation, which
102 * is a conservative default. Useful for informal cases, such as short sentences or chat
103 * messages.
104 */
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -0700105 public static final int HYPHENATION_FREQUENCY_NORMAL =
106 NativeLineBreaker.HYPHENATION_FREQUENCY_NORMAL;
Roozbeh Pournader95c7a132015-05-12 12:01:06 -0700107
108 /**
109 * Value for hyphenation frequency indicating the full amount of automatic hyphenation, typical
110 * in typography. Useful for running text and where it's important to put the maximum amount of
111 * text in a screen with limited space.
112 */
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -0700113 public static final int HYPHENATION_FREQUENCY_FULL =
114 NativeLineBreaker.HYPHENATION_FREQUENCY_FULL;
Roozbeh Pournader95c7a132015-05-12 12:01:06 -0700115
Doug Felt71b8dd72010-02-16 17:27:09 -0800116 private static final ParagraphStyle[] NO_PARA_SPANS =
117 ArrayUtils.emptyArray(ParagraphStyle.class);
Dave Bort76c02262009-04-13 17:17:21 -0700118
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700119 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -0700120 @IntDef(prefix = { "JUSTIFICATION_MODE_" }, value = {
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -0700121 NativeLineBreaker.JUSTIFICATION_MODE_NONE,
122 NativeLineBreaker.JUSTIFICATION_MODE_INTER_WORD
Jeff Sharkeyce8db992017-12-13 20:05:05 -0700123 })
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700124 @Retention(RetentionPolicy.SOURCE)
125 public @interface JustificationMode {}
126
127 /**
128 * Value for justification mode indicating no justification.
129 */
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -0700130 public static final int JUSTIFICATION_MODE_NONE = NativeLineBreaker.JUSTIFICATION_MODE_NONE;
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700131
132 /**
133 * Value for justification mode indicating the text is justified by stretching word spacing.
134 */
Seigo Nonaka41bb4fa2018-08-07 15:15:42 -0700135 public static final int JUSTIFICATION_MODE_INTER_WORD =
136 NativeLineBreaker.JUSTIFICATION_MODE_INTER_WORD;
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700137
Roozbeh Pournader22a167c2017-08-21 12:53:44 -0700138 /*
139 * Line spacing multiplier for default line spacing.
140 */
141 public static final float DEFAULT_LINESPACING_MULTIPLIER = 1.0f;
142
143 /*
144 * Line spacing addition for default line spacing.
145 */
146 public static final float DEFAULT_LINESPACING_ADDITION = 0.0f;
147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 /**
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700149 * Return how wide a layout must be in order to display the specified text with one line per
150 * paragraph.
151 *
152 * <p>As of O, Uses
153 * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
154 * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 */
156 public static float getDesiredWidth(CharSequence source,
157 TextPaint paint) {
158 return getDesiredWidth(source, 0, source.length(), paint);
159 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 /**
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700162 * Return how wide a layout must be in order to display the specified text slice with one
163 * line per paragraph.
164 *
165 * <p>As of O, Uses
166 * {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
167 * the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
168 */
169 public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint) {
170 return getDesiredWidth(source, start, end, paint, TextDirectionHeuristics.FIRSTSTRONG_LTR);
171 }
172
173 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800174 * Return how wide a layout must be in order to display the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 * specified text slice with one line per paragraph.
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700176 *
177 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 */
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700179 public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint,
180 TextDirectionHeuristic textDir) {
Seigo Nonaka917748e2017-08-03 17:42:28 -0700181 return getDesiredWidthWithLimit(source, start, end, paint, textDir, Float.MAX_VALUE);
182 }
183 /**
184 * Return how wide a layout must be in order to display the
185 * specified text slice with one line per paragraph.
186 *
187 * If the measured width exceeds given limit, returns limit value instead.
188 * @hide
189 */
190 public static float getDesiredWidthWithLimit(CharSequence source, int start, int end,
191 TextPaint paint, TextDirectionHeuristic textDir, float upperLimit) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 float need = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194 int next;
195 for (int i = start; i <= end; i = next) {
196 next = TextUtils.indexOf(source, '\n', i, end);
197
198 if (next < 0)
199 next = end;
200
Doug Felt71b8dd72010-02-16 17:27:09 -0800201 // note, omits trailing paragraph char
Siyamed Sinir79bf9d12016-05-18 19:57:52 -0700202 float w = measurePara(paint, source, i, next, textDir);
Seigo Nonaka917748e2017-08-03 17:42:28 -0700203 if (w > upperLimit) {
204 return upperLimit;
205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
207 if (w > need)
208 need = w;
209
210 next++;
211 }
212
213 return need;
214 }
215
216 /**
217 * Subclasses of Layout use this constructor to set the display text,
218 * width, and other standard properties.
Doug Felt71b8dd72010-02-16 17:27:09 -0800219 * @param text the text to render
220 * @param paint the default paint for the layout. Styles can override
221 * various attributes of the paint.
222 * @param width the wrapping width for the text.
223 * @param align whether to left, right, or center the text. Styles can
224 * override the alignment.
225 * @param spacingMult factor by which to scale the font size to get the
226 * default line spacing
227 * @param spacingAdd amount to add to the default line spacing
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 */
229 protected Layout(CharSequence text, TextPaint paint,
230 int width, Alignment align,
Doug Felt71b8dd72010-02-16 17:27:09 -0800231 float spacingMult, float spacingAdd) {
Doug Feltcb3791202011-07-07 11:57:48 -0700232 this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
233 spacingMult, spacingAdd);
234 }
235
236 /**
237 * Subclasses of Layout use this constructor to set the display text,
238 * width, and other standard properties.
239 * @param text the text to render
240 * @param paint the default paint for the layout. Styles can override
241 * various attributes of the paint.
242 * @param width the wrapping width for the text.
243 * @param align whether to left, right, or center the text. Styles can
244 * override the alignment.
245 * @param spacingMult factor by which to scale the font size to get the
246 * default line spacing
247 * @param spacingAdd amount to add to the default line spacing
248 *
249 * @hide
250 */
251 protected Layout(CharSequence text, TextPaint paint,
252 int width, Alignment align, TextDirectionHeuristic textDir,
253 float spacingMult, float spacingAdd) {
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 if (width < 0)
256 throw new IllegalArgumentException("Layout: " + width + " < 0");
257
Doug Felte8e45f22010-03-29 14:58:40 -0700258 // Ensure paint doesn't have baselineShift set.
259 // While normally we don't modify the paint the user passed in,
260 // we were already doing this in Styled.drawUniformRun with both
261 // baselineShift and bgColor. We probably should reevaluate bgColor.
262 if (paint != null) {
263 paint.bgColor = 0;
264 paint.baselineShift = 0;
265 }
266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 mText = text;
268 mPaint = paint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 mWidth = width;
270 mAlignment = align;
Doug Felt71b8dd72010-02-16 17:27:09 -0800271 mSpacingMult = spacingMult;
272 mSpacingAdd = spacingAdd;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 mSpannedText = text instanceof Spanned;
Doug Feltcb3791202011-07-07 11:57:48 -0700274 mTextDir = textDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 }
276
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900277 /** @hide */
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700278 protected void setJustificationMode(@JustificationMode int justificationMode) {
279 mJustificationMode = justificationMode;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900280 }
281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 /**
283 * Replace constructor properties of this Layout with new ones. Be careful.
284 */
285 /* package */ void replaceWith(CharSequence text, TextPaint paint,
286 int width, Alignment align,
287 float spacingmult, float spacingadd) {
288 if (width < 0) {
289 throw new IllegalArgumentException("Layout: " + width + " < 0");
290 }
291
292 mText = text;
293 mPaint = paint;
294 mWidth = width;
295 mAlignment = align;
296 mSpacingMult = spacingmult;
297 mSpacingAdd = spacingadd;
298 mSpannedText = text instanceof Spanned;
299 }
300
301 /**
302 * Draw this Layout on the specified Canvas.
303 */
304 public void draw(Canvas c) {
305 draw(c, null, null, 0);
306 }
307
308 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800309 * Draw this Layout on the specified canvas, with the highlight path drawn
310 * between the background and the text.
311 *
Gilles Debunne6c488de2012-03-01 16:20:35 -0800312 * @param canvas the canvas
Doug Felt71b8dd72010-02-16 17:27:09 -0800313 * @param highlight the path of the highlight or cursor; can be null
314 * @param highlightPaint the paint for the highlight
315 * @param cursorOffsetVertical the amount to temporarily translate the
316 * canvas while rendering the highlight
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 */
Gilles Debunne6c488de2012-03-01 16:20:35 -0800318 public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
319 int cursorOffsetVertical) {
320 final long lineRange = getLineRangeForDraw(canvas);
321 int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
322 int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
323 if (lastLine < 0) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324
Gilles Debunne6c488de2012-03-01 16:20:35 -0800325 drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
326 firstLine, lastLine);
327 drawText(canvas, firstLine, lastLine);
328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900330 private boolean isJustificationRequired(int lineNum) {
Seigo Nonaka4b4730d2017-03-31 09:42:16 -0700331 if (mJustificationMode == JUSTIFICATION_MODE_NONE) return false;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900332 final int lineEnd = getLineEnd(lineNum);
333 return lineEnd < mText.length() && mText.charAt(lineEnd - 1) != '\n';
334 }
335
336 private float getJustifyWidth(int lineNum) {
337 Alignment paraAlign = mAlignment;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900338
339 int left = 0;
340 int right = mWidth;
341
342 final int dir = getParagraphDirection(lineNum);
343
344 ParagraphStyle[] spans = NO_PARA_SPANS;
345 if (mSpannedText) {
346 Spanned sp = (Spanned) mText;
347 final int start = getLineStart(lineNum);
348
349 final boolean isFirstParaLine = (start == 0 || mText.charAt(start - 1) == '\n');
350
351 if (isFirstParaLine) {
352 final int spanEnd = sp.nextSpanTransition(start, mText.length(),
353 ParagraphStyle.class);
354 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
355
356 for (int n = spans.length - 1; n >= 0; n--) {
357 if (spans[n] instanceof AlignmentSpan) {
358 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
359 break;
360 }
361 }
362 }
363
364 final int length = spans.length;
365 boolean useFirstLineMargin = isFirstParaLine;
366 for (int n = 0; n < length; n++) {
367 if (spans[n] instanceof LeadingMarginSpan2) {
368 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
369 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
370 if (lineNum < startLine + count) {
371 useFirstLineMargin = true;
372 break;
373 }
374 }
375 }
376 for (int n = 0; n < length; n++) {
377 if (spans[n] instanceof LeadingMarginSpan) {
378 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
379 if (dir == DIR_RIGHT_TO_LEFT) {
380 right -= margin.getLeadingMargin(useFirstLineMargin);
381 } else {
382 left += margin.getLeadingMargin(useFirstLineMargin);
383 }
384 }
385 }
386 }
387
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900388 final Alignment align;
389 if (paraAlign == Alignment.ALIGN_LEFT) {
390 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
391 } else if (paraAlign == Alignment.ALIGN_RIGHT) {
392 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
393 } else {
394 align = paraAlign;
395 }
396
397 final int indentWidth;
398 if (align == Alignment.ALIGN_NORMAL) {
399 if (dir == DIR_LEFT_TO_RIGHT) {
400 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
401 } else {
402 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
403 }
404 } else if (align == Alignment.ALIGN_OPPOSITE) {
405 if (dir == DIR_LEFT_TO_RIGHT) {
406 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
407 } else {
408 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
409 }
410 } else { // Alignment.ALIGN_CENTER
411 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
412 }
413
414 return right - left - indentWidth;
415 }
416
Gilles Debunne6c488de2012-03-01 16:20:35 -0800417 /**
418 * @hide
419 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100420 @UnsupportedAppUsage
Gilles Debunne6c488de2012-03-01 16:20:35 -0800421 public void drawText(Canvas canvas, int firstLine, int lastLine) {
422 int previousLineBottom = getLineTop(firstLine);
423 int previousLineEnd = getLineStart(firstLine);
Doug Felt71b8dd72010-02-16 17:27:09 -0800424 ParagraphStyle[] spans = NO_PARA_SPANS;
Doug Feltc982f602010-05-25 11:51:40 -0700425 int spanEnd = 0;
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -0700426 final TextPaint paint = mWorkPaint;
427 paint.set(mPaint);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800428 CharSequence buf = mText;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700430 Alignment paraAlign = mAlignment;
Doug Feltc982f602010-05-25 11:51:40 -0700431 TabStops tabStops = null;
432 boolean tabStopsIsInitialized = false;
Doug Felt9f7a4442010-03-01 12:45:56 -0800433
Doug Felte8e45f22010-03-29 14:58:40 -0700434 TextLine tl = TextLine.obtain();
Doug Feltc982f602010-05-25 11:51:40 -0700435
Gilles Debunne6c488de2012-03-01 16:20:35 -0800436 // Draw the lines, one at a time.
437 // The baseline is the top of the following line minus the current line's descent.
Raph Levien26d443a2015-03-30 14:18:32 -0700438 for (int lineNum = firstLine; lineNum <= lastLine; lineNum++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 int start = previousLineEnd;
Raph Levien26d443a2015-03-30 14:18:32 -0700440 previousLineEnd = getLineStart(lineNum + 1);
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900441 final boolean justify = isJustificationRequired(lineNum);
Raph Levien26d443a2015-03-30 14:18:32 -0700442 int end = getLineVisibleEnd(lineNum, start, previousLineEnd);
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -0700443 paint.setHyphenEdit(getHyphen(lineNum));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444
445 int ltop = previousLineBottom;
Raph Levien26d443a2015-03-30 14:18:32 -0700446 int lbottom = getLineTop(lineNum + 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 previousLineBottom = lbottom;
Raph Levien26d443a2015-03-30 14:18:32 -0700448 int lbaseline = lbottom - getLineDescent(lineNum);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449
Raph Levien26d443a2015-03-30 14:18:32 -0700450 int dir = getParagraphDirection(lineNum);
Doug Feltc982f602010-05-25 11:51:40 -0700451 int left = 0;
452 int right = mWidth;
453
Gilles Debunne6c488de2012-03-01 16:20:35 -0800454 if (mSpannedText) {
Doug Feltc982f602010-05-25 11:51:40 -0700455 Spanned sp = (Spanned) buf;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800456 int textLength = buf.length();
457 boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
Doug Felt0c702b82010-05-14 10:55:42 -0700458
Doug Feltc982f602010-05-25 11:51:40 -0700459 // New batch of paragraph styles, collect into spans array.
460 // Compute the alignment, last alignment style wins.
461 // Reset tabStops, we'll rebuild if we encounter a line with
462 // tabs.
463 // We expect paragraph spans to be relatively infrequent, use
464 // spanEnd so that we can check less frequently. Since
465 // paragraph styles ought to apply to entire paragraphs, we can
466 // just collect the ones present at the start of the paragraph.
467 // If spanEnd is before the end of the paragraph, that's not
468 // our problem.
Raph Levien26d443a2015-03-30 14:18:32 -0700469 if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
Doug Feltc982f602010-05-25 11:51:40 -0700470 spanEnd = sp.nextSpanTransition(start, textLength,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 ParagraphStyle.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -0700472 spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
Doug Felt9f7a4442010-03-01 12:45:56 -0800473
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700474 paraAlign = mAlignment;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800475 for (int n = spans.length - 1; n >= 0; n--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 if (spans[n] instanceof AlignmentSpan) {
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700477 paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 break;
479 }
480 }
Doug Felt0c702b82010-05-14 10:55:42 -0700481
Doug Feltc982f602010-05-25 11:51:40 -0700482 tabStopsIsInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800484
Doug Feltc982f602010-05-25 11:51:40 -0700485 // Draw all leading margin spans. Adjust left or right according
486 // to the paragraph direction of the line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 final int length = spans.length;
Anish Athalyeab08c6d2014-08-08 12:09:58 -0700488 boolean useFirstLineMargin = isFirstParaLine;
489 for (int n = 0; n < length; n++) {
490 if (spans[n] instanceof LeadingMarginSpan2) {
491 int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
492 int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
493 // if there is more than one LeadingMarginSpan2, use
494 // the count that is greatest
Raph Levien26d443a2015-03-30 14:18:32 -0700495 if (lineNum < startLine + count) {
Anish Athalyeab08c6d2014-08-08 12:09:58 -0700496 useFirstLineMargin = true;
497 break;
498 }
499 }
500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 for (int n = 0; n < length; n++) {
502 if (spans[n] instanceof LeadingMarginSpan) {
503 LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 if (dir == DIR_RIGHT_TO_LEFT) {
Gilles Debunne6c488de2012-03-01 16:20:35 -0800505 margin.drawLeadingMargin(canvas, paint, right, dir, ltop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 lbaseline, lbottom, buf,
Doug Felt71b8dd72010-02-16 17:27:09 -0800507 start, end, isFirstParaLine, this);
Doug Feltc982f602010-05-25 11:51:40 -0700508 right -= margin.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 } else {
Gilles Debunne6c488de2012-03-01 16:20:35 -0800510 margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 lbaseline, lbottom, buf,
Doug Felt71b8dd72010-02-16 17:27:09 -0800512 start, end, isFirstParaLine, this);
Doug Feltc982f602010-05-25 11:51:40 -0700513 left += margin.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 }
515 }
516 }
517 }
518
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700519 boolean hasTab = getLineContainsTab(lineNum);
Doug Feltc982f602010-05-25 11:51:40 -0700520 // Can't tell if we have tabs for sure, currently
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700521 if (hasTab && !tabStopsIsInitialized) {
Doug Feltc982f602010-05-25 11:51:40 -0700522 if (tabStops == null) {
523 tabStops = new TabStops(TAB_INCREMENT, spans);
524 } else {
525 tabStops.reset(TAB_INCREMENT, spans);
526 }
527 tabStopsIsInitialized = true;
528 }
529
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700530 // Determine whether the line aligns to normal, opposite, or center.
531 Alignment align = paraAlign;
532 if (align == Alignment.ALIGN_LEFT) {
533 align = (dir == DIR_LEFT_TO_RIGHT) ?
534 Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
535 } else if (align == Alignment.ALIGN_RIGHT) {
536 align = (dir == DIR_LEFT_TO_RIGHT) ?
537 Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
538 }
539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 int x;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900541 final int indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 if (align == Alignment.ALIGN_NORMAL) {
543 if (dir == DIR_LEFT_TO_RIGHT) {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900544 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
545 x = left + indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 } else {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900547 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
548 x = right - indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 }
550 } else {
Raph Levien26d443a2015-03-30 14:18:32 -0700551 int max = (int)getLineExtent(lineNum, tabStops, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 if (align == Alignment.ALIGN_OPPOSITE) {
Doug Feltc982f602010-05-25 11:51:40 -0700553 if (dir == DIR_LEFT_TO_RIGHT) {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900554 indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
555 x = right - max - indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 } else {
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900557 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
558 x = left - max + indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 }
Doug Feltc982f602010-05-25 11:51:40 -0700560 } else { // Alignment.ALIGN_CENTER
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900561 indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
Doug Feltc982f602010-05-25 11:51:40 -0700562 max = max & ~1;
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900563 x = ((right + left - max) >> 1) + indentWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 }
565 }
566
Raph Levien26d443a2015-03-30 14:18:32 -0700567 Directions directions = getLineDirections(lineNum);
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900568 if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTab && !justify) {
Doug Felt71b8dd72010-02-16 17:27:09 -0800569 // XXX: assumes there's nothing additional to be done
Gilles Debunne6c488de2012-03-01 16:20:35 -0800570 canvas.drawText(buf, start, end, x, lbaseline, paint);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 } else {
Mihai Popace642dc2018-05-24 14:25:11 +0100572 tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops,
573 getEllipsisStart(lineNum),
574 getEllipsisStart(lineNum) + getEllipsisCount(lineNum));
Seigo Nonaka09da71a2016-11-28 16:24:14 +0900575 if (justify) {
576 tl.justify(right - left - indentWidth);
577 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800578 tl.draw(canvas, x, ltop, lbaseline, lbottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 }
580 }
Doug Feltc982f602010-05-25 11:51:40 -0700581
Doug Felte8e45f22010-03-29 14:58:40 -0700582 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584
585 /**
Gilles Debunne6c488de2012-03-01 16:20:35 -0800586 * @hide
587 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100588 @UnsupportedAppUsage
Gilles Debunne6c488de2012-03-01 16:20:35 -0800589 public void drawBackground(Canvas canvas, Path highlight, Paint highlightPaint,
590 int cursorOffsetVertical, int firstLine, int lastLine) {
591 // First, draw LineBackgroundSpans.
592 // LineBackgroundSpans know nothing about the alignment, margins, or
593 // direction of the layout or line. XXX: Should they?
594 // They are evaluated at each line.
595 if (mSpannedText) {
Gilles Debunneeca5b732012-04-25 18:48:42 -0700596 if (mLineBackgroundSpans == null) {
597 mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700598 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800599
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700600 Spanned buffer = (Spanned) mText;
601 int textLength = buffer.length();
Gilles Debunneeca5b732012-04-25 18:48:42 -0700602 mLineBackgroundSpans.init(buffer, 0, textLength);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800603
Gilles Debunneeca5b732012-04-25 18:48:42 -0700604 if (mLineBackgroundSpans.numberOfSpans > 0) {
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700605 int previousLineBottom = getLineTop(firstLine);
606 int previousLineEnd = getLineStart(firstLine);
607 ParagraphStyle[] spans = NO_PARA_SPANS;
608 int spansLength = 0;
609 TextPaint paint = mPaint;
610 int spanEnd = 0;
611 final int width = mWidth;
612 for (int i = firstLine; i <= lastLine; i++) {
613 int start = previousLineEnd;
614 int end = getLineStart(i + 1);
615 previousLineEnd = end;
Gilles Debunne6c488de2012-03-01 16:20:35 -0800616
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700617 int ltop = previousLineBottom;
618 int lbottom = getLineTop(i + 1);
619 previousLineBottom = lbottom;
620 int lbaseline = lbottom - getLineDescent(i);
621
Haoyu Zhang60b09832018-09-10 10:49:56 -0700622 if (end >= spanEnd) {
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700623 // These should be infrequent, so we'll use this so that
624 // we don't have to check as often.
Gilles Debunneeca5b732012-04-25 18:48:42 -0700625 spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700626 // All LineBackgroundSpans on a line contribute to its background.
627 spansLength = 0;
628 // Duplication of the logic of getParagraphSpans
629 if (start != end || start == 0) {
630 // Equivalent to a getSpans(start, end), but filling the 'spans' local
631 // array instead to reduce memory allocation
Gilles Debunneeca5b732012-04-25 18:48:42 -0700632 for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
633 // equal test is valid since both intervals are not empty by
634 // construction
635 if (mLineBackgroundSpans.spanStarts[j] >= end ||
636 mLineBackgroundSpans.spanEnds[j] <= start) continue;
Adam Lesinski776abc22014-03-07 11:30:59 -0500637 spans = GrowingArrayUtils.append(
638 spans, spansLength, mLineBackgroundSpans.spans[j]);
639 spansLength++;
Gilles Debunne60e3b3f2012-03-13 11:26:05 -0700640 }
641 }
642 }
643
644 for (int n = 0; n < spansLength; n++) {
645 LineBackgroundSpan lineBackgroundSpan = (LineBackgroundSpan) spans[n];
646 lineBackgroundSpan.drawBackground(canvas, paint, 0, width,
647 ltop, lbaseline, lbottom,
648 buffer, start, end, i);
649 }
Gilles Debunne6c488de2012-03-01 16:20:35 -0800650 }
651 }
Gilles Debunneeca5b732012-04-25 18:48:42 -0700652 mLineBackgroundSpans.recycle();
Gilles Debunne6c488de2012-03-01 16:20:35 -0800653 }
654
655 // There can be a highlight even without spans if we are drawing
656 // a non-spanned transformation of a spanned editing buffer.
657 if (highlight != null) {
658 if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
659 canvas.drawPath(highlight, highlightPaint);
660 if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
661 }
662 }
663
664 /**
665 * @param canvas
666 * @return The range of lines that need to be drawn, possibly empty.
667 * @hide
668 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100669 @UnsupportedAppUsage
Gilles Debunne6c488de2012-03-01 16:20:35 -0800670 public long getLineRangeForDraw(Canvas canvas) {
671 int dtop, dbottom;
672
673 synchronized (sTempRect) {
674 if (!canvas.getClipBounds(sTempRect)) {
675 // Negative range end used as a special flag
676 return TextUtils.packRangeInLong(0, -1);
677 }
678
679 dtop = sTempRect.top;
680 dbottom = sTempRect.bottom;
681 }
682
683 final int top = Math.max(dtop, 0);
684 final int bottom = Math.min(getLineTop(getLineCount()), dbottom);
685
Gilles Debunne2fba3382012-06-11 17:46:24 -0700686 if (top >= bottom) return TextUtils.packRangeInLong(0, -1);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800687 return TextUtils.packRangeInLong(getLineForVertical(top), getLineForVertical(bottom));
688 }
689
690 /**
Doug Feltc982f602010-05-25 11:51:40 -0700691 * Return the start position of the line, given the left and right bounds
692 * of the margins.
Doug Felt0c702b82010-05-14 10:55:42 -0700693 *
Doug Feltc982f602010-05-25 11:51:40 -0700694 * @param line the line index
695 * @param left the left bounds (0, or leading margin if ltr para)
696 * @param right the right bounds (width, minus leading margin if rtl para)
697 * @return the start position of the line (to right of line if rtl para)
698 */
699 private int getLineStartPos(int line, int left, int right) {
700 // Adjust the point at which to start rendering depending on the
701 // alignment of the paragraph.
702 Alignment align = getParagraphAlignment(line);
703 int dir = getParagraphDirection(line);
704
Doug Feltc0ccf0c2011-06-23 16:13:18 -0700705 if (align == Alignment.ALIGN_LEFT) {
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700706 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
707 } else if (align == Alignment.ALIGN_RIGHT) {
708 align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
709 }
710
711 int x;
712 if (align == Alignment.ALIGN_NORMAL) {
Doug Feltc982f602010-05-25 11:51:40 -0700713 if (dir == DIR_LEFT_TO_RIGHT) {
Raph Levien2ea52902015-07-01 14:39:31 -0700714 x = left + getIndentAdjust(line, Alignment.ALIGN_LEFT);
Doug Feltc982f602010-05-25 11:51:40 -0700715 } else {
Raph Levien2ea52902015-07-01 14:39:31 -0700716 x = right + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
Doug Feltc982f602010-05-25 11:51:40 -0700717 }
718 } else {
719 TabStops tabStops = null;
720 if (mSpannedText && getLineContainsTab(line)) {
721 Spanned spanned = (Spanned) mText;
722 int start = getLineStart(line);
723 int spanEnd = spanned.nextSpanTransition(start, spanned.length(),
724 TabStopSpan.class);
Gilles Debunne6c488de2012-03-01 16:20:35 -0800725 TabStopSpan[] tabSpans = getParagraphSpans(spanned, start, spanEnd,
726 TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -0700727 if (tabSpans.length > 0) {
728 tabStops = new TabStops(TAB_INCREMENT, tabSpans);
729 }
730 }
731 int max = (int)getLineExtent(line, tabStops, false);
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700732 if (align == Alignment.ALIGN_OPPOSITE) {
Doug Feltc982f602010-05-25 11:51:40 -0700733 if (dir == DIR_LEFT_TO_RIGHT) {
Raph Levien2ea52902015-07-01 14:39:31 -0700734 x = right - max + getIndentAdjust(line, Alignment.ALIGN_RIGHT);
Doug Feltc982f602010-05-25 11:51:40 -0700735 } else {
Fabrice Di Megliodb24f0a2012-10-03 17:17:14 -0700736 // max is negative here
Raph Levien2ea52902015-07-01 14:39:31 -0700737 x = left - max + getIndentAdjust(line, Alignment.ALIGN_LEFT);
Doug Feltc982f602010-05-25 11:51:40 -0700738 }
739 } else { // Alignment.ALIGN_CENTER
740 max = max & ~1;
Raph Levien2ea52902015-07-01 14:39:31 -0700741 x = (left + right - max) >> 1 + getIndentAdjust(line, Alignment.ALIGN_CENTER);
Doug Feltc982f602010-05-25 11:51:40 -0700742 }
743 }
744 return x;
745 }
746
747 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 * Return the text that is displayed by this Layout.
749 */
750 public final CharSequence getText() {
751 return mText;
752 }
753
754 /**
755 * Return the base Paint properties for this layout.
756 * Do NOT change the paint, which may result in funny
757 * drawing for this layout.
758 */
759 public final TextPaint getPaint() {
760 return mPaint;
761 }
762
763 /**
764 * Return the width of this layout.
765 */
766 public final int getWidth() {
767 return mWidth;
768 }
769
770 /**
771 * Return the width to which this Layout is ellipsizing, or
772 * {@link #getWidth} if it is not doing anything special.
773 */
774 public int getEllipsizedWidth() {
775 return mWidth;
776 }
777
778 /**
779 * Increase the width of this layout to the specified width.
Doug Felt71b8dd72010-02-16 17:27:09 -0800780 * Be careful to use this only when you know it is appropriate&mdash;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 * it does not cause the text to reflow to use the full new width.
782 */
783 public final void increaseWidthTo(int wid) {
784 if (wid < mWidth) {
785 throw new RuntimeException("attempted to reduce Layout width");
786 }
787
788 mWidth = wid;
789 }
Doug Felt9f7a4442010-03-01 12:45:56 -0800790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 /**
792 * Return the total height of this layout.
793 */
794 public int getHeight() {
Doug Felt71b8dd72010-02-16 17:27:09 -0800795 return getLineTop(getLineCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
797
798 /**
Siyamed Sinir0745c722016-05-31 20:39:33 -0700799 * Return the total height of this layout.
800 *
801 * @param cap if true and max lines is set, returns the height of the layout at the max lines.
802 *
803 * @hide
804 */
805 public int getHeight(boolean cap) {
806 return getHeight();
807 }
808
809 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 * Return the base alignment of this layout.
811 */
812 public final Alignment getAlignment() {
813 return mAlignment;
814 }
815
816 /**
817 * Return what the text height is multiplied by to get the line height.
818 */
819 public final float getSpacingMultiplier() {
820 return mSpacingMult;
821 }
822
823 /**
824 * Return the number of units of leading that are added to each line.
825 */
826 public final float getSpacingAdd() {
827 return mSpacingAdd;
828 }
829
830 /**
Doug Feltcb3791202011-07-07 11:57:48 -0700831 * Return the heuristic used to determine paragraph text direction.
832 * @hide
833 */
834 public final TextDirectionHeuristic getTextDirectionHeuristic() {
835 return mTextDir;
836 }
837
838 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 * Return the number of lines of text in this layout.
840 */
841 public abstract int getLineCount();
Doug Felt9f7a4442010-03-01 12:45:56 -0800842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 /**
844 * Return the baseline for the specified line (0&hellip;getLineCount() - 1)
845 * If bounds is not null, return the top, left, right, bottom extents
846 * of the specified line in it.
847 * @param line which line to examine (0..getLineCount() - 1)
848 * @param bounds Optional. If not null, it returns the extent of the line
849 * @return the Y-coordinate of the baseline
850 */
851 public int getLineBounds(int line, Rect bounds) {
852 if (bounds != null) {
853 bounds.left = 0; // ???
854 bounds.top = getLineTop(line);
855 bounds.right = mWidth; // ???
Doug Felt71b8dd72010-02-16 17:27:09 -0800856 bounds.bottom = getLineTop(line + 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 }
858 return getLineBaseline(line);
859 }
860
861 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800862 * Return the vertical position of the top of the specified line
863 * (0&hellip;getLineCount()).
864 * If the specified line is equal to the line count, returns the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 * bottom of the last line.
866 */
867 public abstract int getLineTop(int line);
868
869 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800870 * Return the descent of the specified line(0&hellip;getLineCount() - 1).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 */
872 public abstract int getLineDescent(int line);
873
874 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800875 * Return the text offset of the beginning of the specified line (
876 * 0&hellip;getLineCount()). If the specified line is equal to the line
877 * count, returns the length of the text.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 */
879 public abstract int getLineStart(int line);
880
881 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800882 * Returns the primary directionality of the paragraph containing the
883 * specified line, either 1 for left-to-right lines, or -1 for right-to-left
884 * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 */
886 public abstract int getParagraphDirection(int line);
887
888 /**
The Android Open Source Project10592532009-03-18 17:39:46 -0700889 * Returns whether the specified line contains one or more
Roozbeh Pournader112d9c72015-08-07 12:44:41 -0700890 * characters that need to be handled specially, like tabs.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 */
892 public abstract boolean getLineContainsTab(int line);
893
894 /**
Doug Felt71b8dd72010-02-16 17:27:09 -0800895 * Returns the directional run information for the specified line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 * The array alternates counts of characters in left-to-right
897 * and right-to-left segments of the line.
Doug Felt71b8dd72010-02-16 17:27:09 -0800898 *
899 * <p>NOTE: this is inadequate to support bidirectional text, and will change.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 */
901 public abstract Directions getLineDirections(int line);
902
903 /**
904 * Returns the (negative) number of extra pixels of ascent padding in the
905 * top line of the Layout.
906 */
907 public abstract int getTopPadding();
908
909 /**
910 * Returns the number of extra pixels of descent padding in the
911 * bottom line of the Layout.
912 */
913 public abstract int getBottomPadding();
914
Raph Levien26d443a2015-03-30 14:18:32 -0700915 /**
916 * Returns the hyphen edit for a line.
917 *
918 * @hide
919 */
920 public int getHyphen(int line) {
921 return 0;
922 }
923
Raph Levien2ea52902015-07-01 14:39:31 -0700924 /**
925 * Returns the left indent for a line.
926 *
927 * @hide
928 */
929 public int getIndentAdjust(int line, Alignment alignment) {
930 return 0;
931 }
Doug Felt4e0c5e52010-03-15 16:56:02 -0700932
933 /**
934 * Returns true if the character at offset and the preceding character
935 * are at different run levels (and thus there's a split caret).
936 * @param offset the offset
937 * @return true if at a level boundary
Gilles Debunnef75c97e2011-02-10 16:09:53 -0800938 * @hide
Doug Felt4e0c5e52010-03-15 16:56:02 -0700939 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100940 @UnsupportedAppUsage
Gilles Debunnef75c97e2011-02-10 16:09:53 -0800941 public boolean isLevelBoundary(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -0800942 int line = getLineForOffset(offset);
Doug Felt4e0c5e52010-03-15 16:56:02 -0700943 Directions dirs = getLineDirections(line);
944 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
945 return false;
946 }
947
948 int[] runs = dirs.mDirections;
Doug Felt9f7a4442010-03-01 12:45:56 -0800949 int lineStart = getLineStart(line);
Doug Felt4e0c5e52010-03-15 16:56:02 -0700950 int lineEnd = getLineEnd(line);
951 if (offset == lineStart || offset == lineEnd) {
952 int paraLevel = getParagraphDirection(line) == 1 ? 0 : 1;
953 int runIndex = offset == lineStart ? 0 : runs.length - 2;
954 return ((runs[runIndex + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK) != paraLevel;
955 }
956
957 offset -= lineStart;
Doug Felt9f7a4442010-03-01 12:45:56 -0800958 for (int i = 0; i < runs.length; i += 2) {
Doug Felt4e0c5e52010-03-15 16:56:02 -0700959 if (offset == runs[i]) {
960 return true;
Doug Felt9f7a4442010-03-01 12:45:56 -0800961 }
962 }
Doug Felt4e0c5e52010-03-15 16:56:02 -0700963 return false;
Doug Felt9f7a4442010-03-01 12:45:56 -0800964 }
965
Fabrice Di Meglio34d2eba2011-08-31 19:46:15 -0700966 /**
967 * Returns true if the character at offset is right to left (RTL).
968 * @param offset the offset
969 * @return true if the character is RTL, false if it is LTR
970 */
971 public boolean isRtlCharAt(int offset) {
972 int line = getLineForOffset(offset);
973 Directions dirs = getLineDirections(line);
974 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
975 return false;
976 }
977 if (dirs == DIRS_ALL_RIGHT_TO_LEFT) {
978 return true;
979 }
980 int[] runs = dirs.mDirections;
981 int lineStart = getLineStart(line);
982 for (int i = 0; i < runs.length; i += 2) {
Raph Levien87506202014-09-04 12:47:03 -0700983 int start = lineStart + runs[i];
984 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
985 if (offset >= start && offset < limit) {
Fabrice Di Meglio34d2eba2011-08-31 19:46:15 -0700986 int level = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
987 return ((level & 1) != 0);
988 }
989 }
990 // Should happen only if the offset is "out of bounds"
991 return false;
992 }
993
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +0900994 /**
995 * Returns the range of the run that the character at offset belongs to.
996 * @param offset the offset
997 * @return The range of the run
998 * @hide
999 */
1000 public long getRunRange(int offset) {
1001 int line = getLineForOffset(offset);
1002 Directions dirs = getLineDirections(line);
1003 if (dirs == DIRS_ALL_LEFT_TO_RIGHT || dirs == DIRS_ALL_RIGHT_TO_LEFT) {
1004 return TextUtils.packRangeInLong(0, getLineEnd(line));
1005 }
1006 int[] runs = dirs.mDirections;
1007 int lineStart = getLineStart(line);
1008 for (int i = 0; i < runs.length; i += 2) {
1009 int start = lineStart + runs[i];
1010 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1011 if (offset >= start && offset < limit) {
1012 return TextUtils.packRangeInLong(start, limit);
1013 }
1014 }
1015 // Should happen only if the offset is "out of bounds"
1016 return TextUtils.packRangeInLong(0, getLineEnd(line));
1017 }
1018
Mihai Popa7626c862018-05-09 17:31:48 +01001019 /**
1020 * Checks if the trailing BiDi level should be used for an offset
1021 *
1022 * This method is useful when the offset is at the BiDi level transition point and determine
1023 * which run need to be used. For example, let's think about following input: (L* denotes
1024 * Left-to-Right characters, R* denotes Right-to-Left characters.)
1025 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1026 * Input (Display Order): L1 L2 L3 R3 R2 R1 L4 L5 L6
1027 *
1028 * Then, think about selecting the range (3, 6). The offset=3 and offset=6 are ambiguous here
1029 * since they are at the BiDi transition point. In Android, the offset is considered to be
1030 * associated with the trailing run if the BiDi level of the trailing run is higher than of the
1031 * previous run. In this case, the BiDi level of the input text is as follows:
1032 *
1033 * Input (Logical Order): L1 L2 L3 R1 R2 R3 L4 L5 L6
1034 * BiDi Run: [ Run 0 ][ Run 1 ][ Run 2 ]
1035 * BiDi Level: 0 0 0 1 1 1 0 0 0
1036 *
1037 * Thus, offset = 3 is part of Run 1 and this method returns true for offset = 3, since the BiDi
1038 * level of Run 1 is higher than the level of Run 0. Similarly, the offset = 6 is a part of Run
1039 * 1 and this method returns false for the offset = 6 since the BiDi level of Run 1 is higher
1040 * than the level of Run 2.
1041 *
1042 * @returns true if offset is at the BiDi level transition point and trailing BiDi level is
1043 * higher than previous BiDi level. See above for the detail.
1044 * @hide
1045 */
Seigo Nonaka19e75a62018-05-16 16:57:33 -07001046 @VisibleForTesting
1047 public boolean primaryIsTrailingPrevious(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001048 int line = getLineForOffset(offset);
1049 int lineStart = getLineStart(line);
Doug Felt4e0c5e52010-03-15 16:56:02 -07001050 int lineEnd = getLineEnd(line);
Doug Felt9f7a4442010-03-01 12:45:56 -08001051 int[] runs = getLineDirections(line).mDirections;
1052
1053 int levelAt = -1;
1054 for (int i = 0; i < runs.length; i += 2) {
1055 int start = lineStart + runs[i];
1056 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1057 if (limit > lineEnd) {
1058 limit = lineEnd;
1059 }
1060 if (offset >= start && offset < limit) {
1061 if (offset > start) {
1062 // Previous character is at same level, so don't use trailing.
1063 return false;
1064 }
1065 levelAt = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1066 break;
1067 }
1068 }
1069 if (levelAt == -1) {
1070 // Offset was limit of line.
1071 levelAt = getParagraphDirection(line) == 1 ? 0 : 1;
1072 }
1073
1074 // At level boundary, check previous level.
1075 int levelBefore = -1;
1076 if (offset == lineStart) {
1077 levelBefore = getParagraphDirection(line) == 1 ? 0 : 1;
1078 } else {
1079 offset -= 1;
1080 for (int i = 0; i < runs.length; i += 2) {
1081 int start = lineStart + runs[i];
1082 int limit = start + (runs[i+1] & RUN_LENGTH_MASK);
1083 if (limit > lineEnd) {
1084 limit = lineEnd;
1085 }
1086 if (offset >= start && offset < limit) {
1087 levelBefore = (runs[i+1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK;
1088 break;
1089 }
1090 }
1091 }
1092
1093 return levelBefore < levelAt;
1094 }
1095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001097 * Computes in linear time the results of calling
1098 * #primaryIsTrailingPrevious for all offsets on a line.
1099 * @param line The line giving the offsets we compute the information for
1100 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1101 * @hide
1102 */
1103 @VisibleForTesting
1104 public boolean[] primaryIsTrailingPreviousAllLineOffsets(int line) {
1105 int lineStart = getLineStart(line);
1106 int lineEnd = getLineEnd(line);
1107 int[] runs = getLineDirections(line).mDirections;
1108
1109 boolean[] trailing = new boolean[lineEnd - lineStart + 1];
1110
1111 byte[] level = new byte[lineEnd - lineStart + 1];
1112 for (int i = 0; i < runs.length; i += 2) {
1113 int start = lineStart + runs[i];
1114 int limit = start + (runs[i + 1] & RUN_LENGTH_MASK);
1115 if (limit > lineEnd) {
1116 limit = lineEnd;
1117 }
1118 level[limit - lineStart - 1] =
1119 (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1120 }
1121
1122 for (int i = 0; i < runs.length; i += 2) {
1123 int start = lineStart + runs[i];
1124 byte currentLevel = (byte) ((runs[i + 1] >>> RUN_LEVEL_SHIFT) & RUN_LEVEL_MASK);
1125 trailing[start - lineStart] = currentLevel > (start == lineStart
1126 ? (getParagraphDirection(line) == 1 ? 0 : 1)
1127 : level[start - lineStart - 1]);
1128 }
1129
1130 return trailing;
1131 }
1132
1133 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 * Get the primary horizontal position for the specified text offset.
1135 * This is the location where a new character would be inserted in
1136 * the paragraph's primary direction.
1137 */
1138 public float getPrimaryHorizontal(int offset) {
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001139 return getPrimaryHorizontal(offset, false /* not clamped */);
Raph Levienafe8e9b2012-12-19 16:09:32 -08001140 }
1141
1142 /**
1143 * Get the primary horizontal position for the specified text offset, but
1144 * optionally clamp it so that it doesn't exceed the width of the layout.
1145 * @hide
1146 */
Mathew Inwoodefeab842018-08-14 15:21:30 +01001147 @UnsupportedAppUsage
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001148 public float getPrimaryHorizontal(int offset, boolean clamped) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001149 boolean trailing = primaryIsTrailingPrevious(offset);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001150 return getHorizontal(offset, trailing, clamped);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
1152
1153 /**
1154 * Get the secondary horizontal position for the specified text offset.
1155 * This is the location where a new character would be inserted in
1156 * the direction other than the paragraph's primary direction.
1157 */
1158 public float getSecondaryHorizontal(int offset) {
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001159 return getSecondaryHorizontal(offset, false /* not clamped */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
1161
Raph Levienafe8e9b2012-12-19 16:09:32 -08001162 /**
1163 * Get the secondary horizontal position for the specified text offset, but
1164 * optionally clamp it so that it doesn't exceed the width of the layout.
1165 * @hide
1166 */
Mathew Inwoodefeab842018-08-14 15:21:30 +01001167 @UnsupportedAppUsage
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001168 public float getSecondaryHorizontal(int offset, boolean clamped) {
Raph Levienafe8e9b2012-12-19 16:09:32 -08001169 boolean trailing = primaryIsTrailingPrevious(offset);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001170 return getHorizontal(offset, !trailing, clamped);
Raph Levienafe8e9b2012-12-19 16:09:32 -08001171 }
1172
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001173 private float getHorizontal(int offset, boolean primary) {
1174 return primary ? getPrimaryHorizontal(offset) : getSecondaryHorizontal(offset);
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09001175 }
1176
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001177 private float getHorizontal(int offset, boolean trailing, boolean clamped) {
1178 int line = getLineForOffset(offset);
1179
Raph Levienafe8e9b2012-12-19 16:09:32 -08001180 return getHorizontal(offset, trailing, line, clamped);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
1182
Raph Levienafe8e9b2012-12-19 16:09:32 -08001183 private float getHorizontal(int offset, boolean trailing, int line, boolean clamped) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 int start = getLineStart(line);
Doug Felte8e45f22010-03-29 14:58:40 -07001185 int end = getLineEnd(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 int dir = getParagraphDirection(line);
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001187 boolean hasTab = getLineContainsTab(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 Directions directions = getLineDirections(line);
1189
Doug Feltc982f602010-05-25 11:51:40 -07001190 TabStops tabStops = null;
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001191 if (hasTab && mText instanceof Spanned) {
Doug Feltc982f602010-05-25 11:51:40 -07001192 // Just checking this line should be good enough, tabs should be
1193 // consistent across all lines in a paragraph.
Eric Fischer74d31ef2010-08-05 15:29:36 -07001194 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -07001195 if (tabs.length > 0) {
1196 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
1199
Doug Felte8e45f22010-03-29 14:58:40 -07001200 TextLine tl = TextLine.obtain();
Mihai Popace642dc2018-05-24 14:25:11 +01001201 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops,
1202 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Doug Felte8e45f22010-03-29 14:58:40 -07001203 float wid = tl.measure(offset - start, trailing, null);
1204 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205
Raph Levienafe8e9b2012-12-19 16:09:32 -08001206 if (clamped && wid > mWidth) {
1207 wid = mWidth;
1208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 int left = getParagraphLeft(line);
1210 int right = getParagraphRight(line);
1211
Doug Feltc982f602010-05-25 11:51:40 -07001212 return getLineStartPos(line, left, right) + wid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 }
1214
1215 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001216 * Computes in linear time the results of calling
1217 * #getHorizontal for all offsets on a line.
1218 * @param line The line giving the offsets we compute information for
1219 * @param clamped Whether to clamp the results to the width of the layout
1220 * @param primary Whether the results should be the primary or the secondary horizontal
1221 * @return The array of results, indexed from 0, where 0 corresponds to the line start offset
1222 */
1223 private float[] getLineHorizontals(int line, boolean clamped, boolean primary) {
1224 int start = getLineStart(line);
1225 int end = getLineEnd(line);
1226 int dir = getParagraphDirection(line);
1227 boolean hasTab = getLineContainsTab(line);
1228 Directions directions = getLineDirections(line);
1229
1230 TabStops tabStops = null;
1231 if (hasTab && mText instanceof Spanned) {
1232 // Just checking this line should be good enough, tabs should be
1233 // consistent across all lines in a paragraph.
1234 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
1235 if (tabs.length > 0) {
1236 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1237 }
1238 }
1239
1240 TextLine tl = TextLine.obtain();
Mihai Popace642dc2018-05-24 14:25:11 +01001241 tl.set(mPaint, mText, start, end, dir, directions, hasTab, tabStops,
1242 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Mihai Popa7626c862018-05-09 17:31:48 +01001243 boolean[] trailings = primaryIsTrailingPreviousAllLineOffsets(line);
1244 if (!primary) {
1245 for (int offset = 0; offset < trailings.length; ++offset) {
1246 trailings[offset] = !trailings[offset];
1247 }
1248 }
1249 float[] wid = tl.measureAllOffsets(trailings, null);
1250 TextLine.recycle(tl);
1251
1252 if (clamped) {
1253 for (int offset = 0; offset <= wid.length; ++offset) {
1254 if (wid[offset] > mWidth) {
1255 wid[offset] = mWidth;
1256 }
1257 }
1258 }
1259 int left = getParagraphLeft(line);
1260 int right = getParagraphRight(line);
1261
1262 int lineStartPos = getLineStartPos(line, left, right);
1263 float[] horizontal = new float[end - start + 1];
1264 for (int offset = 0; offset < horizontal.length; ++offset) {
1265 horizontal[offset] = lineStartPos + wid[offset];
1266 }
1267 return horizontal;
1268 }
1269
1270 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 * Get the leftmost position that should be exposed for horizontal
1272 * scrolling on the specified line.
1273 */
1274 public float getLineLeft(int line) {
1275 int dir = getParagraphDirection(line);
1276 Alignment align = getParagraphAlignment(line);
1277
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001278 if (align == Alignment.ALIGN_LEFT) {
1279 return 0;
1280 } else if (align == Alignment.ALIGN_NORMAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 if (dir == DIR_RIGHT_TO_LEFT)
1282 return getParagraphRight(line) - getLineMax(line);
1283 else
1284 return 0;
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001285 } else if (align == Alignment.ALIGN_RIGHT) {
1286 return mWidth - getLineMax(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 } else if (align == Alignment.ALIGN_OPPOSITE) {
1288 if (dir == DIR_RIGHT_TO_LEFT)
1289 return 0;
1290 else
1291 return mWidth - getLineMax(line);
1292 } else { /* align == Alignment.ALIGN_CENTER */
1293 int left = getParagraphLeft(line);
1294 int right = getParagraphRight(line);
1295 int max = ((int) getLineMax(line)) & ~1;
1296
1297 return left + ((right - left) - max) / 2;
1298 }
1299 }
1300
1301 /**
1302 * Get the rightmost position that should be exposed for horizontal
1303 * scrolling on the specified line.
1304 */
1305 public float getLineRight(int line) {
1306 int dir = getParagraphDirection(line);
1307 Alignment align = getParagraphAlignment(line);
1308
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001309 if (align == Alignment.ALIGN_LEFT) {
1310 return getParagraphLeft(line) + getLineMax(line);
1311 } else if (align == Alignment.ALIGN_NORMAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 if (dir == DIR_RIGHT_TO_LEFT)
1313 return mWidth;
1314 else
1315 return getParagraphLeft(line) + getLineMax(line);
Doug Feltc0ccf0c2011-06-23 16:13:18 -07001316 } else if (align == Alignment.ALIGN_RIGHT) {
1317 return mWidth;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 } else if (align == Alignment.ALIGN_OPPOSITE) {
1319 if (dir == DIR_RIGHT_TO_LEFT)
1320 return getLineMax(line);
1321 else
1322 return mWidth;
1323 } else { /* align == Alignment.ALIGN_CENTER */
1324 int left = getParagraphLeft(line);
1325 int right = getParagraphRight(line);
1326 int max = ((int) getLineMax(line)) & ~1;
1327
1328 return right - ((right - left) - max) / 2;
1329 }
1330 }
1331
1332 /**
Doug Felt0c702b82010-05-14 10:55:42 -07001333 * Gets the unsigned horizontal extent of the specified line, including
Doug Feltc982f602010-05-25 11:51:40 -07001334 * leading margin indent, but excluding trailing whitespace.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 */
1336 public float getLineMax(int line) {
Doug Feltc982f602010-05-25 11:51:40 -07001337 float margin = getParagraphLeadingMargin(line);
1338 float signedExtent = getLineExtent(line, false);
Anish Athalyec14b3ad2014-07-24 18:03:21 -07001339 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
1341
1342 /**
Doug Feltc982f602010-05-25 11:51:40 -07001343 * Gets the unsigned horizontal extent of the specified line, including
1344 * leading margin indent and trailing whitespace.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 */
1346 public float getLineWidth(int line) {
Doug Feltc982f602010-05-25 11:51:40 -07001347 float margin = getParagraphLeadingMargin(line);
1348 float signedExtent = getLineExtent(line, true);
Anish Athalyec14b3ad2014-07-24 18:03:21 -07001349 return margin + (signedExtent >= 0 ? signedExtent : -signedExtent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 }
1351
Doug Feltc982f602010-05-25 11:51:40 -07001352 /**
1353 * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the
1354 * tab stops instead of using the ones passed in.
1355 * @param line the index of the line
1356 * @param full whether to include trailing whitespace
1357 * @return the extent of the line
1358 */
1359 private float getLineExtent(int line, boolean full) {
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001360 final int start = getLineStart(line);
1361 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
Doug Feltc982f602010-05-25 11:51:40 -07001362
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001363 final boolean hasTabs = getLineContainsTab(line);
Doug Feltc982f602010-05-25 11:51:40 -07001364 TabStops tabStops = null;
Roozbeh Pournader112d9c72015-08-07 12:44:41 -07001365 if (hasTabs && mText instanceof Spanned) {
Doug Feltc982f602010-05-25 11:51:40 -07001366 // Just checking this line should be good enough, tabs should be
1367 // consistent across all lines in a paragraph.
Eric Fischer74d31ef2010-08-05 15:29:36 -07001368 TabStopSpan[] tabs = getParagraphSpans((Spanned) mText, start, end, TabStopSpan.class);
Doug Feltc982f602010-05-25 11:51:40 -07001369 if (tabs.length > 0) {
1370 tabStops = new TabStops(TAB_INCREMENT, tabs); // XXX should reuse
1371 }
1372 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001373 final Directions directions = getLineDirections(line);
Fabrice Di Meglio8059e0902011-08-10 16:31:58 -07001374 // Returned directions can actually be null
1375 if (directions == null) {
1376 return 0f;
1377 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001378 final int dir = getParagraphDirection(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001380 final TextLine tl = TextLine.obtain();
1381 final TextPaint paint = mWorkPaint;
1382 paint.set(mPaint);
1383 paint.setHyphenEdit(getHyphen(line));
Mihai Popace642dc2018-05-24 14:25:11 +01001384 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops,
1385 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001386 if (isJustificationRequired(line)) {
1387 tl.justify(getJustifyWidth(line));
1388 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001389 final float width = tl.metrics(null);
Doug Feltc982f602010-05-25 11:51:40 -07001390 TextLine.recycle(tl);
1391 return width;
1392 }
1393
1394 /**
1395 * Returns the signed horizontal extent of the specified line, excluding
1396 * leading margin. If full is false, excludes trailing whitespace.
1397 * @param line the index of the line
1398 * @param tabStops the tab stops, can be null if we know they're not used.
1399 * @param full whether to include trailing whitespace
1400 * @return the extent of the text on this line
1401 */
1402 private float getLineExtent(int line, TabStops tabStops, boolean full) {
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001403 final int start = getLineStart(line);
1404 final int end = full ? getLineEnd(line) : getLineVisibleEnd(line);
1405 final boolean hasTabs = getLineContainsTab(line);
1406 final Directions directions = getLineDirections(line);
1407 final int dir = getParagraphDirection(line);
Doug Feltc982f602010-05-25 11:51:40 -07001408
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001409 final TextLine tl = TextLine.obtain();
1410 final TextPaint paint = mWorkPaint;
1411 paint.set(mPaint);
1412 paint.setHyphenEdit(getHyphen(line));
Mihai Popace642dc2018-05-24 14:25:11 +01001413 tl.set(paint, mText, start, end, dir, directions, hasTabs, tabStops,
1414 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001415 if (isJustificationRequired(line)) {
1416 tl.justify(getJustifyWidth(line));
1417 }
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07001418 final float width = tl.metrics(null);
Doug Felte8e45f22010-03-29 14:58:40 -07001419 TextLine.recycle(tl);
1420 return width;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
1422
1423 /**
1424 * Get the line number corresponding to the specified vertical position.
1425 * If you ask for a position above 0, you get 0; if you ask for a position
1426 * below the bottom of the text, you get the last line.
1427 */
1428 // FIXME: It may be faster to do a linear search for layouts without many lines.
1429 public int getLineForVertical(int vertical) {
1430 int high = getLineCount(), low = -1, guess;
1431
1432 while (high - low > 1) {
1433 guess = (high + low) / 2;
1434
1435 if (getLineTop(guess) > vertical)
1436 high = guess;
1437 else
1438 low = guess;
1439 }
1440
1441 if (low < 0)
1442 return 0;
1443 else
1444 return low;
1445 }
1446
1447 /**
1448 * Get the line number on which the specified text offset appears.
1449 * If you ask for a position before 0, you get 0; if you ask for a position
1450 * beyond the end of the text, you get the last line.
1451 */
1452 public int getLineForOffset(int offset) {
1453 int high = getLineCount(), low = -1, guess;
1454
1455 while (high - low > 1) {
1456 guess = (high + low) / 2;
1457
1458 if (getLineStart(guess) > offset)
1459 high = guess;
1460 else
1461 low = guess;
1462 }
1463
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001464 if (low < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 return 0;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001466 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 return low;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
1470
1471 /**
Doug Felt9f7a4442010-03-01 12:45:56 -08001472 * Get the character offset on the specified line whose position is
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 * closest to the specified horizontal position.
1474 */
1475 public int getOffsetForHorizontal(int line, float horiz) {
Keisuke Kuroyanagif0bb87b72016-02-08 23:52:55 +09001476 return getOffsetForHorizontal(line, horiz, true);
1477 }
1478
1479 /**
1480 * Get the character offset on the specified line whose position is
1481 * closest to the specified horizontal position.
1482 *
1483 * @param line the line used to find the closest offset
1484 * @param horiz the horizontal position used to find the closest offset
1485 * @param primary whether to use the primary position or secondary position to find the offset
1486 *
1487 * @hide
1488 */
1489 public int getOffsetForHorizontal(int line, float horiz, boolean primary) {
Raph Levienedb27f12015-06-01 14:34:47 -07001490 // TODO: use Paint.getOffsetForAdvance to avoid binary search
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001491 final int lineEndOffset = getLineEnd(line);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001492 final int lineStartOffset = getLineStart(line);
1493
1494 Directions dirs = getLineDirections(line);
1495
1496 TextLine tl = TextLine.obtain();
1497 // XXX: we don't care about tabs as we just use TextLine#getOffsetToLeftRightOf here.
1498 tl.set(mPaint, mText, lineStartOffset, lineEndOffset, getParagraphDirection(line), dirs,
Mihai Popace642dc2018-05-24 14:25:11 +01001499 false, null,
1500 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Mihai Popa7626c862018-05-09 17:31:48 +01001501 final HorizontalMeasurementProvider horizontal =
1502 new HorizontalMeasurementProvider(line, primary);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001503
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001504 final int max;
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001505 if (line == getLineCount() - 1) {
1506 max = lineEndOffset;
1507 } else {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001508 max = tl.getOffsetToLeftRightOf(lineEndOffset - lineStartOffset,
1509 !isRtlCharAt(lineEndOffset - 1)) + lineStartOffset;
Keisuke Kuroyanagi00ad16d2015-08-27 18:15:48 +09001510 }
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001511 int best = lineStartOffset;
Mihai Popa7626c862018-05-09 17:31:48 +01001512 float bestdist = Math.abs(horizontal.get(lineStartOffset) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513
Doug Felt9f7a4442010-03-01 12:45:56 -08001514 for (int i = 0; i < dirs.mDirections.length; i += 2) {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001515 int here = lineStartOffset + dirs.mDirections[i];
Doug Felt9f7a4442010-03-01 12:45:56 -08001516 int there = here + (dirs.mDirections[i+1] & RUN_LENGTH_MASK);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001517 boolean isRtl = (dirs.mDirections[i+1] & RUN_RTL_FLAG) != 0;
1518 int swap = isRtl ? -1 : 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519
1520 if (there > max)
1521 there = max;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 int high = there - 1 + 1, low = here + 1 - 1, guess;
1523
1524 while (high - low > 1) {
1525 guess = (high + low) / 2;
1526 int adguess = getOffsetAtStartOf(guess);
1527
Mihai Popa7626c862018-05-09 17:31:48 +01001528 if (horizontal.get(adguess) * swap >= horiz * swap) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 high = guess;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001530 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 low = guess;
Keisuke Kuroyanagi7c263dd2017-01-12 19:24:18 +09001532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534
1535 if (low < here + 1)
1536 low = here + 1;
1537
1538 if (low < there) {
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001539 int aft = tl.getOffsetToLeftRightOf(low - lineStartOffset, isRtl) + lineStartOffset;
1540 low = tl.getOffsetToLeftRightOf(aft - lineStartOffset, !isRtl) + lineStartOffset;
1541 if (low >= here && low < there) {
Mihai Popa7626c862018-05-09 17:31:48 +01001542 float dist = Math.abs(horizontal.get(low) - horiz);
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001543 if (aft < there) {
Mihai Popa7626c862018-05-09 17:31:48 +01001544 float other = Math.abs(horizontal.get(aft) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001546 if (other < dist) {
1547 dist = other;
1548 low = aft;
1549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001552 if (dist < bestdist) {
1553 bestdist = dist;
1554 best = low;
1555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 }
1557 }
1558
Mihai Popa7626c862018-05-09 17:31:48 +01001559 float dist = Math.abs(horizontal.get(here) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560
1561 if (dist < bestdist) {
1562 bestdist = dist;
1563 best = here;
1564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
1566
Mihai Popa7626c862018-05-09 17:31:48 +01001567 float dist = Math.abs(horizontal.get(max) - horiz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568
Raph Levien373b7a82013-09-20 15:11:52 -07001569 if (dist <= bestdist) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 best = max;
1571 }
1572
Keisuke Kuroyanagi5bff01d2016-01-08 19:55:17 +09001573 TextLine.recycle(tl);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 return best;
1575 }
1576
1577 /**
Mihai Popa7626c862018-05-09 17:31:48 +01001578 * Responds to #getHorizontal queries, by selecting the better strategy between:
1579 * - calling #getHorizontal explicitly for each query
1580 * - precomputing all #getHorizontal measurements, and responding to any query in constant time
1581 * The first strategy is used for LTR-only text, while the second is used for all other cases.
1582 * The class is currently only used in #getOffsetForHorizontal, so reuse with care in other
1583 * contexts.
1584 */
1585 private class HorizontalMeasurementProvider {
1586 private final int mLine;
1587 private final boolean mPrimary;
1588
1589 private float[] mHorizontals;
1590 private int mLineStartOffset;
1591
1592 HorizontalMeasurementProvider(final int line, final boolean primary) {
1593 mLine = line;
1594 mPrimary = primary;
1595 init();
1596 }
1597
1598 private void init() {
1599 final Directions dirs = getLineDirections(mLine);
1600 if (dirs == DIRS_ALL_LEFT_TO_RIGHT) {
1601 return;
1602 }
1603
1604 mHorizontals = getLineHorizontals(mLine, false, mPrimary);
1605 mLineStartOffset = getLineStart(mLine);
1606 }
1607
1608 float get(final int offset) {
Siyamed Sinir58df7952018-08-14 18:43:56 -07001609 final int index = offset - mLineStartOffset;
1610 if (mHorizontals == null || index < 0 || index >= mHorizontals.length) {
Mihai Popa7626c862018-05-09 17:31:48 +01001611 return getHorizontal(offset, mPrimary);
1612 } else {
Siyamed Sinir58df7952018-08-14 18:43:56 -07001613 return mHorizontals[index];
Mihai Popa7626c862018-05-09 17:31:48 +01001614 }
1615 }
1616 }
1617
1618 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 * Return the text offset after the last character on the specified line.
1620 */
1621 public final int getLineEnd(int line) {
1622 return getLineStart(line + 1);
1623 }
1624
Doug Felt9f7a4442010-03-01 12:45:56 -08001625 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 * Return the text offset after the last visible character (so whitespace
1627 * is not counted) on the specified line.
1628 */
1629 public int getLineVisibleEnd(int line) {
1630 return getLineVisibleEnd(line, getLineStart(line), getLineStart(line+1));
1631 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 private int getLineVisibleEnd(int line, int start, int end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 CharSequence text = mText;
1635 char ch;
1636 if (line == getLineCount() - 1) {
1637 return end;
1638 }
1639
1640 for (; end > start; end--) {
1641 ch = text.charAt(end - 1);
1642
1643 if (ch == '\n') {
1644 return end - 1;
1645 }
1646
Seigo Nonaka09da71a2016-11-28 16:24:14 +09001647 if (!TextLine.isLineEndSpace(ch)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 break;
1649 }
1650
1651 }
1652
1653 return end;
1654 }
1655
1656 /**
1657 * Return the vertical position of the bottom of the specified line.
1658 */
1659 public final int getLineBottom(int line) {
1660 return getLineTop(line + 1);
1661 }
1662
1663 /**
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001664 * Return the vertical position of the bottom of the specified line without the line spacing
1665 * added.
1666 *
1667 * @hide
1668 */
1669 public final int getLineBottomWithoutSpacing(int line) {
1670 return getLineTop(line + 1) - getLineExtra(line);
1671 }
1672
1673 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 * Return the vertical position of the baseline of the specified line.
1675 */
1676 public final int getLineBaseline(int line) {
1677 // getLineTop(line+1) == getLineTop(line)
1678 return getLineTop(line+1) - getLineDescent(line);
1679 }
1680
1681 /**
1682 * Get the ascent of the text on the specified line.
1683 * The return value is negative to match the Paint.ascent() convention.
1684 */
1685 public final int getLineAscent(int line) {
1686 // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line)
1687 return getLineTop(line) - (getLineTop(line+1) - getLineDescent(line));
1688 }
1689
Siyamed Sinir0fa89d62017-07-24 20:46:41 -07001690 /**
1691 * Return the extra space added as a result of line spacing attributes
1692 * {@link #getSpacingAdd()} and {@link #getSpacingMultiplier()}. Default value is {@code zero}.
1693 *
1694 * @param line the index of the line, the value should be equal or greater than {@code zero}
1695 * @hide
1696 */
1697 public int getLineExtra(@IntRange(from = 0) int line) {
1698 return 0;
1699 }
1700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 public int getOffsetToLeftOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001702 return getOffsetToLeftRightOf(offset, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 }
1704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 public int getOffsetToRightOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001706 return getOffsetToLeftRightOf(offset, false);
1707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708
Doug Felt9f7a4442010-03-01 12:45:56 -08001709 private int getOffsetToLeftRightOf(int caret, boolean toLeft) {
1710 int line = getLineForOffset(caret);
1711 int lineStart = getLineStart(line);
1712 int lineEnd = getLineEnd(line);
Doug Felte8e45f22010-03-29 14:58:40 -07001713 int lineDir = getParagraphDirection(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001715 boolean lineChanged = false;
Doug Felte8e45f22010-03-29 14:58:40 -07001716 boolean advance = toLeft == (lineDir == DIR_RIGHT_TO_LEFT);
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001717 // if walking off line, look at the line we're headed to
1718 if (advance) {
1719 if (caret == lineEnd) {
Doug Felte8e45f22010-03-29 14:58:40 -07001720 if (line < getLineCount() - 1) {
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001721 lineChanged = true;
Doug Felte8e45f22010-03-29 14:58:40 -07001722 ++line;
1723 } else {
1724 return caret; // at very end, don't move
1725 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001726 }
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001727 } else {
1728 if (caret == lineStart) {
1729 if (line > 0) {
1730 lineChanged = true;
1731 --line;
1732 } else {
1733 return caret; // at very start, don't move
1734 }
1735 }
1736 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001737
Gilles Debunne162bf0f2010-11-16 16:23:53 -08001738 if (lineChanged) {
Doug Felte8e45f22010-03-29 14:58:40 -07001739 lineStart = getLineStart(line);
1740 lineEnd = getLineEnd(line);
1741 int newDir = getParagraphDirection(line);
1742 if (newDir != lineDir) {
1743 // unusual case. we want to walk onto the line, but it runs
1744 // in a different direction than this one, so we fake movement
1745 // in the opposite direction.
1746 toLeft = !toLeft;
1747 lineDir = newDir;
1748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 }
Doug Felt9f7a4442010-03-01 12:45:56 -08001750
Doug Felte8e45f22010-03-29 14:58:40 -07001751 Directions directions = getLineDirections(line);
Doug Felt9f7a4442010-03-01 12:45:56 -08001752
Doug Felte8e45f22010-03-29 14:58:40 -07001753 TextLine tl = TextLine.obtain();
1754 // XXX: we don't care about tabs
Mihai Popace642dc2018-05-24 14:25:11 +01001755 tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null,
1756 getEllipsisStart(line), getEllipsisStart(line) + getEllipsisCount(line));
Doug Felte8e45f22010-03-29 14:58:40 -07001757 caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft);
Siyamed Sinira273a702017-10-05 11:22:12 -07001758 TextLine.recycle(tl);
Doug Felte8e45f22010-03-29 14:58:40 -07001759 return caret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761
1762 private int getOffsetAtStartOf(int offset) {
Doug Felt9f7a4442010-03-01 12:45:56 -08001763 // XXX this probably should skip local reorderings and
1764 // zero-width characters, look at callers
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 if (offset == 0)
1766 return 0;
1767
1768 CharSequence text = mText;
1769 char c = text.charAt(offset);
1770
1771 if (c >= '\uDC00' && c <= '\uDFFF') {
1772 char c1 = text.charAt(offset - 1);
1773
1774 if (c1 >= '\uD800' && c1 <= '\uDBFF')
1775 offset -= 1;
1776 }
1777
1778 if (mSpannedText) {
1779 ReplacementSpan[] spans = ((Spanned) text).getSpans(offset, offset,
1780 ReplacementSpan.class);
1781
1782 for (int i = 0; i < spans.length; i++) {
1783 int start = ((Spanned) text).getSpanStart(spans[i]);
1784 int end = ((Spanned) text).getSpanEnd(spans[i]);
1785
1786 if (start < offset && end > offset)
1787 offset = start;
1788 }
1789 }
1790
1791 return offset;
1792 }
1793
1794 /**
Raph Levienafe8e9b2012-12-19 16:09:32 -08001795 * Determine whether we should clamp cursor position. Currently it's
1796 * only robust for left-aligned displays.
1797 * @hide
1798 */
Mathew Inwoodefeab842018-08-14 15:21:30 +01001799 @UnsupportedAppUsage
Raph Levienafe8e9b2012-12-19 16:09:32 -08001800 public boolean shouldClampCursor(int line) {
1801 // Only clamp cursor position in left-aligned displays.
1802 switch (getParagraphAlignment(line)) {
1803 case ALIGN_LEFT:
1804 return true;
1805 case ALIGN_NORMAL:
1806 return getParagraphDirection(line) > 0;
1807 default:
1808 return false;
1809 }
1810
1811 }
1812 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 * Fills in the specified Path with a representation of a cursor
1814 * at the specified offset. This will often be a vertical line
Doug Felt4e0c5e52010-03-15 16:56:02 -07001815 * but can be multiple discontinuous lines in text with multiple
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 * directionalities.
1817 */
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001818 public void getCursorPath(final int point, final Path dest, final CharSequence editingBuffer) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 dest.reset();
1820
1821 int line = getLineForOffset(point);
1822 int top = getLineTop(line);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001823 int bottom = getLineBottomWithoutSpacing(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824
Raph Levienafe8e9b2012-12-19 16:09:32 -08001825 boolean clamped = shouldClampCursor(line);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001826 float h1 = getPrimaryHorizontal(point, clamped) - 0.5f;
1827 float h2 = isLevelBoundary(point) ? getSecondaryHorizontal(point, clamped) - 0.5f : h1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828
Jeff Brown497a92c2010-09-12 17:55:08 -07001829 int caps = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) |
1830 TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING);
1831 int fn = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 int dist = 0;
1833
1834 if (caps != 0 || fn != 0) {
1835 dist = (bottom - top) >> 2;
1836
1837 if (fn != 0)
1838 top += dist;
1839 if (caps != 0)
1840 bottom -= dist;
1841 }
1842
1843 if (h1 < 0.5f)
1844 h1 = 0.5f;
1845 if (h2 < 0.5f)
1846 h2 = 0.5f;
1847
Jozef BABJAK2fb503f2011-03-17 09:54:51 +01001848 if (Float.compare(h1, h2) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 dest.moveTo(h1, top);
1850 dest.lineTo(h1, bottom);
1851 } else {
1852 dest.moveTo(h1, top);
1853 dest.lineTo(h1, (top + bottom) >> 1);
1854
1855 dest.moveTo(h2, (top + bottom) >> 1);
1856 dest.lineTo(h2, bottom);
1857 }
1858
1859 if (caps == 2) {
1860 dest.moveTo(h2, bottom);
1861 dest.lineTo(h2 - dist, bottom + dist);
1862 dest.lineTo(h2, bottom);
1863 dest.lineTo(h2 + dist, bottom + dist);
1864 } else if (caps == 1) {
1865 dest.moveTo(h2, bottom);
1866 dest.lineTo(h2 - dist, bottom + dist);
1867
1868 dest.moveTo(h2 - dist, bottom + dist - 0.5f);
1869 dest.lineTo(h2 + dist, bottom + dist - 0.5f);
1870
1871 dest.moveTo(h2 + dist, bottom + dist);
1872 dest.lineTo(h2, bottom);
1873 }
1874
1875 if (fn == 2) {
1876 dest.moveTo(h1, top);
1877 dest.lineTo(h1 - dist, top - dist);
1878 dest.lineTo(h1, top);
1879 dest.lineTo(h1 + dist, top - dist);
1880 } else if (fn == 1) {
1881 dest.moveTo(h1, top);
1882 dest.lineTo(h1 - dist, top - dist);
1883
1884 dest.moveTo(h1 - dist, top - dist + 0.5f);
1885 dest.lineTo(h1 + dist, top - dist + 0.5f);
1886
1887 dest.moveTo(h1 + dist, top - dist);
1888 dest.lineTo(h1, top);
1889 }
1890 }
1891
1892 private void addSelection(int line, int start, int end,
Petar Šeginab92c5392017-09-06 15:25:05 +01001893 int top, int bottom, SelectionRectangleConsumer consumer) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 int linestart = getLineStart(line);
1895 int lineend = getLineEnd(line);
1896 Directions dirs = getLineDirections(line);
1897
Petar Šeginafb748b32017-08-07 12:37:52 +01001898 if (lineend > linestart && mText.charAt(lineend - 1) == '\n') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 lineend--;
Petar Šeginafb748b32017-08-07 12:37:52 +01001900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901
Doug Felt9f7a4442010-03-01 12:45:56 -08001902 for (int i = 0; i < dirs.mDirections.length; i += 2) {
1903 int here = linestart + dirs.mDirections[i];
Petar Šeginafb748b32017-08-07 12:37:52 +01001904 int there = here + (dirs.mDirections[i + 1] & RUN_LENGTH_MASK);
Doug Felt9f7a4442010-03-01 12:45:56 -08001905
Petar Šeginafb748b32017-08-07 12:37:52 +01001906 if (there > lineend) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 there = lineend;
Petar Šeginafb748b32017-08-07 12:37:52 +01001908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909
1910 if (start <= there && end >= here) {
1911 int st = Math.max(start, here);
1912 int en = Math.min(end, there);
1913
1914 if (st != en) {
Raph Levienafe8e9b2012-12-19 16:09:32 -08001915 float h1 = getHorizontal(st, false, line, false /* not clamped */);
1916 float h2 = getHorizontal(en, true, line, false /* not clamped */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917
Fabrice Di Meglio37166012011-08-31 13:56:37 -07001918 float left = Math.min(h1, h2);
1919 float right = Math.max(h1, h2);
1920
Petar Šegina8f1f74e2017-09-07 14:26:28 +01001921 final @TextSelectionLayout int layout =
1922 ((dirs.mDirections[i + 1] & RUN_RTL_FLAG) != 0)
1923 ? TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT
1924 : TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT;
1925
1926 consumer.accept(left, top, right, bottom, layout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
1928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
1930 }
1931
1932 /**
1933 * Fills in the specified Path with a representation of a highlight
1934 * between the specified offsets. This will often be a rectangle
1935 * or a potentially discontinuous set of rectangles. If the start
1936 * and end are the same, the returned path is empty.
1937 */
1938 public void getSelectionPath(int start, int end, Path dest) {
1939 dest.reset();
Petar Šeginab92c5392017-09-06 15:25:05 +01001940 getSelection(start, end, (left, top, right, bottom, textSelectionLayout) ->
Petar Šeginafb748b32017-08-07 12:37:52 +01001941 dest.addRect(left, top, right, bottom, Path.Direction.CW));
1942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943
Petar Šeginafb748b32017-08-07 12:37:52 +01001944 /**
1945 * Calculates the rectangles which should be highlighted to indicate a selection between start
Petar Šeginab92c5392017-09-06 15:25:05 +01001946 * and end and feeds them into the given {@link SelectionRectangleConsumer}.
Petar Šeginafb748b32017-08-07 12:37:52 +01001947 *
1948 * @param start the starting index of the selection
1949 * @param end the ending index of the selection
Petar Šeginab92c5392017-09-06 15:25:05 +01001950 * @param consumer the {@link SelectionRectangleConsumer} which will receive the generated
1951 * rectangles. It will be called every time a rectangle is generated.
Petar Šeginafb748b32017-08-07 12:37:52 +01001952 * @hide
1953 * @see #getSelectionPath(int, int, Path)
1954 */
Petar Šeginab92c5392017-09-06 15:25:05 +01001955 public final void getSelection(int start, int end, final SelectionRectangleConsumer consumer) {
Petar Šeginafb748b32017-08-07 12:37:52 +01001956 if (start == end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 return;
Petar Šeginafb748b32017-08-07 12:37:52 +01001958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959
1960 if (end < start) {
1961 int temp = end;
1962 end = start;
1963 start = temp;
1964 }
1965
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001966 final int startline = getLineForOffset(start);
1967 final int endline = getLineForOffset(end);
Roozbeh Pournader7557a5a2017-04-11 18:34:42 -07001968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 int top = getLineTop(startline);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001970 int bottom = getLineBottomWithoutSpacing(endline);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971
1972 if (startline == endline) {
Petar Šeginafb748b32017-08-07 12:37:52 +01001973 addSelection(startline, start, end, top, bottom, consumer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 } else {
1975 final float width = mWidth;
1976
1977 addSelection(startline, start, getLineEnd(startline),
Petar Šeginafb748b32017-08-07 12:37:52 +01001978 top, getLineBottom(startline), consumer);
Doug Felt9f7a4442010-03-01 12:45:56 -08001979
Petar Šeginafb748b32017-08-07 12:37:52 +01001980 if (getParagraphDirection(startline) == DIR_RIGHT_TO_LEFT) {
Petar Šeginab92c5392017-09-06 15:25:05 +01001981 consumer.accept(getLineLeft(startline), top, 0, getLineBottom(startline),
Petar Šegina3a92fb62017-09-07 21:03:24 +01001982 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001983 } else {
Petar Šeginab92c5392017-09-06 15:25:05 +01001984 consumer.accept(getLineRight(startline), top, width, getLineBottom(startline),
Petar Šegina3a92fb62017-09-07 21:03:24 +01001985 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginafb748b32017-08-07 12:37:52 +01001986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987
1988 for (int i = startline + 1; i < endline; i++) {
1989 top = getLineTop(i);
1990 bottom = getLineBottom(i);
Petar Šeginab92c5392017-09-06 15:25:05 +01001991 if (getParagraphDirection(i) == DIR_RIGHT_TO_LEFT) {
Petar Šegina3a92fb62017-09-07 21:03:24 +01001992 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginab92c5392017-09-06 15:25:05 +01001993 } else {
Petar Šegina3a92fb62017-09-07 21:03:24 +01001994 consumer.accept(0, top, width, bottom, TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginab92c5392017-09-06 15:25:05 +01001995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
1997
1998 top = getLineTop(endline);
Siyamed Sinira60b59d2017-07-26 09:26:41 -07001999 bottom = getLineBottomWithoutSpacing(endline);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000
Petar Šeginafb748b32017-08-07 12:37:52 +01002001 addSelection(endline, getLineStart(endline), end, top, bottom, consumer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002
Petar Šeginafb748b32017-08-07 12:37:52 +01002003 if (getParagraphDirection(endline) == DIR_RIGHT_TO_LEFT) {
Petar Šeginab92c5392017-09-06 15:25:05 +01002004 consumer.accept(width, top, getLineRight(endline), bottom,
Petar Šegina3a92fb62017-09-07 21:03:24 +01002005 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT);
Petar Šeginafb748b32017-08-07 12:37:52 +01002006 } else {
Petar Šeginab92c5392017-09-06 15:25:05 +01002007 consumer.accept(0, top, getLineLeft(endline), bottom,
Petar Šegina3a92fb62017-09-07 21:03:24 +01002008 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT);
Petar Šeginafb748b32017-08-07 12:37:52 +01002009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 }
2011 }
2012
2013 /**
2014 * Get the alignment of the specified paragraph, taking into account
2015 * markup attached to it.
2016 */
2017 public final Alignment getParagraphAlignment(int line) {
2018 Alignment align = mAlignment;
2019
2020 if (mSpannedText) {
2021 Spanned sp = (Spanned) mText;
Eric Fischer74d31ef2010-08-05 15:29:36 -07002022 AlignmentSpan[] spans = getParagraphSpans(sp, getLineStart(line),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 getLineEnd(line),
2024 AlignmentSpan.class);
2025
2026 int spanLength = spans.length;
2027 if (spanLength > 0) {
2028 align = spans[spanLength-1].getAlignment();
2029 }
2030 }
2031
2032 return align;
2033 }
2034
2035 /**
2036 * Get the left edge of the specified paragraph, inset by left margins.
2037 */
2038 public final int getParagraphLeft(int line) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 int left = 0;
Doug Feltc982f602010-05-25 11:51:40 -07002040 int dir = getParagraphDirection(line);
2041 if (dir == DIR_RIGHT_TO_LEFT || !mSpannedText) {
2042 return left; // leading margin has no impact, or no styles
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
Doug Feltc982f602010-05-25 11:51:40 -07002044 return getParagraphLeadingMargin(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
2046
2047 /**
2048 * Get the right edge of the specified paragraph, inset by right margins.
2049 */
2050 public final int getParagraphRight(int line) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 int right = mWidth;
Doug Feltc982f602010-05-25 11:51:40 -07002052 int dir = getParagraphDirection(line);
2053 if (dir == DIR_LEFT_TO_RIGHT || !mSpannedText) {
2054 return right; // leading margin has no impact, or no styles
2055 }
2056 return right - getParagraphLeadingMargin(line);
2057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058
Doug Feltc982f602010-05-25 11:51:40 -07002059 /**
2060 * Returns the effective leading margin (unsigned) for this line,
2061 * taking into account LeadingMarginSpan and LeadingMarginSpan2.
2062 * @param line the line index
2063 * @return the leading margin of this line
2064 */
2065 private int getParagraphLeadingMargin(int line) {
2066 if (!mSpannedText) {
2067 return 0;
2068 }
2069 Spanned spanned = (Spanned) mText;
Doug Felt0c702b82010-05-14 10:55:42 -07002070
Doug Feltc982f602010-05-25 11:51:40 -07002071 int lineStart = getLineStart(line);
2072 int lineEnd = getLineEnd(line);
Doug Felt0c702b82010-05-14 10:55:42 -07002073 int spanEnd = spanned.nextSpanTransition(lineStart, lineEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002074 LeadingMarginSpan.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002075 LeadingMarginSpan[] spans = getParagraphSpans(spanned, lineStart, spanEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002076 LeadingMarginSpan.class);
2077 if (spans.length == 0) {
2078 return 0; // no leading margin span;
2079 }
Doug Felt0c702b82010-05-14 10:55:42 -07002080
Doug Feltc982f602010-05-25 11:51:40 -07002081 int margin = 0;
Doug Felt0c702b82010-05-14 10:55:42 -07002082
Siyamed Sinira273a702017-10-05 11:22:12 -07002083 boolean useFirstLineMargin = lineStart == 0 || spanned.charAt(lineStart - 1) == '\n';
Anish Athalyeab08c6d2014-08-08 12:09:58 -07002084 for (int i = 0; i < spans.length; i++) {
2085 if (spans[i] instanceof LeadingMarginSpan2) {
2086 int spStart = spanned.getSpanStart(spans[i]);
2087 int spanLine = getLineForOffset(spStart);
2088 int count = ((LeadingMarginSpan2) spans[i]).getLeadingMarginLineCount();
2089 // if there is more than one LeadingMarginSpan2, use the count that is greatest
2090 useFirstLineMargin |= line < spanLine + count;
2091 }
2092 }
Doug Feltc982f602010-05-25 11:51:40 -07002093 for (int i = 0; i < spans.length; i++) {
2094 LeadingMarginSpan span = spans[i];
Doug Feltc982f602010-05-25 11:51:40 -07002095 margin += span.getLeadingMargin(useFirstLineMargin);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
2097
Doug Feltc982f602010-05-25 11:51:40 -07002098 return margin;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 }
2100
Roozbeh Pournader9a9179d2017-08-29 14:14:28 -07002101 private static float measurePara(TextPaint paint, CharSequence text, int start, int end,
Siyamed Sinir79bf9d12016-05-18 19:57:52 -07002102 TextDirectionHeuristic textDir) {
Seigo Nonaka9d3bd082018-01-11 10:02:12 -08002103 MeasuredParagraph mt = null;
Doug Felte8e45f22010-03-29 14:58:40 -07002104 TextLine tl = TextLine.obtain();
2105 try {
Seigo Nonaka9d3bd082018-01-11 10:02:12 -08002106 mt = MeasuredParagraph.buildForBidi(text, start, end, textDir, mt);
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002107 final char[] chars = mt.getChars();
2108 final int len = chars.length;
2109 final Directions directions = mt.getDirections(0, len);
2110 final int dir = mt.getParagraphDir();
Doug Feltc982f602010-05-25 11:51:40 -07002111 boolean hasTabs = false;
2112 TabStops tabStops = null;
Anish Athalyec14b3ad2014-07-24 18:03:21 -07002113 // leading margins should be taken into account when measuring a paragraph
2114 int margin = 0;
2115 if (text instanceof Spanned) {
2116 Spanned spanned = (Spanned) text;
2117 LeadingMarginSpan[] spans = getParagraphSpans(spanned, start, end,
2118 LeadingMarginSpan.class);
2119 for (LeadingMarginSpan lms : spans) {
2120 margin += lms.getLeadingMargin(true);
2121 }
2122 }
Doug Feltc982f602010-05-25 11:51:40 -07002123 for (int i = 0; i < len; ++i) {
2124 if (chars[i] == '\t') {
2125 hasTabs = true;
2126 if (text instanceof Spanned) {
2127 Spanned spanned = (Spanned) text;
Doug Felt0c702b82010-05-14 10:55:42 -07002128 int spanEnd = spanned.nextSpanTransition(start, end,
Doug Feltc982f602010-05-25 11:51:40 -07002129 TabStopSpan.class);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002130 TabStopSpan[] spans = getParagraphSpans(spanned, start, spanEnd,
Doug Feltc982f602010-05-25 11:51:40 -07002131 TabStopSpan.class);
2132 if (spans.length > 0) {
2133 tabStops = new TabStops(TAB_INCREMENT, spans);
2134 }
2135 }
2136 break;
2137 }
2138 }
Mihai Popace642dc2018-05-24 14:25:11 +01002139 tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops,
2140 0 /* ellipsisStart */, 0 /* ellipsisEnd */);
Siyamed Sinir79bf9d12016-05-18 19:57:52 -07002141 return margin + Math.abs(tl.metrics(null));
Doug Felte8e45f22010-03-29 14:58:40 -07002142 } finally {
2143 TextLine.recycle(tl);
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002144 if (mt != null) {
2145 mt.recycle();
2146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 }
2149
Doug Felt71b8dd72010-02-16 17:27:09 -08002150 /**
Doug Feltc982f602010-05-25 11:51:40 -07002151 * @hide
2152 */
Seigo Nonaka32afe262018-05-16 22:05:27 -07002153 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2154 public static class TabStops {
Doug Feltc982f602010-05-25 11:51:40 -07002155 private int[] mStops;
2156 private int mNumStops;
2157 private int mIncrement;
Doug Felt0c702b82010-05-14 10:55:42 -07002158
Seigo Nonaka32afe262018-05-16 22:05:27 -07002159 public TabStops(int increment, Object[] spans) {
Doug Feltc982f602010-05-25 11:51:40 -07002160 reset(increment, spans);
2161 }
Doug Felt0c702b82010-05-14 10:55:42 -07002162
Doug Feltc982f602010-05-25 11:51:40 -07002163 void reset(int increment, Object[] spans) {
2164 this.mIncrement = increment;
2165
2166 int ns = 0;
2167 if (spans != null) {
2168 int[] stops = this.mStops;
2169 for (Object o : spans) {
2170 if (o instanceof TabStopSpan) {
2171 if (stops == null) {
2172 stops = new int[10];
2173 } else if (ns == stops.length) {
2174 int[] nstops = new int[ns * 2];
2175 for (int i = 0; i < ns; ++i) {
2176 nstops[i] = stops[i];
2177 }
2178 stops = nstops;
2179 }
2180 stops[ns++] = ((TabStopSpan) o).getTabStop();
2181 }
2182 }
2183 if (ns > 1) {
2184 Arrays.sort(stops, 0, ns);
2185 }
2186 if (stops != this.mStops) {
2187 this.mStops = stops;
2188 }
2189 }
2190 this.mNumStops = ns;
2191 }
Doug Felt0c702b82010-05-14 10:55:42 -07002192
Doug Feltc982f602010-05-25 11:51:40 -07002193 float nextTab(float h) {
2194 int ns = this.mNumStops;
2195 if (ns > 0) {
2196 int[] stops = this.mStops;
2197 for (int i = 0; i < ns; ++i) {
2198 int stop = stops[i];
2199 if (stop > h) {
2200 return stop;
2201 }
2202 }
2203 }
2204 return nextDefaultStop(h, mIncrement);
2205 }
2206
2207 public static float nextDefaultStop(float h, int inc) {
2208 return ((int) ((h + inc) / inc)) * inc;
2209 }
2210 }
Doug Felt0c702b82010-05-14 10:55:42 -07002211
Doug Feltc982f602010-05-25 11:51:40 -07002212 /**
Doug Felt71b8dd72010-02-16 17:27:09 -08002213 * Returns the position of the next tab stop after h on the line.
2214 *
2215 * @param text the text
2216 * @param start start of the line
2217 * @param end limit of the line
2218 * @param h the current horizontal offset
2219 * @param tabs the tabs, can be null. If it is null, any tabs in effect
2220 * on the line will be used. If there are no tabs, a default offset
2221 * will be used to compute the tab stop.
2222 * @return the offset of the next tab stop.
2223 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 /* package */ static float nextTab(CharSequence text, int start, int end,
2225 float h, Object[] tabs) {
2226 float nh = Float.MAX_VALUE;
2227 boolean alltabs = false;
2228
2229 if (text instanceof Spanned) {
2230 if (tabs == null) {
Eric Fischer74d31ef2010-08-05 15:29:36 -07002231 tabs = getParagraphSpans((Spanned) text, start, end, TabStopSpan.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 alltabs = true;
2233 }
2234
2235 for (int i = 0; i < tabs.length; i++) {
2236 if (!alltabs) {
2237 if (!(tabs[i] instanceof TabStopSpan))
2238 continue;
2239 }
2240
2241 int where = ((TabStopSpan) tabs[i]).getTabStop();
2242
2243 if (where < nh && where > h)
2244 nh = where;
2245 }
2246
2247 if (nh != Float.MAX_VALUE)
2248 return nh;
2249 }
2250
2251 return ((int) ((h + TAB_INCREMENT) / TAB_INCREMENT)) * TAB_INCREMENT;
2252 }
2253
2254 protected final boolean isSpanned() {
2255 return mSpannedText;
2256 }
2257
Eric Fischer74d31ef2010-08-05 15:29:36 -07002258 /**
2259 * Returns the same as <code>text.getSpans()</code>, except where
2260 * <code>start</code> and <code>end</code> are the same and are not
2261 * at the very beginning of the text, in which case an empty array
2262 * is returned instead.
2263 * <p>
2264 * This is needed because of the special case that <code>getSpans()</code>
2265 * on an empty range returns the spans adjacent to that range, which is
2266 * primarily for the sake of <code>TextWatchers</code> so they will get
2267 * notifications when text goes from empty to non-empty. But it also
2268 * has the unfortunate side effect that if the text ends with an empty
2269 * paragraph, that paragraph accidentally picks up the styles of the
2270 * preceding paragraph (even though those styles will not be picked up
2271 * by new text that is inserted into the empty paragraph).
2272 * <p>
2273 * The reason it just checks whether <code>start</code> and <code>end</code>
2274 * is the same is that the only time a line can contain 0 characters
2275 * is if it is the final paragraph of the Layout; otherwise any line will
2276 * contain at least one printing or newline character. The reason for the
2277 * additional check if <code>start</code> is greater than 0 is that
2278 * if the empty paragraph is the entire content of the buffer, paragraph
2279 * styles that are already applied to the buffer will apply to text that
2280 * is inserted into it.
2281 */
Gilles Debunneeca5b732012-04-25 18:48:42 -07002282 /* package */static <T> T[] getParagraphSpans(Spanned text, int start, int end, Class<T> type) {
Eric Fischer74d31ef2010-08-05 15:29:36 -07002283 if (start == end && start > 0) {
Gilles Debunne6c488de2012-03-01 16:20:35 -08002284 return ArrayUtils.emptyArray(type);
Eric Fischer74d31ef2010-08-05 15:29:36 -07002285 }
2286
Siyamed Sinirfa05ba02016-01-12 10:54:43 -08002287 if(text instanceof SpannableStringBuilder) {
2288 return ((SpannableStringBuilder) text).getSpans(start, end, type, false);
2289 } else {
2290 return text.getSpans(start, end, type);
2291 }
Eric Fischer74d31ef2010-08-05 15:29:36 -07002292 }
2293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 private void ellipsize(int start, int end, int line,
Fabrice Di Meglio8d44fff2012-06-13 15:45:38 -07002295 char[] dest, int destoff, TextUtils.TruncateAt method) {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002296 final int ellipsisCount = getEllipsisCount(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 if (ellipsisCount == 0) {
2298 return;
2299 }
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002300 final int ellipsisStart = getEllipsisStart(line);
2301 final int lineStart = getLineStart(line);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002303 final String ellipsisString = TextUtils.getEllipsisString(method);
2304 final int ellipsisStringLen = ellipsisString.length();
Roozbeh Pournader1051bbe2017-07-25 13:52:57 -07002305 // Use the ellipsis string only if there are that at least as many characters to replace.
2306 final boolean useEllipsisString = ellipsisCount >= ellipsisStringLen;
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002307 for (int i = 0; i < ellipsisCount; i++) {
2308 final char c;
Roozbeh Pournader1051bbe2017-07-25 13:52:57 -07002309 if (useEllipsisString && i < ellipsisStringLen) {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002310 c = ellipsisString.charAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 } else {
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002312 c = TextUtils.ELLIPSIS_FILLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 }
2314
Roozbeh Pournader9ea756f2017-07-25 11:20:29 -07002315 final int a = i + ellipsisStart + lineStart;
2316 if (start <= a && a < end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 dest[destoff + a - start] = c;
2318 }
2319 }
2320 }
2321
2322 /**
2323 * Stores information about bidirectional (left-to-right or right-to-left)
Doug Felt9f7a4442010-03-01 12:45:56 -08002324 * text within the layout of a line.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 */
2326 public static class Directions {
Siyamed Sinired09ae12016-02-16 14:36:26 -08002327 /**
Petar Šegina7c31d5c2017-09-25 12:19:28 +01002328 * Directions represents directional runs within a line of text. Runs are pairs of ints
2329 * listed in visual order, starting from the leading margin. The first int of each pair is
2330 * the offset from the first character of the line to the start of the run. The second int
2331 * represents both the length and level of the run. The length is in the lower bits,
2332 * accessed by masking with RUN_LENGTH_MASK. The level is in the higher bits, accessed by
2333 * shifting by RUN_LEVEL_SHIFT and masking by RUN_LEVEL_MASK. To simply test for an RTL
2334 * direction, test the bit using RUN_RTL_FLAG, if set then the direction is rtl.
Siyamed Sinired09ae12016-02-16 14:36:26 -08002335 * @hide
2336 */
2337 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2338 public int[] mDirections;
2339
2340 /**
2341 * @hide
2342 */
2343 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
2344 public Directions(int[] dirs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 mDirections = dirs;
2346 }
2347 }
2348
2349 /**
2350 * Return the offset of the first character to be ellipsized away,
2351 * relative to the start of the line. (So 0 if the beginning of the
2352 * line is ellipsized, not getLineStart().)
2353 */
2354 public abstract int getEllipsisStart(int line);
Doug Felte8e45f22010-03-29 14:58:40 -07002355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 /**
2357 * Returns the number of characters to be ellipsized away, or 0 if
2358 * no ellipsis is to take place.
2359 */
2360 public abstract int getEllipsisCount(int line);
2361
2362 /* package */ static class Ellipsizer implements CharSequence, GetChars {
2363 /* package */ CharSequence mText;
2364 /* package */ Layout mLayout;
2365 /* package */ int mWidth;
2366 /* package */ TextUtils.TruncateAt mMethod;
2367
2368 public Ellipsizer(CharSequence s) {
2369 mText = s;
2370 }
2371
2372 public char charAt(int off) {
2373 char[] buf = TextUtils.obtain(1);
2374 getChars(off, off + 1, buf, 0);
2375 char ret = buf[0];
2376
2377 TextUtils.recycle(buf);
2378 return ret;
2379 }
2380
2381 public void getChars(int start, int end, char[] dest, int destoff) {
2382 int line1 = mLayout.getLineForOffset(start);
2383 int line2 = mLayout.getLineForOffset(end);
2384
2385 TextUtils.getChars(mText, start, end, dest, destoff);
2386
2387 for (int i = line1; i <= line2; i++) {
Fabrice Di Meglio8d44fff2012-06-13 15:45:38 -07002388 mLayout.ellipsize(start, end, i, dest, destoff, mMethod);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 }
2390 }
2391
2392 public int length() {
2393 return mText.length();
2394 }
Doug Felt9f7a4442010-03-01 12:45:56 -08002395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 public CharSequence subSequence(int start, int end) {
2397 char[] s = new char[end - start];
2398 getChars(start, end, s, 0);
2399 return new String(s);
2400 }
2401
Gilles Debunne162bf0f2010-11-16 16:23:53 -08002402 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 public String toString() {
2404 char[] s = new char[length()];
2405 getChars(0, length(), s, 0);
2406 return new String(s);
2407 }
2408
2409 }
2410
Gilles Debunne6c488de2012-03-01 16:20:35 -08002411 /* package */ static class SpannedEllipsizer extends Ellipsizer implements Spanned {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 private Spanned mSpanned;
2413
2414 public SpannedEllipsizer(CharSequence display) {
2415 super(display);
2416 mSpanned = (Spanned) display;
2417 }
2418
2419 public <T> T[] getSpans(int start, int end, Class<T> type) {
2420 return mSpanned.getSpans(start, end, type);
2421 }
2422
2423 public int getSpanStart(Object tag) {
2424 return mSpanned.getSpanStart(tag);
2425 }
2426
2427 public int getSpanEnd(Object tag) {
2428 return mSpanned.getSpanEnd(tag);
2429 }
2430
2431 public int getSpanFlags(Object tag) {
2432 return mSpanned.getSpanFlags(tag);
2433 }
2434
Gilles Debunne6c488de2012-03-01 16:20:35 -08002435 @SuppressWarnings("rawtypes")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 public int nextSpanTransition(int start, int limit, Class type) {
2437 return mSpanned.nextSpanTransition(start, limit, type);
2438 }
2439
Gilles Debunne162bf0f2010-11-16 16:23:53 -08002440 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 public CharSequence subSequence(int start, int end) {
2442 char[] s = new char[end - start];
2443 getChars(start, end, s, 0);
2444
2445 SpannableString ss = new SpannableString(new String(s));
2446 TextUtils.copySpansFrom(mSpanned, start, end, Object.class, ss, 0);
2447 return ss;
2448 }
2449 }
2450
2451 private CharSequence mText;
Mathew Inwoodefeab842018-08-14 15:21:30 +01002452 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 private TextPaint mPaint;
Roozbeh Pournaderb1f03652017-08-08 15:49:01 -07002454 private TextPaint mWorkPaint = new TextPaint();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 private int mWidth;
2456 private Alignment mAlignment = Alignment.ALIGN_NORMAL;
2457 private float mSpacingMult;
2458 private float mSpacingAdd;
Romain Guyc4d8eb62010-08-18 20:48:33 -07002459 private static final Rect sTempRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 private boolean mSpannedText;
Doug Feltcb3791202011-07-07 11:57:48 -07002461 private TextDirectionHeuristic mTextDir;
Gilles Debunneeca5b732012-04-25 18:48:42 -07002462 private SpanSet<LineBackgroundSpan> mLineBackgroundSpans;
Seigo Nonaka4b4730d2017-03-31 09:42:16 -07002463 private int mJustificationMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002465 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -07002466 @IntDef(prefix = { "DIR_" }, value = {
2467 DIR_LEFT_TO_RIGHT,
2468 DIR_RIGHT_TO_LEFT
2469 })
Seigo Nonakaf1644f72017-11-27 22:09:49 -08002470 @Retention(RetentionPolicy.SOURCE)
2471 public @interface Direction {}
2472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 public static final int DIR_LEFT_TO_RIGHT = 1;
2474 public static final int DIR_RIGHT_TO_LEFT = -1;
Doug Felt9f7a4442010-03-01 12:45:56 -08002475
Doug Felt20178d62010-02-22 13:39:01 -08002476 /* package */ static final int DIR_REQUEST_LTR = 1;
2477 /* package */ static final int DIR_REQUEST_RTL = -1;
Mathew Inwoodefeab842018-08-14 15:21:30 +01002478 @UnsupportedAppUsage
Doug Felt20178d62010-02-22 13:39:01 -08002479 /* package */ static final int DIR_REQUEST_DEFAULT_LTR = 2;
2480 /* package */ static final int DIR_REQUEST_DEFAULT_RTL = -2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481
Doug Felt9f7a4442010-03-01 12:45:56 -08002482 /* package */ static final int RUN_LENGTH_MASK = 0x03ffffff;
2483 /* package */ static final int RUN_LEVEL_SHIFT = 26;
2484 /* package */ static final int RUN_LEVEL_MASK = 0x3f;
2485 /* package */ static final int RUN_RTL_FLAG = 1 << RUN_LEVEL_SHIFT;
2486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 public enum Alignment {
2488 ALIGN_NORMAL,
2489 ALIGN_OPPOSITE,
2490 ALIGN_CENTER,
Doug Feltc0ccf0c2011-06-23 16:13:18 -07002491 /** @hide */
Mathew Inwoodefeab842018-08-14 15:21:30 +01002492 @UnsupportedAppUsage
Doug Feltc0ccf0c2011-06-23 16:13:18 -07002493 ALIGN_LEFT,
2494 /** @hide */
Mathew Inwoodefeab842018-08-14 15:21:30 +01002495 @UnsupportedAppUsage
Doug Feltc0ccf0c2011-06-23 16:13:18 -07002496 ALIGN_RIGHT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 }
2498
2499 private static final int TAB_INCREMENT = 20;
2500
Siyamed Sinired09ae12016-02-16 14:36:26 -08002501 /** @hide */
2502 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Mathew Inwoodefeab842018-08-14 15:21:30 +01002503 @UnsupportedAppUsage
Siyamed Sinired09ae12016-02-16 14:36:26 -08002504 public static final Directions DIRS_ALL_LEFT_TO_RIGHT =
Doug Felt9f7a4442010-03-01 12:45:56 -08002505 new Directions(new int[] { 0, RUN_LENGTH_MASK });
Siyamed Sinired09ae12016-02-16 14:36:26 -08002506
2507 /** @hide */
2508 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Mathew Inwoodefeab842018-08-14 15:21:30 +01002509 @UnsupportedAppUsage
Siyamed Sinired09ae12016-02-16 14:36:26 -08002510 public static final Directions DIRS_ALL_RIGHT_TO_LEFT =
Doug Felt9f7a4442010-03-01 12:45:56 -08002511 new Directions(new int[] { 0, RUN_LENGTH_MASK | RUN_RTL_FLAG });
Gilles Debunne0a4db3c2011-01-14 12:12:04 -08002512
Petar Šeginafb748b32017-08-07 12:37:52 +01002513 /** @hide */
Petar Šeginab92c5392017-09-06 15:25:05 +01002514 @Retention(RetentionPolicy.SOURCE)
Jeff Sharkeyce8db992017-12-13 20:05:05 -07002515 @IntDef(prefix = { "TEXT_SELECTION_LAYOUT_" }, value = {
2516 TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT,
2517 TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT
2518 })
Petar Šegina3a92fb62017-09-07 21:03:24 +01002519 public @interface TextSelectionLayout {}
2520
2521 /** @hide */
2522 public static final int TEXT_SELECTION_LAYOUT_RIGHT_TO_LEFT = 0;
2523 /** @hide */
2524 public static final int TEXT_SELECTION_LAYOUT_LEFT_TO_RIGHT = 1;
Petar Šeginab92c5392017-09-06 15:25:05 +01002525
2526 /** @hide */
Petar Šeginafb748b32017-08-07 12:37:52 +01002527 @FunctionalInterface
Petar Šeginab92c5392017-09-06 15:25:05 +01002528 public interface SelectionRectangleConsumer {
Petar Šeginafb748b32017-08-07 12:37:52 +01002529 /**
2530 * Performs this operation on the given rectangle.
2531 *
2532 * @param left the left edge of the rectangle
2533 * @param top the top edge of the rectangle
2534 * @param right the right edge of the rectangle
2535 * @param bottom the bottom edge of the rectangle
Petar Šeginab92c5392017-09-06 15:25:05 +01002536 * @param textSelectionLayout the layout (RTL or LTR) of the text covered by this
2537 * selection rectangle
Petar Šeginafb748b32017-08-07 12:37:52 +01002538 */
Petar Šeginab92c5392017-09-06 15:25:05 +01002539 void accept(float left, float top, float right, float bottom,
2540 @TextSelectionLayout int textSelectionLayout);
Petar Šeginafb748b32017-08-07 12:37:52 +01002541 }
2542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543}