dxpdf 0.3.1

A fast DOCX-to-PDF converter powered by Skia
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
//! Font resolution and caching with per-render ownership (`FontRegistry`).
//!
//! `FontRegistry` is the single source of truth for typeface data within
//! one render. It owns:
//!
//! - the document's embedded-font bytes (deobfuscated upstream by the
//!   parser per ECMA-376 §17.8.3.3),
//! - a cache of resolved Skia [`Typeface`]s keyed by (family, weight,
//!   slant), with embedded fonts taking priority over system resolution.
//!
//! A `FontRegistry` is constructed per render and passed by reference to
//! layout and paint. The previous `thread_local!` typeface cache leaked
//! typefaces across renders — once font subsetting mutates them, that
//! becomes a real correctness bug. With per-render ownership, no such
//! leakage is possible.

use std::cell::{OnceCell, RefCell};
use std::collections::HashMap;

use skia_safe::font_style::{Slant, Weight, Width};
use skia_safe::{Data, Font, FontMgr, FontStyle, Typeface};

use crate::model::{EmbeddedFont, EmbeddedFontVariant};
use crate::render::dimension::Pt;

// ─── Public types ───────────────────────────────────────────────────────────

/// Stable id for an embedded font registered in the registry.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EmbeddedFontId(u32);

impl EmbeddedFontId {
    pub fn raw(self) -> u32 {
        self.0
    }
}

/// Identity for a Skia [`Typeface`], wrapping `Typeface::unique_id`.
/// Used as the join key with [`crate::render::subset::CodepointUsage`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TypefaceId(pub u32);

impl From<&Typeface> for TypefaceId {
    fn from(tf: &Typeface) -> Self {
        Self(tf.unique_id())
    }
}

/// Single source of truth for "where did this typeface come from?" — drives
/// byte extraction during subsetting (Embedded → registry's bytes, System →
/// `Typeface::to_font_data`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TypefaceOrigin {
    /// Resolved from a font embedded in the DOCX (`word/fonts/*.odttf`).
    Embedded { id: EmbeddedFontId },
    /// Resolved through Skia's `FontMgr` — exact match, substitution, or
    /// system default fallback. The id is the original Skia typeface id
    /// at resolution time.
    System { typeface_id: TypefaceId },
}

#[derive(Clone, Debug)]
pub struct TypefaceEntry {
    pub typeface: Typeface,
    pub origin: TypefaceOrigin,
}

/// Cache key for resolved typefaces — case-insensitive family + weight + slant.
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
pub struct TypefaceKey {
    pub family_lc: String,
    pub weight: i32,
    pub slant: skia_safe::font_style::Slant,
}

