-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
shape_result.cc
2062 lines (1836 loc) · 75.2 KB
/
shape_result.cc
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) 2012 Google Inc. All rights reserved.
* Copyright (C) 2013 BlackBerry Limited. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result.h"
#include <hb.h>
#include <algorithm>
#include <limits>
#include <memory>
#include <utility>
#include "base/containers/adapters.h"
#include "base/memory/ptr_util.h"
#include "base/numerics/safe_conversions.h"
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/fonts/character_range.h"
#include "third_party/blink/renderer/platform/fonts/font.h"
#include "third_party/blink/renderer/platform/fonts/shaping/glyph_bounds_accumulator.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_inline_headers.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_spacing.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
#include "third_party/blink/renderer/platform/wtf/size_assertions.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "ui/gfx/geometry/skia_conversions.h"
namespace blink {
constexpr unsigned HarfBuzzRunGlyphData::kMaxCharacterIndex;
constexpr unsigned HarfBuzzRunGlyphData::kMaxGlyphs;
struct SameSizeAsHarfBuzzRunGlyphData {
unsigned glyph : 16;
unsigned char_index_and_bit_field : 16;
float advance;
};
ASSERT_SIZE(HarfBuzzRunGlyphData, SameSizeAsHarfBuzzRunGlyphData);
struct SameSizeAsRunInfo : public RefCounted<SameSizeAsRunInfo> {
struct GlyphDataCollection {
void* pointers[2];
unsigned integer;
} glyph_data;
void* pointer;
Vector<int> vector;
int integers[6];
};
ASSERT_SIZE(ShapeResult::RunInfo, SameSizeAsRunInfo);
struct SameSizeAsShapeResult : public RefCounted<SameSizeAsShapeResult> {
float floats[5];
Vector<int> vector;
void* pointers[2];
unsigned integers[2];
unsigned bitfields : 32;
};
ASSERT_SIZE(ShapeResult, SameSizeAsShapeResult);
unsigned ShapeResult::RunInfo::NextSafeToBreakOffset(unsigned offset) const {
DCHECK_LE(offset, num_characters_);
if (IsLtr()) {
for (const auto& glyph_data : glyph_data_) {
if (glyph_data.safe_to_break_before &&
glyph_data.character_index >= offset)
return glyph_data.character_index;
}
} else {
for (const auto& glyph_data : base::Reversed(glyph_data_)) {
if (glyph_data.safe_to_break_before &&
glyph_data.character_index >= offset)
return glyph_data.character_index;
}
}
// Next safe break is at the end of the run.
return num_characters_;
}
unsigned ShapeResult::RunInfo::PreviousSafeToBreakOffset(
unsigned offset) const {
if (offset >= num_characters_)
return num_characters_;
if (IsLtr()) {
for (const auto& glyph_data : base::Reversed(glyph_data_)) {
if (glyph_data.safe_to_break_before &&
glyph_data.character_index <= offset)
return glyph_data.character_index;
}
} else {
for (const auto& glyph_data : glyph_data_) {
if (glyph_data.safe_to_break_before &&
glyph_data.character_index <= offset)
return glyph_data.character_index;
}
}
// Next safe break is at the start of the run.
return 0;
}
float ShapeResult::RunInfo::XPositionForVisualOffset(
unsigned offset,
AdjustMidCluster adjust_mid_cluster) const {
DCHECK_LT(offset, num_characters_);
if (IsRtl())
offset = num_characters_ - offset - 1;
return XPositionForOffset(offset, adjust_mid_cluster);
}
unsigned ShapeResult::RunInfo::NumGraphemes(unsigned start,
unsigned end) const {
if (graphemes_.size() == 0 || start >= num_characters_)
return 0;
CHECK_LT(start, end);
CHECK_LE(end, num_characters_);
CHECK_EQ(num_characters_, graphemes_.size());
return graphemes_[end - 1] - graphemes_[start] + 1;
}
void ShapeResult::EnsureGraphemes(const StringView& text) const {
CHECK_EQ(NumCharacters(), text.length());
// Hit-testing, canvas, etc. may still call this function for 0-length text,
// or glyphs may be missing at all.
if (runs_.empty())
return;
bool is_computed = !runs_.front()->graphemes_.empty();
#if DCHECK_IS_ON()
for (const auto& run : runs_)
DCHECK_EQ(is_computed, !run->graphemes_.empty());
#endif
if (is_computed)
return;
unsigned result_start_index = StartIndex();
for (const scoped_refptr<RunInfo>& run : runs_) {
if (!run)
continue;
DCHECK_GE(run->start_index_, result_start_index);
GraphemesClusterList(
StringView(text, run->start_index_ - result_start_index,
run->num_characters_),
&run->graphemes_);
}
}
// XPositionForOffset returns the X position (in layout space) from the
// beginning of the run to the beginning of the cluster of glyphs for X
// character.
// For RTL, beginning means the right most side of the cluster.
// Characters may spawn multiple glyphs.
// In the case that multiple characters form a Unicode grapheme cluster, we
// distribute the width of the grapheme cluster among the number of cursor
// positions returned by cursor-based TextBreakIterator.
float ShapeResult::RunInfo::XPositionForOffset(
unsigned offset,
AdjustMidCluster adjust_mid_cluster) const {
DCHECK_LE(offset, num_characters_);
const unsigned num_glyphs = glyph_data_.size();
// In this context, a glyph sequence is a sequence of glyphs that shares the
// same character_index and therefore represent the same interval of source
// characters. glyph_sequence_start marks the character index at the beginning
// of the interval of characters for which this glyph sequence was formed as
// the result of shaping; glyph_sequence_end marks the end of the interval of
// characters for which this glyph sequence was formed. [glyph_sequence_start,
// glyph_sequence_end) is inclusive on the start for the range of characters
// of the current sequence we are visiting.
unsigned glyph_sequence_start = 0;
unsigned glyph_sequence_end = num_characters_;
// the advance of the current glyph sequence.
float glyph_sequence_advance = 0.0;
// the accumulated advance up to the current glyph sequence.
float accumulated_position = 0;
if (IsLtr()) {
for (unsigned i = 0; i < num_glyphs; ++i) {
unsigned current_glyph_char_index = glyph_data_[i].character_index;
// If this glyph is still part of the same glyph sequence for the grapheme
// cluster at character index glyph_sequence_start, add its advance to the
// glyph_sequence's advance.
if (glyph_sequence_start == current_glyph_char_index) {
glyph_sequence_advance += glyph_data_[i].advance;
continue;
}
// We are about to move out of a glyph sequence that contains offset, so
// the current glyph sequence is the one we are looking for.
if (glyph_sequence_start <= offset && offset < current_glyph_char_index) {
glyph_sequence_end = current_glyph_char_index;
break;
}
glyph_sequence_start = current_glyph_char_index;
// Since we always update glyph_sequence_end when we break, set this to
// last_character in case this is the final iteration of the loop.
glyph_sequence_end = num_characters_;
accumulated_position += glyph_sequence_advance;
glyph_sequence_advance = glyph_data_[i].advance;
}
} else {
glyph_sequence_start = glyph_sequence_end = num_characters_;
for (unsigned i = 0; i < num_glyphs; ++i) {
unsigned current_glyph_char_index = glyph_data_[i].character_index;
// If this glyph is still part of the same glyph sequence for the grapheme
// cluster at character index glyph_sequence_start, add its advance to the
// glyph_sequence's advance.
if (glyph_sequence_start == current_glyph_char_index) {
glyph_sequence_advance += glyph_data_[i].advance;
continue;
}
// We are about to move out of a glyph sequence that contains offset, so
// the current glyph sequence is the one we are looking for.
if (glyph_sequence_start <= offset && offset < glyph_sequence_end) {
break;
}
glyph_sequence_end = glyph_sequence_start;
glyph_sequence_start = current_glyph_char_index;
accumulated_position += glyph_sequence_advance;
glyph_sequence_advance = glyph_data_[i].advance;
}
}
// This is the character position inside the glyph sequence.
unsigned pos = offset - glyph_sequence_start;
// We calculate the number of Unicode grapheme clusters (actually cursor
// position stops) on the subset of characters. We use this to divide
// glyph_sequence_advance by the number of unicode grapheme clusters this
// glyph sequence was shaped for, and thus linearly interpolate the cursor
// position based on accumulated position and a fraction of
// glyph_sequence_advance.
unsigned graphemes = NumGraphemes(glyph_sequence_start, glyph_sequence_end);
if (graphemes > 1) {
DCHECK_GE(glyph_sequence_end, glyph_sequence_start);
unsigned size = glyph_sequence_end - glyph_sequence_start;
unsigned place = graphemes * pos / size;
pos -= place;
glyph_sequence_advance = glyph_sequence_advance / graphemes;
if (IsRtl()) {
accumulated_position += glyph_sequence_advance * (graphemes - place - 1);
} else {
accumulated_position += glyph_sequence_advance * place;
}
}
// Re-adapt based on adjust_mid_cluster. On LTR, if we want AdjustToEnd and
// offset is not at the beginning, we need to jump to the right side of the
// grapheme. On RTL, if we want AdjustToStart and offset is not at the end, we
// need to jump to the left side of the grapheme.
if (IsLtr() && adjust_mid_cluster == AdjustMidCluster::kToEnd && pos != 0) {
accumulated_position += glyph_sequence_advance;
} else if (IsRtl() && adjust_mid_cluster == AdjustMidCluster::kToEnd &&
pos != 0) {
accumulated_position -= glyph_sequence_advance;
}
if (IsRtl()) {
// For RTL, we return the right side.
accumulated_position += glyph_sequence_advance;
}
return accumulated_position;
}
// In some ways, CharacterIndexForXPosition is the reverse of
// XPositionForOffset. Given a target pixel distance on screen space, returns a
// character index for the end of the interval that would be included within
// that space. @break_glyphs controls whether we use grapheme information
// to break glyphs into grapheme clusters and return character that are a part
// of a glyph.
void ShapeResult::RunInfo::CharacterIndexForXPosition(
float target_x,
BreakGlyphsOption break_glyphs,
GlyphIndexResult* result) const {
DCHECK(target_x >= 0 && target_x <= width_);
result->origin_x = 0;
unsigned glyph_sequence_start = 0;
unsigned glyph_sequence_end = num_characters_;
result->advance = 0.0;
// on RTL, we start on the last index.
if (IsRtl()) {
glyph_sequence_start = glyph_sequence_end = num_characters_;
}
for (const HarfBuzzRunGlyphData& glyph_data : glyph_data_) {
unsigned current_glyph_char_index = glyph_data.character_index;
// If the glyph is part of the same sequence, we just accumulate the
// advance.
if (glyph_sequence_start == current_glyph_char_index) {
result->advance += glyph_data.advance;
continue;
}
// Since we are about to move to the next sequence of glyphs, check if
// the target falls inside it, if it does, we found our sequence.
if (result->origin_x + result->advance > target_x) {
if (IsLtr()) {
glyph_sequence_end = current_glyph_char_index;
}
break;
}
// Move to the next sequence, update accumulated_x.
if (IsRtl()) {
// Notice that on RTL, as we move to our next sequence, we already know
// both bounds. Nonetheless, we still need to move forward so we can
// capture all glyphs of this sequence.
glyph_sequence_end = glyph_sequence_start;
}
glyph_sequence_start = current_glyph_char_index;
result->origin_x += result->advance;
result->advance = glyph_data.advance;
}
// At this point, we have [glyph_sequence_start, glyph_sequence_end)
// representing a sequence of glyphs, of size glyph_sequence_advance. We
// linearly interpolate how much space each character takes, and reduce the
// sequence to only match the character size.
if (break_glyphs && glyph_sequence_end > glyph_sequence_start) {
int graphemes = NumGraphemes(glyph_sequence_start, glyph_sequence_end);
if (graphemes > 1) {
float unit_size = result->advance / graphemes;
unsigned step = floor((target_x - result->origin_x) / unit_size);
unsigned glyph_length = glyph_sequence_end - glyph_sequence_start;
unsigned final_size = floor(glyph_length / graphemes);
result->origin_x += unit_size * step;
if (IsLtr()) {
glyph_sequence_start += step;
glyph_sequence_end = glyph_sequence_start + final_size;
} else {
glyph_sequence_end -= step;
glyph_sequence_start = glyph_sequence_end - final_size;
}
result->advance = unit_size;
}
}
if (IsLtr()) {
result->left_character_index = glyph_sequence_start;
result->right_character_index = glyph_sequence_end;
} else {
result->left_character_index = glyph_sequence_end;
result->right_character_index = glyph_sequence_start;
}
}
ShapeResult::ShapeResult(scoped_refptr<const SimpleFontData> font_data,
unsigned start_index,
unsigned num_characters,
TextDirection direction)
: width_(0),
primary_font_(font_data),
start_index_(start_index),
num_characters_(num_characters),
num_glyphs_(0),
direction_(static_cast<unsigned>(direction)),
has_vertical_offsets_(false),
is_applied_spacing_(false) {}
ShapeResult::ShapeResult(const Font* font,
unsigned start_index,
unsigned num_characters,
TextDirection direction)
: ShapeResult(font->PrimaryFont(), start_index, num_characters, direction) {
}
ShapeResult::ShapeResult(const ShapeResult& other)
: width_(other.width_),
primary_font_(other.primary_font_),
start_index_(other.start_index_),
num_characters_(other.num_characters_),
num_glyphs_(other.num_glyphs_),
direction_(other.direction_),
has_vertical_offsets_(other.has_vertical_offsets_),
is_applied_spacing_(other.is_applied_spacing_) {
runs_.reserve(other.runs_.size());
for (const auto& run : other.runs_)
runs_.push_back(run->Create(*run.get()));
}
ShapeResult::~ShapeResult() = default;
size_t ShapeResult::ByteSize() const {
size_t self_byte_size = sizeof(*this);
for (unsigned i = 0; i < runs_.size(); ++i) {
self_byte_size += runs_[i]->ByteSize();
}
return self_byte_size;
}
bool ShapeResult::IsStartSafeToBreak() const {
// Empty is likely a |SubRange| at the middle of a cluster or a ligature.
if (UNLIKELY(runs_.empty()))
return false;
const RunInfo* run = nullptr;
const HarfBuzzRunGlyphData* glyph_data = nullptr;
if (IsLtr()) {
run = runs_.front().get();
glyph_data = &run->glyph_data_.front();
} else {
run = runs_.back().get();
glyph_data = &run->glyph_data_.back();
}
return glyph_data->safe_to_break_before &&
// If the glyph for the first character is missing, consider not safe.
StartIndex() == run->start_index_ + glyph_data->character_index;
}
unsigned ShapeResult::NextSafeToBreakOffset(unsigned index) const {
for (auto* it = runs_.begin(); it != runs_.end(); ++it) {
const auto& run = *it;
if (!run)
continue;
unsigned run_start = run->start_index_;
if (index >= run_start) {
unsigned offset = index - run_start;
if (offset <= run->num_characters_) {
return run->NextSafeToBreakOffset(offset) + run_start;
}
if (IsRtl()) {
if (it == runs_.begin())
return run_start + run->num_characters_;
const auto& previous_run = *--it;
return previous_run->start_index_;
}
} else if (IsLtr()) {
return run_start;
}
}
return EndIndex();
}
unsigned ShapeResult::PreviousSafeToBreakOffset(unsigned index) const {
for (auto it = runs_.rbegin(); it != runs_.rend(); ++it) {
const auto& run = *it;
if (!run)
continue;
unsigned run_start = run->start_index_;
if (index >= run_start) {
unsigned offset = index - run_start;
if (offset <= run->num_characters_) {
return run->PreviousSafeToBreakOffset(offset) + run_start;
}
if (IsLtr()) {
return run_start + run->num_characters_;
}
} else if (IsRtl()) {
if (it == runs_.rbegin())
return run->start_index_;
const auto& previous_run = *--it;
return previous_run->start_index_ + previous_run->num_characters_;
}
}
return StartIndex();
}
// If the position is outside of the result, returns the start or the end offset
// depends on the position.
void ShapeResult::OffsetForPosition(float target_x,
BreakGlyphsOption break_glyphs,
GlyphIndexResult* result) const {
if (target_x <= 0) {
if (IsRtl()) {
result->left_character_index = result->right_character_index =
NumCharacters();
}
return;
}
unsigned characters_so_far = IsRtl() ? NumCharacters() : 0;
float current_x = 0;
for (const scoped_refptr<RunInfo>& run_ptr : runs_) {
const RunInfo* run = run_ptr.get();
if (!run)
continue;
if (IsRtl())
characters_so_far -= run->num_characters_;
float next_x = current_x + run->width_;
float offset_for_run = target_x - current_x;
if (offset_for_run >= 0 && offset_for_run < run->width_) {
// The x value in question is within this script run.
run->CharacterIndexForXPosition(offset_for_run, break_glyphs, result);
result->characters_on_left_runs = characters_so_far;
if (IsRtl()) {
result->left_character_index =
characters_so_far + result->left_character_index;
result->right_character_index =
characters_so_far + result->right_character_index;
DCHECK_LE(result->left_character_index, NumCharacters() + 1);
DCHECK_LE(result->right_character_index, NumCharacters());
} else {
result->left_character_index += characters_so_far;
result->right_character_index += characters_so_far;
DCHECK_LE(result->left_character_index, NumCharacters());
DCHECK_LE(result->right_character_index, NumCharacters() + 1);
}
result->origin_x += current_x;
return;
}
if (IsLtr())
characters_so_far += run->num_characters_;
current_x = next_x;
}
if (IsRtl()) {
result->left_character_index = 0;
result->right_character_index = 0;
} else {
result->left_character_index += characters_so_far;
result->right_character_index += characters_so_far;
}
result->characters_on_left_runs = characters_so_far;
DCHECK_LE(result->left_character_index, NumCharacters());
DCHECK_LE(result->right_character_index, NumCharacters() + 1);
}
unsigned ShapeResult::OffsetForPosition(float x,
BreakGlyphsOption break_glyphs) const {
GlyphIndexResult result;
OffsetForPosition(x, break_glyphs, &result);
// For LTR, the offset is always the left one.
if (IsLtr())
return result.left_character_index;
// For RTL the offset is the right one, except that the interval is open
// on other side. So in case we are exactly at the boundary, we return the
// left index.
if (x == result.origin_x)
return result.left_character_index;
return result.right_character_index;
}
unsigned ShapeResult::CaretOffsetForHitTest(
float x,
const StringView& text,
BreakGlyphsOption break_glyphs_option) const {
if (break_glyphs_option)
EnsureGraphemes(text);
GlyphIndexResult result;
OffsetForPosition(x, break_glyphs_option, &result);
if (x - result.origin_x <= result.advance / 2)
return result.left_character_index;
return result.right_character_index;
}
unsigned ShapeResult::OffsetToFit(float x, TextDirection line_direction) const {
GlyphIndexResult result;
OffsetForPosition(x, BreakGlyphsOption(false), &result);
if (blink::IsLtr(line_direction))
return result.left_character_index;
if (x == result.origin_x)
return result.left_character_index;
return result.right_character_index;
}
float ShapeResult::PositionForOffset(
unsigned absolute_offset,
AdjustMidCluster adjust_mid_cluster) const {
float x = 0;
float offset_x = 0;
// The absolute_offset argument represents the offset for the entire
// ShapeResult while offset is continuously updated to be relative to the
// current run.
unsigned offset = absolute_offset;
if (IsRtl()) {
// Convert logical offsets to visual offsets, because results are in
// logical order while runs are in visual order.
x = width_;
if (offset < NumCharacters())
offset = NumCharacters() - offset - 1;
x -= Width();
}
for (unsigned i = 0; i < runs_.size(); i++) {
if (!runs_[i])
continue;
DCHECK_EQ(IsRtl(), runs_[i]->IsRtl());
unsigned num_characters = runs_[i]->num_characters_;
if (!offset_x && offset < num_characters) {
offset_x =
runs_[i]->XPositionForVisualOffset(offset, adjust_mid_cluster) + x;
break;
}
offset -= num_characters;
x += runs_[i]->width_;
}
// The position in question might be just after the text.
if (!offset_x && absolute_offset == NumCharacters())
return IsRtl() ? 0 : width_;
return offset_x;
}
float ShapeResult::CaretPositionForOffset(
unsigned offset,
const StringView& text,
AdjustMidCluster adjust_mid_cluster) const {
EnsureGraphemes(text);
return PositionForOffset(offset, adjust_mid_cluster);
}
void ShapeResult::FallbackFonts(
HashSet<const SimpleFontData*>* fallback) const {
DCHECK(fallback);
DCHECK(primary_font_);
for (unsigned i = 0; i < runs_.size(); ++i) {
if (runs_[i] && runs_[i]->font_data_ &&
runs_[i]->font_data_ != primary_font_) {
fallback->insert(runs_[i]->font_data_.get());
}
}
}
void ShapeResult::GetRunFontData(Vector<RunFontData>* font_data) const {
for (const auto& run : runs_) {
font_data->push_back(
RunFontData({run->font_data_.get(), run->glyph_data_.size()}));
}
}
template <bool has_non_zero_glyph_offsets>
float ShapeResult::ForEachGlyphImpl(float initial_advance,
GlyphCallback glyph_callback,
void* context,
const RunInfo& run) const {
auto glyph_offsets = run.glyph_data_.GetOffsets<has_non_zero_glyph_offsets>();
auto total_advance = initial_advance;
bool is_horizontal = HB_DIRECTION_IS_HORIZONTAL(run.direction_);
for (const auto& glyph_data : run.glyph_data_) {
glyph_callback(context, run.start_index_ + glyph_data.character_index,
glyph_data.glyph, *glyph_offsets, total_advance,
is_horizontal, run.canvas_rotation_, run.font_data_.get());
total_advance += glyph_data.advance;
++glyph_offsets;
}
return total_advance;
}
float ShapeResult::ForEachGlyph(float initial_advance,
GlyphCallback glyph_callback,
void* context) const {
auto total_advance = initial_advance;
for (const auto& run : runs_) {
if (run->glyph_data_.HasNonZeroOffsets()) {
total_advance =
ForEachGlyphImpl<true>(total_advance, glyph_callback, context, *run);
} else {
total_advance =
ForEachGlyphImpl<false>(total_advance, glyph_callback, context, *run);
}
}
return total_advance;
}
template <bool has_non_zero_glyph_offsets>
float ShapeResult::ForEachGlyphImpl(float initial_advance,
unsigned from,
unsigned to,
unsigned index_offset,
GlyphCallback glyph_callback,
void* context,
const RunInfo& run) const {
auto glyph_offsets = run.glyph_data_.GetOffsets<has_non_zero_glyph_offsets>();
auto total_advance = initial_advance;
unsigned run_start = run.start_index_ + index_offset;
bool is_horizontal = HB_DIRECTION_IS_HORIZONTAL(run.direction_);
const SimpleFontData* font_data = run.font_data_.get();
if (run.IsLtr()) { // Left-to-right
for (const auto& glyph_data : run.glyph_data_) {
const unsigned character_index = run_start + glyph_data.character_index;
if (character_index >= to)
break;
if (character_index >= from) {
glyph_callback(context, character_index, glyph_data.glyph,
*glyph_offsets, total_advance, is_horizontal,
run.canvas_rotation_, font_data);
}
total_advance += glyph_data.advance;
++glyph_offsets;
}
} else { // Right-to-left
for (const auto& glyph_data : run.glyph_data_) {
const unsigned character_index = run_start + glyph_data.character_index;
if (character_index < from)
break;
if (character_index < to) {
glyph_callback(context, character_index, glyph_data.glyph,
*glyph_offsets, total_advance, is_horizontal,
run.canvas_rotation_, font_data);
}
total_advance += glyph_data.advance;
++glyph_offsets;
}
}
return total_advance;
}
float ShapeResult::ForEachGlyph(float initial_advance,
unsigned from,
unsigned to,
unsigned index_offset,
GlyphCallback glyph_callback,
void* context) const {
auto total_advance = initial_advance;
for (const auto& run : runs_) {
if (run->glyph_data_.HasNonZeroOffsets()) {
total_advance = ForEachGlyphImpl<true>(
total_advance, from, to, index_offset, glyph_callback, context, *run);
} else {
total_advance = ForEachGlyphImpl<false>(
total_advance, from, to, index_offset, glyph_callback, context, *run);
}
}
return total_advance;
}
unsigned ShapeResult::CountGraphemesInCluster(base::span<const UChar> str,
uint16_t start_index,
uint16_t end_index) {
if (start_index > end_index)
std::swap(start_index, end_index);
uint16_t length = end_index - start_index;
TextBreakIterator* cursor_pos_iterator =
CursorMovementIterator(str.subspan(start_index, length));
if (!cursor_pos_iterator)
return 0;
int cursor_pos = cursor_pos_iterator->current();
int num_graphemes = -1;
while (0 <= cursor_pos) {
cursor_pos = cursor_pos_iterator->next();
num_graphemes++;
}
return std::max(0, num_graphemes);
}
float ShapeResult::ForEachGraphemeClusters(const StringView& text,
float initial_advance,
unsigned from,
unsigned to,
unsigned index_offset,
GraphemeClusterCallback callback,
void* context) const {
unsigned run_offset = index_offset;
float advance_so_far = initial_advance;
for (const auto& run : runs_) {
unsigned graphemes_in_cluster = 1;
float cluster_advance = 0;
// FIXME: should this be run->direction_?
bool rtl = Direction() == TextDirection::kRtl;
// A "cluster" in this context means a cluster as it is used by HarfBuzz:
// The minimal group of characters and corresponding glyphs, that cannot be
// broken down further from a text shaping point of view. A cluster can
// contain multiple glyphs and grapheme clusters, with mutually overlapping
// boundaries.
uint16_t cluster_start = static_cast<uint16_t>(
rtl ? run->start_index_ + run->num_characters_ + run_offset
: run->GlyphToCharacterIndex(0) + run_offset);
const unsigned num_glyphs = run->glyph_data_.size();
for (unsigned i = 0; i < num_glyphs; ++i) {
const HarfBuzzRunGlyphData& glyph_data = run->glyph_data_[i];
uint16_t current_character_index =
run->start_index_ + glyph_data.character_index + run_offset;
bool is_run_end = (i + 1 == num_glyphs);
bool is_cluster_end =
is_run_end || (run->GlyphToCharacterIndex(i + 1) + run_offset !=
current_character_index);
if ((rtl && current_character_index >= to) ||
(!rtl && current_character_index < from)) {
advance_so_far += glyph_data.advance;
rtl ? --cluster_start : ++cluster_start;
continue;
}
cluster_advance += glyph_data.advance;
if (text.Is8Bit()) {
callback(context, current_character_index, advance_so_far, 1,
glyph_data.advance, run->canvas_rotation_);
advance_so_far += glyph_data.advance;
} else if (is_cluster_end) {
uint16_t cluster_end;
if (rtl) {
cluster_end = current_character_index;
} else {
cluster_end = static_cast<uint16_t>(
is_run_end ? run->start_index_ + run->num_characters_ + run_offset
: run->GlyphToCharacterIndex(i + 1) + run_offset);
}
graphemes_in_cluster =
CountGraphemesInCluster(text.Span16(), cluster_start, cluster_end);
if (!graphemes_in_cluster || !cluster_advance)
continue;
callback(context, current_character_index, advance_so_far,
graphemes_in_cluster, cluster_advance, run->canvas_rotation_);
advance_so_far += cluster_advance;
cluster_start = cluster_end;
cluster_advance = 0;
}
}
}
return advance_so_far;
}
// TODO(kojii): VC2015 fails to explicit instantiation of a member function.
// Typed functions + this private function are to instantiate instances.
template <typename TextContainerType>
void ShapeResult::ApplySpacingImpl(
ShapeResultSpacing<TextContainerType>& spacing,
int text_start_offset) {
float offset = 0;
float total_space = 0;
float space = 0;
for (auto& run : runs_) {
if (!run)
continue;
unsigned run_start_index = run->start_index_ + text_start_offset;
float total_space_for_run = 0;
for (wtf_size_t i = 0; i < run->glyph_data_.size(); i++) {
HarfBuzzRunGlyphData& glyph_data = run->glyph_data_[i];
// Skip if it's not a grapheme cluster boundary.
if (i + 1 < run->glyph_data_.size() &&
glyph_data.character_index ==
run->glyph_data_[i + 1].character_index) {
continue;
}
typename ShapeResultSpacing<TextContainerType>::ComputeSpacingParameters
parameters{.index = run_start_index + glyph_data.character_index,
.original_advance = glyph_data.advance};
space = spacing.ComputeSpacing(parameters, offset);
glyph_data.advance += space;
total_space_for_run += space;
// |offset| is non-zero only when justifying CJK characters that follow
// non-CJK characters.
if (UNLIKELY(offset)) {
if (run->IsHorizontal()) {
run->glyph_data_.AddOffsetWidthAt(i, offset);
} else {
run->glyph_data_.AddOffsetHeightAt(i, offset);
has_vertical_offsets_ = true;
}
offset = 0;
}
}
run->width_ += total_space_for_run;
total_space += total_space_for_run;
}
width_ += total_space;
// The spacing on the right of the last glyph does not affect the glyph
// bounding box. Thus, the glyph bounding box becomes smaller than the advance
// if the letter spacing is positve, or larger if negative.
if (space) {
total_space -= space;
// TODO(kojii): crbug.com/768284: There are cases where
// InlineTextBox::LogicalWidth() is round down of ShapeResult::Width() in
// LayoutUnit. Ceiling the width did not help. Add 1px to avoid cut-off.
if (space < 0)
total_space += 1;
}
}
void ShapeResult::ApplySpacing(ShapeResultSpacing<String>& spacing,
int text_start_offset) {
// For simplicity, we apply spacing once only. If you want to do multiple
// time, please get rid of below |DCHECK()|.
DCHECK(!is_applied_spacing_) << this;
is_applied_spacing_ = true;
ApplySpacingImpl(spacing, text_start_offset);
}
scoped_refptr<ShapeResult> ShapeResult::ApplySpacingToCopy(
ShapeResultSpacing<TextRun>& spacing,
const TextRun& run) const {
unsigned index_of_sub_run = spacing.Text().IndexOfSubRun(run);
DCHECK_NE(std::numeric_limits<unsigned>::max(), index_of_sub_run);
scoped_refptr<ShapeResult> result = ShapeResult::Create(*this);
if (index_of_sub_run != std::numeric_limits<unsigned>::max())
result->ApplySpacingImpl(spacing, index_of_sub_run);
return result;
}
namespace {
float HarfBuzzPositionToFloat(hb_position_t value) {
return static_cast<float>(value) / (1 << 16);
}
// Checks whether it's safe to break without reshaping before the given glyph.
bool IsSafeToBreakBefore(const hb_glyph_info_t* glyph_infos,
unsigned i,
unsigned num_glyph,
TextDirection direction) {
if (direction == TextDirection::kLtr) {
// Before the first glyph is safe to break.
if (!i)
return true;
// Not at a cluster boundary.
if (glyph_infos[i].cluster == glyph_infos[i - 1].cluster)
return false;
} else {
DCHECK_EQ(direction, TextDirection::kRtl);
// Before the first glyph is safe to break.
if (i == num_glyph - 1)
return true;
// Not at a cluster boundary.
if (glyph_infos[i].cluster == glyph_infos[i + 1].cluster)
return false;
}
// The HB_GLYPH_FLAG_UNSAFE_TO_BREAK flag is set for all glyphs in a
// given cluster so we only need to check the last one.
hb_glyph_flags_t flags = hb_glyph_info_get_glyph_flags(glyph_infos + i);
return (flags & HB_GLYPH_FLAG_UNSAFE_TO_BREAK) == 0;
}
} // anonymous namespace
// This function computes the number of glyphs and characters that can fit into
// this RunInfo.
//
// HarfBuzzRunGlyphData has a limit kMaxCharacterIndex for the character index
// in order to packsave memory. Also, RunInfo has kMaxGlyphs to make the number
// of glyphs predictable and to minimize the buffer reallocations.
void ShapeResult::RunInfo::LimitNumGlyphs(unsigned start_glyph,
unsigned* num_glyphs_in_out,
unsigned* num_glyphs_removed_out,
const bool is_ltr,
const hb_glyph_info_t* glyph_infos) {
unsigned num_glyphs = *num_glyphs_in_out;
CHECK_GT(num_glyphs, 0u);