mirrored from https://skia.googlesource.com/skia
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
TextLine.cpp
1540 lines (1386 loc) · 63.4 KB
/
TextLine.cpp
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 2019 Google LLC.
#include "modules/skparagraph/src/TextLine.h"
#include "include/core/SkBlurTypes.h"
#include "include/core/SkFont.h"
#include "include/core/SkFontMetrics.h"
#include "include/core/SkMaskFilter.h"
#include "include/core/SkPaint.h"
#include "include/core/SkSpan.h"
#include "include/core/SkString.h"
#include "include/core/SkTextBlob.h"
#include "include/core/SkTypes.h"
#include "include/private/base/SkTemplates.h"
#include "include/private/base/SkTo.h"
#include "modules/skparagraph/include/DartTypes.h"
#include "modules/skparagraph/include/Metrics.h"
#include "modules/skparagraph/include/ParagraphPainter.h"
#include "modules/skparagraph/include/ParagraphStyle.h"
#include "modules/skparagraph/include/TextShadow.h"
#include "modules/skparagraph/include/TextStyle.h"
#include "modules/skparagraph/src/Decorations.h"
#include "modules/skparagraph/src/ParagraphImpl.h"
#include "modules/skparagraph/src/ParagraphPainterImpl.h"
#include "modules/skshaper/include/SkShaper.h"
#include "modules/skshaper/include/SkShaper_harfbuzz.h"
#include "modules/skshaper/include/SkShaper_skunicode.h"
#include <algorithm>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <tuple>
#include <type_traits>
#include <utility>
using namespace skia_private;
namespace skia {
namespace textlayout {
namespace {
// TODO: deal with all the intersection functionality
TextRange intersected(const TextRange& a, const TextRange& b) {
if (a.start == b.start && a.end == b.end) return a;
auto begin = std::max(a.start, b.start);
auto end = std::min(a.end, b.end);
return end >= begin ? TextRange(begin, end) : EMPTY_TEXT;
}
SkScalar littleRound(SkScalar a) {
// This rounding is done to match Flutter tests. Must be removed..
return SkScalarRoundToScalar(a * 100.0)/100.0;
}
TextRange operator*(const TextRange& a, const TextRange& b) {
if (a.start == b.start && a.end == b.end) return a;
auto begin = std::max(a.start, b.start);
auto end = std::min(a.end, b.end);
return end > begin ? TextRange(begin, end) : EMPTY_TEXT;
}
int compareRound(SkScalar a, SkScalar b, bool applyRoundingHack) {
// There is a rounding error that gets bigger when maxWidth gets bigger
// VERY long zalgo text (> 100000) on a VERY long line (> 10000)
// Canvas scaling affects it
// Letter spacing affects it
// It has to be relative to be useful
auto base = std::max(SkScalarAbs(a), SkScalarAbs(b));
auto diff = SkScalarAbs(a - b);
if (nearlyZero(base) || diff / base < 0.001f) {
return 0;
}
auto ra = a;
auto rb = b;
if (applyRoundingHack) {
ra = littleRound(a);
rb = littleRound(b);
}
if (ra < rb) {
return -1;
} else {
return 1;
}
}
} // namespace
TextLine::TextLine(ParagraphImpl* owner,
SkVector offset,
SkVector advance,
BlockRange blocks,
TextRange textExcludingSpaces,
TextRange text,
TextRange textIncludingNewlines,
ClusterRange clusters,
ClusterRange clustersWithGhosts,
SkScalar widthWithSpaces,
InternalLineMetrics sizes)
: fOwner(owner)
, fBlockRange(blocks)
, fTextExcludingSpaces(textExcludingSpaces)
, fText(text)
, fTextIncludingNewlines(textIncludingNewlines)
, fClusterRange(clusters)
, fGhostClusterRange(clustersWithGhosts)
, fRunsInVisualOrder()
, fAdvance(advance)
, fOffset(offset)
, fShift(0.0)
, fWidthWithSpaces(widthWithSpaces)
, fEllipsis(nullptr)
, fSizes(sizes)
, fHasBackground(false)
, fHasShadows(false)
, fHasDecorations(false)
, fAscentStyle(LineMetricStyle::CSS)
, fDescentStyle(LineMetricStyle::CSS)
, fTextBlobCachePopulated(false) {
// Reorder visual runs
auto& start = owner->cluster(fGhostClusterRange.start);
auto& end = owner->cluster(fGhostClusterRange.end - 1);
size_t numRuns = end.runIndex() - start.runIndex() + 1;
for (BlockIndex index = fBlockRange.start; index < fBlockRange.end; ++index) {
auto b = fOwner->styles().begin() + index;
if (b->fStyle.hasBackground()) {
fHasBackground = true;
}
if (b->fStyle.getDecorationType() != TextDecoration::kNoDecoration) {
fHasDecorations = true;
}
if (b->fStyle.getShadowNumber() > 0) {
fHasShadows = true;
}
}
// Get the logical order
// This is just chosen to catch the common/fast cases. Feel free to tweak.
constexpr int kPreallocCount = 4;
AutoSTArray<kPreallocCount, SkUnicode::BidiLevel> runLevels(numRuns);
std::vector<RunIndex> placeholdersInOriginalOrder;
size_t runLevelsIndex = 0;
// Placeholders must be laid out using the original order in which they were added
// in the input. The API does not provide a way to indicate that a placeholder
// position was moved due to bidi reordering.
for (auto runIndex = start.runIndex(); runIndex <= end.runIndex(); ++runIndex) {
auto& run = fOwner->run(runIndex);
runLevels[runLevelsIndex++] = run.fBidiLevel;
fMaxRunMetrics.add(
InternalLineMetrics(run.correctAscent(), run.correctDescent(), run.fFontMetrics.fLeading));
if (run.isPlaceholder()) {
placeholdersInOriginalOrder.push_back(runIndex);
}
}
SkASSERT(runLevelsIndex == numRuns);
AutoSTArray<kPreallocCount, int32_t> logicalOrder(numRuns);
// TODO: hide all these logic in SkUnicode?
fOwner->getUnicode()->reorderVisual(runLevels.data(), numRuns, logicalOrder.data());
auto firstRunIndex = start.runIndex();
auto placeholderIter = placeholdersInOriginalOrder.begin();
for (auto index : logicalOrder) {
auto runIndex = firstRunIndex + index;
if (fOwner->run(runIndex).isPlaceholder()) {
fRunsInVisualOrder.push_back(*placeholderIter++);
} else {
fRunsInVisualOrder.push_back(runIndex);
}
}
// TODO: This is the fix for flutter. Must be removed...
for (auto cluster = &start; cluster <= &end; ++cluster) {
if (!cluster->run().isPlaceholder()) {
fShift += cluster->getHalfLetterSpacing();
break;
}
}
}
void TextLine::paint(ParagraphPainter* painter, SkScalar x, SkScalar y) {
if (fHasBackground) {
this->iterateThroughVisualRuns(false,
[painter, x, y, this]
(const Run* run, SkScalar runOffsetInLine, TextRange textRange, SkScalar* runWidthInLine) {
*runWidthInLine = this->iterateThroughSingleRunByStyles(
TextAdjustment::GlyphCluster, run, runOffsetInLine, textRange, StyleType::kBackground,
[painter, x, y, this](TextRange textRange, const TextStyle& style, const ClipContext& context) {
this->paintBackground(painter, x, y, textRange, style, context);
});
return true;
});
}
if (fHasShadows) {
this->iterateThroughVisualRuns(false,
[painter, x, y, this]
(const Run* run, SkScalar runOffsetInLine, TextRange textRange, SkScalar* runWidthInLine) {
*runWidthInLine = this->iterateThroughSingleRunByStyles(
TextAdjustment::GlyphCluster, run, runOffsetInLine, textRange, StyleType::kShadow,
[painter, x, y, this]
(TextRange textRange, const TextStyle& style, const ClipContext& context) {
this->paintShadow(painter, x, y, textRange, style, context);
});
return true;
});
}
this->ensureTextBlobCachePopulated();
for (auto& record : fTextBlobCache) {
record.paint(painter, x, y);
}
if (fHasDecorations) {
this->iterateThroughVisualRuns(false,
[painter, x, y, this]
(const Run* run, SkScalar runOffsetInLine, TextRange textRange, SkScalar* runWidthInLine) {
*runWidthInLine = this->iterateThroughSingleRunByStyles(
TextAdjustment::GlyphCluster, run, runOffsetInLine, textRange, StyleType::kDecorations,
[painter, x, y, this]
(TextRange textRange, const TextStyle& style, const ClipContext& context) {
this->paintDecorations(painter, x, y, textRange, style, context);
});
return true;
});
}
}
void TextLine::ensureTextBlobCachePopulated() {
if (fTextBlobCachePopulated) {
return;
}
if (fBlockRange.width() == 1 &&
fRunsInVisualOrder.size() == 1 &&
fEllipsis == nullptr &&
fOwner->run(fRunsInVisualOrder[0]).placeholderStyle() == nullptr) {
if (fClusterRange.width() == 0) {
return;
}
// Most common and most simple case
const auto& style = fOwner->block(fBlockRange.start).fStyle;
const auto& run = fOwner->run(fRunsInVisualOrder[0]);
auto clip = SkRect::MakeXYWH(0.0f, this->sizes().runTop(&run, this->fAscentStyle),
fAdvance.fX,
run.calculateHeight(this->fAscentStyle, this->fDescentStyle));
auto& start = fOwner->cluster(fClusterRange.start);
auto& end = fOwner->cluster(fClusterRange.end - 1);
SkASSERT(start.runIndex() == end.runIndex());
GlyphRange glyphs;
if (run.leftToRight()) {
glyphs = GlyphRange(start.startPos(),
end.isHardBreak() ? end.startPos() : end.endPos());
} else {
glyphs = GlyphRange(end.startPos(),
start.isHardBreak() ? start.startPos() : start.endPos());
}
ClipContext context = {/*run=*/&run,
/*pos=*/glyphs.start,
/*size=*/glyphs.width(),
/*fTextShift=*/-run.positionX(glyphs.start), // starting position
/*clip=*/clip, // entire line
/*fExcludedTrailingSpaces=*/0.0f, // no need for that
/*clippingNeeded=*/false}; // no need for that
this->buildTextBlob(fTextExcludingSpaces, style, context);
} else {
this->iterateThroughVisualRuns(false,
[this](const Run* run,
SkScalar runOffsetInLine,
TextRange textRange,
SkScalar* runWidthInLine) {
if (run->placeholderStyle() != nullptr) {
*runWidthInLine = run->advance().fX;
return true;
}
*runWidthInLine = this->iterateThroughSingleRunByStyles(
TextAdjustment::GlyphCluster,
run,
runOffsetInLine,
textRange,
StyleType::kForeground,
[this](TextRange textRange, const TextStyle& style, const ClipContext& context) {
this->buildTextBlob(textRange, style, context);
});
return true;
});
}
fTextBlobCachePopulated = true;
}
void TextLine::format(TextAlign align, SkScalar maxWidth) {
SkScalar delta = maxWidth - this->width();
if (delta <= 0) {
return;
}
// We do nothing for left align
if (align == TextAlign::kJustify) {
if (!this->endsWithHardLineBreak()) {
this->justify(maxWidth);
} else if (fOwner->paragraphStyle().getTextDirection() == TextDirection::kRtl) {
// Justify -> Right align
fShift = delta;
}
} else if (align == TextAlign::kRight) {
fShift = delta;
} else if (align == TextAlign::kCenter) {
fShift = delta / 2;
}
}
void TextLine::scanStyles(StyleType styleType, const RunStyleVisitor& visitor) {
if (this->empty()) {
return;
}
this->iterateThroughVisualRuns(
false,
[this, visitor, styleType](
const Run* run, SkScalar runOffset, TextRange textRange, SkScalar* width) {
*width = this->iterateThroughSingleRunByStyles(
TextAdjustment::GlyphCluster,
run,
runOffset,
textRange,
styleType,
[visitor](TextRange textRange,
const TextStyle& style,
const ClipContext& context) {
visitor(textRange, style, context);
});
return true;
});
}
SkRect TextLine::extendHeight(const ClipContext& context) const {
SkRect result = context.clip;
result.fBottom += std::max(this->fMaxRunMetrics.height() - this->height(), 0.0f);
return result;
}
void TextLine::buildTextBlob(TextRange textRange, const TextStyle& style, const ClipContext& context) {
if (context.run->placeholderStyle() != nullptr) {
return;
}
fTextBlobCache.emplace_back();
TextBlobRecord& record = fTextBlobCache.back();
if (style.hasForeground()) {
record.fPaint = style.getForegroundPaintOrID();
} else {
std::get<SkPaint>(record.fPaint).setColor(style.getColor());
}
record.fVisitor_Run = context.run;
record.fVisitor_Pos = context.pos;
// TODO: This is the change for flutter, must be removed later
SkTextBlobBuilder builder;
context.run->copyTo(builder, SkToU32(context.pos), context.size);
record.fClippingNeeded = context.clippingNeeded;
if (context.clippingNeeded) {
record.fClipRect = extendHeight(context).makeOffset(this->offset());
} else {
record.fClipRect = context.clip.makeOffset(this->offset());
}
SkASSERT(nearlyEqual(context.run->baselineShift(), style.getBaselineShift()));
SkScalar correctedBaseline = SkScalarFloorToScalar(this->baseline() + style.getBaselineShift() + 0.5);
record.fBlob = builder.make();
if (record.fBlob != nullptr) {
record.fBounds.joinPossiblyEmptyRect(record.fBlob->bounds());
}
record.fOffset = SkPoint::Make(this->offset().fX + context.fTextShift,
this->offset().fY + correctedBaseline);
}
void TextLine::TextBlobRecord::paint(ParagraphPainter* painter, SkScalar x, SkScalar y) {
if (fClippingNeeded) {
painter->save();
painter->clipRect(fClipRect.makeOffset(x, y));
}
painter->drawTextBlob(fBlob, x + fOffset.x(), y + fOffset.y(), fPaint);
if (fClippingNeeded) {
painter->restore();
}
}
void TextLine::paintBackground(ParagraphPainter* painter,
SkScalar x,
SkScalar y,
TextRange textRange,
const TextStyle& style,
const ClipContext& context) const {
if (style.hasBackground()) {
painter->drawRect(context.clip.makeOffset(this->offset() + SkPoint::Make(x, y)),
style.getBackgroundPaintOrID());
}
}
void TextLine::paintShadow(ParagraphPainter* painter,
SkScalar x,
SkScalar y,
TextRange textRange,
const TextStyle& style,
const ClipContext& context) const {
SkScalar correctedBaseline = SkScalarFloorToScalar(this->baseline() + style.getBaselineShift() + 0.5);
for (TextShadow shadow : style.getShadows()) {
if (!shadow.hasShadow()) continue;
SkTextBlobBuilder builder;
context.run->copyTo(builder, context.pos, context.size);
if (context.clippingNeeded) {
painter->save();
SkRect clip = extendHeight(context);
clip.offset(x, y);
clip.offset(this->offset());
painter->clipRect(clip);
}
auto blob = builder.make();
painter->drawTextShadow(blob,
x + this->offset().fX + shadow.fOffset.x() + context.fTextShift,
y + this->offset().fY + shadow.fOffset.y() + correctedBaseline,
shadow.fColor,
SkDoubleToScalar(shadow.fBlurSigma));
if (context.clippingNeeded) {
painter->restore();
}
}
}
void TextLine::paintDecorations(ParagraphPainter* painter, SkScalar x, SkScalar y, TextRange textRange, const TextStyle& style, const ClipContext& context) const {
ParagraphPainterAutoRestore ppar(painter);
painter->translate(x + this->offset().fX, y + this->offset().fY + style.getBaselineShift());
Decorations decorations;
SkScalar correctedBaseline = SkScalarFloorToScalar(-this->sizes().rawAscent() + style.getBaselineShift() + 0.5);
decorations.paint(painter, style, context, correctedBaseline);
}
void TextLine::justify(SkScalar maxWidth) {
int whitespacePatches = 0;
SkScalar textLen = 0;
SkScalar whitespaceLen = 0;
bool whitespacePatch = false;
// Take leading whitespaces width but do not increment a whitespace patch number
bool leadingWhitespaces = false;
this->iterateThroughClustersInGlyphsOrder(false, false,
[&](const Cluster* cluster, ClusterIndex index, bool ghost) {
if (cluster->isWhitespaceBreak()) {
if (index == 0) {
leadingWhitespaces = true;
} else if (!whitespacePatch && !leadingWhitespaces) {
// We only count patches BETWEEN words, not before
++whitespacePatches;
}
whitespacePatch = !leadingWhitespaces;
whitespaceLen += cluster->width();
} else if (cluster->isIdeographic()) {
// Whitespace break before and after
if (!whitespacePatch && index != 0) {
// We only count patches BETWEEN words, not before
++whitespacePatches; // before
}
whitespacePatch = true;
leadingWhitespaces = false;
++whitespacePatches; // after
} else {
whitespacePatch = false;
leadingWhitespaces = false;
}
textLen += cluster->width();
return true;
});
if (whitespacePatch) {
// We only count patches BETWEEN words, not after
--whitespacePatches;
}
if (whitespacePatches == 0) {
if (fOwner->paragraphStyle().getTextDirection() == TextDirection::kRtl) {
// Justify -> Right align
fShift = maxWidth - textLen;
}
return;
}
SkScalar step = (maxWidth - textLen + whitespaceLen) / whitespacePatches;
SkScalar shift = 0.0f;
SkScalar prevShift = 0.0f;
// Deal with the ghost spaces
auto ghostShift = maxWidth - this->fAdvance.fX;
// Spread the extra whitespaces
whitespacePatch = false;
// Do not break on leading whitespaces
leadingWhitespaces = false;
this->iterateThroughClustersInGlyphsOrder(false, true, [&](const Cluster* cluster, ClusterIndex index, bool ghost) {
if (ghost) {
if (cluster->run().leftToRight()) {
this->shiftCluster(cluster, ghostShift, ghostShift);
}
return true;
}
if (cluster->isWhitespaceBreak()) {
if (index == 0) {
leadingWhitespaces = true;
} else if (!whitespacePatch && !leadingWhitespaces) {
shift += step;
whitespacePatch = true;
--whitespacePatches;
}
shift -= cluster->width();
} else if (cluster->isIdeographic()) {
if (!whitespacePatch && index != 0) {
shift += step;
--whitespacePatches;
}
whitespacePatch = false;
leadingWhitespaces = false;
} else {
whitespacePatch = false;
leadingWhitespaces = false;
}
this->shiftCluster(cluster, shift, prevShift);
prevShift = shift;
// We skip ideographic whitespaces
if (!cluster->isWhitespaceBreak() && cluster->isIdeographic()) {
shift += step;
whitespacePatch = true;
--whitespacePatches;
}
return true;
});
if (whitespacePatch && whitespacePatches < 0) {
whitespacePatches++;
shift -= step;
}
SkAssertResult(nearlyEqual(shift, maxWidth - textLen));
SkASSERT(whitespacePatches == 0);
this->fWidthWithSpaces += ghostShift;
this->fAdvance.fX = maxWidth;
}
void TextLine::shiftCluster(const Cluster* cluster, SkScalar shift, SkScalar prevShift) {
auto& run = cluster->run();
auto start = cluster->startPos();
auto end = cluster->endPos();
if (end == run.size()) {
// Set the same shift for the fake last glyph (to avoid all extra checks)
++end;
}
if (run.fJustificationShifts.empty()) {
// Do not fill this array until needed
run.fJustificationShifts.push_back_n(run.size() + 1, { 0, 0 });
}
for (size_t pos = start; pos < end; ++pos) {
run.fJustificationShifts[pos] = { shift, prevShift };
}
}
void TextLine::createEllipsis(SkScalar maxWidth, const SkString& ellipsis, bool) {
// Replace some clusters with the ellipsis
// Go through the clusters in the reverse logical order
// taking off cluster by cluster until the ellipsis fits
SkScalar width = fAdvance.fX;
RunIndex lastRun = EMPTY_RUN;
std::unique_ptr<Run> ellipsisRun;
for (auto clusterIndex = fGhostClusterRange.end; clusterIndex > fGhostClusterRange.start; --clusterIndex) {
auto& cluster = fOwner->cluster(clusterIndex - 1);
// Shape the ellipsis if the run has changed
if (lastRun != cluster.runIndex()) {
ellipsisRun = this->shapeEllipsis(ellipsis, &cluster);
if (ellipsisRun->advance().fX > maxWidth) {
// Ellipsis is bigger than the entire line; no way we can add it at all
// BUT! We can keep scanning in case the next run will give us better results
lastRun = EMPTY_RUN;
continue;
} else {
// We may need to continue
lastRun = cluster.runIndex();
}
}
// See if it fits
if (width + ellipsisRun->advance().fX > maxWidth) {
width -= cluster.width();
// Continue if the ellipsis does not fit
continue;
}
// We found enough room for the ellipsis
fAdvance.fX = width;
fEllipsis = std::move(ellipsisRun);
fEllipsis->setOwner(fOwner);
// Let's update the line
fClusterRange.end = clusterIndex;
fGhostClusterRange.end = fClusterRange.end;
fEllipsis->fClusterStart = cluster.textRange().start;
fText.end = cluster.textRange().end;
fTextIncludingNewlines.end = cluster.textRange().end;
fTextExcludingSpaces.end = cluster.textRange().end;
break;
}
if (!fEllipsis) {
// Weird situation: ellipsis does not fit; no ellipsis then
fClusterRange.end = fClusterRange.start;
fGhostClusterRange.end = fClusterRange.start;
fText.end = fText.start;
fTextIncludingNewlines.end = fTextIncludingNewlines.start;
fTextExcludingSpaces.end = fTextExcludingSpaces.start;
fAdvance.fX = 0;
}
}
std::unique_ptr<Run> TextLine::shapeEllipsis(const SkString& ellipsis, const Cluster* cluster) {
class ShapeHandler final : public SkShaper::RunHandler {
public:
ShapeHandler(SkScalar lineHeight, bool useHalfLeading, SkScalar baselineShift, const SkString& ellipsis)
: fRun(nullptr), fLineHeight(lineHeight), fUseHalfLeading(useHalfLeading), fBaselineShift(baselineShift), fEllipsis(ellipsis) {}
std::unique_ptr<Run> run() & { return std::move(fRun); }
private:
void beginLine() override {}
void runInfo(const RunInfo&) override {}
void commitRunInfo() override {}
Buffer runBuffer(const RunInfo& info) override {
SkASSERT(!fRun);
fRun = std::make_unique<Run>(nullptr, info, 0, fLineHeight, fUseHalfLeading, fBaselineShift, 0, 0);
return fRun->newRunBuffer();
}
void commitRunBuffer(const RunInfo& info) override {
fRun->fAdvance.fX = info.fAdvance.fX;
fRun->fAdvance.fY = fRun->advance().fY;
fRun->fPlaceholderIndex = std::numeric_limits<size_t>::max();
fRun->fEllipsis = true;
}
void commitLine() override {}
std::unique_ptr<Run> fRun;
SkScalar fLineHeight;
bool fUseHalfLeading;
SkScalar fBaselineShift;
SkString fEllipsis;
};
const Run& run = cluster->run();
TextStyle textStyle = fOwner->paragraphStyle().getTextStyle();
for (auto i = fBlockRange.start; i < fBlockRange.end; ++i) {
auto& block = fOwner->block(i);
if (run.leftToRight() && cluster->textRange().end <= block.fRange.end) {
textStyle = block.fStyle;
break;
} else if (!run.leftToRight() && cluster->textRange().start <= block.fRange.end) {
textStyle = block.fStyle;
break;
}
}
auto shaped = [&](sk_sp<SkTypeface> typeface, sk_sp<SkFontMgr> fallback) -> std::unique_ptr<Run> {
ShapeHandler handler(run.heightMultiplier(), run.useHalfLeading(), run.baselineShift(), ellipsis);
SkFont font(std::move(typeface), textStyle.getFontSize());
font.setEdging(SkFont::Edging::kAntiAlias);
font.setHinting(SkFontHinting::kSlight);
font.setSubpixel(true);
std::unique_ptr<SkShaper> shaper = SkShapers::HB::ShapeDontWrapOrReorder(
fOwner->getUnicode(), fallback ? fallback : SkFontMgr::RefEmpty());
const SkBidiIterator::Level defaultLevel = SkBidiIterator::kLTR;
const char* utf8 = ellipsis.c_str();
size_t utf8Bytes = ellipsis.size();
std::unique_ptr<SkShaper::BiDiRunIterator> bidi = SkShapers::unicode::BidiRunIterator(
fOwner->getUnicode(), utf8, utf8Bytes, defaultLevel);
SkASSERT(bidi);
std::unique_ptr<SkShaper::LanguageRunIterator> language =
SkShaper::MakeStdLanguageRunIterator(utf8, utf8Bytes);
SkASSERT(language);
std::unique_ptr<SkShaper::ScriptRunIterator> script =
SkShapers::HB::ScriptRunIterator(utf8, utf8Bytes);
SkASSERT(script);
std::unique_ptr<SkShaper::FontRunIterator> fontRuns = SkShaper::MakeFontMgrRunIterator(
utf8, utf8Bytes, font, fallback ? fallback : SkFontMgr::RefEmpty());
SkASSERT(fontRuns);
shaper->shape(utf8,
utf8Bytes,
*fontRuns,
*bidi,
*script,
*language,
nullptr,
0,
std::numeric_limits<SkScalar>::max(),
&handler);
auto ellipsisRun = handler.run();
ellipsisRun->fTextRange = TextRange(0, ellipsis.size());
ellipsisRun->fOwner = fOwner;
return ellipsisRun;
};
// Check the current font
auto ellipsisRun = shaped(run.fFont.refTypeface(), nullptr);
if (ellipsisRun->isResolved()) {
return ellipsisRun;
}
// Check all allowed fonts
std::vector<sk_sp<SkTypeface>> typefaces = fOwner->fontCollection()->findTypefaces(
textStyle.getFontFamilies(), textStyle.getFontStyle(), textStyle.getFontArguments());
for (const auto& typeface : typefaces) {
ellipsisRun = shaped(typeface, nullptr);
if (ellipsisRun->isResolved()) {
return ellipsisRun;
}
}
// Try the fallback
if (fOwner->fontCollection()->fontFallbackEnabled()) {
const char* ch = ellipsis.c_str();
SkUnichar unicode = SkUTF::NextUTF8WithReplacement(&ch,
ellipsis.c_str()
+ ellipsis.size());
// We do not expect emojis in ellipsis so if they appeat there
// they will not be resolved with the pretiest color emoji font
auto typeface = fOwner->fontCollection()->defaultFallback(
unicode,
textStyle.getFontStyle(),
textStyle.getLocale());
if (typeface) {
ellipsisRun = shaped(typeface, fOwner->fontCollection()->getFallbackManager());
if (ellipsisRun->isResolved()) {
return ellipsisRun;
}
}
}
return ellipsisRun;
}
TextLine::ClipContext TextLine::measureTextInsideOneRun(TextRange textRange,
const Run* run,
SkScalar runOffsetInLine,
SkScalar textOffsetInRunInLine,
bool includeGhostSpaces,
TextAdjustment textAdjustment) const {
ClipContext result = { run, 0, run->size(), 0, SkRect::MakeEmpty(), 0, false };
if (run->fEllipsis) {
// Both ellipsis and placeholders can only be measured as one glyph
result.fTextShift = runOffsetInLine;
result.clip = SkRect::MakeXYWH(runOffsetInLine,
sizes().runTop(run, this->fAscentStyle),
run->advance().fX,
run->calculateHeight(this->fAscentStyle,this->fDescentStyle));
return result;
} else if (run->isPlaceholder()) {
result.fTextShift = runOffsetInLine;
if (SkIsFinite(run->fFontMetrics.fAscent)) {
result.clip = SkRect::MakeXYWH(runOffsetInLine,
sizes().runTop(run, this->fAscentStyle),
run->advance().fX,
run->calculateHeight(this->fAscentStyle,this->fDescentStyle));
} else {
result.clip = SkRect::MakeXYWH(runOffsetInLine, run->fFontMetrics.fAscent, run->advance().fX, 0);
}
return result;
} else if (textRange.empty()) {
return result;
}
TextRange originalTextRange(textRange); // We need it for proportional measurement
// Find [start:end] clusters for the text
while (true) {
// Update textRange by cluster edges (shift start up to the edge of the cluster)
// TODO: remove this limitation?
TextRange updatedTextRange;
bool found;
std::tie(found, updatedTextRange.start, updatedTextRange.end) =
run->findLimitingGlyphClusters(textRange);
if (!found) {
return result;
}
if ((textAdjustment & TextAdjustment::Grapheme) == 0) {
textRange = updatedTextRange;
break;
}
// Update text range by grapheme edges (shift start up to the edge of the grapheme)
std::tie(found, updatedTextRange.start, updatedTextRange.end) =
run->findLimitingGraphemes(updatedTextRange);
if (updatedTextRange == textRange) {
break;
}
// Some clusters are inside graphemes and we need to adjust them
//SkDebugf("Correct range: [%d:%d) -> [%d:%d)\n", textRange.start, textRange.end, startIndex, endIndex);
textRange = updatedTextRange;
// Move the start until it's on the grapheme edge (and glypheme, too)
}
Cluster* start = &fOwner->cluster(fOwner->clusterIndex(textRange.start));
Cluster* end = &fOwner->cluster(fOwner->clusterIndex(textRange.end - (textRange.width() == 0 ? 0 : 1)));
if (!run->leftToRight()) {
std::swap(start, end);
}
result.pos = start->startPos();
result.size = (end->isHardBreak() ? end->startPos() : end->endPos()) - start->startPos();
auto textStartInRun = run->positionX(start->startPos());
auto textStartInLine = runOffsetInLine + textOffsetInRunInLine;
if (!run->leftToRight()) {
std::swap(start, end);
}
/*
if (!run->fJustificationShifts.empty()) {
SkDebugf("Justification for [%d:%d)\n", textRange.start, textRange.end);
for (auto i = result.pos; i < result.pos + result.size; ++i) {
auto j = run->fJustificationShifts[i];
SkDebugf("[%d] = %f %f\n", i, j.fX, j.fY);
}
}
*/
// Calculate the clipping rectangle for the text with cluster edges
// There are 2 cases:
// EOL (when we expect the last cluster clipped without any spaces)
// Anything else (when we want the cluster width contain all the spaces -
// coming from letter spacing or word spacing or justification)
result.clip =
SkRect::MakeXYWH(0,
sizes().runTop(run, this->fAscentStyle),
run->calculateWidth(result.pos, result.pos + result.size, false),
run->calculateHeight(this->fAscentStyle,this->fDescentStyle));
// Correct the width in case the text edges don't match clusters
// TODO: This is where we get smart about selecting a part of a cluster
// by shaping each grapheme separately and then use the result sizes
// to calculate the proportions
auto leftCorrection = start->sizeToChar(originalTextRange.start);
auto rightCorrection = end->sizeFromChar(originalTextRange.end - 1);
/*
SkDebugf("[%d: %d) => [%d: %d), @%d, %d: [%f:%f) + [%f:%f) = ", // جَآَهُ
originalTextRange.start, originalTextRange.end, textRange.start, textRange.end,
result.pos, result.size,
result.clip.fLeft, result.clip.fRight, leftCorrection, rightCorrection);
*/
result.clippingNeeded = leftCorrection != 0 || rightCorrection != 0;
if (run->leftToRight()) {
result.clip.fLeft += leftCorrection;
result.clip.fRight -= rightCorrection;
textStartInLine -= leftCorrection;
} else {
result.clip.fRight -= leftCorrection;
result.clip.fLeft += rightCorrection;
textStartInLine -= rightCorrection;
}
result.clip.offset(textStartInLine, 0);
//SkDebugf("@%f[%f:%f)\n", textStartInLine, result.clip.fLeft, result.clip.fRight);
if (compareRound(result.clip.fRight, fAdvance.fX, fOwner->getApplyRoundingHack()) > 0 && !includeGhostSpaces) {
// There are few cases when we need it.
// The most important one: we measure the text with spaces at the end (or at the beginning in RTL)
// and we should ignore these spaces
if (fOwner->paragraphStyle().getTextDirection() == TextDirection::kLtr) {
// We only use this member for LTR
result.fExcludedTrailingSpaces = std::max(result.clip.fRight - fAdvance.fX, 0.0f);
result.clippingNeeded = true;
result.clip.fRight = fAdvance.fX;
}
}
if (result.clip.width() < 0) {
// Weird situation when glyph offsets move the glyph to the left
// (happens with zalgo texts, for instance)
result.clip.fRight = result.clip.fLeft;
}
// The text must be aligned with the lineOffset
result.fTextShift = textStartInLine - textStartInRun;
return result;
}
void TextLine::iterateThroughClustersInGlyphsOrder(bool reversed,
bool includeGhosts,
const ClustersVisitor& visitor) const {
// Walk through the clusters in the logical order (or reverse)
SkSpan<const size_t> runs(fRunsInVisualOrder.data(), fRunsInVisualOrder.size());
bool ignore = false;
ClusterIndex index = 0;
directional_for_each(runs, !reversed, [&](decltype(runs[0]) r) {
if (ignore) return;
auto run = this->fOwner->run(r);
auto trimmedRange = fClusterRange.intersection(run.clusterRange());
auto trailedRange = fGhostClusterRange.intersection(run.clusterRange());
SkASSERT(trimmedRange.start == trailedRange.start);
auto trailed = fOwner->clusters(trailedRange);
auto trimmed = fOwner->clusters(trimmedRange);
directional_for_each(trailed, reversed != run.leftToRight(), [&](Cluster& cluster) {
if (ignore) return;
bool ghost = &cluster >= trimmed.end();
if (!includeGhosts && ghost) {
return;
}
if (!visitor(&cluster, index++, ghost)) {
ignore = true;
return;
}
});
});
}
SkScalar TextLine::iterateThroughSingleRunByStyles(TextAdjustment textAdjustment,
const Run* run,
SkScalar runOffset,
TextRange textRange,
StyleType styleType,
const RunStyleVisitor& visitor) const {
auto correctContext = [&](TextRange textRange, SkScalar textOffsetInRun) -> ClipContext {
auto result = this->measureTextInsideOneRun(
textRange, run, runOffset, textOffsetInRun, false, textAdjustment);
if (styleType == StyleType::kDecorations) {
// Decorations are drawn based on the real font metrics (regardless of styles and strut)
result.clip.fTop = this->sizes().runTop(run, LineMetricStyle::CSS);
result.clip.fBottom = result.clip.fTop +
run->calculateHeight(LineMetricStyle::CSS, LineMetricStyle::CSS);
}
return result;
};
if (run->fEllipsis) {
// Extra efforts to get the ellipsis text style
ClipContext clipContext = correctContext(run->textRange(), 0.0f);
TextRange testRange(run->fClusterStart, run->fClusterStart + run->textRange().width());
for (BlockIndex index = fBlockRange.start; index < fBlockRange.end; ++index) {
auto block = fOwner->styles().begin() + index;
auto intersect = intersected(block->fRange, testRange);
if (intersect.width() > 0) {
visitor(testRange, block->fStyle, clipContext);
return run->advance().fX;
}
}
SkASSERT(false);
}
if (styleType == StyleType::kNone) {
ClipContext clipContext = correctContext(textRange, 0.0f);
// The placehoder can have height=0 or (exclusively) width=0 and still be a thing
if (clipContext.clip.height() > 0.0f || clipContext.clip.width() > 0.0f) {
visitor(textRange, TextStyle(), clipContext);
return clipContext.clip.width();
} else {
return 0;
}
}
TextIndex start = EMPTY_INDEX;
size_t size = 0;
const TextStyle* prevStyle = nullptr;
SkScalar textOffsetInRun = 0;
const BlockIndex blockRangeSize = fBlockRange.end - fBlockRange.start;
for (BlockIndex index = 0; index <= blockRangeSize; ++index) {
TextRange intersect;
TextStyle* style = nullptr;
if (index < blockRangeSize) {
auto block = fOwner->styles().begin() +
(run->leftToRight() ? fBlockRange.start + index : fBlockRange.end - index - 1);