lievisual 0.3.3

Declarative visual scene IR + pluggable rendering backends (SVG / vello_cpu / GPU).
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
use super::*;
use crate::geometry::{Color, Rect, Size};
use crate::text::style::HANGING_ASCENT_RATIO;
use parley::fontique::{Collection, CollectionOptions, SourceCache};
use parley::style::FontFamily;
use parley::{FontContext, LayoutContext, StyleProperty};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};

// A font-byte cache shared across layouts: the key is the stable `id()` of parley's
// `Blob` (unique per font). This avoids every Run `to_vec`-ing a whole font file
// (potentially tens of MB), which would make memory blow up with text volume. Each
// unique font is copied only once per process, and the rest of the Runs share it via
// `Arc`.
static FONT_BYTE_CACHE: OnceLock<Mutex<HashMap<u64, Arc<Vec<u8>>>>> = OnceLock::new();

// Process-wide font **collection** (`shared: true` makes every clone observe later
// registrations). Each thread's `FontContext` is built from a clone of it, so a font
// registered on one thread is visible on all threads (including ones started later) —
// with a plain per-thread `FontContext::new()` the registration stayed thread-local and
// worker threads silently fell back to a default font.
static GLOBAL_FONT_COLLECTION: OnceLock<Mutex<Collection>> = OnceLock::new();

/// The process-wide font collection (system fonts + everything ever registered).
fn global_font_collection() -> &'static Mutex<Collection> {
    GLOBAL_FONT_COLLECTION.get_or_init(|| {
        Mutex::new(Collection::new(CollectionOptions {
            shared: true,
            ..Default::default()
        }))
    })
}

/// Build a fresh `FontContext` sharing the global collection.
fn new_font_context() -> FontContext {
    let collection = global_font_collection()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .clone();
    FontContext {
        collection,
        source_cache: SourceCache::default(),
    }
}

// One cached layout context per thread: lazily initialized, reused by every
// measurement / layout within the thread. parley's official guidance designs
// FontContext (font library + LRU source cache) and LayoutContext (scratch + glyph
// cache) as "one per application / per thread"; thread_local realizes that semantics and
// avoids the system-font scanning and allocation of rebuilding each time. Every
// parley-related operation goes through with_cached_context to reuse this same pair of
// instances; the font collection behind them is shared process-wide (see
// `global_font_collection`).
thread_local! {
    static FONT_CONTEXT: RefCell<FontContext> = RefCell::new(new_font_context());
    static LAYOUT_CONTEXT: RefCell<LayoutContext<Color>> = RefCell::new(LayoutContext::new());
}

/// Borrow the thread-local cached contexts to perform one layout (the single entry
/// point for all parley operations).
fn with_cached_context<R>(f: impl FnOnce(&mut FontContext, &mut LayoutContext<Color>) -> R) -> R {
    FONT_CONTEXT.with(|fc| {
        LAYOUT_CONTEXT.with(|lc| {
            let mut fc = fc.borrow_mut();
            let mut lc = lc.borrow_mut();
            f(&mut fc, &mut lc)
        })
    })
}

/// Measure rich text (a [`RichSpan`] list, canvas `measureText`) and return
/// size / metrics / reusable layout.
///
/// Reuses the thread-local cached `FontContext` / `LayoutContext` (parley internally
/// caches fonts, glyphs, and scratch allocations), avoiding the system-font scan that
/// rebuilding each call would cause. `max_width` acts as the wrap limit for the whole
/// paragraph. A plain string is the special case of a single [`RichSpan`].
pub fn measure_text(spans: &[RichSpan], max_width: Option<f64>) -> TextMeasure {
    with_cached_context(|fc, lc| {
        let layout = build_rich_layout(spans, max_width, fc, lc);
        let metrics = layout_metrics(&layout);
        TextMeasure {
            size: Size::new(metrics.width, metrics.height),
            metrics,
            layout: Arc::new(layout),
        }
    })
}

/// Lay out rich text (a [`RichSpan`] list) into a single [`TextLayout`], returning an
/// `Arc` (which can be fed directly as the pre-computed `layout` of
/// [`crate::scene::Element::Text`] to the renderer).
///
/// Shares the same TLS context with [`measure_text`]; reuse it for "layout only"
/// scenarios to avoid re-layout.
pub fn layout_text(spans: &[RichSpan], max_width: Option<f64>) -> Arc<TextLayout> {
    with_cached_context(|fc, lc| Arc::new(build_rich_layout(spans, max_width, fc, lc)))
}

