incular-text 0.1.0

Text layout and typography foundations for Incular
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
//! Parley-backed text shaping, fallback, bidi ordering, and line breaking.
//!
//! Incular deliberately keeps its renderer-facing glyph protocol small. Parley
//! owns all font discovery, fallback selection and shaping; this module only
//! translates its positioned glyph runs into `incular-rendering` commands.

use super::{FontFamily, FontStyle, TextAffinity, TextAlign, TextOverflow, TextStyle};
use icu_segmenter::GraphemeClusterSegmenter;
pub use incular_assets::FontId;
use incular_assets::{FontBytes, FontHandle};
use incular_core::{Offset, Size};
use incular_rendering::{GlyphPosition, GlyphRun};
use parley::{
    Alignment, AlignmentOptions, FontContext, FontStack, FontWeight as ParleyFontWeight, Layout,
    LayoutContext, PositionedLayoutItem, StyleProperty,
};
use std::{
    borrow::Cow,
    collections::{HashMap, HashSet, VecDeque, hash_map::DefaultHasher},
    hash::{Hash, Hasher},
    sync::{Arc, OnceLock},
};

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextMetrics {
    pub size: Size,
    pub baseline: f32,
    pub line_height: f32,
}

/// One shaped cluster's visual span on a line, in text-area coordinates
/// with `left <= right`. Spans follow visual order, so a logical byte
/// range can cover several disjoint spans in mixed-direction text.
/// Consumers merge spans intersecting a selection instead of assuming
/// the range maps to one rectangle. Zero-advance clusters are kept because
/// they still own caret stops; selection ignores them.
#[derive(Clone, Copy, Debug)]
pub struct TextClusterSpan {
    pub start: usize,
    pub end: usize,
    pub left: f32,
    pub right: f32,
    /// Whether the cluster belongs to a right-to-left run.
    pub rtl: bool,
}

impl TextLine {
    /// Visual x-intervals covered by a half-open logical byte range on
    /// this line. Collapsed and reversed ranges yield nothing by
    /// policy; callers pass normalized ranges and never rely on
    /// rejection. Caret rendering stays separate: collapsed positions
    /// highlight nothing here and resolve through caret stops instead.
    ///
    /// Four granularities meet here and are not interchangeable: the
    /// range arrives in UTF-8 bytes (clamped to char boundaries
    /// upstream, so mid-char bytes never arrive); shaping clusters are
    /// the coverage granularity (a range splitting a cluster expands
    /// to the whole shaped cluster, since no visual edge exists
    /// inside it); visual order comes from the stored spans, never
    /// from re-sorting bytes or glyphs downstream. Touching spans
    /// merge; genuinely disjoint spans stay separate. An empty line
    /// covered by a nonempty range yields its caret point. Observed
    /// clusters here are char-or-finer, so wider-than-grapheme
    /// clusters would follow the same rule untested.
    #[must_use]
    pub fn selection_spans(&self, start: usize, end: usize) -> Vec<(f32, f32)> {
        if start >= end {
            return Vec::new();
        }
        let mut spans: Vec<(f32, f32)> = self
            .clusters
            .iter()
            .filter(|span| span.left < span.right && span.start < end && start < span.end)
            .map(|span| (span.left, span.right))
            .collect();
        if spans.is_empty() && self.start == self.end && start <= self.start && self.end <= end {
            spans.push((self.offset, self.offset));
        }
        spans.sort_by(|left, right| left.0.total_cmp(&right.0));
        let mut merged: Vec<(f32, f32)> = Vec::with_capacity(spans.len());
        for (left, right) in spans {
            if let Some(last) = merged.last_mut()
                && left <= last.1
            {
                last.1 = last.1.max(right);
            } else {
                merged.push((left, right));
            }
        }
        merged
    }
}

#[derive(Clone, Debug)]
pub struct TextLine {
    pub runs: Arc<[Arc<GlyphRun>]>,
    pub glyphs: Arc<[GlyphPosition]>,
    pub clusters: Arc<[TextClusterSpan]>,
    pub width: f32,
    /// Horizontal alignment offset in text-area coordinates. Glyph and
    /// caret x positions already include it; `width` stays the unshifted
    /// advance so extent checks keep working. Consumers mapping absolute
    /// x positions must add this to `width` instead of re-deriving the
    /// alignment.
    pub offset: f32,
    pub baseline: f32,
    pub start: usize,
    /// End of selectable/caret text on this visual line. This excludes a
    /// trailing hard line-break which has no shaped glyph of its own.
    pub caret_end: usize,
    pub end: usize,
}

#[derive(Clone, Debug)]
pub struct FontRunDebug {
    pub range: std::ops::Range<usize>,
    pub font: FontId,
    pub direction: &'static str,
}

/// A visual insertion point emitted by the shaping engine.
///
/// A logical byte offset can have two distinct visual positions at a bidi run
/// boundary. `affinity` keeps those positions separate, matching the concept
/// used by Parley's cursor implementation and preventing an arrow key from
/// jumping through a right-to-left run in logical UTF-8 order.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextCaretPosition {
    pub offset: usize,
    pub affinity: TextAffinity,
    pub x: f32,
    pub line: usize,
}

