text-typeset 1.8.0

Turns rich text documents into GPU-ready glyph quads
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
use crate::font::registry::FontRegistry;
use crate::font::resolve::{ResolvedFont, resolve_font};
use crate::layout::line::LayoutLine;
use crate::layout::paragraph::{Alignment, Hyphenator, RunOrder, break_into_lines};
use crate::shaping::run::{ShapedGlyph, ShapedRun};
use crate::shaping::shaper::{
    BidiParagraph, FontMetricsPx, TextDirection, analyze_paragraph, font_metrics_px, shape_text,
    shape_text_with_fallback, to_harfrust_features,
};

/// Computed layout for a single block (paragraph).
#[derive(Clone)]
pub struct BlockLayout {
    pub block_id: usize,
    /// Document character position of the block start.
    pub position: usize,
    /// Laid out lines within the block.
    pub lines: Vec<LayoutLine>,
    /// Top edge relative to document start (set by flow layout).
    pub y: f32,
    /// Total height: top_margin + sum(line heights) + bottom_margin.
    pub height: f32,
    pub top_margin: f32,
    pub bottom_margin: f32,
    pub left_margin: f32,
    pub right_margin: f32,
    /// Shaped list marker (positioned to the left of the content area).
    /// None if the block is not a list item.
    pub list_marker: Option<ShapedListMarker>,
    /// The paragraph's *resolved* base direction — never `Auto`.
    ///
    /// `BlockLayoutParams::base_direction` may ask for auto-detection;
    /// this is what the bidi analysis actually settled on. Selection
    /// painting and caret motion need the answer, not the question.
    pub base_direction: TextDirection,
    /// Block background color (RGBA). None means transparent.
    pub background_color: Option<[f32; 4]>,
}

/// A shaped list marker ready for rendering.
#[derive(Clone)]
pub struct ShapedListMarker {
    pub run: ShapedRun,
    /// X position of the marker (relative to block left edge, before content indent).
    pub x: f32,
}

/// Parameters extracted from text-document's BlockFormat / TextFormat.
/// This is a plain struct so block layout doesn't depend on text-document types.
#[derive(Clone)]
pub struct BlockLayoutParams {
    pub block_id: usize,
    pub position: usize,
    pub text: String,
    pub fragments: Vec<FragmentParams>,
    pub alignment: Alignment,
    pub top_margin: f32,
    pub bottom_margin: f32,
    pub left_margin: f32,
    pub right_margin: f32,
    pub text_indent: f32,
    /// List marker text (e.g., "1.", "•", "a)"). Empty if not a list item.
    pub list_marker: String,
    /// Additional left indent for list items (in pixels).
    pub list_indent: f32,
    /// Tab stop positions in pixels from the left margin.
    pub tab_positions: Vec<f32>,
    /// The paragraph's base reading direction.
    ///
    /// `Auto` applies UAX #9 rules P2/P3 (first strong character wins).
    /// An explicit direction overrides that, which is what a stored
    /// per-block direction is for: auto-detection reads an Arabic
    /// paragraph opening with a Latin acronym as left-to-right.
    ///
    /// Drives three things: which direction each bidi run shapes with,
    /// the visual order of a line's runs, and — when `alignment` is
    /// `Start`/`End` — which edge the text sits against.
    pub base_direction: TextDirection,
    /// Line height multiplier. 1.0 = normal (from font metrics), 1.5 = 150%, 2.0 = double.
    /// None means use font metrics (ascent + descent + leading).
    pub line_height_multiplier: Option<f32>,
    /// If true, prevent line wrapping. The entire block is one long line.
    pub non_breakable_lines: bool,
    /// Hyphenation during line wrapping (`None` = off). See
    /// [`crate::types::Hyphenation`].
    pub hyphenation: Option<crate::types::Hyphenation>,
    /// Checkbox marker: None = no checkbox, Some(false) = unchecked, Some(true) = checked.
    pub checkbox: Option<bool>,
    /// Block background color (RGBA). None means transparent.
    pub background_color: Option<[f32; 4]>,
}