/// Build a rich-text layout with a `RangedBuilder` (shared by measurement and
/// rendering so sizes stay consistent) and extract it into a self-contained
/// [`TextLayout`] (with glyph-level runs / glyphs and extended attributes).
fn build_rich_layout(
    spans: &[RichSpan],
    max_width: Option<f64>,
    font_cx: &mut FontContext,
    layout_cx: &mut LayoutContext<Color>,
) -> TextLayout {
    if spans.is_empty() {
        let empty = TextStyle::new(Color::BLACK, 12.0, "sans-serif");
        return build_layout(font_cx, layout_cx, "", &empty, max_width);
    }

    // Concatenate all text and record the byte range of each span.
    let mut combined = String::new();
    let mut ranges: Vec<(usize, usize)> = Vec::with_capacity(spans.len());
    for span in spans {
        let start = combined.len();
        combined.push_str(&span.text);
        ranges.push((start, combined.len()));
    }

    let mut builder = layout_cx.ranged_builder(font_cx, &combined, 1.0, true);

    // Use the first span's style as the default; override differing properties per span.
    let base = &spans[0].style;
    push_text_style_defaults(&mut builder, base);

    for (i, span) in spans.iter().enumerate().skip(1) {
        let (start, end) = ranges[i];
        if start >= end {
            continue;
        }
        push_style_diff(&mut builder, &span.style, base, start..end);
    }

    let mut layout = builder.build(&combined);
    // Set alignment before line breaking (parley 0.13 applies it during break_all_lines).
    // Center/Right align multi-line within the block, Justify adjusts letter spacing.
    // The renderer's dx only positions the whole block relative to the anchor — the two
    // are orthogonal.
    set_parley_align(&mut layout, spans[0].style.align);
    layout.break_all_lines(max_width.map(|w| w as f32));

    // Extract into a self-contained structure; extended attributes
    // (url/decoration/background/baseline_shift) are mapped onto each run by span byte
    // range.
    extract_lines_from_parley(&layout, &combined, spans)
}

/// Parse a CSS `font-family` list into parley's `FontFamily` (consistent with
/// [`build_layout`]).
fn font_family_prop(raw: &str) -> FontFamily<'_> {
    use parley::style::FontFamilyName;
    let families: Vec<FontFamilyName> = FontFamilyName::parse_css_list(raw)
        .filter_map(Result::ok)
        .collect();
    if families.is_empty() {
        FontFamily::named(raw)
    } else {
        FontFamily::List(families.into())
    }
}

fn parley_font_style(style: FontStyle) -> parley::style::FontStyle {
    match style {
        FontStyle::Normal => parley::style::FontStyle::Normal,
        FontStyle::Italic => parley::style::FontStyle::Italic,
        FontStyle::Oblique => parley::style::FontStyle::Oblique(None),
    }
}

fn parley_line_height(lh: f64, font_size: f64) -> parley::style::LineHeight {
    let factor = (lh / font_size.max(1e-6)) as f32;
    parley::style::LineHeight::FontSizeRelative(factor)
}

/// Set parley paragraph alignment (Center/Right align lines within the block, Justify
/// adjusts letter spacing).
///
/// Parley 0.13 renamed `Layout::align` to `set_alignment`: it now records the alignment
/// setting, which is applied when lines are broken. Call this **before**
/// `break_all_lines`; setting it afterwards has no effect on the current lines.
///
/// This is orthogonal to the renderer's anchor offset: parley handles alignment of lines
/// **within the block**, while the renderer's dx positions the **whole block** relative
/// to the anchor.
fn set_parley_align(layout: &mut parley::Layout<Color>, align: TextAlign) {
    let p = match align {
        TextAlign::Left => parley::Alignment::Start,
        TextAlign::Center => parley::Alignment::Center,
        TextAlign::Right => parley::Alignment::End,
        TextAlign::Justify => parley::Alignment::Justify,
    };
    layout.set_alignment(p, parley::AlignmentOptions::default());
}