#[derive(Clone, Debug)]
struct ClusterPosition {
    range: std::ops::Range<usize>,
    left: f32,
    right: f32,
    rtl: bool,
    ligature_start: bool,
    ligature_continuation: bool,
}

impl ClusterPosition {
    fn include(&mut self, other: &Self) {
        self.range.start = self.range.start.min(other.range.start);
        self.range.end = self.range.end.max(other.range.end);
        self.left = self.left.min(other.left);
        self.right = self.right.max(other.right);
        self.ligature_start |= other.ligature_start;
        self.ligature_continuation |= other.ligature_continuation;
    }

    fn can_join(&self, other: &Self) -> bool {
        self.rtl == other.rtl
            && if self.rtl {
                other.range.end == self.range.start
            } else {
                self.range.end == other.range.start
            }
    }
}

#[derive(Clone, Debug)]
pub struct TextLayout {
    pub lines: Arc<[TextLine]>,
    pub metrics: TextMetrics,
    pub font_runs: Arc<[FontRunDebug]>,
    /// Caret stops of every line, derived from the line clusters on first
    /// use: only editing and selection need them.
    caret_positions: OnceLock<Arc<[TextCaretPosition]>>,
    /// Whether the source had content outside the retained layout's visible
    /// bounds. `Visible` layouts deliberately leave this false.
    pub overflowed: bool,
}

/// Paragraph-level layout controls. They deliberately describe behavior in
/// Incular terms and do not expose Parley builder types.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextLayoutOptions {
    pub max_width: Option<f32>,
    pub align: TextAlign,
    pub soft_wrap: bool,
    pub max_lines: Option<usize>,
    pub overflow: TextOverflow,
}

impl TextLayoutOptions {
    #[must_use]
    pub const fn new(max_width: Option<f32>, align: TextAlign) -> Self {
        Self {
            max_width,
            align,
            soft_wrap: true,
            max_lines: None,
            overflow: TextOverflow::Clip,
        }
    }

    #[must_use]
    pub const fn soft_wrap(mut self, soft_wrap: bool) -> Self {
        self.soft_wrap = soft_wrap;
        self
    }

    #[must_use]
    pub const fn max_lines(mut self, max_lines: Option<usize>) -> Self {
        self.max_lines = max_lines;
        self
    }

    #[must_use]
    pub const fn overflow(mut self, overflow: TextOverflow) -> Self {
        self.overflow = overflow;
        self
    }
}

impl Default for TextLayoutOptions {
    fn default() -> Self {
        Self::new(None, TextAlign::Start)
    }
}

impl TextLayout {
    #[must_use]
    pub fn glyph_count(&self) -> usize {
        self.lines.iter().map(|line| line.glyphs.len()).sum()
    }

    /// Returns the visual insertion points for one laid-out line in
    /// left-to-right screen order.
    #[must_use]
    pub fn line_caret_positions(&self, line: usize) -> &[TextCaretPosition] {
        let caret_positions = self
            .caret_positions
            .get_or_init(|| self.derive_caret_positions());
        let Some(start) = caret_positions
            .iter()
            .position(|position| position.line == line)
        else {
            return &[];
        };
        let end = start
            + caret_positions
                .iter()
                .skip(start)
                .take_while(|position| position.line == line)
                .count();
        &caret_positions[start..end]
    }

    /// Two stops per cluster (logical start and end, placed by direction),
    /// plus the line's start and caret end when no cluster supplies them,
    /// sorted into screen order.
    fn derive_caret_positions(&self) -> Arc<[TextCaretPosition]> {
        let mut positions = Vec::new();
        for (index, line) in self.lines.iter().enumerate() {
            let stop = |offset, affinity, x| TextCaretPosition {
                offset,
                affinity,
                x,
                line: index,
            };
            let first = positions.len();
            for cluster in line.clusters.iter() {
                let (left, right) = if cluster.rtl {
                    (cluster.end, cluster.start)
                } else {
                    (cluster.start, cluster.end)
                };
                let (left_affinity, right_affinity) = if cluster.rtl {
                    (TextAffinity::Upstream, TextAffinity::Downstream)
                } else {
                    (TextAffinity::Downstream, TextAffinity::Upstream)
                };
                positions.push(stop(left, left_affinity, cluster.left));
                positions.push(stop(right, right_affinity, cluster.right));
            }
            let line_stops = &positions[first..];
            if !line_stops.iter().any(|stop| stop.offset == line.start) {
                positions.push(stop(line.start, TextAffinity::Downstream, line.offset));
            }
            if line.caret_end > line.start
                && !positions[first..]
                    .iter()
                    .any(|stop| stop.offset == line.caret_end)
            {
                positions.push(stop(
                    line.caret_end,
                    TextAffinity::Upstream,
                    line.offset + line.width,
                ));
            }
            positions[first..].sort_by(|left, right| {
                left.x
                    .total_cmp(&right.x)
                    .then_with(|| left.offset.cmp(&right.offset))
            });
        }
        positions.into()
    }
}