/// A text fragment with its formatting parameters.
#[derive(Clone)]
pub struct FragmentParams {
    pub text: String,
    /// **Byte** offset of this fragment's first character inside the
    /// owning block's text. Lifted into glyph clusters by
    /// `paragraph::flatten_runs` so glyph clusters
    /// can be compared directly against `unicode-linebreak` break
    /// positions (also bytes) and against the block-level text used
    /// for `byte_offset_to_char_offset` conversion. Hosts threading
    /// text-document `FragmentContent` through the bridge must
    /// translate the char-based `FragmentContent::offset` into bytes
    /// before assigning here.
    pub offset: usize,
    pub length: usize,
    pub font_family: Option<String>,
    pub font_weight: Option<u32>,
    pub font_bold: Option<bool>,
    pub font_italic: Option<bool>,
    pub font_point_size: Option<u32>,
    pub underline_style: crate::types::UnderlineStyle,
    pub overline: bool,
    pub strikeout: bool,
    pub is_link: bool,
    /// Extra space added after each glyph (in pixels). From TextFormat::letter_spacing.
    pub letter_spacing: f32,
    /// Extra space added after space glyphs (in pixels). From TextFormat::word_spacing.
    pub word_spacing: f32,
    /// Text foreground color (RGBA). None means default (black).
    pub foreground_color: Option<[f32; 4]>,
    /// Underline color (RGBA). None means use foreground_color.
    pub underline_color: Option<[f32; 4]>,
    /// Text-level background highlight color (RGBA). None means transparent.
    pub background_color: Option<[f32; 4]>,
    /// Hyperlink destination URL.
    pub anchor_href: Option<String>,
    /// Tooltip text.
    pub tooltip: Option<String>,
    /// Vertical alignment (normal, superscript, subscript).
    pub vertical_alignment: crate::types::VerticalAlignment,
    /// If Some, this fragment represents an inline image placeholder.
    pub image_name: Option<String>,
    /// Image width in pixels. Only meaningful when image_name is Some.
    pub image_width: f32,
    /// Image height in pixels. Only meaningful when image_name is Some.
    pub image_height: f32,
    /// If Some, this fragment is a footnote reference and this is the marker
    /// to draw at its position — a number, usually, but the host decides.
    ///
    /// The fragment still occupies exactly the **one** `U+FFFC` character its
    /// `text` holds, however many glyphs the marker shapes to. That mismatch is
    /// the whole point and the whole hazard: the marker is *presentation*, and
    /// the document must not grow a character because a footnote reached two
    /// digits. So the marker is shaped on its own and every resulting glyph is
    /// pinned to the sentinel's cluster, which is what stops the caret landing
    /// between the `1` and the `2` of note twelve.
    ///
    /// Distinct from [`Self::image_name`] rather than folded in with it: an
    /// image reserves a box of a size the host measured, a marker reserves
    /// whatever its own glyphs advance to, and only the latter needs a font.
    pub footnote_marker: Option<String>,
    /// Discretionary OpenType features to toggle during shaping. Empty =
    /// font defaults. See [`crate::types::FontFeature`].
    pub features: Vec<crate::types::FontFeature>,
}

/// The directional slices of one fragment, in logical order.
///
/// Intersects the fragment's byte span with the paragraph's bidi runs and
/// yields `(span, direction, level)` for each overlap. A fragment lying
/// wholly inside one bidi run — the overwhelmingly common case — yields a
/// single slice covering it, so uniform text costs nothing extra.
///
/// Falls back to one `Auto` slice when the analysis produced no runs
/// (empty block text), which preserves the pre-bidi behaviour.
fn fragment_bidi_slices(
    bidi: &BidiParagraph,
    frag: &FragmentParams,
) -> Vec<(std::ops::Range<usize>, TextDirection, u8)> {
    let frag_end = frag.offset + frag.text.len();

    if bidi.runs.is_empty() {
        return vec![(frag.offset..frag_end, TextDirection::Auto, 0)];
    }

    let mut slices = Vec::new();
    for run in &bidi.runs {
        let start = run.byte_range.start.max(frag.offset);
        let end = run.byte_range.end.min(frag_end);
        if start < end {
            slices.push((start..end, run.direction, run.level));
        }
    }

    // A fragment outside the analysed text (a host bug, or a zero-length
    // fragment) still deserves a shot at shaping rather than vanishing.
    if slices.is_empty() {
        slices.push((frag.offset..frag_end, TextDirection::Auto, 0));
    }
    slices
}