/// Push the `TextStyle`'s typographic properties as the builder's defaults (shared by
/// `build_layout` and `build_rich_layout`, so plain text and rich text map consistently).
///
/// Covers: font family / size / width / weight / style / color / line height / letter
/// spacing / underline / strikethrough. When `line_height` is `None` it is left unset
/// (the font's default is used).
fn push_text_style_defaults(builder: &mut parley::RangedBuilder<'_, Color>, style: &TextStyle) {
    builder.push_default(StyleProperty::FontFamily(font_family_prop(
        &style.font_family,
    )));
    builder.push_default(StyleProperty::FontSize(style.font_size as f32));
    builder.push_default(StyleProperty::Brush(style.color));
    builder.push_default(StyleProperty::FontWeight(parley::style::FontWeight::new(
        style.font_weight.value(),
    )));
    builder.push_default(StyleProperty::FontStyle(parley_font_style(
        style.font_style,
    )));

    builder.push_default(StyleProperty::FontWidth(
        parley::style::FontWidth::from_ratio(style.font_width.ratio()),
    ));

    if let Some(lh) = style.line_height {
        builder.push_default(StyleProperty::LineHeight(parley_line_height(
            lh,
            style.font_size,
        )));
    }
    if style.letter_spacing != 0.0 {
        builder.push_default(StyleProperty::LetterSpacing(style.letter_spacing as f32));
    }
    builder.push_default(StyleProperty::Underline(style.underline));
    builder.push_default(StyleProperty::UnderlineBrush(style.underline_color));
    builder.push_default(StyleProperty::Strikethrough(style.strikethrough));
    builder.push_default(StyleProperty::StrikethroughBrush(style.strikethrough_color));
}

/// Push only the style properties of `TextStyle` that differ from `base`, over the
/// given range (per-span for rich text).
fn push_style_diff(
    builder: &mut parley::RangedBuilder<'_, Color>,
    s: &TextStyle,
    base: &TextStyle,
    range: std::ops::Range<usize>,
) {
    if s.font_family != base.font_family {
        builder.push(
            StyleProperty::FontFamily(font_family_prop(&s.font_family)),
            range.clone(),
        );
    }
    if (s.font_size - base.font_size).abs() > f64::EPSILON {
        builder.push(StyleProperty::FontSize(s.font_size as f32), range.clone());
    }
    if s.color != base.color {
        builder.push(StyleProperty::Brush(s.color), range.clone());
    }
    if s.font_weight != base.font_weight {
        builder.push(
            StyleProperty::FontWeight(parley::style::FontWeight::new(s.font_weight.value())),
            range.clone(),
        );
    }
    if s.font_style != base.font_style {
        builder.push(
            StyleProperty::FontStyle(parley_font_style(s.font_style)),
            range.clone(),
        );
    }
    if s.font_width != base.font_width {
        builder.push(
            StyleProperty::FontWidth(parley::style::FontWidth::from_ratio(s.font_width.ratio())),
            range.clone(),
        );
    }
    if s.line_height != base.line_height {
        builder.push(
            StyleProperty::LineHeight(parley_line_height(
                s.line_height.unwrap_or(s.font_size),
                s.font_size,
            )),
            range.clone(),
        );
    }
    if (s.letter_spacing - base.letter_spacing).abs() > f64::EPSILON {
        builder.push(
            StyleProperty::LetterSpacing(s.letter_spacing as f32),
            range.clone(),
        );
    }
    if s.underline != base.underline {
        builder.push(StyleProperty::Underline(s.underline), range.clone());
    }
    if s.underline_color != base.underline_color {
        builder.push(
            StyleProperty::UnderlineBrush(s.underline_color),
            range.clone(),
        );
    }
    if s.strikethrough != base.strikethrough {
        builder.push(StyleProperty::Strikethrough(s.strikethrough), range.clone());
    }
    if s.strikethrough_color != base.strikethrough_color {
        builder.push(
            StyleProperty::StrikethroughBrush(s.strikethrough_color),
            range.clone(),
        );
    }
}

pub fn layout_metrics(layout: &TextLayout) -> TextMetrics {
    let width = layout.width;
    let height = layout.height;

    let (ascent, descent, baseline, line_height) = match layout.lines.first() {
        Some(line) => {
            let m = line.metrics;
            // Parley 0.13: derive ascent/descent from content block coords.
            let ascent = m.baseline - m.content_block_min;
            let descent = m.content_block_max - m.baseline;
            (
                ascent as f64,
                descent as f64,
                m.baseline as f64,
                m.line_height as f64,
            )
        }
        None => (0.0, 0.0, 0.0, 0.0),
    };

    TextMetrics {
        width,
        height,
        actual_bounding_box_left: 0.0,
        actual_bounding_box_right: width,
        font_bounding_box_ascent: ascent,
        font_bounding_box_descent: descent,
        actual_bounding_box_ascent: ascent,
        actual_bounding_box_descent: descent,
        em_height_ascent: ascent,
        em_height_descent: descent,
        hanging_baseline: ascent * HANGING_ASCENT_RATIO,
        alphabetic_baseline: baseline,
        ideographic_baseline: baseline + descent * 0.1,
        line_height,
    }
}