/// Layout/cache counters. Legacy field names are retained for source
/// compatibility; Parley performs fallback and coverage resolution internally.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TextDiagnostics {
    pub layouts_requested: u64,
    pub cache_hits: u64,
    pub cache_misses: u64,
    pub font_resolution_requests: u64,
    pub font_resolution_cache_hits: u64,
    pub font_resolution_cache_misses: u64,
    pub coverage_queries: u64,
    pub fallback_runs: u64,
    pub fallback_fonts_used: u64,
    pub missing_clusters: u64,
    pub shaping_runs: u64,
    // Task 15 document-granularity instrumentation.
    /// Paragraphs examined by the document path.
    pub paragraphs_considered: u64,
    /// Paragraphs that required fresh shaping (cache misses at paragraph
    /// granularity).
    pub paragraphs_reshaped: u64,
    /// Parley layouts satisfied entirely from cache.
    pub parley_layouts_reused: u64,
    /// Multi-paragraph documents assembled from retained paragraphs.
    pub documents_composed: u64,
}

#[derive(Hash, PartialEq, Eq)]
struct LayoutKey {
    text: String,
    family: FontFamily,
    fallbacks: Arc<[FontFamily]>,
    size: u32,
    weight: u16,
    style: FontStyle,
    line_height: Option<(u8, u32)>,
    letter_spacing: u32,
    font_variations: Option<Arc<str>>,
    font_features: Option<Arc<str>>,
    width: Option<u32>,
    align: TextAlign,
    soft_wrap: bool,
    max_lines: Option<usize>,
    overflow: TextOverflow,
    generation: u64,
}

impl LayoutKey {
    fn new(text: &str, style: &TextStyle, options: TextLayoutOptions, generation: u64) -> Self {
        Self {
            text: text.into(),
            family: style.family.clone(),
            fallbacks: style.fallback_families.clone(),
            size: style.size.to_bits(),
            weight: style.weight.0,
            style: style.style,
            line_height: style.line_height.map(|lh| match lh {
                crate::LineHeight::Normal => (0, 0),
                crate::LineHeight::Multiplier(m) => (1, m.to_bits()),
                crate::LineHeight::Absolute(a) => (2, a.to_bits()),
            }),
            letter_spacing: style.letter_spacing.to_bits(),
            font_variations: style.font_variations.clone(),
            font_features: style.font_features.clone(),
            width: options.max_width.map(f32::to_bits),
            align: options.align,
            soft_wrap: options.soft_wrap,
            max_lines: options.max_lines,
            overflow: options.overflow,
            generation,
        }
    }
}

/// The sole owner of font discovery and app-registered fonts. Parley owns the
/// actual font collection and resolves scripts, bidi direction and fallback.
pub struct TextEngine {
    /// One `FontHandle` per distinct font blob. Handles share the font bytes
    /// through a single `Arc`, so every cached text layout references the
    /// same allocation instead of holding a private copy of the whole font
    /// file (the Task 15 root cause of ~500 KB retained per shaped string
    /// and a full-file memcpy plus full-file hash per glyph run).
    font_handles: HashMap<(usize, usize, u32), FontHandle>,
    font_context: FontContext,
    layout_context: LayoutContext<()>,
    generation: u64,
    cache: HashMap<Arc<LayoutKey>, Arc<TextLayout>>,
    order: VecDeque<Arc<LayoutKey>>,
    diagnostics: TextDiagnostics,
}

impl Default for TextEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl TextEngine {
    #[must_use]
    pub fn new() -> Self {
        Self {
            font_handles: HashMap::new(),
            font_context: FontContext::new(),
            layout_context: LayoutContext::new(),
            generation: 1,
            cache: HashMap::new(),
            order: VecDeque::new(),
            diagnostics: TextDiagnostics::default(),
        }
    }

    #[must_use]
    pub const fn diagnostics(&self) -> TextDiagnostics {
        self.diagnostics
    }

    #[must_use]
    pub const fn font_database_generation(&self) -> u64 {
        self.generation
    }

    /// Registers all faces in a TrueType/OpenType byte buffer with Parley's
    /// Fontique collection. Invalid buffers are harmless: Fontique ignores
    /// them, while the generation still invalidates stale cached layouts.
    pub fn register_font_bytes(&mut self, bytes: impl Into<Vec<u8>>) {
        self.font_context
            .collection
            .register_fonts(parley::fontique::Blob::from(bytes.into()), None);
        self.generation = self
            .generation
            .checked_add(1)
            .expect("font database generation exhausted");
        self.cache.clear();
        self.order.clear();
    }

    pub fn layout(
        &mut self,
        text: &str,
        style: &TextStyle,
        max_width: Option<f32>,
        align: TextAlign,
    ) -> Arc<TextLayout> {
        self.layout_with_options(text, style, TextLayoutOptions::new(max_width, align))
    }