/// Lay out a single block: resolve fonts, shape fragments, break into lines.
///
/// `scale_factor` is the device pixel ratio. Layout output is always in
/// logical pixels; the scale factor affects shaping/rasterization precision.
pub fn layout_block(
    registry: &FontRegistry,
    params: &BlockLayoutParams,
    available_width: f32,
    scale_factor: f32,
    font_scale: f32,
) -> BlockLayout {
    let effective_left_margin = params.left_margin + params.list_indent;
    let content_width = (available_width - effective_left_margin - params.right_margin).max(0.0);

    // Resolve the paragraph's bidi structure once, over the whole block
    // text. It has to be the whole text: the algorithm's resolution of a
    // neutral character (a space, a comma) depends on the strong
    // characters on *both* sides of it, which a per-fragment analysis
    // cannot see.
    let bidi = analyze_paragraph(&params.text, params.base_direction);
    let base_direction = bidi.base_direction();

    // Resolve fonts and shape each fragment
    let mut shaped_runs = Vec::new();
    let mut default_metrics: Option<FontMetricsPx> = None;

    for frag in &params.fragments {
        // Inline image: create a synthetic run with one placeholder glyph
        if let Some(ref image_name) = frag.image_name {
            // An image is a neutral character in the bidi algorithm, so
            // it takes the level of whatever run covers its offset.
            // Hardcoding 0 left it at paragraph level inside RTL prose,
            // where it broke the contiguous run rule L2 reverses and so
            // stayed on the wrong side of the text around it.
            let (image_direction, image_level) = fragment_bidi_slices(&bidi, frag)
                .first()
                .map(|(_, d, l)| (*d, *l))
                .unwrap_or((TextDirection::LeftToRight, 0));
            let image_glyph = ShapedGlyph {
                glyph_id: 0,
                cluster: 0,
                x_advance: frag.image_width,
                y_advance: 0.0,
                x_offset: 0.0,
                y_offset: 0.0,
                font_face_id: crate::types::FontFaceId(0),
            };
            let run = ShapedRun {
                font_face_id: crate::types::FontFaceId(0),
                size_px: 0.0,
                weight: 400,
                glyphs: vec![image_glyph],
                advance_width: frag.image_width,
                text_range: frag.offset..frag.offset + frag.text.len(),
                direction: image_direction,
                bidi_level: image_level,
                underline_style: frag.underline_style,
                overline: false,
                strikeout: false,
                is_link: frag.is_link,
                foreground_color: None,
                underline_color: None,
                background_color: None,
                anchor_href: frag.anchor_href.clone(),
                tooltip: frag.tooltip.clone(),
                vertical_alignment: crate::types::VerticalAlignment::Normal,
                image_name: Some(image_name.clone()),
                image_height: frag.image_height,
            };
            shaped_runs.push(run);
            continue;
        }

        // Scale font size for superscript/subscript
        let font_point_size = match frag.vertical_alignment {
            crate::types::VerticalAlignment::SuperScript
            | crate::types::VerticalAlignment::SubScript => frag
                .font_point_size
                .map(|s| ((s as f32 * 0.65) as u32).max(1)),
            crate::types::VerticalAlignment::Normal => frag.font_point_size,
        };

        let resolved = resolve_font(
            registry,
            frag.font_family.as_deref(),
            frag.font_weight,
            frag.font_bold,
            frag.font_italic,
            font_point_size,
            scale_factor,
            font_scale,
        );

        if let Some(resolved) = resolved {
            // Capture default metrics from the first resolved font
            if default_metrics.is_none() {
                default_metrics = font_metrics_px(registry, &resolved);
            }

            let features = to_harfrust_features(&frag.features);

            // A footnote reference: shape the *marker* and pin it to the
            // sentinel.
            //
            // The fragment's own text is one `U+FFFC`, three bytes wide and one
            // character long; the marker is whatever the host wants drawn there.
            // Shaping the marker through the ordinary path below is not an
            // option — that path slices `frag.text` by byte range, so a marker
            // longer than the sentinel would read past it, and a marker shorter
            // than it would leave a coverage gap. Shaping it standalone and
            // then overwriting the run's own coordinates is the same graft
            // `append_hyphen` performs for a hyphen that is likewise not in the
            // text.
            //
            // Every glyph is collapsed onto the sentinel's cluster. Clusters are
            // what hit-testing, caret movement and line breaking all read, so
            // one shared value makes the marker atomic in all three at once: a
            // click anywhere in it resolves to the sentinel, the caret cannot
            // stop inside it, and a line cannot break within it.
            //
            // Deliberately no `image_height`: that field is what makes
            // `break_into_lines` inflate a line to fit, and an inflated line is
            // then excluded from the interline multiplier. A marker is smaller
            // than the text it rides on and must stay an ordinary line, or a
            // footnote would quietly change the leading of the paragraph
            // holding it.
            if let Some(marker) = frag.footnote_marker.as_deref() {
                let (direction, level) = fragment_bidi_slices(&bidi, frag)
                    .first()
                    .map(|(_, d, l)| (*d, *l))
                    .unwrap_or((TextDirection::LeftToRight, 0));

                if let Some(mut run) =
                    shape_text_with_fallback(registry, &resolved, marker, 0, direction, &features)
                {
                    // Cluster 0, not `frag.offset`: clusters are **run-local**
                    // here and `flatten_runs` lifts them by `text_range.start`
                    // on the way out. Pinning them to the absolute offset
                    // instead double-counts it, which puts every stop past the
                    // end of the run — the caret after a footnote then lands
                    // wherever the *next* run happens to start, and a marker of
                    // two digits measures the same as one of one. The image
                    // branch above uses the same `cluster: 0` for the same
                    // reason.
                    for glyph in &mut run.glyphs {
                        glyph.cluster = 0;
                    }
                    run.text_range = frag.offset..frag.offset + frag.text.len();
                    run.bidi_level = level;
                    run.underline_style = frag.underline_style;
                    run.overline = frag.overline;
                    run.strikeout = frag.strikeout;
                    run.is_link = frag.is_link;
                    run.foreground_color = frag.foreground_color;
                    run.underline_color = frag.underline_color;
                    run.background_color = frag.background_color;
                    run.anchor_href = frag.anchor_href.clone();
                    run.tooltip = frag.tooltip.clone();
                    run.vertical_alignment = frag.vertical_alignment;
                    shaped_runs.push(run);
                }
                continue;
            }

            // Shape each directional slice of the fragment separately. A
            // fragment is a *formatting* span (one bold/italic/font run),
            // which has nothing to do with where the text changes
            // direction — so shaping a fragment as a single unit is what
            // left mixed Arabic/Latin prose in raw logical order. Cutting
            // it at the bidi boundaries gives every run one uniform
            // direction, and `break_into_lines` reorders them per line.
            for (span, direction, level) in fragment_bidi_slices(&bidi, frag) {
                let local = (span.start - frag.offset)..(span.end - frag.offset);
                let Some(piece) = frag.text.get(local) else {
                    // The host's fragment offsets disagree with the block
                    // text it also supplied. Nothing good can come of
                    // guessing which is right; skip the slice rather than
                    // panic on a bad byte index.
                    continue;
                };
                if piece.is_empty() {
                    continue;
                }

                if let Some(mut run) = shape_text_with_fallback(
                    registry, &resolved, piece, span.start, direction, &features,
                ) {
                    run.bidi_level = level;
                    run.underline_style = frag.underline_style;
                    run.overline = frag.overline;
                    run.strikeout = frag.strikeout;
                    run.is_link = frag.is_link;
                    run.foreground_color = frag.foreground_color;
                    run.underline_color = frag.underline_color;
                    run.background_color = frag.background_color;
                    run.anchor_href = frag.anchor_href.clone();
                    run.tooltip = frag.tooltip.clone();
                    run.vertical_alignment = frag.vertical_alignment;

                    // Both of these map `glyph.cluster` back into the text
                    // they were shaped from, so they get the slice — not
                    // the whole fragment.
                    if frag.letter_spacing != 0.0 || frag.word_spacing != 0.0 {
                        apply_spacing(&mut run, piece, frag.letter_spacing, frag.word_spacing);
                    }
                    if !params.tab_positions.is_empty() {
                        apply_tab_stops(&mut run, piece, &params.tab_positions);
                    }

                    shaped_runs.push(run);
                }
            }
        }
    }

    // Fallback metrics if no fragments resolved
    let metrics =
        default_metrics.unwrap_or_else(|| get_default_metrics(registry, scale_factor, font_scale));

    // Non-breakable lines: use infinite width to prevent wrapping
    let wrap_width = if params.non_breakable_lines {
        f32::INFINITY
    } else {
        content_width
    };

    // Hyphenation: a hyphen glyph shaped in the default font, supplied only
    // when enabled and wrapping is in effect.
    let hyphenator = params
        .hyphenation
        .filter(|_| !params.non_breakable_lines)
        .and_then(|h| {
            shape_hyphen(registry, scale_factor, font_scale).map(|glyph| Hyphenator {
                glyph,
                language: h.language,
            })
        });

    // Break shaped runs into lines
    let mut lines = break_into_lines(
        shaped_runs,
        &params.text,
        wrap_width,
        params.alignment,
        params.text_indent,
        &metrics,
        hyphenator,
        RunOrder::Logical(base_direction),
    );

    // Apply line height multiplier.
    //
    // The multiplier expresses "N times the font's own line box", so it must
    // stretch only that font-driven space. A line holding an inline image
    // taller than the font's ascent already reports `line_height` inflated to
    // fit the picture (`break_into_lines`, paragraph.rs), and multiplying THAT
    // adds a fraction of the *image's* height as blank space below it — a 1.5×
    // interline setting turned a 200px image into ~100px of dead space before
    // the next block, which is the "huge gap under an image" report.
    //
    // So the multiplier is applied only to lines that were not image-inflated,
    // which leaves it working in both directions. Comparing against a *scaled*
    // natural height instead would silently cancel any multiplier below 1.0 for
    // every line in the block, image or not — and sub-1.0 line heights arrive
    // unclamped from imported HTML (`line-height: 0.8`) and from djot's
    // `{line_height=800}`.
    let line_height_mul = params.line_height_multiplier.unwrap_or(1.0).max(0.1);
    let natural_line_height = metrics.ascent + metrics.descent + metrics.leading;

    // Compute y positions for each line (relative to block content top)
    let mut y = 0.0f32;
    for line in &mut lines {
        if line_height_mul != 1.0 && line.line_height <= natural_line_height + f32::EPSILON {
            line.line_height *= line_height_mul;
        }
        line.y = y + line.ascent; // y is the baseline position
        y += line.line_height;
    }

    let content_height = y;
    let total_height = params.top_margin + content_height + params.bottom_margin;

    // Shape list marker or checkbox marker
    let list_marker = if params.checkbox.is_some() {
        shape_checkbox_marker(registry, &metrics, params, scale_factor, font_scale)
    } else if !params.list_marker.is_empty() {
        shape_list_marker(registry, &metrics, params, scale_factor, font_scale)
    } else {
        None
    };

    BlockLayout {
        block_id: params.block_id,
        position: params.position,
        base_direction,
        lines,
        y: 0.0, // set by flow layout
        height: total_height,
        top_margin: params.top_margin,
        bottom_margin: params.bottom_margin,
        left_margin: effective_left_margin,
        right_margin: params.right_margin,
        list_marker,
        background_color: params.background_color,
    }
}