/// Build a parley layout (shared by measurement and rendering so sizes stay
/// consistent) and extract it into a self-contained [`TextLayout`].
pub(crate) fn build_layout(
    font_ctx: &mut FontContext,
    layout_ctx: &mut LayoutContext<Color>,
    content: &str,
    style: &TextStyle,
    max_width: Option<f64>,
) -> TextLayout {
    // scale = 1.0 (display scaling); font size is set via the FontSize property, so
    // layout coordinates remain logical pixels.
    let mut builder = layout_ctx.ranged_builder(font_ctx, content, 1.0, true);
    push_text_style_defaults(&mut builder, style);

    let mut layout = builder.build(content);
    // Set alignment before line breaking (parley 0.13 applies it during break_all_lines).
    // Center/Right align multi-line within the block, Justify adjusts letter spacing.
    // The renderer's dx only positions the whole block relative to the anchor — the two
    // are orthogonal.
    set_parley_align(&mut layout, style.align);
    // Max width is the wrap limit; pass None when unlimited.
    layout.break_all_lines(max_width.map(|w| w as f32));

    // Treat a plain string as a single span and extract into a self-contained structure.
    let span = RichSpan::new(content.to_string(), style.clone());
    let spans = std::slice::from_ref(&span);
    extract_lines_from_parley(&layout, content, spans)
}

/// Raw glyph data (coordinates relative to the layout origin); used only during
/// extraction.
struct GlyphRaw {
    id: u32,
    x: f32,
    y: f32,
    advance: f32,
    /// The owning cluster's text range (byte offsets into `full_text`).
    ///
    /// parley 的 Run 是「字体级」运行:同一字体的一个 Run 可横跨多个样式区间
    /// (parley 只在样式属性变化处拆出多个 GlyphRun,但它们共享同一个 Run,
    /// `Run::text_range()` 返回的是整个字体级运行的范围)。因此每个 GlyphRun
    /// 的真实文本范围必须从其字形的 cluster 区间推导,不能直接用
    /// `run.text_range()`,否则合并运行下所有 piece 都会拿到全文范围。
    cluster_start: u32,
    cluster_end: u32,
}