    /// Shapes a paragraph with retained wrapping and overflow policy.
    pub fn layout_with_options(
        &mut self,
        text: &str,
        style: &TextStyle,
        options: TextLayoutOptions,
    ) -> Arc<TextLayout> {
        self.diagnostics.layouts_requested += 1;
        // Documents with hard line breaks compose from retained per-paragraph
        // layouts so editing one paragraph never reshapes the rest. Overflow
        // policies keep the exact monolithic semantics and stay on the
        // whole-string path.
        // With soft wrapping, `Clip` can only trigger on single-line
        // horizontal overflow, which a hard-break document never has; so this
        // route preserves monolithic semantics exactly.
        if text.contains('\n')
            && options.max_lines.is_none()
            && (options.soft_wrap || options.overflow == TextOverflow::Visible)
        {
            let layout = self.layout_document(text, style, options);
            return Arc::new(layout);
        }
        let key = LayoutKey::new(text, style, options, self.generation);
        if let Some(layout) = self.cache.get(&key) {
            self.diagnostics.cache_hits += 1;
            return layout.clone();
        }

        self.diagnostics.cache_misses += 1;
        let layout = Arc::new(self.shape_and_wrap(text, style, options));
        self.store(key, layout.clone());
        layout
    }

    /// FIFO insertion with the measured pool size. The previous 256-entry cap
    /// thrashed under large-document workloads (Task 15 profiling).
    fn store(&mut self, key: LayoutKey, layout: Arc<TextLayout>) {
        const LAYOUT_CACHE_CAPACITY: usize = 2048;
        if self.order.len() == LAYOUT_CACHE_CAPACITY
            && let Some(old) = self.order.pop_front()
        {
            self.cache.remove(old.as_ref());
        }
        // The queue and map own the same key allocation. Cloning LayoutKey here
        // used to duplicate its text (and any owned family) for every entry.
        let key = Arc::new(key);
        self.order.push_back(key.clone());
        self.cache.insert(key, layout);
    }

    /// Composes a multi-paragraph document from per-paragraph retained
    /// layouts. Shaping reuse is exact (paragraph slice == cache key);
    /// assembly copies line data with vertical and byte-range rebasing.
    fn layout_document(
        &mut self,
        text: &str,
        style: &TextStyle,
        options: TextLayoutOptions,
    ) -> TextLayout {
        self.diagnostics.documents_composed += 1;
        let paragraph_options = TextLayoutOptions {
            max_lines: None,
            overflow: TextOverflow::Visible,
            ..options
        };
        let mut byte_start = 0usize;
        let mut lines: Vec<TextLine> = Vec::new();
        let mut font_runs = Vec::new();
        let mut width = 0f32;
        let mut height = 0f32;
        let mut line_height = 0f32;
        let mut overflowed = false;
        for paragraph in text.split('\n') {
            self.diagnostics.paragraphs_considered += 1;
            let key = LayoutKey::new(paragraph, style, paragraph_options, self.generation);
            let paragraph_layout = if let Some(existing) = self.cache.get(&key) {
                self.diagnostics.parley_layouts_reused += 1;
                self.diagnostics.cache_hits += 1;
                existing.clone()
            } else {
                self.diagnostics.paragraphs_reshaped += 1;
                self.diagnostics.cache_misses += 1;
                let built = Arc::new(self.shape_and_wrap(paragraph, style, paragraph_options));
                self.store(key, built.clone());
                built
            };
            // Font-run metadata belongs to the paragraph, not each visual line.
            // Rebase it once even when soft wrapping creates multiple lines.
            for run in paragraph_layout.font_runs.iter() {
                let mut rebased = run.clone();
                rebased.range.start += byte_start;
                rebased.range.end += byte_start;
                font_runs.push(rebased);
            }
            for line in paragraph_layout.lines.iter() {
                let glyphs: Vec<GlyphPosition> = line
                    .glyphs
                    .iter()
                    .map(|glyph| {
                        let mut shifted = *glyph;
                        // Stored glyph y is negative parley space; moving the
                        // paragraph down by `height` subtracts from it.
                        shifted.offset.y -= height;
                        // Clusters index the full document string, so caret
                        // and selection mapping stay globally consistent.
                        shifted.cluster += byte_start as u32;
                        shifted
                    })
                    .collect();
                let shifted_runs: Vec<Arc<GlyphRun>> = line
                    .runs
                    .iter()
                    .map(|run| {
                        let mut shifted = (**run).clone();
                        shifted.origin.y += height;
                        Arc::new(shifted)
                    })
                    .collect();
                lines.push(TextLine {
                    runs: shifted_runs.into(),
                    glyphs: glyphs.into(),
                    clusters: line
                        .clusters
                        .iter()
                        .map(|span| TextClusterSpan {
                            start: span.start + byte_start,
                            end: span.end + byte_start,
                            left: span.left,
                            right: span.right,
                            rtl: span.rtl,
                        })
                        .collect(),
                    width: line.width,
                    offset: line.offset,
                    baseline: line.baseline + height,
                    start: line.start + byte_start,
                    caret_end: line.caret_end + byte_start,
                    end: line.end + byte_start,
                });
            }
            width = width.max(paragraph_layout.metrics.size.width);
            height += paragraph_layout.metrics.size.height;
            line_height = paragraph_layout.metrics.line_height;
            overflowed |= paragraph_layout.overflowed;
            byte_start += paragraph.len() + 1; // include the hard break
        }
        if lines.is_empty() {
            lines.push(TextLine {
                runs: Arc::new([]),
                glyphs: Arc::new([]),
                clusters: Arc::new([]),
                width: 0.,
                offset: 0.,
                baseline: 0.,
                start: 0,
                caret_end: 0,
                end: 0,
            });
        }
        let baseline = lines[0].baseline;
        TextLayout {
            lines: lines.into(),
            metrics: TextMetrics {
                size: Size::new(width, height),
                baseline,
                line_height,
            },
            font_runs: font_runs.into(),
            caret_positions: OnceLock::new(),
            overflowed,
        }
    }