/// A resolved paint-only color overlay span for one character range of a block.
///
/// `char_start`/`char_end` are **block-relative character offsets** — the same
/// space as the post-layout `ShapedGlyph::cluster` values (see
/// `break_into_lines`, which converts clusters to char offsets). Each field is
/// `None` when the overlay does not override it (the base run's value is kept).
/// Applying paint spans never changes glyph geometry, advances, or line breaks
/// — only color / decoration attributes — so the layout does not reflow.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PaintSpan {
    pub char_start: usize,
    pub char_end: usize,
    pub foreground_color: Option<[f32; 4]>,
    pub underline_color: Option<[f32; 4]>,
    pub background_color: Option<[f32; 4]>,
    pub underline_style: Option<crate::types::UnderlineStyle>,
    pub overline: Option<bool>,
    pub strikeout: Option<bool>,
}

/// The effective set of overrides for one glyph, used to group consecutive
/// glyphs that share the same paint result into a single output run.
#[derive(Clone, Default, PartialEq)]
struct PaintOverride {
    foreground_color: Option<[f32; 4]>,
    underline_color: Option<[f32; 4]>,
    background_color: Option<[f32; 4]>,
    underline_style: Option<crate::types::UnderlineStyle>,
    overline: Option<bool>,
    strikeout: Option<bool>,
}