/// Extract a self-contained [`TextLayout`] from a parley Layout, mapping extended
/// attributes (`url` / `decoration` / `background_color` / `baseline_shift`) onto each
/// run by span byte range.
///
/// Each [`TextLine::bounds`] gives the line's position within the layout: `x` is the
/// leftmost glyph's offset from the layout's left, `y` is the cumulative offset of the
/// line top from the layout top. A run's `glyphs[].x/y` are offsets relative to the
/// line origin (self-contained, drawable independently of the layout / full_text).
///
/// Font bytes are deduplicated process-wide by `Blob::id()`; each unique font is
/// `to_vec`-ed only once into an `Arc`, and the rest of the runs share it, avoiding
/// per-run copies of a whole font file that would blow up memory.
fn extract_lines_from_parley(
    layout: &parley::Layout<Color>,
    full_text: &str,
    spans: &[RichSpan],
) -> TextLayout {
    // Build the span byte-range table, used to look up extended attributes
    // (url/decoration/background/baseline_shift).
    let mut span_ranges: Vec<(usize, usize, &TextStyle)> = Vec::with_capacity(spans.len());
    let mut acc = 0usize;
    for span in spans {
        let end = acc + span.text.len();
        span_ranges.push((acc, end, &span.style));
        acc = end;
    }

    let mut lines = Vec::new();
    let mut row_top_rel = 0.0_f32;

    for line in layout.lines() {
        let m = line.metrics();

        // Parley 0.13: block-axis coords are absolute (relative to layout origin).
        // Convert to line-relative offsets so consumers don't need row_top_rel.
        let baseline_rel = m.baseline - row_top_rel;
        let block_min_rel = m.block_min_coord - row_top_rel;
        let block_max_rel = m.block_max_coord - row_top_rel;
        let content_min_rel = m.content_block_min_coord - row_top_rel;
        let content_max_rel = m.content_block_max_coord - row_top_rel;

        // cap_height / x_height live on parley's `FontMetrics`, not `LineMetrics`.
        // Take them from the first glyph run of the line — font-level constants,
        // identical across runs of the same font, and stable across text changes.
        let (cap_height, x_height) = line
            .items()
            .find_map(|item| match item {
                parley::layout::PositionedLayoutItem::GlyphRun(gr) => {
                    let rm = gr.run().font_metrics();
                    Some((rm.cap_height.unwrap_or(0.0), rm.x_height.unwrap_or(0.0)))
                }
                _ => None,
            })
            .unwrap_or((0.0, 0.0));

        let line_metrics = LineMetrics {
            line_height: m.line_height,
            baseline: baseline_rel,
            block_min: block_min_rel,
            block_max: block_max_rel,
            content_block_min: content_min_rel,
            content_block_max: content_max_rel,
            cap_height,
            x_height,
        };
        let line_height = m.line_height;
        let baseline_y = baseline_rel; // used by TextRun below

        let mut glyph_data: Vec<(GlyphRaw, usize)> = Vec::new();
        #[allow(clippy::type_complexity)]
        let mut run_infos: Vec<(Color, Arc<Vec<u8>>, u32, f32, bool, bool)> = Vec::new();

        // GlyphRun 的簇归属:parley 的 Run 是「字体级」运行,同一 Run 拆出的多个
        // GlyphRun(样式区间)共享它,`run().visual_clusters()` 迭代的是整个字体级
        // Run 的簇。因此必须先把同一字体级 Run 的所有 GlyphRun 聚合起来,再按顺序
        // 用簇的字形数去消耗聚合后的定位字形序列,簇区间才能与字形正确对齐。
        // 字体级 Run 在一行内以 text_range 唯一标识(各 Run 的范围互不重叠)。
        let glyph_runs: Vec<_> = line
            .items()
            .filter_map(|item| match item {
                parley::layout::PositionedLayoutItem::GlyphRun(gr) => Some(gr),
                _ => None,
            })
            .collect();

        let mut next_run_idx = 0;
        let mut gr = 0usize;
        while gr < glyph_runs.len() {
            let font_range = glyph_runs[gr].run().text_range();
            let mut group_end = gr;
            while group_end < glyph_runs.len()
                && glyph_runs[group_end].run().text_range() == font_range
            {
                group_end += 1;
            }

            // 聚合该字体级 Run 的全部定位字形(按视觉顺序),同时为每个 GlyphRun
            // 登记 run_infos(颜色 / 字体 / 粗斜体)。
            // (glyph, run_idx)。
            let mut flat: Vec<(parley::layout::Glyph, usize)> = Vec::new();
            for glyph_run in &glyph_runs[gr..group_end] {
                let run = glyph_run.run();
                let color = glyph_run.style().brush;
                // Font bytes + collection index: bytes are deduplicated in cache by Blob::id().
                let font = run.font();
                let blob = &font.data;
                let font_id = blob.id();
                let font_index = font.index;
                let font_arc = {
                    let mut cache = FONT_BYTE_CACHE
                        .get_or_init(|| Mutex::new(HashMap::new()))
                        .lock()
                        .expect("font cache poisoned");
                    cache
                        .entry(font_id)
                        .or_insert_with(|| Arc::new(blob.data().to_vec()))
                        .clone()
                };
                let font_size = run.font_size();

                // Font weight / italic (needed by backends using system fonts such as SVG).
                // 取自字体级 Run 的属性(同一 Run 内不变),在收集阶段固化,
                // 后续无需再借用 parley 的 `Run`。
                let font_attrs = run.font_attrs();
                let font_weight_bold = font_attrs.weight >= parley::fontique::FontWeight::BOLD;
                let font_style_italic = font_attrs.style != parley::fontique::FontStyle::Normal;

                run_infos.push((
                    color,
                    font_arc,
                    font_index,
                    font_size,
                    font_weight_bold,
                    font_style_italic,
                ));
                let run_idx = next_run_idx;
                next_run_idx += 1;

                for g in glyph_run.positioned_glyphs() {
                    flat.push((g, run_idx));
                }
            }

            // 按簇消耗字形:第 k 个簇拥有 k_clusters 个字形,与聚合字形序列顺序
            // 一一对应(簇切片与 GlyphRun 字形切片都出自同一字形数组、同序)。
            let mut qi = 0usize;
            for cluster in glyph_runs[gr].run().visual_clusters() {
                let cluster_range = cluster.text_range();
                for _ in 0..cluster.glyphs().count() {
                    let Some((g, run_idx)) = flat.get(qi) else {
                        break;
                    };
                    glyph_data.push((
                        GlyphRaw {
                            id: g.id,
                            x: g.x,
                            y: g.y,
                            advance: g.advance,
                            cluster_start: cluster_range.start as u32,
                            cluster_end: cluster_range.end as u32,
                        },
                        *run_idx,
                    ));
                    qi += 1;
                }
            }
            // 防御:簇数与字形数不一致时(理论不发生),剩余字形退化为整个
            // 字体级 Run 的范围,至少保证字形不丢。
            for (g, run_idx) in &flat[qi..] {
                glyph_data.push((
                    GlyphRaw {
                        id: g.id,
                        x: g.x,
                        y: g.y,
                        advance: g.advance,
                        cluster_start: font_range.start as u32,
                        cluster_end: font_range.end as u32,
                    },
                    *run_idx,
                ));
            }

            gr = group_end;
        }

        if glyph_data.is_empty() {
            row_top_rel += line_height;
            continue;
        }

        let min_x = glyph_data
            .iter()
            .map(|(g, _)| g.x)
            .fold(f32::INFINITY, f32::min);
        let max_x = glyph_data
            .iter()
            .map(|(g, _)| g.x)
            .fold(f32::NEG_INFINITY, f32::max);
        let width = max_x - min_x;

        let mut runs = Vec::new();

        // Split glyphs by font-run index (GlyphRun). 一个字体级 Run 拆出的多个
        // GlyphRun(样式区间)在此各自成组;跨 span 的进一步切分交给
        // [`TextRun::split_at`](见下)。
        let mut run_glyph_ranges: Vec<(usize, usize)> = Vec::new();
        let mut current_start = 0;
        let mut last_run_idx = glyph_data[0].1;
        for (i, (_, run_idx)) in glyph_data.iter().enumerate() {
            if *run_idx != last_run_idx {
                run_glyph_ranges.push((current_start, i));
                current_start = i;
                last_run_idx = *run_idx;
            }
        }
        run_glyph_ranges.push((current_start, glyph_data.len()));

        let span_of = |pos: usize| -> usize {
            span_ranges
                .iter()
                .position(|(s, e, _)| *s <= pos && pos < *e)
                .unwrap_or(span_ranges.len().saturating_sub(1))
        };

        for (start_idx, end_idx) in run_glyph_ranges.iter() {
            let run_idx = glyph_data[*start_idx].1;
            let (color, font_data, font_index, font_size, font_weight_bold, font_style_italic) =
                &run_infos[run_idx];

            // GlyphRun 的真实文本范围:首字形 cluster 起点 → 末字形 cluster 终点
            //(多字形共享同一簇时取最大终点,防退化)。不能使用 `Run::text_range()`——
            // 那是字体级 Run 的全范围,一个字体级 Run 拆出多个 GlyphRun 时,
            // 所有 GlyphRun 都会拿到全文范围。
            let text_start = glyph_data[*start_idx].0.cluster_start as usize;
            let text_end = glyph_data[*start_idx..*end_idx]
                .iter()
                .map(|(g, _)| g.cluster_end as usize)
                .max()
                .unwrap_or(text_start)
                .max(text_start)
                .min(full_text.len());

            let run_text = full_text
                .get(text_start..text_end)
                .map(str::to_string)
                .unwrap_or_default();

            // Normalize the cluster into a local offset relative to run_text (self-contained).
            let relative_glyphs: Vec<Glyph> = glyph_data[*start_idx..*end_idx]
                .iter()
                .map(|(g, _)| Glyph {
                    id: g.id,
                    x: g.x - min_x,
                    y: g.y - row_top_rel,
                    advance: g.advance,
                    cluster: g.cluster_start.saturating_sub(text_start as u32),
                })
                .collect();

            let base = TextRun {
                text: run_text,
                font_data: font_data.clone(),
                font_index: *font_index,
                font_size: *font_size,
                font_weight_bold: *font_weight_bold,
                font_style_italic: *font_style_italic,
                color: *color,
                advance: relative_glyphs.iter().map(|g| g.advance).sum(),
                glyphs: relative_glyphs,
                is_rtl: false,
                baseline_x: glyph_data[*start_idx].0.x - min_x,
                baseline_y,
                url: None,
                decoration: TextDecoration::None,
                baseline_shift: 0.0,
                background_color: None,
            };

            // Span 边界切分:扩展属性(url / background_color / baseline_shift)是
            // span 级的,parley 无法感知(不是 parley 样式属性),同一 GlyphRun 可能
            // 覆盖多个 span。若不切分,某 span 的背景色 / 链接会泄漏到相邻 span 的
            // 文本上(例如「普通文本 + 高亮 span + 普通文本」同字体同色时,整行都会
            // 被涂上高亮背景)。
            let mut cuts: Vec<usize> = Vec::new();
            for i in (*start_idx + 1)..*end_idx {
                let prev = &glyph_data[i - 1].0;
                let cur = &glyph_data[i].0;
                if span_of(prev.cluster_start as usize) != span_of(cur.cluster_start as usize) {
                    cuts.push(cur.cluster_start as usize - text_start);
                }
            }
            let pieces = base.split_at(&cuts);

            // 按 piece 的绝对字节区间安扩展属性(piece 必落在单一 span 内),
            // 并应用基线偏移(上标 / 下标):字形 y 平移,baseline_y 反向平移。
            let mut piece_start = text_start;
            for mut piece in pieces {
                let piece_end = piece_start + piece.text.len();
                let (url, decoration, background_color, baseline_shift) =
                    lookup_extended_props(piece_start, piece_end, &span_ranges);
                if baseline_shift != 0.0 {
                    for g in &mut piece.glyphs {
                        g.y += baseline_shift;
                    }
                    piece.baseline_y -= baseline_shift;
                }
                piece.url = url;
                piece.decoration = decoration;
                piece.baseline_shift = baseline_shift;
                piece.background_color = background_color;
                runs.push(piece);
                piece_start = piece_end;
            }
        }

        let bounds = Rect::new(
            min_x as f64,
            row_top_rel as f64,
            (min_x + width) as f64,
            (row_top_rel + line_height) as f64,
        );

        // NOTE: the per-glyph ink_bounds block (a glyph-outline query over every
        // glyph) has been removed. Ink bounds change with text content and cost
        // O(glyphs) per layout; the visual box is now derived from font-level
        // metrics (see TextLine::logical_bounds / cap_bounds).

        lines.push(TextLine {
            runs,
            bounds,
            metrics: line_metrics,
        });

        row_top_rel += line_height;
    }

    let width = layout.width() as f64;
    let height = layout.height() as f64;

    TextLayout {
        lines,
        width,
        height,
    }
}