    fn font_stack(style: &TextStyle) -> FontStack<'static> {
        let mut names = vec![family_name(&style.family)];
        names.extend(style.fallback_families.iter().map(family_name));
        FontStack::Source(names.join(", ").into())
    }

    fn shape_and_wrap(
        &mut self,
        text: &str,
        style: &TextStyle,
        options: TextLayoutOptions,
    ) -> TextLayout {
        let wrap_width = options.soft_wrap.then_some(options.max_width).flatten();
        let layout = self.shape_raw(text, style, wrap_width, options.max_width, options.align);
        let horizontal_overflow = !options.soft_wrap
            && options
                .max_width
                .is_some_and(|width| layout.metrics.size.width > width);
        let line_limit = options
            .max_lines
            .or_else(|| horizontal_overflow.then_some(1));
        let line_overflow = line_limit.is_some_and(|limit| layout.lines.len() > limit);
        if (!horizontal_overflow && !line_overflow) || options.overflow == TextOverflow::Visible {
            return layout;
        }

        let limit = line_limit.unwrap_or(layout.lines.len());
        match options.overflow {
            TextOverflow::Visible => layout,
            TextOverflow::Clip | TextOverflow::Fade => clipped_layout(layout, limit),
            TextOverflow::Ellipsis => self.ellipsized_layout(text, style, options, limit),
        }
    }

    fn ellipsized_layout(
        &mut self,
        text: &str,
        style: &TextStyle,
        options: TextLayoutOptions,
        limit: usize,
    ) -> TextLayout {
        if limit == 0 {
            return clipped_layout(
                self.shape_raw("", style, None, options.max_width, options.align),
                0,
            );
        }
        let wrap_width = options.soft_wrap.then_some(options.max_width).flatten();
        let initial = self.shape_raw(text, style, wrap_width, options.max_width, options.align);
        let end = initial
            .lines
            .get(limit.saturating_sub(1))
            .map_or(0, |line| line.caret_end.min(text.len()));
        let mut end = grapheme_boundary_at_or_before(text, end);

        loop {
            let mut candidate = text[..end].to_owned();
            candidate.push('\u{2026}');
            // The ellipsis always enters Parley as source text and is shaped
            // with the selected/fallback font stack, never appended as a raw
            // renderer glyph or a byte-truncated source suffix.
            let shaped = self.shape_raw(
                &candidate,
                style,
                wrap_width,
                options.max_width,
                options.align,
            );
            let fits_width = options.max_width.is_none_or(|width| {
                shaped
                    .lines
                    .iter()
                    .all(|line| line.width <= width + f32::EPSILON)
            });
            if shaped.lines.len() <= limit && fits_width {
                return TextLayout {
                    overflowed: true,
                    ..shaped
                };
            }
            let previous = previous_grapheme_boundary(text, end);
            if previous == end {
                return TextLayout {
                    overflowed: true,
                    ..shaped
                };
            }
            end = previous;
        }
    }

    fn shape_raw(
        &mut self,
        text: &str,
        style: &TextStyle,
        max_width: Option<f32>,
        align_width: Option<f32>,
        align: TextAlign,
    ) -> TextLayout {
        let mut builder =
            self.layout_context
                .ranged_builder(&mut self.font_context, text, 1.0, true);
        builder.push_default(StyleProperty::FontStack(Self::font_stack(style)));
        builder.push_default(StyleProperty::FontSize(style.size.max(0.0)));
        builder.push_default(StyleProperty::FontWeight(ParleyFontWeight::new(
            style.weight.0 as f32,
        )));
        builder.push_default(StyleProperty::FontStyle(match style.style {
            FontStyle::Normal => parley::FontStyle::Normal,
            FontStyle::Italic => parley::FontStyle::Italic,
        }));
        builder.push_default(StyleProperty::LetterSpacing(style.letter_spacing));
        if let Some(settings) = &style.font_variations {
            builder.push_default(StyleProperty::FontVariations(parley::FontSettings::Source(
                Cow::Owned(settings.to_string()),
            )));
        }
        if let Some(settings) = &style.font_features {
            builder.push_default(StyleProperty::FontFeatures(parley::FontSettings::Source(
                Cow::Owned(settings.to_string()),
            )));
        }
        if let Some(line_height) = style.line_height
            && let Some(parley_lh) = line_height.to_parley(style.size)
        {
            builder.push_default(StyleProperty::LineHeight(parley_lh));
        }

        let mut layout: Layout<()> = builder.build(text);
        layout.break_all_lines(max_width);
        // Alignment resolves against the measured width even when the text
        // does not wrap: single-line content otherwise ignores alignment
        // because the wrap width is empty.
        layout.align(
            align_width,
            match align {
                TextAlign::Start => Alignment::Start,
                TextAlign::Center => Alignment::Center,
                TextAlign::End => Alignment::End,
                TextAlign::Justify => Alignment::Justify,
            },
            AlignmentOptions::default(),
        );

        self.translate_layout(&layout, text)
    }

    fn font_handle_for(&mut self, font: &parley::FontData) -> FontHandle {
        font_handle(self, font)
    }

    fn translate_layout(&mut self, layout: &Layout<()>, text: &str) -> TextLayout {
        let mut lines = Vec::new();
        let mut font_runs = Vec::new();
        let mut used_fonts = HashSet::new();
        // First glyph run decides the primary font; resolve its handle before
        // the mutable translation loop so borrowck stays trivial.
        let primary_handle = layout
            .lines()
            .flat_map(|line| line.runs())
            .next()
            .map(|run| self.font_handle_for(run.font()));
        let primary = primary_handle.as_ref().map(FontHandle::id);

        for line in layout.lines() {
            let metrics = line.metrics();
            let range = line.text_range();
            let mut runs: Vec<Arc<GlyphRun>> = Vec::new();
            let mut glyphs = Vec::new();
            let mut caret_end = range.start;
            // Walk Parley's visual cluster advances once for the whole line.
            // This is the same cell geometry Parley uses for hit testing and
            // accounts for per-cluster spacing and justified advances. A
            // source cluster can be split across font/style glyph runs, so
            // merge duplicate byte ranges into one logical span and caret
            // pair here rather than deriving cells separately per glyph run.
            let mut cluster_positions: Vec<ClusterPosition> = Vec::new();
            let mut cluster_position_index: HashMap<(usize, usize), usize> = HashMap::new();
            let mut cluster_x = metrics.offset;
            for run in line.runs() {
                let rtl = run.is_rtl();
                for cluster in run.visual_clusters() {
                    let cluster_range = cluster.text_range();
                    // Invisible continuation clusters still own source bytes.
                    // Keep the logical line endpoint through their ranges so
                    // a final ligature component does not lose its caret stop.
                    caret_end = caret_end.max(cluster_range.end);
                    let edge = cluster_x + cluster.advance();
                    let ligature_start = cluster.is_ligature_start();
                    let ligature_continuation = cluster.is_ligature_continuation();
                    let mut cluster_glyphs = cluster.glyphs();
                    let Some(first_glyph) = cluster_glyphs.next() else {
                        // A shaping cluster can carry advance for an
                        // invisible continuation. Ligature components remain
                        // part of the start cluster's selectable range, while
                        // standalone join controls have no visible selection
                        // geometry of their own.
                        let is_join_control =
                            text.get(cluster_range.clone()).is_some_and(|component| {
                                !component.is_empty()
                                    && component.chars().all(|character| {
                                        matches!(character, '\u{200C}' | '\u{200D}')
                                    })
                            });
                        if ligature_continuation && !is_join_control {
                            let position = ClusterPosition {
                                range: cluster_range.clone(),
                                left: cluster_x.min(edge),
                                right: cluster_x.max(edge),
                                rtl,
                                ligature_start,
                                ligature_continuation,
                            };
                            let key = (cluster_range.start, cluster_range.end);
                            if let Some(index) = cluster_position_index.get(&key).copied() {
                                cluster_positions[index].include(&position);
                            } else {
                                cluster_position_index.insert(key, cluster_positions.len());
                                cluster_positions.push(position);
                            }
                        }
                        cluster_x = edge;
                        continue;
                    };
                    let glyph_advance = std::iter::once(first_glyph)
                        .chain(cluster_glyphs)
                        .map(|glyph| glyph.advance)
                        .sum::<f32>();
                    // Ligature components can share a larger glyph advance
                    // than their divided cluster advances; retain the glyph's
                    // full cell so no caret or selection edge lands inside
                    // that ligature. Justification and letter spacing can
                    // also grow the cluster cell beyond its raw glyphs.
                    let visible_edge = cluster_x + cluster.advance().max(glyph_advance);
                    let left = cluster_x.min(visible_edge);
                    let right = cluster_x.max(visible_edge);
                    let position = ClusterPosition {
                        range: cluster_range.clone(),
                        left,
                        right,
                        rtl,
                        ligature_start,
                        ligature_continuation,
                    };
                    let key = (cluster_range.start, cluster_range.end);
                    if let Some(index) = cluster_position_index.get(&key).copied() {
                        cluster_positions[index].include(&position);
                    } else {
                        cluster_position_index.insert(key, cluster_positions.len());
                        cluster_positions.push(position);
                    }
                    cluster_x = edge;
                }
            }
            for item in line.items() {
                let PositionedLayoutItem::GlyphRun(parley_run) = item else {
                    continue;
                };
                let run = parley_run.run();
                let font = self.font_handle_for(run.font());
                let font_id = font.id();
                if Some(font_id) != primary {
                    self.diagnostics.fallback_runs += 1;
                }
                used_fonts.insert(font_id);
                self.diagnostics.shaping_runs += 1;

                // `PositionedLayoutItem::GlyphRun` is a line-local slice of
                // the underlying shaping run. Parley's renderer-facing Glyph
                // intentionally has no byte index, so recover each glyph's
                // cluster from the authoritative visual-cluster sequence
                // before translating it. This keeps caret movement and
                // selection on shaped cluster boundaries instead of assigning
                // every glyph to the run's first byte.
                //
                // Order and cardinality correspond structurally, not by
                // length coincidence: `glyphs()` and `positioned_glyphs()`
                // both iterate `Run::visual_clusters().flat_map(glyphs)`,
                // the latter only adding running x (which already carries
                // the line offset). The window below re-locates this
                // style-uniform slice within that same sequence, so the
                // zip pairs each positioned glyph with its own cluster
                // for RTL runs, ligatures, and multi-glyph clusters alike.
                let visible_glyphs = parley_run.glyphs().collect::<Vec<_>>();
                let all_clustered_glyphs = run
                    .visual_clusters()
                    .flat_map(|cluster| {
                        let cluster_range = cluster.text_range();
                        cluster
                            .glyphs()
                            .map(move |glyph| (glyph, cluster_range.clone()))
                    })
                    .collect::<Vec<_>>();
                let first_glyph = all_clustered_glyphs
                    .windows(visible_glyphs.len())
                    .position(|candidate| {
                        candidate
                            .iter()
                            .zip(&visible_glyphs)
                            .all(|((glyph, _), visible)| glyph == visible)
                    })
                    .unwrap_or(0);
                let clusters = all_clustered_glyphs
                    .iter()
                    .skip(first_glyph)
                    .map(|(_, range)| range.clone())
                    .take(visible_glyphs.len())
                    .collect::<Vec<_>>();
                let positions: Vec<_> = parley_run
                    .positioned_glyphs()
                    .zip(
                        clusters
                            .iter()
                            .map(|range| range.start as u32)
                            .chain(std::iter::repeat(run.text_range().start as u32)),
                    )
                    .map(|(glyph, cluster)| GlyphPosition {
                        id: glyph.id as u16,
                        // Incular's renderer uses `origin.y - offset.y`; Parley
                        // exposes glyph y from its top-left layout coordinate.
                        // Parley seeds positioned glyph x with the line
                        // alignment offset, so adding it again would translate
                        // aligned text twice.
                        offset: Offset::new(glyph.x, -glyph.y),
                        advance: glyph.advance,
                        cluster,
                    })
                    .collect();
                if runs.len() == 1 {
                    glyphs.extend(runs[0].glyphs.iter().copied());
                }
                if !runs.is_empty() {
                    glyphs.extend(positions.iter().copied());
                }
                runs.push(Arc::new(GlyphRun {
                    font,
                    font_size: run.font_size(),
                    origin: Offset::ZERO,
                    glyphs: positions.into(),
                }));
                font_runs.push(FontRunDebug {
                    range: run.text_range(),
                    font: font_id,
                    direction: if run.is_rtl() { "rtl" } else { "ltr" },
                });
            }
            // Every merged cluster, including zero-advance ones that only
            // carry caret stops; the layout derives its stops from these.
            let cluster_spans: Vec<_> = merge_ligature_components(cluster_positions)
                .iter()
                .map(|position| TextClusterSpan {
                    start: position.range.start,
                    end: position.range.end,
                    left: position.left,
                    right: position.right,
                    rtl: position.rtl,
                })
                .collect();
            // The common one-run line has exactly the same positioned glyphs
            // for caret handling and painting. Share the immutable allocation
            // instead of retaining a second copy in TextLine.
            let glyphs = if runs.len() == 1 {
                runs[0].glyphs.clone()
            } else {
                glyphs.into()
            };
            lines.push(TextLine {
                runs: runs.into(),
                glyphs,
                clusters: cluster_spans.into(),
                width: metrics.advance,
                offset: metrics.offset,
                baseline: metrics.baseline,
                start: range.start,
                caret_end,
                end: range.end,
            });
        }

        if lines.is_empty() {
            lines.push(TextLine {
                runs: Arc::new([]),
                glyphs: Arc::new([]),
                clusters: Arc::new([]),
                width: 0.0,
                offset: 0.0,
                baseline: 0.0,
                start: 0,
                caret_end: 0,
                end: 0,
            });
        }
        self.diagnostics.fallback_fonts_used += used_fonts.len().saturating_sub(1) as u64;
        let baseline = lines[0].baseline;
        let line_height = layout
            .lines()
            .next()
            .map_or(0.0, |line| line.metrics().line_height);
        TextLayout {
            lines: lines.into(),
            metrics: TextMetrics {
                size: Size::new(layout.width(), layout.height()),
                baseline,
                line_height,
            },
            font_runs: font_runs.into(),
            caret_positions: OnceLock::new(),
            overflowed: false,
        }
    }
}