impl PaintOverride {
    fn is_noop(&self) -> bool {
        *self == PaintOverride::default()
    }

    /// Merge the overlapping spans covering `char_off` (last span wins per
    /// field). Overlay spans from `extract_paint_spans` are already disjoint,
    /// but last-wins keeps this correct for arbitrary inputs.
    fn for_char(char_off: usize, spans: &[PaintSpan]) -> Self {
        let mut o = PaintOverride::default();
        for s in spans {
            if s.char_start <= char_off && char_off < s.char_end {
                if s.foreground_color.is_some() {
                    o.foreground_color = s.foreground_color;
                }
                if s.underline_color.is_some() {
                    o.underline_color = s.underline_color;
                }
                if s.background_color.is_some() {
                    o.background_color = s.background_color;
                }
                if s.underline_style.is_some() {
                    o.underline_style = s.underline_style;
                }
                if s.overline.is_some() {
                    o.overline = s.overline;
                }
                if s.strikeout.is_some() {
                    o.strikeout = s.strikeout;
                }
            }
        }
        o
    }

    /// Apply this override onto a positioned run segment, writing color /
    /// decoration fields on BOTH the shaped run and its duplicated
    /// `RunDecorations` (the renderer reads glyph color from the former and
    /// decoration rects from the latter). `None` fields keep the base value.
    fn apply(&self, run: &mut crate::layout::line::PositionedRun) {
        if let Some(c) = self.foreground_color {
            run.shaped_run.foreground_color = Some(c);
            run.decorations.foreground_color = Some(c);
        }
        if let Some(c) = self.underline_color {
            run.shaped_run.underline_color = Some(c);
            run.decorations.underline_color = Some(c);
        }
        if let Some(c) = self.background_color {
            run.shaped_run.background_color = Some(c);
            run.decorations.background_color = Some(c);
        }
        if let Some(s) = self.underline_style {
            run.shaped_run.underline_style = s;
            run.decorations.underline_style = s;
        }
        if let Some(b) = self.overline {
            run.shaped_run.overline = b;
            run.decorations.overline = b;
        }
        if let Some(b) = self.strikeout {
            run.shaped_run.strikeout = b;
            run.decorations.strikeout = b;
        }
    }
}