/// Look up the extended attributes (url / decoration / background / baseline_shift) for
/// the byte range `[start, end)`.
///
/// A run may span multiple spans (after CJK prioritization, parley often merges a whole
/// line into one run). We therefore match by **range overlap**: prefer a span that
/// overlaps `[start, end)` and carries a url / background; otherwise fall back to the
/// span containing the start point. This way, when "plain text + inline link" is merged
/// into a single run, the link span's url still hits, not just the span at the run's
/// start.
fn lookup_extended_props(
    start: usize,
    end: usize,
    span_ranges: &[(usize, usize, &TextStyle)],
) -> (Option<String>, TextDecoration, Option<Color>, f32) {
    let matched = span_ranges
        .iter()
        .find(|(s, e, st)| {
            *s < end && *e > start && (st.url.is_some() || st.background_color.is_some())
        })
        .or_else(|| {
            span_ranges
                .iter()
                .find(|(s, e, _)| *s <= start && start < *e)
        });
    match matched {
        Some((_, _, st)) => {
            let decoration = if st.underline && st.strikethrough {
                // On conflict treat as none (the caller applies span-level styles itself).
                TextDecoration::None
            } else if st.strikethrough {
                TextDecoration::LineThrough
            } else if st.underline {
                TextDecoration::Underline
            } else {
                TextDecoration::None
            };
            (
                st.url.clone(),
                decoration,
                st.background_color,
                st.baseline_shift as f32,
            )
        }
        None => (None, TextDecoration::None, None, 0.0),
    }
}