/// Coalesces Parley's glyphless ligature components with their rendered
/// cluster. Visual cluster iteration is forward for LTR runs and reversed for
/// RTL runs, so the component sequence starts at opposite ends of a ligature
/// in each direction.
fn merge_ligature_components(positions: Vec<ClusterPosition>) -> Vec<ClusterPosition> {
    let mut merged = Vec::with_capacity(positions.len());
    let mut pending: Option<ClusterPosition> = None;
    let mut pending_has_start = false;

    for position in positions {
        let is_start = position.ligature_start;
        let is_continuation = position.ligature_continuation;
        if !is_start && !is_continuation {
            if let Some(pending) = pending.take() {
                merged.push(pending);
            }
            pending_has_start = false;
            merged.push(position);
            continue;
        }
        // A single source cluster can already cover the whole ligature.
        if is_start && is_continuation {
            if let Some(pending) = pending.take() {
                merged.push(pending);
            }
            pending_has_start = false;
            merged.push(position);
            continue;
        }

        if position.rtl {
            if is_continuation {
                // In visual RTL order, continuations precede their start. A
                // continuation after a completed group begins the next one.
                if pending_has_start {
                    if let Some(pending) = pending.take() {
                        merged.push(pending);
                    }
                    pending_has_start = false;
                }
                let can_extend = pending
                    .as_ref()
                    .is_some_and(|pending| pending.can_join(&position));
                if can_extend {
                    pending
                        .as_mut()
                        .expect("checked pending ligature group")
                        .include(&position);
                } else {
                    if let Some(pending) = pending.take() {
                        merged.push(pending);
                    }
                    pending_has_start = false;
                    pending = Some(position);
                }
            } else {
                // The start completes the pending continuation group.
                match pending.take() {
                    Some(mut pending_group)
                        if !pending_has_start && pending_group.can_join(&position) =>
                    {
                        pending_group.include(&position);
                        merged.push(pending_group);
                    }
                    Some(pending_group) => {
                        merged.push(pending_group);
                        merged.push(position);
                    }
                    None => merged.push(position),
                }
                pending_has_start = false;
            }
        } else if is_start {
            if let Some(pending) = pending.take() {
                merged.push(pending);
            }
            pending = Some(position);
            pending_has_start = true;
        } else if pending.is_some() {
            // LTR starts precede their continuations in visual order. The
            // byte check prevents an excluded join control from being
            // bridged by a later glyphless continuation.
            if pending
                .as_ref()
                .is_some_and(|pending_group| pending_group.can_join(&position))
            {
                pending
                    .as_mut()
                    .expect("checked pending ligature group")
                    .include(&position);
            } else {
                let pending_group = pending.take().expect("pending ligature group");
                merged.push(pending_group);
                pending = Some(position);
                pending_has_start = false;
            }
        } else {
            // A run can begin in the middle of a shaped ligature if a prior
            // fallback/style run owns its start.
            pending = Some(position);
            pending_has_start = false;
        }
    }

    if let Some(pending) = pending {
        merged.push(pending);
    }
    merged
}

