Repository navigation
Expand file tree
/
Copy pathTextLine.java
More file actions
1919 lines (1743 loc) · 82.8 KB
/
Copy pathTextLine.java
File metadata and controls
1919 lines (1743 loc) · 82.8 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) 2010 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 android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.text.PositionedGlyphs;
import android.graphics.text.TextRunShaper;
import android.os.Build;
import android.text.Layout.Directions;
import android.text.Layout.TabStops;
import android.text.style.CharacterStyle;
import android.text.style.MetricAffectingSpan;
import android.text.style.ReplacementSpan;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.ArrayUtils;
import java.util.ArrayList;
/**
* Represents a line of styled text, for measuring in visual order and
* for rendering.
*
* <p>Get a new instance using obtain(), and when finished with it, return it
* to the pool using recycle().
*
* <p>Call set to prepare the instance for use, then either draw, measure,
* metrics, or caretToLeftRightOf.
*
* @hide
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public class TextLine {
private static final boolean DEBUG = false;
private static final char TAB_CHAR = '\t';
private TextPaint mPaint;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
private CharSequence mText;
private int mStart;
private int mLen;
private int mDir;
private Directions mDirections;
private boolean mHasTabs;
private TabStops mTabs;
private char[] mChars;
private boolean mCharsValid;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
private Spanned mSpanned;
private PrecomputedText mComputed;
private RectF mTmpRectForMeasure;
private RectF mTmpRectForPaintAPI;
private Rect mTmpRectForPrecompute;
// Recycling object for Paint APIs. Do not use outside getRunAdvances method.
private Paint.RunInfo mRunInfo;
public static final class LineInfo {
private int mClusterCount;
public int getClusterCount() {
return mClusterCount;
}
public void setClusterCount(int clusterCount) {
mClusterCount = clusterCount;
}
};
private boolean mUseFallbackExtent = false;
// The start and end of a potentially existing ellipsis on this text line.
// We use them to filter out replacement and metric affecting spans on ellipsized away chars.
private int mEllipsisStart;
private int mEllipsisEnd;
// Additional width of whitespace for justification. This value is per whitespace, thus
// the line width will increase by mAddedWidthForJustify x (number of stretchable whitespaces).
private float mAddedWordSpacingInPx;
private float mAddedLetterSpacingInPx;
private boolean mIsJustifying;
@VisibleForTesting
public float getAddedWordSpacingInPx() {
return mAddedWordSpacingInPx;
}
@VisibleForTesting
public float getAddedLetterSpacingInPx() {
return mAddedLetterSpacingInPx;
}
@VisibleForTesting
public boolean isJustifying() {
return mIsJustifying;
}
private final TextPaint mWorkPaint = new TextPaint();
private final TextPaint mActivePaint = new TextPaint();
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
private final SpanSet<MetricAffectingSpan> mMetricAffectingSpanSpanSet =
new SpanSet<MetricAffectingSpan>(MetricAffectingSpan.class);
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
private final SpanSet<CharacterStyle> mCharacterStyleSpanSet =
new SpanSet<CharacterStyle>(CharacterStyle.class);
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
private final SpanSet<ReplacementSpan> mReplacementSpanSpanSet =
new SpanSet<ReplacementSpan>(ReplacementSpan.class);
private final DecorationInfo mDecorationInfo = new DecorationInfo();
private final ArrayList<DecorationInfo> mDecorations = new ArrayList<>();
/** Not allowed to access. If it's for memory leak workaround, it was already fixed M. */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private static final TextLine[] sCached = new TextLine[3];
/**
* Returns a new TextLine from the shared pool.
*
* @return an uninitialized TextLine
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
@UnsupportedAppUsage
public static TextLine obtain() {
TextLine tl;
synchronized (sCached) {
for (int i = sCached.length; --i >= 0;) {
if (sCached[i] != null) {
tl = sCached[i];
sCached[i] = null;
return tl;
}
}
}
tl = new TextLine();
if (DEBUG) {
Log.v("TLINE", "new: " + tl);
}
return tl;
}
/**
* Puts a TextLine back into the shared pool. Do not use this TextLine once
* it has been returned.
* @param tl the textLine
* @return null, as a convenience from clearing references to the provided
* TextLine
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public static TextLine recycle(TextLine tl) {
tl.mText = null;
tl.mPaint = null;
tl.mDirections = null;
tl.mSpanned = null;
tl.mTabs = null;
tl.mChars = null;
tl.mComputed = null;
tl.mUseFallbackExtent = false;
tl.mMetricAffectingSpanSpanSet.recycle();
tl.mCharacterStyleSpanSet.recycle();
tl.mReplacementSpanSpanSet.recycle();
synchronized(sCached) {
for (int i = 0; i < sCached.length; ++i) {
if (sCached[i] == null) {
sCached[i] = tl;
break;
}
}
}
return null;
}
/**
* Initializes a TextLine and prepares it for use.
*
* @param paint the base paint for the line
* @param text the text, can be Styled
* @param start the start of the line relative to the text
* @param limit the limit of the line relative to the text
* @param dir the paragraph direction of this line
* @param directions the directions information of this line
* @param hasTabs true if the line might contain tabs
* @param tabStops the tabStops. Can be null
* @param ellipsisStart the start of the ellipsis relative to the line
* @param ellipsisEnd the end of the ellipsis relative to the line. When there
* is no ellipsis, this should be equal to ellipsisStart.
* @param useFallbackLineSpacing true for enabling fallback line spacing. false for disabling
* fallback line spacing.
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public void set(TextPaint paint, CharSequence text, int start, int limit, int dir,
Directions directions, boolean hasTabs, TabStops tabStops,
int ellipsisStart, int ellipsisEnd, boolean useFallbackLineSpacing) {
mPaint = paint;
mText = text;
mStart = start;
mLen = limit - start;
mDir = dir;
mDirections = directions;
mUseFallbackExtent = useFallbackLineSpacing;
if (mDirections == null) {
throw new IllegalArgumentException("Directions cannot be null");
}
mHasTabs = hasTabs;
mSpanned = null;
boolean hasReplacement = false;
if (text instanceof Spanned) {
mSpanned = (Spanned) text;
mReplacementSpanSpanSet.init(mSpanned, start, limit);
hasReplacement = mReplacementSpanSpanSet.numberOfSpans > 0;
}
mComputed = null;
if (text instanceof PrecomputedText) {
// Here, no need to check line break strategy or hyphenation frequency since there is no
// line break concept here.
mComputed = (PrecomputedText) text;
if (!mComputed.getParams().getTextPaint().equalsForTextMeasurement(paint)) {
mComputed = null;
}
}
mCharsValid = hasReplacement;
if (mCharsValid) {
if (mChars == null || mChars.length < mLen) {
mChars = ArrayUtils.newUnpaddedCharArray(mLen);
}
TextUtils.getChars(text, start, limit, mChars, 0);
if (hasReplacement) {
// Handle these all at once so we don't have to do it as we go.
// Replace the first character of each replacement run with the
// object-replacement character and the remainder with zero width
// non-break space aka BOM. Cursor movement code skips these
// zero-width characters.
char[] chars = mChars;
for (int i = start, inext; i < limit; i = inext) {
inext = mReplacementSpanSpanSet.getNextTransition(i, limit);
if (mReplacementSpanSpanSet.hasSpansIntersecting(i, inext)
&& (i - start >= ellipsisEnd || inext - start <= ellipsisStart)) {
// transition into a span
chars[i - start] = '\ufffc';
for (int j = i - start + 1, e = inext - start; j < e; ++j) {
chars[j] = '\ufeff'; // used as ZWNBS, marks positions to skip
}
}
}
}
}
mTabs = tabStops;
mAddedWordSpacingInPx = 0;
mIsJustifying = false;
mEllipsisStart = ellipsisStart != ellipsisEnd ? ellipsisStart : 0;
mEllipsisEnd = ellipsisStart != ellipsisEnd ? ellipsisEnd : 0;
}
private char charAt(int i) {
return mCharsValid ? mChars[i] : mText.charAt(i + mStart);
}
/**
* Justify the line to the given width.
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public void justify(@Layout.JustificationMode int justificationMode, float justifyWidth) {
int end = mLen;
while (end > 0 && isLineEndSpace(mText.charAt(mStart + end - 1))) {
end--;
}
if (justificationMode == Layout.JUSTIFICATION_MODE_INTER_WORD) {
float width = Math.abs(measure(end, false, null, null, null));
final int spaces = countStretchableSpaces(0, end);
if (spaces == 0) {
// There are no stretchable spaces, so we can't help the justification by adding any
// width.
return;
}
mAddedWordSpacingInPx = (justifyWidth - width) / spaces;
mAddedLetterSpacingInPx = 0;
} else { // justificationMode == Layout.JUSTIFICATION_MODE_LETTER_SPACING
LineInfo lineInfo = new LineInfo();
float width = Math.abs(measure(end, false, null, null, lineInfo));
int lettersCount = lineInfo.getClusterCount();
if (lettersCount < 2) {
return;
}
mAddedLetterSpacingInPx = (justifyWidth - width) / (lettersCount - 1);
if (mAddedLetterSpacingInPx > 0.03) {
// If the letter spacing is more than 0.03em, the ligatures are automatically
// disabled, so re-calculate everything without ligatures.
final String oldFontFeatures = mPaint.getFontFeatureSettings();
mPaint.setFontFeatureSettings(oldFontFeatures + ", \"liga\" off, \"cliga\" off");
width = Math.abs(measure(end, false, null, null, lineInfo));
lettersCount = lineInfo.getClusterCount();
mAddedLetterSpacingInPx = (justifyWidth - width) / (lettersCount - 1);
mPaint.setFontFeatureSettings(oldFontFeatures);
}
mAddedWordSpacingInPx = 0;
}
mIsJustifying = true;
}
/**
* Returns the run flag of at the given BiDi run.
*
* @param bidiRunIndex a BiDi run index.
* @return a run flag of the given BiDi run.
*/
@VisibleForTesting
public static int calculateRunFlag(int bidiRunIndex, int bidiRunCount, int lineDirection) {
if (bidiRunCount == 1) {
// Easy case. If there is only single run, it is most left and most right run.
return Paint.TEXT_RUN_FLAG_LEFT_EDGE | Paint.TEXT_RUN_FLAG_RIGHT_EDGE;
}
if (bidiRunIndex != 0 && bidiRunIndex != (bidiRunCount - 1)) {
// Easy case. If the given run is the middle of the line, it is not the most left or
// the most right run.
return 0;
}
int runFlag = 0;
// For the historical reasons, the BiDi implementation of Android works differently
// from the Java BiDi APIs. The mDirections holds the BiDi runs in visual order, but
// it is reversed order if the paragraph direction is RTL. So, the first BiDi run of
// mDirections is located the most left of the line if the paragraph direction is LTR.
// If the paragraph direction is RTL, the first BiDi run is located the most right of
// the line.
if (bidiRunIndex == 0) {
if (lineDirection == Layout.DIR_LEFT_TO_RIGHT) {
runFlag |= Paint.TEXT_RUN_FLAG_LEFT_EDGE;
} else {
runFlag |= Paint.TEXT_RUN_FLAG_RIGHT_EDGE;
}
}
if (bidiRunIndex == (bidiRunCount - 1)) {
if (lineDirection == Layout.DIR_LEFT_TO_RIGHT) {
runFlag |= Paint.TEXT_RUN_FLAG_RIGHT_EDGE;
} else {
runFlag |= Paint.TEXT_RUN_FLAG_LEFT_EDGE;
}
}
return runFlag;
}
/**
* Resolve the runFlag for the inline span range.
*
* @param runFlag the runFlag of the current BiDi run.
* @param isRtlRun true for RTL run, false for LTR run.
* @param runStart the inclusive BiDi run start offset.
* @param runEnd the exclusive BiDi run end offset.
* @param spanStart the inclusive span start offset.
* @param spanEnd the exclusive span end offset.
* @return the resolved runFlag.
*/
@VisibleForTesting
public static int resolveRunFlagForSubSequence(int runFlag, boolean isRtlRun, int runStart,
int runEnd, int spanStart, int spanEnd) {
if (runFlag == 0) {
// Easy case. If the run is in the middle of the line, any inline span is also in the
// middle of the line.
return 0;
}
int localRunFlag = runFlag;
if ((runFlag & Paint.TEXT_RUN_FLAG_LEFT_EDGE) != 0) {
if (isRtlRun) {
if (spanEnd != runEnd) {
// In the RTL context, the last run is the most left run.
localRunFlag &= ~Paint.TEXT_RUN_FLAG_LEFT_EDGE;
}
} else { // LTR
if (spanStart != runStart) {
// In the LTR context, the first run is the most left run.
localRunFlag &= ~Paint.TEXT_RUN_FLAG_LEFT_EDGE;
}
}
}
if ((runFlag & Paint.TEXT_RUN_FLAG_RIGHT_EDGE) != 0) {
if (isRtlRun) {
if (spanStart != runStart) {
// In the RTL context, the start of the run is the most right run.
localRunFlag &= ~Paint.TEXT_RUN_FLAG_RIGHT_EDGE;
}
} else { // LTR
if (spanEnd != runEnd) {
// In the LTR context, the last run is the most right position.
localRunFlag &= ~Paint.TEXT_RUN_FLAG_RIGHT_EDGE;
}
}
}
return localRunFlag;
}
/**
* Renders the TextLine.
*
* @param c the canvas to render on
* @param x the leading margin position
* @param top the top of the line
* @param y the baseline
* @param bottom the bottom of the line
*/
void draw(Canvas c, float x, int top, int y, int bottom) {
float h = 0;
final int runCount = mDirections.getRunCount();
for (int runIndex = 0; runIndex < runCount; runIndex++) {
final int runStart = mDirections.getRunStart(runIndex);
if (runStart > mLen) break;
final int runLimit = Math.min(runStart + mDirections.getRunLength(runIndex), mLen);
final boolean runIsRtl = mDirections.isRunRtl(runIndex);
final int runFlag = calculateRunFlag(runIndex, runCount, mDir);
int segStart = runStart;
for (int j = mHasTabs ? runStart : runLimit; j <= runLimit; j++) {
if (j == runLimit || charAt(j) == TAB_CHAR) {
h += drawRun(c, segStart, j, runIsRtl, x + h, top, y, bottom,
runIndex != (runCount - 1) || j != mLen, runFlag);
if (j != runLimit) { // charAt(j) == TAB_CHAR
h = mDir * nextTab(h * mDir);
}
segStart = j + 1;
}
}
}
}
/**
* Returns metrics information for the entire line.
*
* @param fmi receives font metrics information, can be null
* @param drawBounds output parameter for drawing bounding box. optional.
* @param returnDrawWidth true for returning width of the bounding box, false for returning
* total advances.
* @param lineInfo an optional output parameter for filling line information.
* @return the signed width of the line
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public float metrics(FontMetricsInt fmi, @Nullable RectF drawBounds, boolean returnDrawWidth,
@Nullable LineInfo lineInfo) {
if (returnDrawWidth) {
if (drawBounds == null) {
if (mTmpRectForMeasure == null) {
mTmpRectForMeasure = new RectF();
}
drawBounds = mTmpRectForMeasure;
}
drawBounds.setEmpty();
float w = measure(mLen, false, fmi, drawBounds, lineInfo);
float boundsWidth;
if (w >= 0) {
boundsWidth = Math.max(drawBounds.right, w) - Math.min(0, drawBounds.left);
} else {
boundsWidth = Math.max(drawBounds.right, 0) - Math.min(w, drawBounds.left);
}
if (Math.abs(w) > boundsWidth) {
return w;
} else {
// bounds width is always positive but output of measure is signed width.
// To be able to use bounds width as signed width, use the sign of the width.
return Math.signum(w) * boundsWidth;
}
} else {
return measure(mLen, false, fmi, drawBounds, lineInfo);
}
}
/**
* Shape the TextLine.
*/
void shape(TextShaper.GlyphsConsumer consumer) {
float horizontal = 0;
float x = 0;
final int runCount = mDirections.getRunCount();
for (int runIndex = 0; runIndex < runCount; runIndex++) {
final int runStart = mDirections.getRunStart(runIndex);
if (runStart > mLen) break;
final int runLimit = Math.min(runStart + mDirections.getRunLength(runIndex), mLen);
final boolean runIsRtl = mDirections.isRunRtl(runIndex);
final int runFlag = calculateRunFlag(runIndex, runCount, mDir);
int segStart = runStart;
for (int j = mHasTabs ? runStart : runLimit; j <= runLimit; j++) {
if (j == runLimit || charAt(j) == TAB_CHAR) {
horizontal += shapeRun(consumer, segStart, j, runIsRtl, x + horizontal,
runIndex != (runCount - 1) || j != mLen, runFlag);
if (j != runLimit) { // charAt(j) == TAB_CHAR
horizontal = mDir * nextTab(horizontal * mDir);
}
segStart = j + 1;
}
}
}
}
/**
* Returns the signed graphical offset from the leading margin.
*
* Following examples are all for measuring offset=3. LX(e.g. L0, L1, ...) denotes a
* character which has LTR BiDi property. On the other hand, RX(e.g. R0, R1, ...) denotes a
* character which has RTL BiDi property. Assuming all character has 1em width.
*
* Example 1: All LTR chars within LTR context
* Input Text (logical) : L0 L1 L2 L3 L4 L5 L6 L7 L8
* Input Text (visual) : L0 L1 L2 L3 L4 L5 L6 L7 L8
* Output(trailing=true) : |--------| (Returns 3em)
* Output(trailing=false): |--------| (Returns 3em)
*
* Example 2: All RTL chars within RTL context.
* Input Text (logical) : R0 R1 R2 R3 R4 R5 R6 R7 R8
* Input Text (visual) : R8 R7 R6 R5 R4 R3 R2 R1 R0
* Output(trailing=true) : |--------| (Returns -3em)
* Output(trailing=false): |--------| (Returns -3em)
*
* Example 3: BiDi chars within LTR context.
* Input Text (logical) : L0 L1 L2 R3 R4 R5 L6 L7 L8
* Input Text (visual) : L0 L1 L2 R5 R4 R3 L6 L7 L8
* Output(trailing=true) : |-----------------| (Returns 6em)
* Output(trailing=false): |--------| (Returns 3em)
*
* Example 4: BiDi chars within RTL context.
* Input Text (logical) : L0 L1 L2 R3 R4 R5 L6 L7 L8
* Input Text (visual) : L6 L7 L8 R5 R4 R3 L0 L1 L2
* Output(trailing=true) : |-----------------| (Returns -6em)
* Output(trailing=false): |--------| (Returns -3em)
*
* @param offset the line-relative character offset, between 0 and the line length, inclusive
* @param trailing no effect if the offset is not on the BiDi transition offset. If the offset
* is on the BiDi transition offset and true is passed, the offset is regarded
* as the edge of the trailing run's edge. If false, the offset is regarded as
* the edge of the preceding run's edge. See example above.
* @param fmi receives metrics information about the requested character, can be null
* @param drawBounds output parameter for drawing bounding box. optional.
* @param lineInfo an optional output parameter for filling line information.
* @return the signed graphical offset from the leading margin to the requested character edge.
* The positive value means the offset is right from the leading edge. The negative
* value means the offset is left from the leading edge.
*/
public float measure(@IntRange(from = 0) int offset, boolean trailing,
@NonNull FontMetricsInt fmi, @Nullable RectF drawBounds, @Nullable LineInfo lineInfo) {
if (offset > mLen) {
throw new IndexOutOfBoundsException(
"offset(" + offset + ") should be less than line limit(" + mLen + ")");
}
if (lineInfo != null) {
lineInfo.setClusterCount(0);
}
final int target = trailing ? offset - 1 : offset;
if (target < 0) {
return 0;
}
float h = 0;
final int runCount = mDirections.getRunCount();
for (int runIndex = 0; runIndex < runCount; runIndex++) {
final int runStart = mDirections.getRunStart(runIndex);
if (runStart > mLen) break;
final int runLimit = Math.min(runStart + mDirections.getRunLength(runIndex), mLen);
final boolean runIsRtl = mDirections.isRunRtl(runIndex);
final int runFlag = calculateRunFlag(runIndex, runCount, mDir);
int segStart = runStart;
for (int j = mHasTabs ? runStart : runLimit; j <= runLimit; j++) {
if (j == runLimit || charAt(j) == TAB_CHAR) {
final boolean targetIsInThisSegment = target >= segStart && target < j;
final boolean sameDirection = (mDir == Layout.DIR_RIGHT_TO_LEFT) == runIsRtl;
if (targetIsInThisSegment && sameDirection) {
return h + measureRun(segStart, offset, j, runIsRtl, fmi, drawBounds, null,
0, h, lineInfo, runFlag);
}
final float segmentWidth = measureRun(segStart, j, j, runIsRtl, fmi, drawBounds,
null, 0, h, lineInfo, runFlag);
h += sameDirection ? segmentWidth : -segmentWidth;
if (targetIsInThisSegment) {
return h + measureRun(segStart, offset, j, runIsRtl, null, null, null, 0,
h, lineInfo, runFlag);
}
if (j != runLimit) { // charAt(j) == TAB_CHAR
if (offset == j) {
return h;
}
h = mDir * nextTab(h * mDir);
if (target == j) {
return h;
}
}
segStart = j + 1;
}
}
}
return h;
}
/**
* Return the signed horizontal bounds of the characters in the line.
*
* The length of the returned array equals to 2 * mLen. The left bound of the i th character
* is stored at index 2 * i. And the right bound of the i th character is stored at index
* (2 * i + 1).
*
* Check the following examples. LX(e.g. L0, L1, ...) denotes a character which has LTR BiDi
* property. On the other hand, RX(e.g. R0, R1, ...) denotes a character which has RTL BiDi
* property. Assuming all character has 1em width.
*
* Example 1: All LTR chars within LTR context
* Input Text (logical) : L0 L1 L2 L3
* Input Text (visual) : L0 L1 L2 L3
* Output : [0em, 1em, 1em, 2em, 2em, 3em, 3em, 4em]
*
* Example 2: All RTL chars within RTL context.
* Input Text (logical) : R0 R1 R2 R3
* Input Text (visual) : R3 R2 R1 R0
* Output : [-1em, 0em, -2em, -1em, -3em, -2em, -4em, -3em]
*
* Example 3: BiDi chars within LTR context.
* Input Text (logical) : L0 L1 R2 R3 L4 L5
* Input Text (visual) : L0 L1 R3 R2 L4 L5
* Output : [0em, 1em, 1em, 2em, 3em, 4em, 2em, 3em, 4em, 5em, 5em, 6em]
*
* Example 4: BiDi chars within RTL context.
* Input Text (logical) : L0 L1 R2 R3 L4 L5
* Input Text (visual) : L4 L5 R3 R2 L0 L1
* Output : [-2em, -1em, -1em, 0em, -3em, -2em, -4em, -3em, -6em, -5em, -5em, -4em]
*
* @param bounds the array to receive the character bounds data. Its length should be at least
* 2 times of the line length.
* @param advances the array to receive the character advance data, nullable. If provided, its
* length should be equal or larger than the line length.
*
* @throws IllegalArgumentException if the given {@code bounds} is null.
* @throws IndexOutOfBoundsException if the given {@code bounds} or {@code advances} doesn't
* have enough space to hold the result.
*/
public void measureAllBounds(@NonNull float[] bounds, @Nullable float[] advances) {
if (bounds == null) {
throw new IllegalArgumentException("bounds can't be null");
}
if (bounds.length < 2 * mLen) {
throw new IndexOutOfBoundsException("bounds doesn't have enough space to receive the "
+ "result, needed: " + (2 * mLen) + " had: " + bounds.length);
}
if (advances == null) {
advances = new float[mLen];
}
if (advances.length < mLen) {
throw new IndexOutOfBoundsException("advance doesn't have enough space to receive the "
+ "result, needed: " + mLen + " had: " + advances.length);
}
float h = 0;
final int runCount = mDirections.getRunCount();
for (int runIndex = 0; runIndex < runCount; runIndex++) {
final int runStart = mDirections.getRunStart(runIndex);
if (runStart > mLen) break;
final int runLimit = Math.min(runStart + mDirections.getRunLength(runIndex), mLen);
final boolean runIsRtl = mDirections.isRunRtl(runIndex);
final int runFlag = calculateRunFlag(runIndex, runCount, mDir);
int segStart = runStart;
for (int j = mHasTabs ? runStart : runLimit; j <= runLimit; j++) {
if (j == runLimit || charAt(j) == TAB_CHAR) {
final boolean sameDirection = (mDir == Layout.DIR_RIGHT_TO_LEFT) == runIsRtl;
final float segmentWidth =
measureRun(segStart, j, j, runIsRtl, null, null, advances, segStart, 0,
null, runFlag);
final float oldh = h;
h += sameDirection ? segmentWidth : -segmentWidth;
float currh = sameDirection ? oldh : h;
for (int offset = segStart; offset < j && offset < mLen; ++offset) {
if (runIsRtl) {
bounds[2 * offset + 1] = currh;
currh -= advances[offset];
bounds[2 * offset] = currh;
} else {
bounds[2 * offset] = currh;
currh += advances[offset];
bounds[2 * offset + 1] = currh;
}
}
if (j != runLimit) { // charAt(j) == TAB_CHAR
final float leftX;
final float rightX;
if (runIsRtl) {
rightX = h;
h = mDir * nextTab(h * mDir);
leftX = h;
} else {
leftX = h;
h = mDir * nextTab(h * mDir);
rightX = h;
}
bounds[2 * j] = leftX;
bounds[2 * j + 1] = rightX;
advances[j] = rightX - leftX;
}
segStart = j + 1;
}
}
}
}
/**
* @see #measure(int, boolean, FontMetricsInt, RectF, LineInfo)
* @return The measure results for all possible offsets
*/
@VisibleForTesting
public float[] measureAllOffsets(boolean[] trailing, FontMetricsInt fmi) {
float[] measurement = new float[mLen + 1];
if (trailing[0]) {
measurement[0] = 0;
}
float horizontal = 0;
final int runCount = mDirections.getRunCount();
for (int runIndex = 0; runIndex < runCount; runIndex++) {
final int runStart = mDirections.getRunStart(runIndex);
if (runStart > mLen) break;
final int runLimit = Math.min(runStart + mDirections.getRunLength(runIndex), mLen);
final boolean runIsRtl = mDirections.isRunRtl(runIndex);
final int runFlag = calculateRunFlag(runIndex, runCount, mDir);
int segStart = runStart;
for (int j = mHasTabs ? runStart : runLimit; j <= runLimit; ++j) {
if (j == runLimit || charAt(j) == TAB_CHAR) {
final float oldHorizontal = horizontal;
final boolean sameDirection =
(mDir == Layout.DIR_RIGHT_TO_LEFT) == runIsRtl;
// We are using measurement to receive character advance here. So that it
// doesn't need to allocate a new array.
// But be aware that when trailing[segStart] is true, measurement[segStart]
// will be computed in the previous run. And we need to store it first in case
// measureRun overwrites the result.
final float previousSegEndHorizontal = measurement[segStart];
final float width =
measureRun(segStart, j, j, runIsRtl, fmi, null, measurement, segStart,
0, null, runFlag);
horizontal += sameDirection ? width : -width;
float currHorizontal = sameDirection ? oldHorizontal : horizontal;
final int segLimit = Math.min(j, mLen);
for (int offset = segStart; offset <= segLimit; ++offset) {
float advance = 0f;
// When offset == segLimit, advance is meaningless.
if (offset < segLimit) {
advance = runIsRtl ? -measurement[offset] : measurement[offset];
}
if (offset == segStart && trailing[offset]) {
// If offset == segStart and trailing[segStart] is true, restore the
// value of measurement[segStart] from the previous run.
measurement[offset] = previousSegEndHorizontal;
} else if (offset != segLimit || trailing[offset]) {
measurement[offset] = currHorizontal;
}
currHorizontal += advance;
}
if (j != runLimit) { // charAt(j) == TAB_CHAR
if (!trailing[j]) {
measurement[j] = horizontal;
}
horizontal = mDir * nextTab(horizontal * mDir);
if (trailing[j + 1]) {
measurement[j + 1] = horizontal;
}
}
segStart = j + 1;
}
}
}
if (!trailing[mLen]) {
measurement[mLen] = horizontal;
}
return measurement;
}
/**
* Draws a unidirectional (but possibly multi-styled) run of text.
*
*
* @param c the canvas to draw on
* @param start the line-relative start
* @param limit the line-relative limit
* @param runIsRtl true if the run is right-to-left
* @param x the position of the run that is closest to the leading margin
* @param top the top of the line
* @param y the baseline
* @param bottom the bottom of the line
* @param needWidth true if the width value is required.
* @param runFlag the run flag to be applied for this run.
* @return the signed width of the run, based on the paragraph direction.
* Only valid if needWidth is true.
*/
private float drawRun(Canvas c, int start,
int limit, boolean runIsRtl, float x, int top, int y, int bottom,
boolean needWidth, int runFlag) {
if ((mDir == Layout.DIR_LEFT_TO_RIGHT) == runIsRtl) {
float w = -measureRun(start, limit, limit, runIsRtl, null, null, null, 0, 0, null,
runFlag);
handleRun(start, limit, limit, runIsRtl, c, null, x + w, top,
y, bottom, null, null, false, null, 0, null, runFlag);
return w;
}
return handleRun(start, limit, limit, runIsRtl, c, null, x, top,
y, bottom, null, null, needWidth, null, 0, null, runFlag);
}
/**
* Measures a unidirectional (but possibly multi-styled) run of text.
*
*
* @param start the line-relative start of the run
* @param offset the offset to measure to, between start and limit inclusive
* @param limit the line-relative limit of the run
* @param runIsRtl true if the run is right-to-left
* @param fmi receives metrics information about the requested
* run, can be null.
* @param advances receives the advance information about the requested run, can be null.
* @param advancesIndex the start index to fill in the advance information.
* @param x horizontal offset of the run.
* @param lineInfo an optional output parameter for filling line information.
* @param runFlag the run flag to be applied for this run.
* @return the signed width from the start of the run to the leading edge
* of the character at offset, based on the run (not paragraph) direction
*/
private float measureRun(int start, int offset, int limit, boolean runIsRtl,
@Nullable FontMetricsInt fmi, @Nullable RectF drawBounds, @Nullable float[] advances,
int advancesIndex, float x, @Nullable LineInfo lineInfo, int runFlag) {
if (drawBounds != null && (mDir == Layout.DIR_LEFT_TO_RIGHT) == runIsRtl) {
float w = -measureRun(start, offset, limit, runIsRtl, null, null, null, 0, 0, null,
runFlag);
return handleRun(start, offset, limit, runIsRtl, null, null, x + w, 0, 0, 0, fmi,
drawBounds, true, advances, advancesIndex, lineInfo, runFlag);
}
return handleRun(start, offset, limit, runIsRtl, null, null, x, 0, 0, 0, fmi, drawBounds,
true, advances, advancesIndex, lineInfo, runFlag);
}
/**
* Shape a unidirectional (but possibly multi-styled) run of text.
*
* @param consumer the consumer of the shape result
* @param start the line-relative start
* @param limit the line-relative limit
* @param runIsRtl true if the run is right-to-left
* @param x the position of the run that is closest to the leading margin
* @param needWidth true if the width value is required.
* @param runFlag the run flag to be applied for this run.
* @return the signed width of the run, based on the paragraph direction.
* Only valid if needWidth is true.
*/
private float shapeRun(TextShaper.GlyphsConsumer consumer, int start,
int limit, boolean runIsRtl, float x, boolean needWidth, int runFlag) {
if ((mDir == Layout.DIR_LEFT_TO_RIGHT) == runIsRtl) {
float w = -measureRun(start, limit, limit, runIsRtl, null, null, null, 0, 0, null,
runFlag);
handleRun(start, limit, limit, runIsRtl, null, consumer, x + w, 0, 0, 0, null, null,
false, null, 0, null, runFlag);
return w;
}
return handleRun(start, limit, limit, runIsRtl, null, consumer, x, 0, 0, 0, null, null,
needWidth, null, 0, null, runFlag);
}
/**
* Walk the cursor through this line, skipping conjuncts and
* zero-width characters.
*
* <p>This function cannot properly walk the cursor off the ends of the line
* since it does not know about any shaping on the previous/following line
* that might affect the cursor position. Callers must either avoid these
* situations or handle the result specially.
*
* @param cursor the starting position of the cursor, between 0 and the
* length of the line, inclusive
* @param toLeft true if the caret is moving to the left.
* @return the new offset. If it is less than 0 or greater than the length
* of the line, the previous/following line should be examined to get the
* actual offset.
*/
int getOffsetToLeftRightOf(int cursor, boolean toLeft) {
// 1) The caret marks the leading edge of a character. The character
// logically before it might be on a different level, and the active caret
// position is on the character at the lower level. If that character
// was the previous character, the caret is on its trailing edge.
// 2) Take this character/edge and move it in the indicated direction.
// This gives you a new character and a new edge.
// 3) This position is between two visually adjacent characters. One of
// these might be at a lower level. The active position is on the
// character at the lower level.
// 4) If the active position is on the trailing edge of the character,
// the new caret position is the following logical character, else it
// is the character.
int lineStart = 0;
int lineEnd = mLen;
boolean paraIsRtl = mDir == -1;
int[] runs = mDirections.mDirections;
int runIndex, runLevel = 0, runStart = lineStart, runLimit = lineEnd, newCaret = -1;
boolean trailing = false;
if (cursor == lineStart) {
runIndex = -2;
} else if (cursor == lineEnd) {
runIndex = runs.length;
} else {
// First, get information about the run containing the character with
// the active caret.
for (runIndex = 0; runIndex < runs.length; runIndex += 2) {
runStart = lineStart + runs[runIndex];
if (cursor >= runStart) {
runLimit = runStart + (runs[runIndex+1] & Layout.RUN_LENGTH_MASK);
if (runLimit > lineEnd) {
runLimit = lineEnd;
}
if (cursor < runLimit) {
runLevel = (runs[runIndex+1] >>> Layout.RUN_LEVEL_SHIFT) &
Layout.RUN_LEVEL_MASK;
if (cursor == runStart) {
// The caret is on a run boundary, see if we should
// use the position on the trailing edge of the previous
// logical character instead.
int prevRunIndex, prevRunLevel, prevRunStart, prevRunLimit;
int pos = cursor - 1;
for (prevRunIndex = 0; prevRunIndex < runs.length; prevRunIndex += 2) {
prevRunStart = lineStart + runs[prevRunIndex];
if (pos >= prevRunStart) {
prevRunLimit = prevRunStart +
(runs[prevRunIndex+1] & Layout.RUN_LENGTH_MASK);
if (prevRunLimit > lineEnd) {
prevRunLimit = lineEnd;
}
if (pos < prevRunLimit) {
prevRunLevel = (runs[prevRunIndex+1] >>> Layout.RUN_LEVEL_SHIFT)
& Layout.RUN_LEVEL_MASK;
if (prevRunLevel < runLevel) {
// Start from logically previous character.
runIndex = prevRunIndex;
runLevel = prevRunLevel;
runStart = prevRunStart;
runLimit = prevRunLimit;
trailing = true;
break;
}
}
}
}
}
break;