/// Apply paint-only color spans to a base [`BlockLayout`], returning a recolored
/// clone. The base is left untouched.
///
/// The result has byte-identical glyph positions, advances, line breaks, line
/// widths, and block height to `base` — only color / decoration attributes
/// differ. This is the "recolor without reshape/reflow" fast path: a run is
/// split into segments at paint-span boundaries (snapped to glyph/cluster
/// boundaries, never mid-cluster) and each segment's color fields are set.
/// Splitting a run never alters any glyph advance, so line widths are preserved.
///
/// Empty `spans` returns an exact (color-preserving) clone of `base`.
pub fn apply_paint_spans(base: &BlockLayout, spans: &[PaintSpan]) -> BlockLayout {
    let mut out = base.clone();
    if spans.is_empty() {
        return out;
    }
    for line in &mut out.lines {
        let mut new_runs: Vec<crate::layout::line::PositionedRun> =
            Vec::with_capacity(line.runs.len());
        for run in line.runs.drain(..) {
            recolor_run_into(run, spans, &mut new_runs);
        }
        line.runs = new_runs;
    }
    out
}

/// Split `run` at paint-span boundaries and push the recolored segment(s) onto
/// `out`. Image / glyph-less runs are passed through unchanged (paint overlays
/// never recolor images).
fn recolor_run_into(
    run: crate::layout::line::PositionedRun,
    spans: &[PaintSpan],
    out: &mut Vec<crate::layout::line::PositionedRun>,
) {
    if run.shaped_run.glyphs.is_empty() || run.shaped_run.image_name.is_some() {
        out.push(run);
        return;
    }

    // Per-glyph effective override, in glyph (visual) order. Works for LTR and
    // RTL alike: we group by adjacency in the glyph array, not by char order.
    let overrides: Vec<PaintOverride> = run
        .shaped_run
        .glyphs
        .iter()
        .map(|g| PaintOverride::for_char(g.cluster as usize, spans))
        .collect();

    // Fast path: the whole run shares one override (the common case, and the
    // only case when `spans` doesn't touch this run — then it's a no-op). Keep
    // the base `advance_width` exactly so a cleared/uncovered run is identical.
    if overrides.iter().all(|o| *o == overrides[0]) {
        let mut seg = run;
        overrides[0].apply(&mut seg);
        out.push(seg);
        return;
    }

    // Split into maximal runs of equal override.
    let glyphs = run.shaped_run.glyphs.clone();
    let mut seg_x = run.x;
    let mut start = 0usize;
    while start < glyphs.len() {
        let ov = &overrides[start];
        let mut end = start + 1;
        while end < glyphs.len() && overrides[end] == *ov {
            end += 1;
        }
        let seg_glyphs: Vec<crate::shaping::run::ShapedGlyph> = glyphs[start..end].to_vec();
        let seg_advance: f32 = seg_glyphs.iter().map(|g| g.x_advance).sum();
        let mut shaped = run.shaped_run.clone();
        shaped.glyphs = seg_glyphs;
        shaped.advance_width = seg_advance;
        let mut seg = crate::layout::line::PositionedRun {
            shaped_run: shaped,
            x: seg_x,
            decorations: run.decorations.clone(),
        };
        if !ov.is_noop() {
            ov.apply(&mut seg);
        }
        out.push(seg);
        seg_x += seg_advance;
        start = end;
    }
}