impl TypefaceKey {
    pub fn new(family: &str, style: FontStyle) -> Self {
        Self {
            family_lc: family.to_lowercase(),
            weight: *style.weight(),
            slant: style.slant(),
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum RegisterError {
    #[error("invalid embedded font data for '{family}' ({variant:?})")]
    InvalidFontData {
        family: String,
        variant: EmbeddedFontVariant,
    },
}

/// Open-source metric-compatible substitutes for proprietary fonts. Tried
/// in order when `match_family_style` for the requested family fails.
const FONT_SUBSTITUTIONS: &[(&str, &[&str])] = &[
    ("Calibri", &["Carlito", "Liberation Sans", "Noto Sans"]),
    ("Cambria", &["Caladea", "Liberation Serif", "Noto Serif"]),
    ("Arial", &["Liberation Sans", "Noto Sans", "Helvetica"]),
    (
        "Times New Roman",
        &["Liberation Serif", "Noto Serif", "Times"],
    ),
    (
        "Courier New",
        &["Liberation Mono", "Noto Sans Mono", "Courier"],
    ),
    ("Verdana", &["DejaVu Sans", "Noto Sans"]),
    ("Georgia", &["DejaVu Serif", "Noto Serif"]),
    ("Trebuchet MS", &["Ubuntu", "Noto Sans"]),
    (
        "Consolas",
        &["Inconsolata", "Liberation Mono", "Noto Sans Mono"],
    ),
    ("Segoe UI", &["Noto Sans", "Liberation Sans"]),
];

#[derive(Debug, Clone)]
struct EmbeddedRecord {
    family: String,
    variant: EmbeddedFontVariant,
    bytes: Vec<u8>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct FaceAlias {
    family: String,
    weight: i32,
}

#[derive(Clone, Debug)]
enum AliasEntry {
    Unique(FaceAlias),
    Ambiguous,
}

#[derive(Default)]
struct FaceAliasIndex {
    aliases: HashMap<String, AliasEntry>,
}

impl FaceAliasIndex {
    fn build(font_mgr: &FontMgr) -> Self {
        let mut index = Self::default();

        for family in font_mgr.family_names() {
            let mut style_set = font_mgr.match_family(&family);
            let count = style_set.count();
            for face_index in 0..count {
                let (style, style_name) = style_set.style(face_index);
                let post_script_name = style_set
                    .new_typeface(face_index)
                    .and_then(|typeface| typeface.post_script_name());
                index.insert_face(
                    &family,
                    style,
                    style_name.as_deref(),
                    post_script_name.as_deref(),
                );
            }
        }

        index
    }

    fn insert_face(
        &mut self,
        family: &str,
        style: FontStyle,
        style_name: Option<&str>,
        post_script_name: Option<&str>,
    ) {
        // This compatibility layer resolves weight-bearing face names. Width
        // and slant aliases require a fuller OpenType identity model.
        if style.width() != Width::NORMAL || style.slant() != Slant::Upright {
            return;
        }

        let alias = FaceAlias {
            family: family.to_owned(),
            weight: *style.weight(),
        };

        if let Some(style_name) = style_name.filter(|name| !name.trim().is_empty()) {
            self.insert_alias(&format!("{family} {style_name}"), alias.clone());
        }
        if let Some(post_script_name) = post_script_name.filter(|name| !name.trim().is_empty()) {
            self.insert_alias(post_script_name, alias.clone());
        }
        for weight_name in canonical_weight_names(alias.weight) {
            self.insert_alias(&format!("{family} {weight_name}"), alias.clone());
        }
    }

    fn insert_alias(&mut self, name: &str, alias: FaceAlias) {
        use std::collections::hash_map::Entry;

        match self.aliases.entry(face_name_key(name)) {
            Entry::Vacant(entry) => {
                entry.insert(AliasEntry::Unique(alias));
            }
            Entry::Occupied(mut entry) => match entry.get() {
                AliasEntry::Unique(existing) if existing == &alias => {}
                AliasEntry::Unique(_) => {
                    entry.insert(AliasEntry::Ambiguous);
                }
                AliasEntry::Ambiguous => {}
            },
        }
    }

    fn resolve(&self, name: &str) -> Option<&FaceAlias> {
        match self.aliases.get(&face_name_key(name))? {
            AliasEntry::Unique(alias) => Some(alias),
            AliasEntry::Ambiguous => None,
        }
    }
}

fn face_name_key(name: &str) -> String {
    name.split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_lowercase()
}

fn canonical_weight_names(weight: i32) -> &'static [&'static str] {
    match weight {
        100 => &["Thin", "Hairline"],
        200 => &["ExtraLight", "Extra Light", "UltraLight", "Ultra Light"],
        300 => &["Light"],
        400 => &["Regular", "Normal"],
        500 => &["Medium"],
        600 => &["Semibold", "SemiBold", "Semi Bold", "DemiBold", "Demi Bold"],
        700 => &["Bold"],
        800 => &["ExtraBold", "Extra Bold", "UltraBold", "Ultra Bold"],
        900 => &["Black", "Heavy"],
        _ => &[],
    }
}

fn merged_alias_weight(alias_weight: i32, requested_weight: i32) -> i32 {
    alias_weight.max(requested_weight)
}

fn style_for_face_alias(alias: &FaceAlias, requested: FontStyle) -> FontStyle {
    FontStyle::new(
        Weight::from(merged_alias_weight(alias.weight, *requested.weight())),
        Width::NORMAL,
        requested.slant(),
    )
}

// ─── FontRegistry ────────────────────────────────────────────────────────────

pub struct FontRegistry {
    font_mgr: FontMgr,
    embedded: Vec<EmbeddedRecord>,
    embedded_index: HashMap<(String, EmbeddedFontVariant), EmbeddedFontId>,
    system_face_aliases: OnceCell<FaceAliasIndex>,
    typefaces: RefCell<HashMap<TypefaceKey, TypefaceEntry>>,
}

impl FontRegistry {
    /// Empty registry without any embedded fonts.
    pub fn new(font_mgr: FontMgr) -> Self {
        Self {
            font_mgr,
            embedded: Vec::new(),
            embedded_index: HashMap::new(),
            system_face_aliases: OnceCell::new(),
            typefaces: RefCell::new(HashMap::new()),
        }
    }

    /// Build a registry, registering all embedded fonts and preloading the
    /// requested family/style combinations.
    pub fn build(font_mgr: FontMgr, embedded: &[EmbeddedFont], families: &[String]) -> Self {
        let mut reg = Self::new(font_mgr);
        for ef in embedded {
            if let Err(err) = reg.register_embedded(&ef.family, ef.variant, ef.data.clone()) {
                log::warn!("{err}");
            }
        }
        reg.preload(families);
        reg
    }

    pub fn font_mgr(&self) -> &FontMgr {
        &self.font_mgr
    }

    pub fn embedded_font_count(&self) -> usize {
        self.embedded.len()
    }

    pub fn cached_typeface_count(&self) -> usize {
        self.typefaces.borrow().len()
    }

    /// Register an embedded font. Subsequent `resolve` calls for the same
    /// family + variant will return this typeface in preference to system
    /// resolution.
    pub fn register_embedded(
        &mut self,
        family: &str,
        variant: EmbeddedFontVariant,
        bytes: Vec<u8>,
    ) -> Result<EmbeddedFontId, RegisterError> {
        let data = Data::new_copy(&bytes);
        let typeface = self.font_mgr.new_from_data(&data, 0).ok_or_else(|| {
            RegisterError::InvalidFontData {
                family: family.to_string(),
                variant,
            }
        })?;
        let id = EmbeddedFontId(self.embedded.len() as u32);
        self.embedded.push(EmbeddedRecord {
            family: family.to_string(),
            variant,
            bytes,
        });
        self.embedded_index
            .insert((family.to_lowercase(), variant), id);
        let style = font_style_for_variant(variant);
        let key = TypefaceKey::new(family, style);
        self.typefaces.borrow_mut().insert(
            key,
            TypefaceEntry {
                typeface,
                origin: TypefaceOrigin::Embedded { id },
            },
        );
        log::debug!("registered embedded font '{}' {:?}", family, variant);
        Ok(id)
    }

    /// Bytes for a registered embedded font.
    pub fn embedded_bytes(&self, id: EmbeddedFontId) -> &[u8] {
        &self.embedded[id.0 as usize].bytes
    }

    /// Family + variant for a registered embedded font.
    pub fn embedded_meta(&self, id: EmbeddedFontId) -> (&str, EmbeddedFontVariant) {
        let r = &self.embedded[id.0 as usize];
        (&r.family, r.variant)
    }

    /// Resolve a typeface by family + style. Embedded fonts win over system.
    /// Cached after the first resolution; later calls are O(1).
    pub fn resolve(&self, family: &str, style: FontStyle) -> TypefaceEntry {
        let key = TypefaceKey::new(family, style);

        if let Some(entry) = self.typefaces.borrow().get(&key) {
            return entry.clone();
        }

        let entry = self.resolve_uncached(family, style);
        self.typefaces.borrow_mut().insert(key, entry.clone());
        entry
    }

    fn resolve_uncached(&self, family: &str, style: FontStyle) -> TypefaceEntry {
        let variant = variant_for_style(style);
        if let Some(id) = self
            .embedded_index
            .get(&(family.to_lowercase(), variant))
            .copied()
        {
            let bytes = &self.embedded[id.0 as usize].bytes;
            let data = Data::new_copy(bytes);
            if let Some(tf) = self.font_mgr.new_from_data(&data, 0) {
                log::debug!("[font] '{}' {:?} → embedded #{}", family, style, id.0);
                return TypefaceEntry {
                    typeface: tf,
                    origin: TypefaceOrigin::Embedded { id },
                };
            }
        }

        if let Some(tf) = match_exact(&self.font_mgr, family, style) {
            log::debug!("[font] '{}' {:?} → exact match", family, style);
            return system_entry(tf);
        }

        if let Some(alias) = self
            .system_face_aliases
            .get_or_init(|| FaceAliasIndex::build(&self.font_mgr))
            .resolve(family)
        {
            let alias_style = style_for_face_alias(alias, style);
            if let Some(tf) = match_exact(&self.font_mgr, &alias.family, alias_style) {
                log::debug!(
                    "[font] '{}' {:?} → face alias '{}' {:?}",
                    family,
                    style,
                    alias.family,
                    alias_style
                );
                return system_entry(tf);
            }
        }

        if let Some((_, subs)) = FONT_SUBSTITUTIONS
            .iter()
            .find(|(name, _)| name.eq_ignore_ascii_case(family))
        {
            for sub in *subs {
                if let Some(tf) = match_exact(&self.font_mgr, sub, style) {
                    log::debug!("[font] '{}' {:?} → substitute '{}'", family, style, sub);
                    return system_entry(tf);
                }
            }
        }

        let tf = self
            .font_mgr
            .legacy_make_typeface(None::<&str>, style)
            .expect("no fallback typeface available");
        log::debug!(
            "[font] '{}' {:?} → system default '{}'",
            family,
            style,
            tf.family_name()
        );
        system_entry(tf)
    }

    /// Resolve a typeface by exact family + style match, or `None` if the
    /// family is neither registered as an embedded font nor present in the
    /// host's font system.
    ///
    /// Unlike [`resolve`], this does not fall back to substitutes or to the
    /// system default — necessary for the emoji pipeline, where substituting
    /// a non-emoji typeface for a missing color emoji font is never correct.
    pub fn resolve_exact(&self, family: &str, style: FontStyle) -> Option<TypefaceEntry> {
        let variant = variant_for_style(style);
        if let Some(id) = self
            .embedded_index
            .get(&(family.to_lowercase(), variant))
            .copied()
        {
            let bytes = &self.embedded[id.0 as usize].bytes;
            let data = Data::new_copy(bytes);
            if let Some(tf) = self.font_mgr.new_from_data(&data, 0) {
                return Some(TypefaceEntry {
                    typeface: tf,
                    origin: TypefaceOrigin::Embedded { id },
                });
            }
        }
        match_exact(&self.font_mgr, family, style).map(system_entry)
    }

    /// Resolve a typeface from the host font system only — bypasses the
    /// embedded-font index. Used by the color emoji pipeline: Word's font
    /// subsetter strips color glyph tables (sbix/CBDT/COLR/SVG) when
    /// embedding emoji fonts, so a docx-embedded "Segoe UI Emoji" carries
    /// the right family name but no color glyphs and must not satisfy
    /// emoji resolution.
    pub fn resolve_system_only(&self, family: &str, style: FontStyle) -> Option<TypefaceEntry> {
        match_exact(&self.font_mgr, family, style).map(system_entry)
    }

    /// Pre-resolve all four style variants for each family.
    pub fn preload(&self, families: &[String]) {
        let styles = [
            FontStyle::normal(),
            FontStyle::bold(),
            FontStyle::italic(),
            FontStyle::bold_italic(),
        ];
        for family in families {
            for &style in &styles {
                self.resolve(family, style);
            }
        }
    }

    /// Replace the typeface for every cached entry whose current id matches
    /// `old_id`. Returns the number of entries updated. Used by the font-
    /// subsetting pass to swap in subsetted bytes; multiple cache keys can
    /// share one underlying typeface (e.g. Calibri → Carlito substitution
    /// causes both keys to point at the same Skia typeface), so we update
    /// them all at once.
    pub fn replace_typeface_by_id(
        &mut self,
        old_id: TypefaceId,
        new_typeface: Typeface,
        new_origin: TypefaceOrigin,
    ) -> usize {
        let mut count = 0;
        for entry in self.typefaces.get_mut().values_mut() {
            if TypefaceId::from(&entry.typeface) == old_id {
                entry.typeface = new_typeface.clone();
                entry.origin = new_origin.clone();
                count += 1;
            }
        }
        count
    }

    /// Snapshot of all cached entries.
    pub fn cached_entries(&self) -> Vec<(TypefaceKey, TypefaceEntry)> {
        self.typefaces
            .borrow()
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect()
    }
}

// ─── Helpers ────────────────────────────────────────────────────────────────

fn font_style_for_variant(v: EmbeddedFontVariant) -> FontStyle {
    match v {
        EmbeddedFontVariant::Regular => FontStyle::normal(),
        EmbeddedFontVariant::Bold => FontStyle::bold(),
        EmbeddedFontVariant::Italic => FontStyle::italic(),
        EmbeddedFontVariant::BoldItalic => FontStyle::bold_italic(),
    }
}

fn variant_for_style(style: FontStyle) -> EmbeddedFontVariant {
    use skia_safe::font_style::{Slant, Weight};
    let bold = *style.weight() >= *Weight::SEMI_BOLD;
    let italic = matches!(style.slant(), Slant::Italic | Slant::Oblique);
    match (bold, italic) {
        (true, true) => EmbeddedFontVariant::BoldItalic,
        (true, false) => EmbeddedFontVariant::Bold,
        (false, true) => EmbeddedFontVariant::Italic,
        (false, false) => EmbeddedFontVariant::Regular,
    }
}

fn match_exact(font_mgr: &FontMgr, family: &str, style: FontStyle) -> Option<Typeface> {
    let tf = font_mgr.match_family_style(family, style)?;
    if tf.family_name().eq_ignore_ascii_case(family) {
        Some(tf)
    } else {
        None
    }
}

fn system_entry(tf: Typeface) -> TypefaceEntry {
    let id = TypefaceId::from(&tf);
    TypefaceEntry {
        typeface: tf,
        origin: TypefaceOrigin::System { typeface_id: id },
    }
}

// ─── FontCache (per-component, not per-render) ──────────────────────────────

#[derive(Hash, Eq, PartialEq)]
struct FontKey {
    family: String,
    /// Font size stored as bits for exact f32 hashing.
    size_bits: u32,
    weight: i32,
    slant: skia_safe::font_style::Slant,
}

/// Raw (un-folded) inputs of the most recent [`FontCache::get`] call plus the
/// slot its result lives in. Words within a run share one `FontProps`, so
/// consecutive calls usually match this exactly and skip the `to_lowercase`
/// allocation and the hash lookup entirely.
struct LastCall {
    family: String,
    size_bits: u32,
    weight: i32,
    slant: skia_safe::font_style::Slant,
    idx: usize,
}

/// Per-component cache of fully-configured `Font` objects, avoiding repeated
/// `FontRegistry::resolve` lookups and `Font::from_typeface` construction.
///
/// `fonts` owns the resolved `Font`s (append-only, so slot indices stay
/// stable); `index` maps a case-folded [`FontKey`] to a slot; `last` is a
/// one-entry fast path keyed on the raw inputs of the previous call, so the
/// common per-word case costs no allocation and no hashing.
///
/// Must be discarded if the underlying `FontRegistry` is mutated (e.g. by
/// `replace_typeface_by_id`). The render pipeline already creates a fresh
/// `FontCache` for layout and another for paint, with the subset pass in
/// between; no stale Font objects can survive.
#[derive(Default)]
pub struct FontCache {
    fonts: Vec<Font>,
    index: HashMap<FontKey, usize>,
    last: Option<LastCall>,
}

impl FontCache {
    pub fn new() -> Self {
        Self::default()
    }

    /// Get or create a `Font` for the given properties.
    pub fn get(
        &mut self,
        registry: &FontRegistry,
        font_family: &str,
        font_size: Pt,
        bold: bool,
        italic: bool,
    ) -> &Font {
        self.get_indexed(registry, font_family, font_size, bold, italic)
            .1
    }

    /// Like [`get`](Self::get), but also returns the resolved `Font`'s stable
    /// slot index. The index is a cheap integer identity for the (family, size,
    /// weight, slant) tuple — higher-level caches (e.g. the measurer's width
    /// memo) key on it to avoid re-hashing the family string per call.
    pub fn get_indexed(
        &mut self,
        registry: &FontRegistry,
        font_family: &str,
        font_size: Pt,
        bold: bool,
        italic: bool,
    ) -> (usize, &Font) {
        let style = match (bold, italic) {
            (true, true) => FontStyle::bold_italic(),
            (true, false) => FontStyle::bold(),
            (false, true) => FontStyle::italic(),
            (false, false) => FontStyle::normal(),
        };
        let size_bits = f32::from(font_size).to_bits();
        let weight = *style.weight();
        let slant = style.slant();

        // Fast path: identical inputs to the previous call. Exact string
        // comparison keeps this behaviour-identical to the case-folded slow
        // path (a hit resolves to the same `Font`), while avoiding the
        // per-call `to_lowercase` allocation and hash probe. `idx` is copied
        // out so the `last` borrow ends before `fonts` is indexed.
        let hit = self.last.as_ref().and_then(|last| {
            (last.size_bits == size_bits
                && last.weight == weight
                && last.slant == slant
                && last.family == font_family)
                .then_some(last.idx)
        });
        if let Some(idx) = hit {
            return (idx, &self.fonts[idx]);
        }

        // Slow path: case-folded hash lookup. The owned `FontKey` (with its
        // lowercased `String`) is built only here — at most once per distinct
        // (family, size, style), not once per call.
        let key = FontKey {
            family: font_family.to_lowercase(),
            size_bits,
            weight,
            slant,
        };
        let idx = match self.index.get(&key) {
            Some(&i) => i,
            None => {
                let resolve_style = FontStyle::new(
                    skia_safe::font_style::Weight::from(weight),
                    skia_safe::font_style::Width::NORMAL,
                    slant,
                );
                let entry = registry.resolve(font_family, resolve_style);
                let mut font = Font::from_typeface(entry.typeface, f32::from(font_size));
                font.set_subpixel(true);
                font.set_linear_metrics(true);
                font.set_hinting(skia_safe::FontHinting::None);
                let i = self.fonts.len();
                self.fonts.push(font);
                self.index.insert(key, i);
                i
            }
        };
        self.last = Some(LastCall {
            family: font_family.to_owned(),
            size_bits,
            weight,
            slant,
            idx,
        });
        (idx, &self.fonts[idx])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use skia_safe::font_style::{Slant, Weight, Width};

    fn fmgr() -> FontMgr {
        FontMgr::new()
    }

    fn test_alias(family: &str, weight: i32) -> FaceAlias {
        FaceAlias {
            family: family.to_owned(),
            weight,
        }
    }

    #[test]
    fn face_aliases_support_semibold_spellings() {
        let mut index = FaceAliasIndex::default();
        index.insert_face(
            "Proxima Nova",
            FontStyle::new(Weight::SEMI_BOLD, Width::NORMAL, Slant::Upright),
            Some("Semibold"),
            Some("ProximaNova-Semibold"),
        );

        for name in [
            "Proxima Nova Semibold",
            "Proxima Nova SemiBold",
            "Proxima Nova Semi Bold",
            "ProximaNova-Semibold",
        ] {
            let alias = index.resolve(name).expect("alias should resolve");
            assert_eq!(alias.family, "Proxima Nova");
            assert_eq!(alias.weight, *Weight::SEMI_BOLD);
        }
    }

    #[test]
    fn face_aliases_support_extra_bold_spellings() {
        let mut index = FaceAliasIndex::default();
        index.insert_face(
            "Inter",
            FontStyle::new(Weight::EXTRA_BOLD, Width::NORMAL, Slant::Upright),
            Some("ExtraBold"),
            Some("Inter-ExtraBold"),
        );

        for name in ["Inter ExtraBold", "Inter Extra Bold", "Inter-ExtraBold"] {
            assert_eq!(
                index.resolve(name).expect("alias should resolve").weight,
                *Weight::EXTRA_BOLD
            );
        }
    }

    #[test]
    fn face_alias_keys_ignore_case_and_repeated_whitespace() {
        assert_eq!(
            face_name_key("  Proxima   Nova SEMIBOLD "),
            face_name_key("proxima nova semibold")
        );
    }

    #[test]
    fn face_alias_keys_preserve_punctuation() {
        assert_ne!(face_name_key("A-B"), face_name_key("AB"));
    }

    #[test]
    fn conflicting_face_aliases_are_ambiguous() {
        let mut index = FaceAliasIndex::default();
        index.insert_alias("Shared Alias", test_alias("Family A", 600));
        index.insert_alias("Shared Alias", test_alias("Family B", 600));

        assert!(index.resolve("Shared Alias").is_none());
    }

    #[test]
    fn requested_weight_never_downgrades_face_alias_weight() {
        assert_eq!(
            merged_alias_weight(*Weight::SEMI_BOLD, *Weight::BOLD),
            *Weight::BOLD
        );
        assert_eq!(
            merged_alias_weight(*Weight::EXTRA_BOLD, *Weight::BOLD),
            *Weight::EXTRA_BOLD
        );
    }

    #[test]
    fn face_alias_style_preserves_requested_slant() {
        let alias = test_alias("Proxima Nova", *Weight::SEMI_BOLD);
        let requested = FontStyle::new(Weight::NORMAL, Width::NORMAL, Slant::Italic);

        let resolved = style_for_face_alias(&alias, requested);

        assert_eq!(*resolved.weight(), *Weight::SEMI_BOLD);
        assert_eq!(resolved.width(), Width::NORMAL);
        assert_eq!(resolved.slant(), Slant::Italic);
    }

    /// Pull bytes from a guaranteed-available system typeface so tests don't
    /// need bundled font fixtures for the registry-level invariants.
    fn arbitrary_system_font_bytes() -> Vec<u8> {
        let mgr = fmgr();
        let tf = mgr
            .legacy_make_typeface(None::<&str>, FontStyle::normal())
            .expect("system has no default typeface — cannot run test");
        let (bytes, _ttc_index) = tf
            .to_font_data()
            .expect("legacy default typeface lacks raw font bytes — cannot run test");
        bytes
    }

    #[test]
    fn registry_empty_after_construction() {
        let r = FontRegistry::new(fmgr());
        assert_eq!(r.embedded_font_count(), 0);
        assert_eq!(r.cached_typeface_count(), 0);
    }

    #[test]
    fn registry_resolves_system_font_idempotently() {
        let r = FontRegistry::new(fmgr());
        let a = r.resolve("DefinitelyNotInstalledXYZ", FontStyle::normal());
        let b = r.resolve("DefinitelyNotInstalledXYZ", FontStyle::normal());
        assert_eq!(
            TypefaceId::from(&a.typeface),
            TypefaceId::from(&b.typeface),
            "second resolution must hit the cache and yield the same typeface"
        );
        assert!(matches!(a.origin, TypefaceOrigin::System { .. }));
    }

    #[test]
    fn registry_embedded_takes_precedence_over_system() {
        let bytes = arbitrary_system_font_bytes();

        let mut without = FontRegistry::new(fmgr());
        let baseline = without.resolve("NonexistentFamilyABC", FontStyle::normal());
        assert!(
            matches!(baseline.origin, TypefaceOrigin::System { .. }),
            "without embedding, an unknown family must fall back to the system path"
        );
        // Quiet the unused-mut warning while making the contrast explicit.
        let _ = &mut without;

        let mut with = FontRegistry::new(fmgr());
        let id = with
            .register_embedded("NonexistentFamilyABC", EmbeddedFontVariant::Regular, bytes)
            .expect("register_embedded should accept a valid system font's bytes");
        let resolved = with.resolve("NonexistentFamilyABC", FontStyle::normal());
        assert_eq!(
            resolved.origin,
            TypefaceOrigin::Embedded { id },
            "after registration, resolution must return the embedded origin"
        );
    }

    #[test]
    fn registry_stores_embedded_bytes_byte_identical() {
        // ECMA-376 §17.8.3.3 deobfuscation is enforced upstream by the parser
        // (see src/docx/parse/fonts.rs::deobfuscate_round_trip). The registry-
        // level invariant is that the bytes it stores must be byte-identical
        // to the bytes handed in — no re-encoding, no normalization.
        let bytes = arbitrary_system_font_bytes();
        let mut r = FontRegistry::new(fmgr());
        let id = r
            .register_embedded(
                "ByteIdentityProbe",
                EmbeddedFontVariant::Regular,
                bytes.clone(),
            )
            .expect("registration should succeed for valid font bytes");
        assert_eq!(
            r.embedded_bytes(id),
            bytes.as_slice(),
            "stored bytes must match the originally passed-in bytes byte-for-byte"
        );
    }

    #[test]
    fn registry_drop_clears_all_typefaces() {
        // Two registries on the same thread must not share state — this is
        // the structural fix for the cross-render poisoning that the previous
        // thread_local!-backed cache caused.
        let r1 = FontRegistry::new(fmgr());
        let _ = r1.resolve("FamilyOne", FontStyle::normal());
        assert_eq!(r1.cached_typeface_count(), 1);
        drop(r1);

        let r2 = FontRegistry::new(fmgr());
        assert_eq!(
            r2.cached_typeface_count(),
            0,
            "a fresh registry must not see typefaces cached by an earlier one"
        );
    }

    #[test]
    fn registry_resolution_records_origin() {
        // Every resolved entry must report a non-default origin variant.
        let bytes = arbitrary_system_font_bytes();
        let mut r = FontRegistry::new(fmgr());
        r.register_embedded("OriginEmbedded", EmbeddedFontVariant::Regular, bytes)
            .unwrap();
        let _ = r.resolve("OriginEmbedded", FontStyle::normal());
        let _ = r.resolve("OriginSystemFallbackXYZ", FontStyle::normal());

        for (_, entry) in r.cached_entries() {
            match entry.origin {
                TypefaceOrigin::Embedded { .. } | TypefaceOrigin::System { .. } => {}
            }
        }
    }

    #[test]
    fn replace_typeface_by_id_updates_all_keys_pointing_at_it() {
        // Two distinct cache keys can share one underlying typeface (e.g. via
        // FONT_SUBSTITUTIONS). The subsetting pass must update them all so
        // paint never sees a stale typeface.
        let mut r = FontRegistry::new(fmgr());

        // Two unknown families → both fall back to the system default → same
        // underlying Skia typeface.
        let a = r.resolve("UnknownFamilyA", FontStyle::normal());
        let b = r.resolve("UnknownFamilyB", FontStyle::normal());
        assert_eq!(
            TypefaceId::from(&a.typeface),
            TypefaceId::from(&b.typeface),
            "test setup precondition — both unknowns must resolve to the same default"
        );
        let shared_id = TypefaceId::from(&a.typeface);

        // Build a *different* typeface to swap in.
        let bytes = arbitrary_system_font_bytes();
        let data = Data::new_copy(&bytes);
        let replacement = r
            .font_mgr()
            .new_from_data(&data, 0)
            .expect("replacement typeface should construct from valid bytes");
        let replacement_origin = TypefaceOrigin::System {
            typeface_id: TypefaceId::from(&replacement),
        };

        let updated = r.replace_typeface_by_id(shared_id, replacement, replacement_origin);
        assert_eq!(
            updated, 2,
            "both shared-typeface entries must be updated in lockstep"
        );

        // Subsequent resolution returns the new typeface, not the old one.
        let after = r.resolve("UnknownFamilyA", FontStyle::normal());
        assert_ne!(
            TypefaceId::from(&after.typeface),
            shared_id,
            "post-replace resolution must yield the new typeface"
        );
    }

    #[test]
    fn font_cache_uses_registry_after_replacement() {
        // The cross-cutting invariant: if the registry is mutated and a
        // *new* FontCache is created afterwards, that cache must produce
        // Fonts backed by the new typeface. (Stale FontCaches must be
        // discarded — that contract is satisfied by the pipeline creating
        // fresh caches around the subset pass.)
        let mut r = FontRegistry::new(fmgr());
        let original = r.resolve("CacheReplaceProbe", FontStyle::normal());
        let original_id = TypefaceId::from(&original.typeface);

        let bytes = arbitrary_system_font_bytes();
        let data = Data::new_copy(&bytes);
        let replacement = r
            .font_mgr()
            .new_from_data(&data, 0)
            .expect("replacement typeface should construct");
        let new_id = TypefaceId::from(&replacement);
        assert_ne!(
            new_id, original_id,
            "test precondition — replacement must be a different typeface"
        );
        let replacement_origin = TypefaceOrigin::System {
            typeface_id: new_id,
        };
        r.replace_typeface_by_id(original_id, replacement, replacement_origin);

        let mut fresh_cache = FontCache::new();
        let font = fresh_cache.get(&r, "CacheReplaceProbe", Pt::new(12.0), false, false);
        assert_eq!(
            TypefaceId::from(&font.typeface()),
            new_id,
            "FontCache must observe the post-replacement typeface"
        );
    }

    #[test]
    fn resolve_exact_returns_none_for_unknown_family() {
        let r = FontRegistry::new(fmgr());
        assert!(
            r.resolve_exact("DefinitelyNotInstalledXYZ", FontStyle::normal())
                .is_none(),
            "unlike resolve(), resolve_exact must not invent a fallback"
        );
    }

    #[test]
    fn resolve_exact_returns_some_for_embedded_family() {
        let bytes = arbitrary_system_font_bytes();
        let mut r = FontRegistry::new(fmgr());
        r.register_embedded("ExactProbe", EmbeddedFontVariant::Regular, bytes)
            .expect("register_embedded should accept valid font bytes");
        let entry = r
            .resolve_exact("ExactProbe", FontStyle::normal())
            .expect("embedded font must be resolvable via exact match");
        assert!(matches!(entry.origin, TypefaceOrigin::Embedded { .. }));
    }

    /// Word's font subsetter strips color glyph tables (sbix/CBDT/COLR/SVG)
    /// when embedding emoji fonts. A docx that embeds e.g. "Segoe UI Emoji"
    /// therefore registers a typeface with the right family name but only
    /// monochrome outlines — rasterizing it produces black blobs instead of
    /// the colored glyph. The emoji pipeline must bypass embedded fonts so
    /// resolution falls through to the host's real color emoji typeface.
    #[test]
    fn resolve_system_only_skips_embedded_fonts() {
        let bytes = arbitrary_system_font_bytes();
        let mut r = FontRegistry::new(fmgr());
        r.register_embedded("SystemOnlyProbe", EmbeddedFontVariant::Regular, bytes)
            .expect("register_embedded should accept valid font bytes");

        // resolve_exact returns the embedded font:
        let exact = r
            .resolve_exact("SystemOnlyProbe", FontStyle::normal())
            .expect("embedded font must be reachable via resolve_exact");
        assert!(matches!(exact.origin, TypefaceOrigin::Embedded { .. }));

        // resolve_system_only must NOT return it (no system font has this
        // synthetic family name):
        assert!(
            r.resolve_system_only("SystemOnlyProbe", FontStyle::normal())
                .is_none(),
            "resolve_system_only must skip embedded fonts so emoji resolution \
             can fall through to the host's color emoji typeface"
        );
    }
}