Repository navigation
Expand file tree
/
Copy pathLayout.java
More file actions
4628 lines (4177 loc) · 184 KB
/
Copy pathLayout.java
File metadata and controls
4628 lines (4177 loc) · 184 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.text;
import static com.android.graphics.hwui.flags.Flags.highContrastTextLuminance;
import static com.android.text.flags.Flags.FLAG_FIX_LINE_HEIGHT_FOR_LOCALE;
import static com.android.text.flags.Flags.FLAG_LETTER_SPACING_JUSTIFICATION;
import static com.android.text.flags.Flags.FLAG_USE_BOUNDS_FOR_WIDTH;
import android.annotation.ColorInt;
import android.annotation.FlaggedApi;
import android.annotation.FloatRange;
import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SuppressLint;
import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.BlendMode;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.text.LineBreakConfig;
import android.graphics.text.LineBreaker;
import android.os.Build;
import android.text.method.TextKeyListener;
import android.text.style.AlignmentSpan;
import android.text.style.LeadingMarginSpan;
import android.text.style.LeadingMarginSpan.LeadingMarginSpan2;
import android.text.style.LineBackgroundSpan;
import android.text.style.ParagraphStyle;
import android.text.style.ReplacementSpan;
import android.text.style.TabStopSpan;
import android.widget.TextView;
import com.android.graphics.hwui.flags.Flags;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.graphics.ColorUtils;
import com.android.internal.util.ArrayUtils;
import com.android.internal.util.GrowingArrayUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.text.BreakIterator;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* A base class that manages text layout in visual elements on
* the screen.
* <p>For text that will be edited, use a {@link DynamicLayout},
* which will be updated as the text changes.
* For text that will not change, use a {@link StaticLayout}.
*/
public abstract class Layout {
// These should match the constants in framework/base/libs/hwui/hwui/DrawTextFunctor.h
private static final float HIGH_CONTRAST_TEXT_BORDER_WIDTH_MIN_PX = 0f;
private static final float HIGH_CONTRAST_TEXT_BORDER_WIDTH_FACTOR = 0f;
private static final float HIGH_CONTRAST_TEXT_BACKGROUND_CORNER_RADIUS_DP = 5f;
// since we're not using soft light yet, this needs to be much lower than the spec'd 0.8
private static final float HIGH_CONTRAST_TEXT_BACKGROUND_ALPHA_PERCENTAGE = 0.5f;
/** @hide */
@IntDef(prefix = { "BREAK_STRATEGY_" }, value = {
LineBreaker.BREAK_STRATEGY_SIMPLE,
LineBreaker.BREAK_STRATEGY_HIGH_QUALITY,
LineBreaker.BREAK_STRATEGY_BALANCED
})
@Retention(RetentionPolicy.SOURCE)
public @interface BreakStrategy {}
/**
* Value for break strategy indicating simple line breaking. Automatic hyphens are not added
* (though soft hyphens are respected), and modifying text generally doesn't affect the layout
* before it (which yields a more consistent user experience when editing), but layout may not
* be the highest quality.
*/
public static final int BREAK_STRATEGY_SIMPLE = LineBreaker.BREAK_STRATEGY_SIMPLE;
/**
* Value for break strategy indicating high quality line breaking, including automatic
* hyphenation and doing whole-paragraph optimization of line breaks.
*/
public static final int BREAK_STRATEGY_HIGH_QUALITY = LineBreaker.BREAK_STRATEGY_HIGH_QUALITY;
/**
* Value for break strategy indicating balanced line breaking. The breaks are chosen to
* make all lines as close to the same length as possible, including automatic hyphenation.
*/
public static final int BREAK_STRATEGY_BALANCED = LineBreaker.BREAK_STRATEGY_BALANCED;
/** @hide */
@IntDef(prefix = { "HYPHENATION_FREQUENCY_" }, value = {
HYPHENATION_FREQUENCY_NORMAL,
HYPHENATION_FREQUENCY_NORMAL_FAST,
HYPHENATION_FREQUENCY_FULL,
HYPHENATION_FREQUENCY_FULL_FAST,
HYPHENATION_FREQUENCY_NONE
})
@Retention(RetentionPolicy.SOURCE)
public @interface HyphenationFrequency {}
/**
* Value for hyphenation frequency indicating no automatic hyphenation. Useful
* for backward compatibility, and for cases where the automatic hyphenation algorithm results
* in incorrect hyphenation. Mid-word breaks may still happen when a word is wider than the
* layout and there is otherwise no valid break. Soft hyphens are ignored and will not be used
* as suggestions for potential line breaks.
*/
public static final int HYPHENATION_FREQUENCY_NONE = 0;
/**
* Value for hyphenation frequency indicating a light amount of automatic hyphenation, which
* is a conservative default. Useful for informal cases, such as short sentences or chat
* messages.
*/
public static final int HYPHENATION_FREQUENCY_NORMAL = 1;
/**
* Value for hyphenation frequency indicating the full amount of automatic hyphenation, typical
* in typography. Useful for running text and where it's important to put the maximum amount of
* text in a screen with limited space.
*/
public static final int HYPHENATION_FREQUENCY_FULL = 2;
/**
* Value for hyphenation frequency indicating a light amount of automatic hyphenation with
* using faster algorithm.
*
* This option is useful for informal cases, such as short sentences or chat messages. To make
* text rendering faster with hyphenation, this algorithm ignores some hyphen character related
* typographic features, e.g. kerning.
*/
public static final int HYPHENATION_FREQUENCY_NORMAL_FAST = 3;
/**
* Value for hyphenation frequency indicating the full amount of automatic hyphenation with
* using faster algorithm.
*
* This option is useful for running text and where it's important to put the maximum amount of
* text in a screen with limited space. To make text rendering faster with hyphenation, this
* algorithm ignores some hyphen character related typographic features, e.g. kerning.
*/
public static final int HYPHENATION_FREQUENCY_FULL_FAST = 4;
private static final ParagraphStyle[] NO_PARA_SPANS =
ArrayUtils.emptyArray(ParagraphStyle.class);
/** @hide */
@IntDef(prefix = { "JUSTIFICATION_MODE_" }, value = {
LineBreaker.JUSTIFICATION_MODE_NONE,
LineBreaker.JUSTIFICATION_MODE_INTER_WORD,
LineBreaker.JUSTIFICATION_MODE_INTER_CHARACTER,
})
@Retention(RetentionPolicy.SOURCE)
public @interface JustificationMode {}
/**
* Value for justification mode indicating no justification.
*/
public static final int JUSTIFICATION_MODE_NONE = LineBreaker.JUSTIFICATION_MODE_NONE;
/**
* Value for justification mode indicating the text is justified by stretching word spacing.
*/
public static final int JUSTIFICATION_MODE_INTER_WORD =
LineBreaker.JUSTIFICATION_MODE_INTER_WORD;
/**
* Value for justification mode indicating the text is justified by stretching letter spacing.
*/
@FlaggedApi(FLAG_LETTER_SPACING_JUSTIFICATION)
public static final int JUSTIFICATION_MODE_INTER_CHARACTER =
LineBreaker.JUSTIFICATION_MODE_INTER_CHARACTER;
/*
* Line spacing multiplier for default line spacing.
*/
public static final float DEFAULT_LINESPACING_MULTIPLIER = 1.0f;
/*
* Line spacing addition for default line spacing.
*/
public static final float DEFAULT_LINESPACING_ADDITION = 0.0f;
/**
* Strategy which considers a text segment to be inside a rectangle area if the segment bounds
* intersect the rectangle.
*/
@NonNull
public static final TextInclusionStrategy INCLUSION_STRATEGY_ANY_OVERLAP =
RectF::intersects;
/**
* Strategy which considers a text segment to be inside a rectangle area if the center of the
* segment bounds is inside the rectangle.
*/
@NonNull
public static final TextInclusionStrategy INCLUSION_STRATEGY_CONTAINS_CENTER =
(segmentBounds, area) ->
area.contains(segmentBounds.centerX(), segmentBounds.centerY());
/**
* Strategy which considers a text segment to be inside a rectangle area if the segment bounds
* are completely contained within the rectangle.
*/
@NonNull
public static final TextInclusionStrategy INCLUSION_STRATEGY_CONTAINS_ALL =
(segmentBounds, area) -> area.contains(segmentBounds);
/**
* Return how wide a layout must be in order to display the specified text with one line per
* paragraph.
*
* <p>As of O, Uses
* {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
* the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
*/
public static float getDesiredWidth(CharSequence source,
TextPaint paint) {
return getDesiredWidth(source, 0, source.length(), paint);
}
/**
* Return how wide a layout must be in order to display the specified text slice with one
* line per paragraph.
*
* <p>As of O, Uses
* {@link TextDirectionHeuristics#FIRSTSTRONG_LTR} as the default text direction heuristics. In
* the earlier versions uses {@link TextDirectionHeuristics#LTR} as the default.</p>
*/
public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint) {
return getDesiredWidth(source, start, end, paint, TextDirectionHeuristics.FIRSTSTRONG_LTR);
}
/**
* Return how wide a layout must be in order to display the
* specified text slice with one line per paragraph.
*
* @hide
*/
public static float getDesiredWidth(CharSequence source, int start, int end, TextPaint paint,
TextDirectionHeuristic textDir) {
return getDesiredWidthWithLimit(source, start, end, paint, textDir, Float.MAX_VALUE, false);
}
/**
* Return how wide a layout must be in order to display the
* specified text slice with one line per paragraph.
*
* If the measured width exceeds given limit, returns limit value instead.
* @hide
*/
public static float getDesiredWidthWithLimit(CharSequence source, int start, int end,
TextPaint paint, TextDirectionHeuristic textDir, float upperLimit,
boolean useBoundsForWidth) {
float need = 0;
int next;
for (int i = start; i <= end; i = next) {
next = TextUtils.indexOf(source, '\n', i, end);
if (next < 0)
next = end;
// note, omits trailing paragraph char
float w = measurePara(paint, source, i, next, textDir, useBoundsForWidth);
if (w > upperLimit) {
return upperLimit;
}
if (w > need)
need = w;
next++;
}
return need;
}
/**
* Subclasses of Layout use this constructor to set the display text,
* width, and other standard properties.
* @param text the text to render
* @param paint the default paint for the layout. Styles can override
* various attributes of the paint.
* @param width the wrapping width for the text.
* @param align whether to left, right, or center the text. Styles can
* override the alignment.
* @param spacingMult factor by which to scale the font size to get the
* default line spacing
* @param spacingAdd amount to add to the default line spacing
*/
protected Layout(CharSequence text, TextPaint paint,
int width, Alignment align,
float spacingMult, float spacingAdd) {
this(text, paint, width, align, TextDirectionHeuristics.FIRSTSTRONG_LTR,
spacingMult, spacingAdd, false, false, 0, null, Integer.MAX_VALUE,
BREAK_STRATEGY_SIMPLE, HYPHENATION_FREQUENCY_NONE, null, null,
JUSTIFICATION_MODE_NONE, LineBreakConfig.NONE, false, false, null);
}
/**
* Subclasses of Layout use this constructor to set the display text,
* width, and other standard properties.
* @param text the text to render
* @param paint the default paint for the layout. Styles can override
* various attributes of the paint.
* @param width the wrapping width for the text.
* @param align whether to left, right, or center the text. Styles can
* override the alignment.
* @param textDir a text direction heuristic.
* @param spacingMult factor by which to scale the font size to get the
* default line spacing
* @param spacingAdd amount to add to the default line spacing
* @param includePad true for enabling including font padding
* @param fallbackLineSpacing true for enabling fallback line spacing
* @param ellipsizedWidth width as used for ellipsizing purpose
* @param ellipsize an ellipsize option
* @param maxLines a maximum number of lines.
* @param breakStrategy a break strategy.
* @param hyphenationFrequency a hyphenation frequency
* @param leftIndents a visually left margins
* @param rightIndents a visually right margins
* @param justificationMode a justification mode
* @param lineBreakConfig a line break config
*
* @hide
*/
protected Layout(
CharSequence text,
TextPaint paint,
int width,
Alignment align,
TextDirectionHeuristic textDir,
float spacingMult,
float spacingAdd,
boolean includePad,
boolean fallbackLineSpacing,
int ellipsizedWidth,
TextUtils.TruncateAt ellipsize,
int maxLines,
int breakStrategy,
int hyphenationFrequency,
int[] leftIndents,
int[] rightIndents,
int justificationMode,
LineBreakConfig lineBreakConfig,
boolean useBoundsForWidth,
boolean shiftDrawingOffsetForStartOverhang,
Paint.FontMetrics minimumFontMetrics
) {
if (width < 0)
throw new IllegalArgumentException("Layout: " + width + " < 0");
// Ensure paint doesn't have baselineShift set.
// While normally we don't modify the paint the user passed in,
// we were already doing this in Styled.drawUniformRun with both
// baselineShift and bgColor. We probably should reevaluate bgColor.
if (paint != null) {
paint.bgColor = 0;
paint.baselineShift = 0;
}
mText = text;
mPaint = paint;
mWidth = width;
mAlignment = align;
mSpacingMult = spacingMult;
mSpacingAdd = spacingAdd;
mSpannedText = text instanceof Spanned;
mTextDir = textDir;
mIncludePad = includePad;
mFallbackLineSpacing = fallbackLineSpacing;
mEllipsizedWidth = ellipsize == null ? width : ellipsizedWidth;
mEllipsize = ellipsize;
mMaxLines = maxLines;
mBreakStrategy = breakStrategy;
mHyphenationFrequency = hyphenationFrequency;
mLeftIndents = leftIndents;
mRightIndents = rightIndents;
mJustificationMode = justificationMode;
mLineBreakConfig = lineBreakConfig;
mUseBoundsForWidth = useBoundsForWidth;
mShiftDrawingOffsetForStartOverhang = shiftDrawingOffsetForStartOverhang;
mMinimumFontMetrics = minimumFontMetrics;
initSpanColors();
}
private void initSpanColors() {
if (mSpannedText && Flags.highContrastTextSmallTextRect()) {
if (mSpanColors == null) {
mSpanColors = new SpanColors();
} else {
mSpanColors.recycle();
}
} else {
mSpanColors = null;
}
}
/**
* Replace constructor properties of this Layout with new ones. Be careful.
*/
/* package */ void replaceWith(CharSequence text, TextPaint paint,
int width, Alignment align,
float spacingmult, float spacingadd) {
if (width < 0) {
throw new IllegalArgumentException("Layout: " + width + " < 0");
}
mText = text;
mPaint = paint;
mWidth = width;
mAlignment = align;
mSpacingMult = spacingmult;
mSpacingAdd = spacingadd;
mSpannedText = text instanceof Spanned;
initSpanColors();
}
/**
* Draw this Layout on the specified Canvas.
*
* This API draws background first, then draws text on top of it.
*
* @see #draw(Canvas, List, List, Path, Paint, int)
*/
public void draw(Canvas c) {
draw(c, (Path) null, (Paint) null, 0);
}
/**
* Draw this Layout on the specified canvas, with the highlight path drawn
* between the background and the text.
*
* @param canvas the canvas
* @param selectionHighlight the path of the selection highlight or cursor; can be null
* @param selectionHighlightPaint the paint for the selection highlight
* @param cursorOffsetVertical the amount to temporarily translate the
* canvas while rendering the highlight
*
* @see #draw(Canvas, List, List, Path, Paint, int)
*/
public void draw(
Canvas canvas, Path selectionHighlight,
Paint selectionHighlightPaint, int cursorOffsetVertical) {
draw(canvas, null, null, selectionHighlight, selectionHighlightPaint, cursorOffsetVertical);
}
/**
* Draw this layout on the specified canvas.
*
* This API draws background first, then draws highlight paths on top of it, then draws
* selection or cursor, then finally draws text on top of it.
*
* @see #drawBackground(Canvas)
* @see #drawText(Canvas)
*
* @param canvas the canvas
* @param highlightPaths the path of the highlights. The highlightPaths and highlightPaints must
* have the same length and aligned in the same order. For example, the
* paint of the n-th of the highlightPaths should be stored at the n-th of
* highlightPaints.
* @param highlightPaints the paints for the highlights. The highlightPaths and highlightPaints
* must have the same length and aligned in the same order. For example,
* the paint of the n-th of the highlightPaths should be stored at the
* n-th of highlightPaints.
* @param selectionPath the selection or cursor path
* @param selectionPaint the paint for the selection or cursor.
* @param cursorOffsetVertical the amount to temporarily translate the canvas while rendering
* the highlight
*/
public void draw(@NonNull Canvas canvas,
@Nullable List<Path> highlightPaths,
@Nullable List<Paint> highlightPaints,
@Nullable Path selectionPath,
@Nullable Paint selectionPaint,
int cursorOffsetVertical) {
float leftShift = 0;
if (mUseBoundsForWidth && mShiftDrawingOffsetForStartOverhang) {
RectF drawingRect = computeDrawingBoundingBox();
if (drawingRect.left < 0) {
leftShift = -drawingRect.left;
canvas.translate(leftShift, 0);
}
}
final long lineRange = getLineRangeForDraw(canvas);
int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
if (lastLine < 0) return;
if (shouldDrawHighlightsOnTop(canvas)) {
drawBackground(canvas, firstLine, lastLine);
} else {
drawWithoutText(canvas, highlightPaths, highlightPaints, selectionPath, selectionPaint,
cursorOffsetVertical, firstLine, lastLine);
}
drawText(canvas, firstLine, lastLine);
// Since high contrast text draws a thick border on the text, the highlight actually makes
// it harder to read. In this case we draw over the top of the text with a blend mode that
// ensures the text stays high-contrast.
if (shouldDrawHighlightsOnTop(canvas)) {
drawHighlights(canvas, highlightPaths, highlightPaints, selectionPath, selectionPaint,
cursorOffsetVertical, firstLine, lastLine);
}
if (leftShift != 0) {
// Manually translate back to the original position because of b/324498002, using
// save/restore disappears the toggle switch drawables.
canvas.translate(-leftShift, 0);
}
}
private static boolean shouldDrawHighlightsOnTop(Canvas canvas) {
return Flags.highContrastTextSmallTextRect() && canvas.isHighContrastTextEnabled();
}
private static Paint setToHighlightPaint(Paint p, BlendMode blendMode, Paint outPaint) {
if (p == null) return null;
outPaint.set(p);
outPaint.setBlendMode(blendMode);
// Yellow for maximum contrast
outPaint.setColor(Color.YELLOW);
return outPaint;
}
/**
* Draw text part of this layout.
*
* Different from {@link #draw(Canvas, List, List, Path, Paint, int)} API, this API only draws
* text part, not drawing highlights, selections, or backgrounds.
*
* @see #draw(Canvas, List, List, Path, Paint, int)
* @see #drawBackground(Canvas)
*
* @param canvas the canvas
*/
public void drawText(@NonNull Canvas canvas) {
final long lineRange = getLineRangeForDraw(canvas);
int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
if (lastLine < 0) return;
drawText(canvas, firstLine, lastLine);
}
/**
* Draw background of this layout.
*
* Different from {@link #draw(Canvas, List, List, Path, Paint, int)} API, this API only draws
* background, not drawing text, highlights or selections. The background here is drawn by
* {@link LineBackgroundSpan} attached to the text.
*
* @see #draw(Canvas, List, List, Path, Paint, int)
* @see #drawText(Canvas)
*
* @param canvas the canvas
*/
public void drawBackground(@NonNull Canvas canvas) {
final long lineRange = getLineRangeForDraw(canvas);
int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
if (lastLine < 0) return;
drawBackground(canvas, firstLine, lastLine);
}
/**
* @hide public for Editor.java
*/
public void drawWithoutText(
@NonNull Canvas canvas,
@Nullable List<Path> highlightPaths,
@Nullable List<Paint> highlightPaints,
@Nullable Path selectionPath,
@Nullable Paint selectionPaint,
int cursorOffsetVertical,
int firstLine,
int lastLine) {
drawBackground(canvas, firstLine, lastLine);
drawHighlights(canvas, highlightPaths, highlightPaints, selectionPath, selectionPaint,
cursorOffsetVertical, firstLine, lastLine);
}
/**
* @hide public for Editor.java
*/
public void drawHighlights(
@NonNull Canvas canvas,
@Nullable List<Path> highlightPaths,
@Nullable List<Paint> highlightPaints,
@Nullable Path selectionPath,
@Nullable Paint selectionPaint,
int cursorOffsetVertical,
int firstLine,
int lastLine) {
if (highlightPaths == null && highlightPaints == null) {
return;
}
if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical);
try {
BlendMode blendMode = determineHighContrastHighlightBlendMode(canvas);
if (highlightPaths != null) {
if (highlightPaints == null) {
throw new IllegalArgumentException(
"if highlight is specified, highlightPaint must be specified.");
}
if (highlightPaints.size() != highlightPaths.size()) {
throw new IllegalArgumentException(
"The highlight path size is different from the size of highlight"
+ " paints");
}
for (int i = 0; i < highlightPaths.size(); ++i) {
final Path highlight = highlightPaths.get(i);
Paint highlightPaint = highlightPaints.get(i);
if (shouldDrawHighlightsOnTop(canvas)) {
highlightPaint = setToHighlightPaint(highlightPaint, blendMode,
mWorkPlainPaint);
}
if (highlight != null) {
canvas.drawPath(highlight, highlightPaint);
}
}
}
if (selectionPath != null) {
if (shouldDrawHighlightsOnTop(canvas)) {
selectionPaint = setToHighlightPaint(selectionPaint, blendMode,
mWorkPlainPaint);
}
canvas.drawPath(selectionPath, selectionPaint);
}
} finally {
if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical);
}
}
@Nullable
private BlendMode determineHighContrastHighlightBlendMode(Canvas canvas) {
if (!shouldDrawHighlightsOnTop(canvas)) {
return null;
}
return isHighContrastTextDark(mPaint.getColor()) ? BlendMode.MULTIPLY
: BlendMode.DIFFERENCE;
}
private boolean isHighContrastTextDark(@ColorInt int color) {
// High-contrast text mode
// Determine if the text is black-on-white or white-on-black, so we know what blendmode will
// give the highest contrast and most realistic text color.
// This equation should match the one in libs/hwui/hwui/DrawTextFunctor.h
if (highContrastTextLuminance()) {
var lab = new double[3];
ColorUtils.colorToLAB(color, lab);
return lab[0] < 50.0;
} else {
int channelSum = Color.red(color) + Color.green(color) + Color.blue(color);
return channelSum < (128 * 3);
}
}
private boolean isJustificationRequired(int lineNum) {
if (mJustificationMode == JUSTIFICATION_MODE_NONE) return false;
final int lineEnd = getLineEnd(lineNum);
return lineEnd < mText.length() && mText.charAt(lineEnd - 1) != '\n';
}
private float getJustifyWidth(int lineNum) {
Alignment paraAlign = mAlignment;
int left = 0;
int right = mWidth;
final int dir = getParagraphDirection(lineNum);
ParagraphStyle[] spans = NO_PARA_SPANS;
if (mSpannedText) {
Spanned sp = (Spanned) mText;
final int start = getLineStart(lineNum);
final boolean isFirstParaLine = (start == 0 || mText.charAt(start - 1) == '\n');
if (isFirstParaLine) {
final int spanEnd = sp.nextSpanTransition(start, mText.length(),
ParagraphStyle.class);
spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
for (int n = spans.length - 1; n >= 0; n--) {
if (spans[n] instanceof AlignmentSpan) {
paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
break;
}
}
}
final int length = spans.length;
boolean useFirstLineMargin = isFirstParaLine;
for (int n = 0; n < length; n++) {
if (spans[n] instanceof LeadingMarginSpan2) {
int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
if (lineNum < startLine + count) {
useFirstLineMargin = true;
break;
}
}
}
for (int n = 0; n < length; n++) {
if (spans[n] instanceof LeadingMarginSpan) {
LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
if (dir == DIR_RIGHT_TO_LEFT) {
right -= margin.getLeadingMargin(useFirstLineMargin);
} else {
left += margin.getLeadingMargin(useFirstLineMargin);
}
}
}
}
final Alignment align;
if (paraAlign == Alignment.ALIGN_LEFT) {
align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
} else if (paraAlign == Alignment.ALIGN_RIGHT) {
align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
} else {
align = paraAlign;
}
final int indentWidth;
if (align == Alignment.ALIGN_NORMAL) {
if (dir == DIR_LEFT_TO_RIGHT) {
indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
} else {
indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
}
} else if (align == Alignment.ALIGN_OPPOSITE) {
if (dir == DIR_LEFT_TO_RIGHT) {
indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
} else {
indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
}
} else { // Alignment.ALIGN_CENTER
indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
}
return right - left - indentWidth;
}
/**
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void drawText(Canvas canvas, int firstLine, int lastLine) {
int previousLineBottom = getLineTop(firstLine);
int previousLineEnd = getLineStart(firstLine);
ParagraphStyle[] spans = NO_PARA_SPANS;
int spanEnd = 0;
final TextPaint paint = mWorkPaint;
paint.set(mPaint);
CharSequence buf = mText;
Alignment paraAlign = mAlignment;
TabStops tabStops = null;
boolean tabStopsIsInitialized = false;
TextLine tl = TextLine.obtain();
// Draw the lines, one at a time.
// The baseline is the top of the following line minus the current line's descent.
for (int lineNum = firstLine; lineNum <= lastLine; lineNum++) {
int start = previousLineEnd;
previousLineEnd = getLineStart(lineNum + 1);
final boolean justify = isJustificationRequired(lineNum);
int end = getLineVisibleEnd(lineNum, start, previousLineEnd,
true /* trailingSpaceAtLastLineIsVisible */);
paint.setStartHyphenEdit(getStartHyphenEdit(lineNum));
paint.setEndHyphenEdit(getEndHyphenEdit(lineNum));
int ltop = previousLineBottom;
int lbottom = getLineTop(lineNum + 1);
previousLineBottom = lbottom;
int lbaseline = lbottom - getLineDescent(lineNum);
int dir = getParagraphDirection(lineNum);
int left = 0;
int right = mWidth;
if (mSpannedText) {
Spanned sp = (Spanned) buf;
int textLength = buf.length();
boolean isFirstParaLine = (start == 0 || buf.charAt(start - 1) == '\n');
// New batch of paragraph styles, collect into spans array.
// Compute the alignment, last alignment style wins.
// Reset tabStops, we'll rebuild if we encounter a line with
// tabs.
// We expect paragraph spans to be relatively infrequent, use
// spanEnd so that we can check less frequently. Since
// paragraph styles ought to apply to entire paragraphs, we can
// just collect the ones present at the start of the paragraph.
// If spanEnd is before the end of the paragraph, that's not
// our problem.
if (start >= spanEnd && (lineNum == firstLine || isFirstParaLine)) {
spanEnd = sp.nextSpanTransition(start, textLength,
ParagraphStyle.class);
spans = getParagraphSpans(sp, start, spanEnd, ParagraphStyle.class);
paraAlign = mAlignment;
for (int n = spans.length - 1; n >= 0; n--) {
if (spans[n] instanceof AlignmentSpan) {
paraAlign = ((AlignmentSpan) spans[n]).getAlignment();
break;
}
}
tabStopsIsInitialized = false;
}
// Draw all leading margin spans. Adjust left or right according
// to the paragraph direction of the line.
final int length = spans.length;
boolean useFirstLineMargin = isFirstParaLine;
for (int n = 0; n < length; n++) {
if (spans[n] instanceof LeadingMarginSpan2) {
int count = ((LeadingMarginSpan2) spans[n]).getLeadingMarginLineCount();
int startLine = getLineForOffset(sp.getSpanStart(spans[n]));
// if there is more than one LeadingMarginSpan2, use
// the count that is greatest
if (lineNum < startLine + count) {
useFirstLineMargin = true;
break;
}
}
}
for (int n = 0; n < length; n++) {
if (spans[n] instanceof LeadingMarginSpan) {
LeadingMarginSpan margin = (LeadingMarginSpan) spans[n];
if (dir == DIR_RIGHT_TO_LEFT) {
margin.drawLeadingMargin(canvas, paint, right, dir, ltop,
lbaseline, lbottom, buf,
start, end, isFirstParaLine, this);
right -= margin.getLeadingMargin(useFirstLineMargin);
} else {
margin.drawLeadingMargin(canvas, paint, left, dir, ltop,
lbaseline, lbottom, buf,
start, end, isFirstParaLine, this);
left += margin.getLeadingMargin(useFirstLineMargin);
}
}
}
}
boolean hasTab = getLineContainsTab(lineNum);
// Can't tell if we have tabs for sure, currently
if (hasTab && !tabStopsIsInitialized) {
if (tabStops == null) {
tabStops = new TabStops(TAB_INCREMENT, spans);
} else {
tabStops.reset(TAB_INCREMENT, spans);
}
tabStopsIsInitialized = true;
}
// Determine whether the line aligns to normal, opposite, or center.
Alignment align = paraAlign;
if (align == Alignment.ALIGN_LEFT) {
align = (dir == DIR_LEFT_TO_RIGHT) ?
Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE;
} else if (align == Alignment.ALIGN_RIGHT) {
align = (dir == DIR_LEFT_TO_RIGHT) ?
Alignment.ALIGN_OPPOSITE : Alignment.ALIGN_NORMAL;
}
int x;
final int indentWidth;
if (align == Alignment.ALIGN_NORMAL) {
if (dir == DIR_LEFT_TO_RIGHT) {
indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
x = left + indentWidth;
} else {
indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
x = right - indentWidth;
}
} else {
int max = (int)getLineExtent(lineNum, tabStops, false);
if (align == Alignment.ALIGN_OPPOSITE) {
if (dir == DIR_LEFT_TO_RIGHT) {
indentWidth = -getIndentAdjust(lineNum, Alignment.ALIGN_RIGHT);
x = right - max - indentWidth;
} else {
indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_LEFT);
x = left - max + indentWidth;
}
} else { // Alignment.ALIGN_CENTER
indentWidth = getIndentAdjust(lineNum, Alignment.ALIGN_CENTER);
max = max & ~1;
x = ((right + left - max) >> 1) + indentWidth;
}
}
Directions directions = getLineDirections(lineNum);
if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTab && !justify) {
// XXX: assumes there's nothing additional to be done
canvas.drawText(buf, start, end, x, lbaseline, paint);
} else {
tl.set(paint, buf, start, end, dir, directions, hasTab, tabStops,
getEllipsisStart(lineNum),
getEllipsisStart(lineNum) + getEllipsisCount(lineNum),
isFallbackLineSpacingEnabled());
if (justify) {
tl.justify(mJustificationMode, right - left - indentWidth);
}
tl.draw(canvas, x, ltop, lbaseline, lbottom);
}
}
TextLine.recycle(tl);
}
/**
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void drawBackground(
@NonNull Canvas canvas,
int firstLine, int lastLine) {
drawHighContrastBackground(canvas, firstLine, lastLine);
// First, draw LineBackgroundSpans.
// LineBackgroundSpans know nothing about the alignment, margins, or
// direction of the layout or line. XXX: Should they?
// They are evaluated at each line.
if (mSpannedText) {
if (mLineBackgroundSpans == null) {
mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.class);
}
Spanned buffer = (Spanned) mText;
int textLength = buffer.length();
mLineBackgroundSpans.init(buffer, 0, textLength);
if (mLineBackgroundSpans.numberOfSpans > 0) {
int previousLineBottom = getLineTop(firstLine);
int previousLineEnd = getLineStart(firstLine);
ParagraphStyle[] spans = NO_PARA_SPANS;
int spansLength = 0;
TextPaint paint = mPaint;
int spanEnd = 0;
final int width = mWidth;
for (int i = firstLine; i <= lastLine; i++) {
int start = previousLineEnd;
int end = getLineStart(i + 1);
previousLineEnd = end;
int ltop = previousLineBottom;
int lbottom = getLineTop(i + 1);
previousLineBottom = lbottom;
int lbaseline = lbottom - getLineDescent(i);
if (end >= spanEnd) {
// These should be infrequent, so we'll use this so that
// we don't have to check as often.
spanEnd = mLineBackgroundSpans.getNextTransition(start, textLength);
// All LineBackgroundSpans on a line contribute to its background.
spansLength = 0;
// Duplication of the logic of getParagraphSpans
if (start != end || start == 0) {
// Equivalent to a getSpans(start, end), but filling the 'spans' local
// array instead to reduce memory allocation
for (int j = 0; j < mLineBackgroundSpans.numberOfSpans; j++) {
// equal test is valid since both intervals are not empty by
// construction
if (mLineBackgroundSpans.spanStarts[j] >= end ||
mLineBackgroundSpans.spanEnds[j] <= start) continue;
spans = GrowingArrayUtils.append(
spans, spansLength, mLineBackgroundSpans.spans[j]);
spansLength++;