/// Add letter_spacing (to all glyphs) and word_spacing (to space glyphs).
fn apply_spacing(run: &mut ShapedRun, text: &str, letter_spacing: f32, word_spacing: f32) {
    let mut extra_advance = 0.0f32;
    for glyph in &mut run.glyphs {
        glyph.x_advance += letter_spacing;
        extra_advance += letter_spacing;

        // Add word_spacing to space characters.
        // Detect spaces by mapping cluster back to the text.
        if word_spacing != 0.0 {
            let byte_offset = glyph.cluster as usize;
            if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
                && ch == ' '
            {
                glyph.x_advance += word_spacing;
                extra_advance += word_spacing;
            }
        }
    }
    run.advance_width += extra_advance;
}

/// Shape a hyphen glyph (`-`) in the default font, for appending at
/// hyphenated line breaks. Returns `None` if no default font resolves.
pub(crate) fn shape_hyphen(
    registry: &FontRegistry,
    scale_factor: f32,
    font_scale: f32,
) -> Option<ShapedGlyph> {
    let resolved = resolve_font(
        registry,
        None,
        None,
        None,
        None,
        None,
        scale_factor,
        font_scale,
    )?;
    let run = shape_text(registry, &resolved, "-", 0)?;
    run.glyphs.into_iter().next()
}