/// Font source.
#[derive(Debug, Clone)]
pub enum FontSource {
    /// Load from a file path.
    Path(std::path::PathBuf),
    /// Load from in-memory data.
    Memory(Vec<u8>),
}

/// Register a custom font into the process-wide font collection.
///
/// Once loaded, the font can be referenced by its `font_family` name in text styles.
/// Registration is visible to **every** thread (each thread's context is a clone of the
/// shared collection), so it covers measurement and rendering alike, including threads
/// started after the registration.
pub fn register_font(source: FontSource, family_name_override: Option<&str>) -> Result<(), String> {
    register_font_generic(source, family_name_override, None)
}

/// Register a custom font and optionally associate it with a **generic font family**
/// (`GenericFamily`).
///
/// Same as [`register_font`], with the extra ability to attach the font to a generic
/// family such as `sans-serif` / `monospace` / `serif`, so that `font-family: monospace`
/// uses the registered font instead of the system default. With `generic_family` set to
/// `None` it is equivalent to [`register_font`].
///
/// The generic-family type [`parley::fontique::GenericFamily`] is re-exported via
/// [`crate::parley`].
pub fn register_font_generic(
    source: FontSource,
    family_name_override: Option<&str>,
    generic_family: Option<parley::fontique::GenericFamily>,
) -> Result<(), String> {
    use parley::fontique::Blob;
    use std::sync::Arc;

    let data = match source {
        FontSource::Path(path) => {
            let bytes =
                std::fs::read(&path).map_err(|e| format!("Failed to read font file: {e}"))?;
            Blob::new(Arc::new(bytes))
        }
        FontSource::Memory(bytes) => Blob::new(Arc::new(bytes)),
    };

    let override_info = family_name_override.map(|name| parley::fontique::FontInfoOverride {
        family_name: Some(name),
        ..Default::default()
    });

    // Register into the process-wide (shared) collection: every clone — including the
    // current thread's and those created by threads started later — observes it.
    let mut collection = global_font_collection()
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let registered = collection.register_fonts(data, override_info);
    if let Some(generic) = generic_family {
        let ids: Vec<_> = registered.into_iter().map(|(id, _)| id).collect();
        collection.append_generic_families(generic, ids.into_iter());
    }
    drop(collection);
    // Touch the thread-local context once so it pulls the new shared state (fontique
    // syncs lazily on the next query; this makes it deterministic for the caller).
    with_cached_context(|font_cx, _| {
        let _ = font_cx.collection.family_names().count();
    });
    Ok(())
}