fn clipped_layout(mut layout: TextLayout, limit: usize) -> TextLayout {
    let lines = layout.lines.iter().take(limit).cloned().collect::<Vec<_>>();
    let width = lines
        .iter()
        .fold(0.0_f32, |width, line| width.max(line.width));
    layout.metrics.size = Size::new(width, layout.metrics.line_height * lines.len() as f32);
    layout.metrics.baseline = lines.first().map_or(0.0, |line| line.baseline);
    layout.lines = lines.into();
    layout.overflowed = true;
    layout
}

fn grapheme_boundary_at_or_before(text: &str, offset: usize) -> usize {
    GraphemeClusterSegmenter::new()
        .segment_str(text)
        .take_while(|boundary| *boundary <= offset)
        .last()
        .unwrap_or(0)
}

fn previous_grapheme_boundary(text: &str, offset: usize) -> usize {
    GraphemeClusterSegmenter::new()
        .segment_str(text)
        .take_while(|boundary| *boundary < offset)
        .last()
        .unwrap_or(0)
}

fn family_name(family: &FontFamily) -> String {
    match family {
        FontFamily::SansSerif => "sans-serif".into(),
        FontFamily::Serif => "serif".into(),
        FontFamily::Monospace => "monospace".into(),
        FontFamily::Cursive => "cursive".into(),
        FontFamily::SystemUi => "system-ui".into(),
        FontFamily::Named(name) => format!("'{name}'"),
    }
}

/// Identity for one font blob sighting. Pointer identity is stable because
/// `Blob` clones share the same backing allocation, so repeated sightings of
/// the same face never re-copy or re-hash the bytes.
type FontBlobKey = (usize, usize, u32);

fn font_blob_key(font: &parley::FontData) -> FontBlobKey {
    (
        font.data.as_ref().as_ptr() as usize,
        font.data.as_ref().len(),
        font.index,
    )
}

/// Returns the shared handle for this font blob, building it (one full-file
/// hash, no copy) on first sight only.
fn font_handle(engine: &mut TextEngine, font: &parley::FontData) -> FontHandle {
    let key = font_blob_key(font);
    if let Some(handle) = engine.font_handles.get(&key) {
        return handle.clone();
    }
    let mut hasher = DefaultHasher::new();
    font.data.as_ref().hash(&mut hasher);
    hasher.write_u64(u64::from(font.index));
    let id = FontId(hasher.finish());
    // Share discovery's (typically memory-mapped) source instead of copying
    // the whole font file into a private heap allocation.
    let handle = FontHandle::with_face_index(
        id,
        FontBytes::from_shared(font.data.clone().into_raw_parts().0),
        font.index,
    );
    engine.font_handles.insert(key, handle.clone());
    handle
}