/// Shape the list marker text and position it in the indent area.
fn shape_list_marker(
    registry: &FontRegistry,
    _metrics: &FontMetricsPx,
    params: &BlockLayoutParams,
    scale_factor: f32,
    font_scale: f32,
) -> Option<ShapedListMarker> {
    // Use the default font for the marker
    let resolved = resolve_font(
        registry,
        None,
        None,
        None,
        None,
        None,
        scale_factor,
        font_scale,
    )?;
    let run = shape_text(registry, &resolved, &params.list_marker, 0)?;

    // Position the marker: right-aligned within the indent area, with a small gap
    let gap = 4.0; // pixels between marker and content
    let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
    let marker_x = marker_x.max(params.left_margin);

    Some(ShapedListMarker { run, x: marker_x })
}

/// Expand tab character advances to reach the next tab stop position.
fn apply_tab_stops(run: &mut ShapedRun, text: &str, tab_positions: &[f32]) {
    let default_tab = 48.0; // default tab width if no stops defined
    let mut pen_x = 0.0f32;

    for glyph in &mut run.glyphs {
        let byte_offset = glyph.cluster as usize;
        if let Some(ch) = text.get(byte_offset..).and_then(|s| s.chars().next())
            && ch == '\t'
        {
            // Find the next tab stop after the current pen position
            let next_stop = tab_positions
                .iter()
                .find(|&&stop| stop > pen_x + 1.0)
                .copied()
                .unwrap_or_else(|| {
                    // Past all defined stops: use default tab increments
                    let last = tab_positions.last().copied().unwrap_or(0.0);
                    let increment = if tab_positions.len() >= 2 {
                        tab_positions[1] - tab_positions[0]
                    } else {
                        default_tab
                    };
                    let mut stop = last + increment;
                    while stop <= pen_x + 1.0 {
                        stop += increment;
                    }
                    stop
                });

            let tab_advance = next_stop - pen_x;
            let delta = tab_advance - glyph.x_advance;
            glyph.x_advance = tab_advance;
            run.advance_width += delta;
        }
        pen_x += glyph.x_advance;
    }
}

/// Shape a checkbox marker (unchecked or checked) for rendering in the margin.
fn shape_checkbox_marker(
    registry: &FontRegistry,
    _metrics: &FontMetricsPx,
    params: &BlockLayoutParams,
    scale_factor: f32,
    font_scale: f32,
) -> Option<ShapedListMarker> {
    let checked = params.checkbox?;
    let marker_text = if checked { "\u{2611}" } else { "\u{2610}" }; // ballot box with/without check

    let resolved = resolve_font(
        registry,
        None,
        None,
        None,
        None,
        None,
        scale_factor,
        font_scale,
    )?;
    let run = shape_text(registry, &resolved, marker_text, 0)?;

    // If the font doesn't have the ballot box characters, use ASCII fallback
    let run = if run.glyphs.iter().any(|g| g.glyph_id == 0) {
        let fallback_text = if checked { "[x]" } else { "[ ]" };
        shape_text(registry, &resolved, fallback_text, 0)?
    } else {
        run
    };

    let gap = 4.0;
    let marker_x = params.left_margin + params.list_indent - run.advance_width - gap;
    let marker_x = marker_x.max(params.left_margin);

    Some(ShapedListMarker { run, x: marker_x })
}

fn get_default_metrics(
    registry: &FontRegistry,
    scale_factor: f32,
    font_scale: f32,
) -> FontMetricsPx {
    if let Some(default_id) = registry.default_font() {
        let resolved = ResolvedFont {
            font_face_id: default_id,
            size_px: registry.default_size_px() * font_scale,
            face_index: registry.get(default_id).map(|e| e.face_index).unwrap_or(0),
            swash_cache_key: registry
                .get(default_id)
                .map(|e| e.swash_cache_key)
                .unwrap_or_default(),
            scale_factor,
            weight: 400,
        };
        if let Some(m) = font_metrics_px(registry, &resolved) {
            return m;
        }
    }
    // Absolute fallback: synthetic metrics for 16px
    FontMetricsPx {
        ascent: 14.0,
        descent: 4.0,
        leading: 0.0,
        underline_offset: -2.0,
        strikeout_offset: 5.0,
        stroke_size: 1.0,
    }
}