/// Parse a generic family name (`"monospace"` / `"sans-serif"`, etc.) into parley's
/// [`parley::fontique::GenericFamily`].
///
/// Used to associate a registered font with a generic family (see
/// [`register_font_generic`]) and to normalize generic family names inside `font-family`.
/// Returns `None` when the name is not recognized.
#[must_use]
pub fn parse_generic_family(name: &str) -> Option<parley::fontique::GenericFamily> {
    use parley::fontique::GenericFamily;
    match name.to_lowercase().as_str() {
        "serif" => Some(GenericFamily::Serif),
        "sans-serif" | "sansserif" => Some(GenericFamily::SansSerif),
        "monospace" => Some(GenericFamily::Monospace),
        "cursive" => Some(GenericFamily::Cursive),
        "fantasy" => Some(GenericFamily::Fantasy),
        "system-ui" | "systemui" => Some(GenericFamily::SystemUi),
        "ui-serif" | "uiserif" => Some(GenericFamily::UiSerif),
        "ui-sans-serif" | "uisansserif" => Some(GenericFamily::UiSansSerif),
        "ui-monospace" | "uimonospace" => Some(GenericFamily::UiMonospace),
        "ui-rounded" | "uirounded" => Some(GenericFamily::UiRounded),
        "emoji" => Some(GenericFamily::Emoji),
        "math" => Some(GenericFamily::Math),
        "fangsong" => Some(GenericFamily::FangSong),
        _ => None,
    }
}

pub fn compute_text_offset(
    layout: &TextLayout,
    align: TextAlign,
    baseline: TextBaseline,
) -> (f64, f64) {
    let layout_width = layout.width;
    let layout_height = layout.height;

    let x_offset = match align {
        TextAlign::Left | TextAlign::Justify => 0.0,
        TextAlign::Center => -layout_width / 2.0,
        TextAlign::Right => -layout_width,
    };

    let y_offset = match baseline {
        TextBaseline::Top => 0.0,

        // Visual centering: use cap bounds (baseline - cap_height → baseline).
        // Mirrors CSS `text-box-edge: cap alphabetic`. cap_height is a
        // font-level constant, so the offset does NOT jump when button text
        // changes.
        TextBaseline::Middle => {
            let cb = layout.cap_bounds();
            let vh = (cb.max_y() - cb.min_y()).max(0.0);
            if vh > 0.0 {
                -(cb.min_y() + vh / 2.0)
            } else {
                -layout_height / 2.0
            }
        }

        // Bottom: use logical (content) bounds so descenders (g / y / p / q)
        // are not clipped. Cap bounds would cut everything below the baseline.
        TextBaseline::Bottom => {
            let lb = layout.logical_bounds();
            let vh = (lb.max_y() - lb.min_y()).max(0.0);
            if vh > 0.0 {
                -(lb.min_y() + vh)
            } else {
                -layout_height
            }
        }

        TextBaseline::Alphabetic => -layout_metrics(layout).alphabetic_baseline,

        TextBaseline::Hanging => {
            let m = layout_metrics(layout);
            if layout.lines.is_empty() {
                -(layout_height * HANGING_ASCENT_RATIO)
            } else {
                -m.hanging_baseline
            }
        }
        TextBaseline::Ideographic => {
            let m = layout_metrics(layout);
            if layout.lines.is_empty() {
                -(layout_height * HANGING_ASCENT_RATIO)
            } else {
                -m.ideographic_baseline
            }
        }
    };

    (x_offset, y_offset)
}