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
// Copyright 2021 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::inline_box::InlineBox;
use crate::layout::{ContentWidths, Glyph, LineMetrics, RunMetrics, Style};
use crate::style::Brush;
use crate::util::nearly_zero;
use crate::{FontData, IndentOptions, InlineBoxKind, LineHeight, OverflowWrap, TextWrapMode};
use core::ops::Range;
use alloc::vec::Vec;
use crate::analysis::cluster::Whitespace;
use crate::analysis::{Boundary, CharInfo};
#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) struct ClusterData {
pub(crate) info: ClusterInfo,
/// Cluster flags (see impl methods for details).
pub(crate) flags: u16,
/// Style index for this cluster.
pub(crate) style_index: u16,
/// Number of glyphs in this cluster (0xFF = single glyph stored inline)
pub(crate) glyph_len: u8,
/// Number of text bytes in this cluster
pub(crate) text_len: u8,
/// If `glyph_len == 0xFF`, then `glyph_offset` is a glyph identifier,
/// otherwise, it's an offset into the glyph array with the base
/// taken from the owning run.
pub(crate) glyph_offset: u32,
/// Offset into the text for this cluster
pub(crate) text_offset: u16,
/// Advance width for this cluster
pub(crate) advance: f32,
}
impl ClusterData {
pub(crate) const LIGATURE_START: u16 = 1;
pub(crate) const LIGATURE_COMPONENT: u16 = 2;
#[inline(always)]
pub(crate) fn is_ligature_start(self) -> bool {
self.flags & Self::LIGATURE_START != 0
}
#[inline(always)]
pub(crate) fn is_ligature_component(self) -> bool {
self.flags & Self::LIGATURE_COMPONENT != 0
}
#[inline(always)]
pub(crate) fn text_range(self, run: &RunData) -> Range<usize> {
let start = run.text_range.start + self.text_offset as usize;
start..start + self.text_len as usize
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) struct ClusterInfo {
boundary: Boundary,
source_char: char,
}
impl ClusterInfo {
pub(crate) fn new(boundary: Boundary, source_char: char) -> Self {
Self {
boundary,
source_char,
}
}
// Returns the boundary type of the cluster.
pub(crate) fn boundary(self) -> Boundary {
self.boundary
}
// Returns the whitespace type of the cluster.
pub(crate) fn whitespace(self) -> Whitespace {
to_whitespace(self.source_char)
}
/// Returns if the cluster is a line boundary.
pub(crate) fn is_boundary(self) -> bool {
self.boundary != Boundary::None
}
/// Returns if the cluster is an emoji.
pub(crate) fn is_emoji(self) -> bool {
// TODO: Defer to ICU4X properties (see: https://docs.rs/icu/latest/icu/properties/props/struct.Emoji.html).
matches!(self.source_char as u32, 0x1F600..=0x1F64F | 0x1F300..=0x1F5FF | 0x1F680..=0x1F6FF | 0x2600..=0x26FF | 0x2700..=0x27BF)
}
/// Returns if the cluster is any whitespace.
pub(crate) fn is_whitespace(self) -> bool {
self.source_char.is_whitespace()
}
/// Returns the cluster's original character.
pub(crate) fn source_char(self) -> char {
self.source_char
}
}
const fn to_whitespace(c: char) -> Whitespace {
const LINE_SEPARATOR: char = '\u{2028}';
const PARAGRAPH_SEPARATOR: char = '\u{2029}';
match c {
' ' => Whitespace::Space,
'\t' => Whitespace::Tab,
'\n' | '\r' | LINE_SEPARATOR | PARAGRAPH_SEPARATOR => Whitespace::Newline,
'\u{00A0}' => Whitespace::NoBreakSpace,
_ => Whitespace::None,
}
}
/// `HarfRust`-based run data
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RunData {
/// Index of the font for the run.
pub(crate) font_index: usize,
/// Font size.
pub(crate) font_size: f32,
/// Font attributes, needed for accessibility.
pub(crate) font_attrs: fontique::Attributes,
/// Synthesis for rendering (contains variation settings)
pub(crate) synthesis: fontique::Synthesis,
/// Range of normalized coordinates in the layout data.
pub(crate) coords_range: Range<usize>,
/// Range of the source text.
pub(crate) text_range: Range<usize>,
/// Bidi level for the run.
pub(crate) bidi_level: u8,
/// Range of clusters.
pub(crate) cluster_range: Range<usize>,
/// Base for glyph indices.
pub(crate) glyph_start: usize,
/// Metrics for the run.
pub(crate) metrics: RunMetrics,
/// Additional word spacing.
pub(crate) word_spacing: f32,
/// Additional letter spacing.
pub(crate) letter_spacing: f32,
/// Total advance of the run.
pub(crate) advance: f32,
}
#[derive(Copy, Clone, Default, PartialEq, Debug)]
pub enum BreakReason {
#[default]
None,
Regular,
Explicit,
Emergency,
}
#[derive(Clone, Default, Debug, PartialEq)]
pub(crate) struct LineData {
/// Range of the source text.
pub(crate) text_range: Range<usize>,
/// Range of line items.
pub(crate) item_range: Range<usize>,
/// Metrics for the line.
pub(crate) metrics: LineMetrics,
/// The cause of the line break.
pub(crate) break_reason: BreakReason,
/// Maximum advance for the line.
pub(crate) max_advance: f32,
/// Number of justified clusters on the line.
pub(crate) num_spaces: usize,
/// Text indent applied to this line.
pub(crate) indent: f32,
}
impl LineData {
pub(crate) fn size(&self) -> f32 {
self.metrics.ascent + self.metrics.descent + self.metrics.leading
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct LineItemData {
/// Whether the item is a run or an inline box
pub(crate) kind: LayoutItemKind,
/// The index of the run or inline box in the runs or `inline_boxes` vec
pub(crate) index: usize,
/// Bidi level for the item (used for reordering)
pub(crate) bidi_level: u8,
/// Advance (size in direction of text flow) for the run.
pub(crate) advance: f32,
// Fields that only apply to text runs (Ignored for boxes)
// TODO: factor this out?
/// True if the run is composed entirely of whitespace.
pub(crate) is_whitespace: bool,
/// True if the run ends in whitespace.
pub(crate) has_trailing_whitespace: bool,
/// Range of the source text.
pub(crate) text_range: Range<usize>,
/// Range of clusters.
pub(crate) cluster_range: Range<usize>,
}
impl LineItemData {
pub(crate) fn is_text_run(&self) -> bool {
self.kind == LayoutItemKind::TextRun
}
#[inline(always)]
pub(crate) fn is_rtl(&self) -> bool {
self.bidi_level & 1 != 0
}
/// If the item is a text run
/// - Determine if it consists entirely of whitespace (`is_whitespace` property)
/// - Determine if it has trailing whitespace (`has_trailing_whitespace` property)
pub(crate) fn compute_whitespace_properties<B: Brush>(&mut self, layout_data: &LayoutData<B>) {
// Skip items which are not text runs
if self.kind != LayoutItemKind::TextRun {
return;
}
self.is_whitespace = true;
if self.is_rtl() {
// RTL runs check for "trailing" whitespace at the front.
for cluster in layout_data.clusters[self.cluster_range.clone()].iter() {
if cluster.info.is_whitespace() {
self.has_trailing_whitespace = true;
} else {
self.is_whitespace = false;
break;
}
}
} else {
for cluster in layout_data.clusters[self.cluster_range.clone()]
.iter()
.rev()
{
if cluster.info.is_whitespace() {
self.has_trailing_whitespace = true;
} else {
self.is_whitespace = false;
break;
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LayoutItemKind {
TextRun,
InlineBox,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct LayoutItem {
/// Whether the item is a run or an inline box
pub(crate) kind: LayoutItemKind,
/// The index of the run or inline box in the runs or `inline_boxes` vec
pub(crate) index: usize,
/// Bidi level for the item (used for reordering)
pub(crate) bidi_level: u8,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LayoutData<B: Brush> {
// General settings (directly from the "builder")
/// The display scale factor
pub(crate) scale: f32,
/// Whether metrics should be quantized to pixel boundaries
pub(crate) quantize: bool,
/// The `BiDi` base level
pub(crate) base_level: u8,
/// The length of the text in the layout
pub(crate) text_len: usize,
// Output of style resolution (input to line breaking)
pub(crate) styles: Vec<Style<B>>,
pub(crate) inline_boxes: Vec<InlineBox>,
// Output of shaping (input to line breaking)
pub(crate) fonts: Vec<FontData>,
pub(crate) coords: Vec<i16>,
pub(crate) runs: Vec<RunData>,
pub(crate) items: Vec<LayoutItem>,
pub(crate) clusters: Vec<ClusterData>,
pub(crate) glyphs: Vec<Glyph>,
// Output of line breaking
/// The lines in the
pub(crate) lines: Vec<LineData>,
/// Items within each line
pub(crate) line_items: Vec<LineItemData>,
/// The width constraint that was used to line break the layout
pub(crate) layout_max_advance: f32,
/// The computed width of the layout excluding trailing whitespace
pub(crate) width: f32,
/// The computed width of the layout including trailing whitespace
pub(crate) full_width: f32,
/// The computed height of the layout
pub(crate) height: f32,
// Output of alignment
#[cfg(feature = "accesskit")]
/// Directly store the alignment if accessibility is enabled so we can
/// set the corresponding AccessKit property.
pub(crate) alignment: Option<super::Alignment>,
/// Whether the layout is aligned with [`crate::Alignment::Justify`].
pub(crate) is_aligned_justified: bool,
/// The text-indent amount in layout units.
pub(crate) indent_amount: f32,
/// Options controlling text-indent behavior (each-line, hanging).
pub(crate) indent_options: IndentOptions,
}
impl<B: Brush> Default for LayoutData<B> {
fn default() -> Self {
Self {
scale: 1.,
quantize: true,
base_level: 0,
text_len: 0,
width: 0.,
full_width: 0.,
height: 0.,
fonts: Vec::new(),
coords: Vec::new(),
styles: Vec::new(),
inline_boxes: Vec::new(),
runs: Vec::new(),
items: Vec::new(),
clusters: Vec::new(),
glyphs: Vec::new(),
lines: Vec::new(),
line_items: Vec::new(),
#[cfg(feature = "accesskit")]
alignment: None,
is_aligned_justified: false,
layout_max_advance: 0.0,
indent_amount: 0.0,
indent_options: IndentOptions::default(),
}
}
}
impl<B: Brush> LayoutData<B> {
pub(crate) fn clear(&mut self) {
self.scale = 1.;
self.quantize = true;
self.base_level = 0;
self.text_len = 0;
self.width = 0.;
self.full_width = 0.;
self.height = 0.;
self.fonts.clear();
self.coords.clear();
self.styles.clear();
self.inline_boxes.clear();
self.runs.clear();
self.items.clear();
self.clusters.clear();
self.glyphs.clear();
self.lines.clear();
self.line_items.clear();
}
/// Push an inline box to the list of items
pub(crate) fn push_inline_box(&mut self, index: usize) {
// Give the box the same bidi level as the preceding text run
// (or else default to 0 if there is not yet a text run)
let bidi_level = self.runs.last().map(|r| r.bidi_level).unwrap_or(0);
self.items.push(LayoutItem {
kind: LayoutItemKind::InlineBox,
index,
bidi_level,
});
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn push_run(
&mut self,
font: FontData,
font_size: f32,
font_attrs: fontique::Attributes,
synthesis: fontique::Synthesis,
glyph_buffer: &harfrust::GlyphBuffer,
bidi_level: u8,
style_index: u16,
word_spacing: f32,
letter_spacing: f32,
source_text: &str,
char_infos: &[(CharInfo, u16)], // From text analysis
text_range: Range<usize>, // The text range this run covers
coords: &[harfrust::NormalizedCoord],
) {
let coords_start = self.coords.len();
self.coords.extend(coords.iter().map(|c| c.to_bits()));
let coords_end = self.coords.len();
let font_index = self
.fonts
.iter()
.position(|f| *f == font)
.unwrap_or_else(|| {
let index = self.fonts.len();
self.fonts.push(font);
index
});
let metrics = {
let font = &self.fonts[font_index];
let font_ref = skrifa::FontRef::from_index(font.data.as_ref(), font.index).unwrap();
skrifa::metrics::Metrics::new(&font_ref, skrifa::prelude::Size::new(font_size), coords)
};
let units_per_em = metrics.units_per_em as f32;
let metrics = {
let (underline_offset, underline_size) = if let Some(underline) = metrics.underline {
(underline.offset, underline.thickness)
} else {
// Default values from Harfbuzz: https://github.com/harfbuzz/harfbuzz/blob/00492ec7df0038f41f78d43d477c183e4e4c506e/src/hb-ot-metrics.cc#L334
let default = units_per_em / 18.0;
(default, default)
};
let (strikethrough_offset, strikethrough_size) =
if let Some(strikeout) = metrics.strikeout {
(strikeout.offset, strikeout.thickness)
} else {
// Default values from HarfBuzz: https://github.com/harfbuzz/harfbuzz/blob/00492ec7df0038f41f78d43d477c183e4e4c506e/src/hb-ot-metrics.cc#L334-L347
(metrics.ascent / 2.0, units_per_em / 18.0)
};
// Compute line height
let style = &self.styles[style_index as usize];
let line_height = match style.line_height {
LineHeight::Absolute(value) => value,
LineHeight::FontSizeRelative(value) => value * font_size,
LineHeight::MetricsRelative(value) => {
(metrics.ascent - metrics.descent + metrics.leading) * value
}
};
RunMetrics {
ascent: metrics.ascent,
descent: -metrics.descent,
leading: metrics.leading,
underline_offset,
underline_size,
strikethrough_offset,
strikethrough_size,
line_height,
x_height: metrics.x_height,
cap_height: metrics.cap_height,
}
};
let cluster_range = self.clusters.len()..self.clusters.len();
let mut run = RunData {
font_index,
font_size,
font_attrs,
synthesis,
coords_range: coords_start..coords_end,
text_range,
bidi_level,
cluster_range,
glyph_start: self.glyphs.len(),
metrics,
word_spacing,
letter_spacing,
advance: 0.,
};
// `HarfRust` returns glyphs in visual order, so we need to process them as such while
// maintaining logical ordering of clusters.
let glyph_infos = glyph_buffer.glyph_infos();
if glyph_infos.is_empty() {
return;
}
let glyph_positions = glyph_buffer.glyph_positions();
let scale_factor = font_size / units_per_em;
let cluster_range_start = self.clusters.len();
let is_rtl = bidi_level & 1 == 1;
if !is_rtl {
run.advance = process_clusters(
Direction::Ltr,
&mut self.clusters,
&mut self.glyphs,
scale_factor,
glyph_infos,
glyph_positions,
char_infos,
source_text.char_indices(),
);
} else {
run.advance = process_clusters(
Direction::Rtl,
&mut self.clusters,
&mut self.glyphs,
scale_factor,
glyph_infos,
glyph_positions,
char_infos,
source_text.char_indices().rev(),
);
// Reverse clusters into logical order for RTL
let clusters_len = self.clusters.len();
self.clusters[cluster_range_start..clusters_len].reverse();
}
run.cluster_range = cluster_range_start..self.clusters.len();
if !run.cluster_range.is_empty() {
self.runs.push(run);
self.items.push(LayoutItem {
kind: LayoutItemKind::TextRun,
index: self.runs.len() - 1,
bidi_level,
});
}
}
pub(crate) fn finish(&mut self) {
for run in &self.runs {
let word = run.word_spacing;
let letter = run.letter_spacing;
if nearly_zero(word) && nearly_zero(letter) {
continue;
}
let clusters = &mut self.clusters[run.cluster_range.clone()];
for cluster in clusters {
let mut spacing = letter;
if !nearly_zero(word) && cluster.info.whitespace().is_space_or_nbsp() {
spacing += word;
}
if !nearly_zero(spacing) {
cluster.advance += spacing;
if cluster.glyph_len != 0xFF {
let start = run.glyph_start + cluster.glyph_offset as usize;
let end = start + cluster.glyph_len as usize;
let glyphs = &mut self.glyphs[start..end];
if let Some(last) = glyphs.last_mut() {
last.advance += spacing;
}
}
}
}
}
}
// TODO: this method does not handle mixed direction text at all.
pub(crate) fn calculate_content_widths(&self) -> ContentWidths {
fn whitespace_advance(cluster: Option<&ClusterData>) -> f32 {
cluster
.filter(|cluster| cluster.info.whitespace().is_space_or_nbsp())
.map_or(0.0, |cluster| cluster.advance)
}
let mut min_width = 0.0_f32;
let mut max_width = 0.0_f32;
let mut running_min_width = 0.0;
let mut running_max_width = 0.0;
let mut text_wrap_mode = TextWrapMode::Wrap;
let mut prev_cluster: Option<&ClusterData> = None;
let is_rtl = self.base_level & 1 == 1;
for item in &self.items {
match item.kind {
LayoutItemKind::TextRun => {
let run = &self.runs[item.index];
let clusters = &self.clusters[run.cluster_range.clone()];
if is_rtl {
prev_cluster = clusters.first();
}
for cluster in clusters {
let boundary = cluster.info.boundary();
let style = &self.styles[cluster.style_index as usize];
let prev_text_wrap_mode = text_wrap_mode;
text_wrap_mode = style.text_wrap_mode;
if boundary == Boundary::Mandatory
|| (prev_text_wrap_mode == TextWrapMode::Wrap
&& (boundary == Boundary::Line
|| style.overflow_wrap == OverflowWrap::Anywhere))
{
let trailing_whitespace = whitespace_advance(prev_cluster);
min_width = min_width.max(running_min_width - trailing_whitespace);
running_min_width = 0.0;
if boundary == Boundary::Mandatory {
max_width = max_width.max(running_max_width - trailing_whitespace);
running_max_width = 0.0;
}
}
running_min_width += cluster.advance;
running_max_width += cluster.advance;
if !is_rtl {
prev_cluster = Some(cluster);
}
}
let trailing_whitespace = whitespace_advance(prev_cluster);
min_width = min_width.max(running_min_width - trailing_whitespace);
}
LayoutItemKind::InlineBox => {
let ibox = &self.inline_boxes[item.index];
if ibox.kind == InlineBoxKind::InFlow {
running_max_width += ibox.width;
if text_wrap_mode == TextWrapMode::Wrap {
let trailing_whitespace = whitespace_advance(prev_cluster);
min_width = min_width.max(running_min_width - trailing_whitespace);
min_width = min_width.max(ibox.width);
running_min_width = 0.0;
} else {
running_min_width += ibox.width;
}
}
prev_cluster = None;
}
}
let trailing_whitespace = whitespace_advance(prev_cluster);
max_width = max_width.max(running_max_width - trailing_whitespace);
}
let trailing_whitespace = whitespace_advance(prev_cluster);
min_width = min_width.max(running_min_width - trailing_whitespace);
ContentWidths {
min: min_width,
max: max_width,
}
}
}
/// Processes shaped glyphs from `HarfRust` and converts them into `ClusterData` and `Glyph`.
///
/// # Parameters
///
/// ## Output Parameters (mutated by this function):
/// * `clusters` - Vector where new `ClusterData` entries will be pushed.
/// * `glyphs` - Vector where new `Glyph` entries will be pushed. Note: single-glyph clusters
/// with zero offsets may be inlined directly into `ClusterData`.
///
/// ## Input Parameters:
/// * `direction` - Direction of the text.
/// * `scale_factor` - Scaling factor used to convert font units to the target size.
/// * `glyph_infos` - `HarfRust` glyph information in visual order.
/// * `glyph_positions` - `HarfRust` glyph positioning data in visual order.
/// * `char_infos` - Character information from text analysis, indexed by cluster ID.
/// * `char_indices_iter` - Iterator over (`byte_offset`, `char`) pairs from the source text.
/// Should be in logical order (forward for LTR, reverse for RTL).
fn process_clusters<I: Iterator<Item = (usize, char)>>(
direction: Direction,
clusters: &mut Vec<ClusterData>,
glyphs: &mut Vec<Glyph>,
scale_factor: f32,
glyph_infos: &[harfrust::GlyphInfo],
glyph_positions: &[harfrust::GlyphPosition],
char_infos: &[(CharInfo, u16)],
char_indices_iter: I,
) -> f32 {
let mut char_indices_iter = char_indices_iter.peekable();
let mut cluster_start_char = char_indices_iter.next().unwrap();
let mut total_glyphs: u32 = 0;
let mut cluster_glyph_offset: u32 = 0;
let start_cluster_id = glyph_infos.first().unwrap().cluster;
let mut cluster_id = start_cluster_id;
let mut char_info = char_infos[cluster_id as usize];
let mut run_advance = 0.0;
let mut cluster_advance = 0.0;
// If the current cluster might be a single-glyph, zero-offset cluster, we defer
// pushing the first glyph to `glyphs` because it might be inlined into `ClusterData`.
let mut pending_inline_glyph: Option<Glyph> = None;
// The mental model for understanding this function is best grasped by first reading
// the HarfBuzz docs on [clusters](https://harfbuzz.github.io/working-with-harfbuzz-clusters.html).
//
// `num_components` is the number of characters in the current cluster. Since source text's characters
// were inserted into `HarfRust`'s buffer using their logical indices as the cluster ID, `HarfRust` will
// assign the first character's cluster ID (in logical order) to the merged cluster because the minimum
// ID is selected for [merging](https://github.com/harfbuzz/harfrust/blob/a38025fb336230b492366740c86021bb406bcd0d/src/hb/buffer.rs#L920-L924).
//
// So, the number of components in a given cluster is dependent on `direction`.
// - In LTR, `num_components` is the difference between the next cluster and the current cluster.
// - In RTL, `num_components` is the difference between the last cluster and the current cluster.
// This is because we must compare the current cluster to its next larger ID (in other words, the next
// logical index, which is visually downstream in LTR and visually upstream in RTL).
//
// For example, consider the LTR text for "afi" where "fi" form a ligature.
// Initial cluster values: 0, 1, 2 (logical + visual order)
// `HarfRust` assignation: 0, 1, 1
// Cluster count: 2
// `num_components`: (1 - 0 =) 1, (3 - 1 =) 2
//
// Now consider the RTL text for "ØØ¯Ø§Ù‹".
// Initial cluster values: 0, 1, 2, 3 (logical, or in-memory, order)
// Reversed cluster values: 3, 2, 1, 0 (visual order - the return order of `HarfRust` for RTL)
// `HarfRust` assignation: 3, 2, 0, 0
// Cluster count: 3
// `num_components`: (4 - 3 =) 1, (3 - 2 =) 1, (2 - 0 =) 2
let num_components =
|next_cluster: u32, current_cluster: u32, last_cluster: u32| match direction {
Direction::Ltr => next_cluster - current_cluster,
Direction::Rtl => last_cluster - current_cluster,
};
let mut last_cluster_id: u32 = match direction {
Direction::Ltr => 0,
Direction::Rtl => char_infos.len() as u32,
};
for (glyph_info, glyph_pos) in glyph_infos.iter().zip(glyph_positions.iter()) {
// Flush previous cluster if we've reached a new cluster
if cluster_id != glyph_info.cluster {
run_advance += cluster_advance;
let num_components = num_components(glyph_info.cluster, cluster_id, last_cluster_id);
cluster_advance /= num_components as f32;
let is_newline = to_whitespace(cluster_start_char.1) == Whitespace::Newline;
let cluster_type = if num_components > 1 {
debug_assert!(!is_newline);
ClusterType::LigatureStart
} else if is_newline {
ClusterType::Newline
} else {
ClusterType::Regular
};
let inline_glyph_id = if matches!(cluster_type, ClusterType::Regular) {
pending_inline_glyph.take().map(|g| g.id)
} else {
// This isn't a regular cluster, so we don't inline the glyph and push
// it to `glyphs`.
if let Some(pending) = pending_inline_glyph.take() {
glyphs.push(pending);
total_glyphs += 1;
}
None
};
push_cluster(
clusters,
char_info,
cluster_start_char,
cluster_glyph_offset,
cluster_advance,
total_glyphs,
cluster_type,
inline_glyph_id,
);
cluster_glyph_offset = total_glyphs;
if num_components > 1 {
// Skip characters until we reach the current cluster
for i in 1..num_components {
cluster_start_char = char_indices_iter.next().unwrap();
if to_whitespace(cluster_start_char.1) == Whitespace::Space {
break;
}
let char_info_ = match direction {
Direction::Ltr => char_infos[(cluster_id + i) as usize],
Direction::Rtl => char_infos[(cluster_id + num_components - i) as usize],
};
push_cluster(
clusters,
char_info_,
cluster_start_char,
cluster_glyph_offset,
cluster_advance,
total_glyphs,
ClusterType::LigatureComponent,
None,
);
}
}
cluster_start_char = char_indices_iter.next().unwrap();
cluster_advance = 0.0;
last_cluster_id = cluster_id;
cluster_id = glyph_info.cluster;
char_info = char_infos[cluster_id as usize];
pending_inline_glyph = None;
}
let glyph = Glyph {
id: glyph_info.glyph_id,
style_index: char_info.1,
x: (glyph_pos.x_offset as f32) * scale_factor,
// Convert from font space (Y-up) to layout space (Y-down)
y: -(glyph_pos.y_offset as f32) * scale_factor,
advance: (glyph_pos.x_advance as f32) * scale_factor,
};
cluster_advance += glyph.advance;
// Push any pending glyph. If it was a zero-offset, single glyph cluster, it would
// have been pushed in the first `if` block.
if let Some(pending) = pending_inline_glyph.take() {
glyphs.push(pending);
total_glyphs += 1;
}
if total_glyphs == cluster_glyph_offset && glyph.x == 0.0 && glyph.y == 0.0 {
// Defer this potential zero-offset, single glyph cluster
pending_inline_glyph = Some(glyph);
} else {
glyphs.push(glyph);
total_glyphs += 1;
}
}
// Push the last cluster
{
// See comment above `num_components` for why we use `char_infos.len()` for LTR and 0 for RTL.
let next_cluster_id = match direction {
Direction::Ltr => char_infos.len() as u32,
Direction::Rtl => 0,
};
let num_components = num_components(next_cluster_id, cluster_id, last_cluster_id);
if num_components > 1 {
// This is a ligature - create ligature start + ligature components
if let Some(pending) = pending_inline_glyph.take() {
glyphs.push(pending);
total_glyphs += 1;
}
let ligature_advance = cluster_advance / num_components as f32;
push_cluster(
clusters,
char_info,
cluster_start_char,
cluster_glyph_offset,
ligature_advance,
total_glyphs,
ClusterType::LigatureStart,
None,
);
cluster_glyph_offset = total_glyphs;
// Create ligature component clusters for the remaining characters
let mut i = 1;
for char in char_indices_iter {
if to_whitespace(char.1) == Whitespace::Space {
break;
}
let component_char_info = match direction {
Direction::Ltr => char_infos[(cluster_id + i) as usize],
Direction::Rtl => char_infos[(cluster_id + num_components - i) as usize],
};
push_cluster(
clusters,
component_char_info,
char,
cluster_glyph_offset,
ligature_advance,
total_glyphs,
ClusterType::LigatureComponent,
None,
);
i += 1;
}
} else {
let is_newline = to_whitespace(cluster_start_char.1) == Whitespace::Newline;
let cluster_type = if is_newline {
ClusterType::Newline
} else {
ClusterType::Regular
};
let mut inline_glyph_id = None;
match cluster_type {
ClusterType::Regular => {
if total_glyphs == cluster_glyph_offset {
if let Some(pending) = pending_inline_glyph.take() {
inline_glyph_id = Some(pending.id);
}
}
}
_ => {
if let Some(pending) = pending_inline_glyph.take() {
glyphs.push(pending);
total_glyphs += 1;
}
}
}
push_cluster(
clusters,
char_info,
cluster_start_char,
cluster_glyph_offset,
cluster_advance,
total_glyphs,
cluster_type,
inline_glyph_id,
);
}
}
run_advance
}
#[derive(PartialEq)]
enum Direction {
Ltr,
Rtl,
}
enum ClusterType {
LigatureStart,
LigatureComponent,
Regular,
Newline,
}
impl From<&ClusterType> for u16 {
fn from(cluster_type: &ClusterType) -> Self {
match cluster_type {
ClusterType::LigatureStart => ClusterData::LIGATURE_START,
ClusterType::LigatureComponent => ClusterData::LIGATURE_COMPONENT,
ClusterType::Regular | ClusterType::Newline => 0, // No special flags
}
}
}
fn push_cluster(
clusters: &mut Vec<ClusterData>,
char_info: (CharInfo, u16),
cluster_start_char: (usize, char),
glyph_offset: u32,
advance: f32,
total_glyphs: u32,
cluster_type: ClusterType,
inline_glyph_id: Option<u32>,
) {
let glyph_len = (total_glyphs - glyph_offset) as u8;
let (final_glyph_len, final_glyph_offset, final_advance) = match cluster_type {
ClusterType::LigatureComponent => {
// Ligature components have no glyphs, only advance.
debug_assert_eq!(glyph_len, 0);
(0_u8, 0_u32, advance)
}
ClusterType::Newline => {
// Newline clusters are stripped of their glyph contribution.
debug_assert_eq!(glyph_len, 1);
(0_u8, 0_u32, 0.0)
}
_ if inline_glyph_id.is_some() => {
// Inline glyphs are stored inline within `ClusterData`
debug_assert_eq!(glyph_len, 0);
(0xFF_u8, inline_glyph_id.unwrap(), advance)
}
ClusterType::Regular | ClusterType::LigatureStart => {
// Regular and ligature start clusters maintain their glyphs and advance.
debug_assert_ne!(glyph_len, 0);
(glyph_len, glyph_offset, advance)
}
};
clusters.push(ClusterData {
info: ClusterInfo::new(char_info.0.boundary, cluster_start_char.1),
flags: (&cluster_type).into(),
style_index: char_info.1,
glyph_len: final_glyph_len,
text_len: cluster_start_char.1.len_utf8() as u8,
glyph_offset: final_glyph_offset,
text_offset: cluster_start_char.0 as u16,
advance: final_advance,
});
}