ironpress 1.4.3

Pure Rust HTML/CSS/Markdown to PDF converter with layout engine, LaTeX math, tables, images, custom fonts, and streaming output. No browser, no system dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use crate::parser::css::{CssRule, CssValue, parse_inline_style};
use crate::parser::dom::DomNode;
use crate::parser::ttf::{TtfFont, parse_ttf, parse_ttf_with_index};
use crate::style::computed::{FontFamily, FontStack, parse_font_stack};
use std::collections::hash_map::Entry;
use std::collections::{BTreeSet, HashMap};
use std::process::Command;

const FONT_VARIANTS: &[FontVariant] = &[
    FontVariant::new(false, false),
    FontVariant::new(true, false),
    FontVariant::new(false, true),
    FontVariant::new(true, true),
];

const UI_SANS_FALLBACK_FAMILIES: &[&str] = &[
    "DejaVu Sans",
    "Arial",
    "Noto Sans",
    "Liberation Sans",
    "FreeSans",
];

#[derive(Clone, Copy)]
struct FontVariant {
    bold: bool,
    italic: bool,
}

impl FontVariant {
    const fn new(bold: bool, italic: bool) -> Self {
        Self { bold, italic }
    }

    const fn style(self) -> fontdb::Style {
        if self.italic {
            fontdb::Style::Italic
        } else {
            fontdb::Style::Normal
        }
    }

    const fn weight(self) -> fontdb::Weight {
        if self.bold {
            fontdb::Weight::BOLD
        } else {
            fontdb::Weight::NORMAL
        }
    }

    const fn fontconfig_style(self) -> &'static str {
        match (self.bold, self.italic) {
            (true, true) => "Bold Italic",
            (true, false) => "Bold",
            (false, true) => "Italic",
            (false, false) => "Regular",
        }
    }
}

struct SystemFontQuery<'a> {
    family: &'a str,
    variant: FontVariant,
}

impl<'a> SystemFontQuery<'a> {
    fn new(family: &'a str, variant: FontVariant) -> Self {
        Self { family, variant }
    }

    fn variant_key(&self) -> String {
        font_variant_key(self.family, self.variant.bold, self.variant.italic)
    }

    fn normalized_family(&self) -> &str {
        match self.family.trim().to_ascii_lowercase().as_str() {
            "ui-sans-serif" | "system-ui" | "-apple-system" | "blinkmacsystemfont" => "sans-serif",
            "ui-serif" => "serif",
            "ui-monospace" => "monospace",
            _ => self.family.trim(),
        }
    }

    fn prefers_ui_sans_resolution(&self) -> bool {
        matches!(
            self.family.trim().to_ascii_lowercase().as_str(),
            "ui-sans-serif" | "system-ui" | "-apple-system" | "blinkmacsystemfont"
        )
    }

    fn fontconfig_pattern(&self) -> String {
        format!(
            "{}:style={}",
            self.normalized_family(),
            self.variant.fontconfig_style()
        )
    }

    fn fontdb_families(&self) -> Vec<fontdb::Family<'_>> {
        if self.prefers_ui_sans_resolution() {
            return vec![
                fontdb::Family::Name("DejaVu Sans"),
                fontdb::Family::Name("Arial"),
                fontdb::Family::Name("Noto Sans"),
                fontdb::Family::Name("Liberation Sans"),
                fontdb::Family::Name("FreeSans"),
                fontdb::Family::SansSerif,
            ];
        }

        match self.normalized_family() {
            "sans-serif" => vec![fontdb::Family::SansSerif],
            "serif" => vec![fontdb::Family::Serif],
            "monospace" => vec![fontdb::Family::Monospace],
            family => vec![fontdb::Family::Name(family)],
        }
    }
}

pub(crate) fn font_variant_key(family: &str, bold: bool, italic: bool) -> String {
    let base = family.trim().to_ascii_lowercase();
    match (bold, italic) {
        (false, false) => base,
        (true, false) => format!("{base}__bold"),
        (false, true) => format!("{base}__italic"),
        (true, true) => format!("{base}__bold_italic"),
    }
}

fn exact_font_variant_key(family: &str, bold: bool, italic: bool) -> String {
    let base = family.trim();
    match (bold, italic) {
        (false, false) => base.to_string(),
        (true, false) => format!("{base}__bold"),
        (false, true) => format!("{base}__italic"),
        (true, true) => format!("{base}__bold_italic"),
    }
}

pub(crate) fn find_font<'a>(
    fonts: &'a HashMap<String, TtfFont>,
    family: &str,
    bold: bool,
    italic: bool,
) -> Option<(&'a str, &'a TtfFont)> {
    let candidates = [
        font_variant_key(family, bold, italic),
        font_variant_key(family, false, false),
        exact_font_variant_key(family, bold, italic),
        exact_font_variant_key(family, false, false),
    ];

    candidates.into_iter().find_map(|key| {
        fonts
            .get_key_value(&key)
            .map(|(name, font)| (name.as_str(), font))
    })
}

pub(crate) fn resolve_font_family(
    stack: &FontStack,
    fonts: &HashMap<String, TtfFont>,
    bold: bool,
    italic: bool,
) -> FontFamily {
    for family in stack.families() {
        match family {
            FontFamily::Custom(name) if find_font(fonts, name, bold, italic).is_some() => {
                return FontFamily::Custom(name.clone());
            }
            FontFamily::TimesRoman => {
                // Prefer system Times New Roman (exact Chromium match),
                // fall back to bundled Liberation Serif.
                if find_font(fonts, "Times New Roman", bold, italic).is_some() {
                    return FontFamily::Custom("Times New Roman".to_string());
                }
                if find_font(fonts, "Liberation Serif", bold, italic).is_some() {
                    return FontFamily::Custom("Liberation Serif".to_string());
                }
                return FontFamily::TimesRoman;
            }
            FontFamily::Helvetica => {
                if find_font(fonts, "Arial", bold, italic).is_some() {
                    return FontFamily::Custom("Arial".to_string());
                }
                if find_font(fonts, "Liberation Sans", bold, italic).is_some() {
                    return FontFamily::Custom("Liberation Sans".to_string());
                }
                return FontFamily::Helvetica;
            }
            FontFamily::Courier => {
                if find_font(fonts, "Courier New", bold, italic).is_some() {
                    return FontFamily::Custom("Courier New".to_string());
                }
                if find_font(fonts, "Liberation Mono", bold, italic).is_some() {
                    return FontFamily::Custom("Liberation Mono".to_string());
                }
                return FontFamily::Courier;
            }
            FontFamily::Custom(_) => {}
        }
    }

    if find_font(fonts, "Liberation Sans", bold, italic).is_some() {
        return FontFamily::Custom("Liberation Sans".to_string());
    }

    stack
        .families()
        .iter()
        .find(|family| !matches!(family, FontFamily::Custom(_)))
        .cloned()
        .unwrap_or_default()
}

/// Key used to store the Unicode fallback font in the font map.
pub(crate) const UNICODE_FALLBACK_KEY: &str = "__unicode_fallback";
pub(crate) const EMOJI_FALLBACK_KEY: &str = "__emoji_fallback";

/// Candidate font families for emoji rendering.
/// Prefer vector/outline fonts (Noto Emoji, Symbola) over bitmap fonts
/// (Apple Color Emoji, Noto Color Emoji) since our TTF parser doesn't
/// support CBDT/CBLC bitmap tables.
const EMOJI_FALLBACK_FAMILIES: &[&str] = &[
    "Noto Emoji",
    "Symbola",
    "Segoe UI Symbol",
    "Segoe UI Emoji",
    "Noto Color Emoji",
    "Apple Color Emoji",
    "EmojiOne",
    "Twitter Color Emoji",
];

/// Candidate font families to try when looking for a Unicode fallback font.
/// Ordered by breadth of Unicode coverage (CJK, symbols, etc.).
/// Includes macOS-specific CJK fonts (Hiragino, PingFang, STHeiti) alongside
/// cross-platform options (Noto Sans CJK, Arial Unicode MS, DejaVu Sans).
const UNICODE_FALLBACK_FAMILIES: &[&str] = &[
    "Noto Sans CJK SC",
    "Noto Sans CJK",
    "Noto Sans SC",
    "Arial Unicode MS",
    // macOS CJK fonts
    "Hiragino Sans",
    "Hiragino Kaku Gothic Pro",
    "PingFang SC",
    "Heiti SC",
    "STHeiti",
    // Linux / cross-platform
    "Noto Sans",
    "DejaVu Sans",
    "Liberation Sans",
    "FreeSans",
];

/// Load a single Unicode-capable fallback font for characters outside
/// WinAnsiEncoding.  The font is registered under [`UNICODE_FALLBACK_KEY`].
///
/// This enables CJK and other non-Latin characters to render correctly
/// instead of appearing as rectangles/tofu when the document uses a
/// standard PDF font (Helvetica, Times-Roman, Courier).
pub(crate) fn load_unicode_fallback_font(fonts: &mut HashMap<String, TtfFont>) {
    if fonts.contains_key(UNICODE_FALLBACK_KEY) {
        return;
    }

    let db = system_fontdb();

    for family in UNICODE_FALLBACK_FAMILIES {
        let query = SystemFontQuery::new(family, FontVariant::new(false, false));
        if let Some(font) = query_fontdb_font(db, &query).or_else(|| query_fontconfig_font(&query))
        {
            fonts.insert(UNICODE_FALLBACK_KEY.to_string(), font);
            return;
        }
    }
}

/// Load an emoji font for emoji character rendering.
/// Prefers the bundled Noto Emoji (monochrome, vector outlines, 295KB)
/// which works everywhere. Falls back to system fonts only if the
/// bundled font fails to parse.
pub(crate) fn load_emoji_fallback_font(fonts: &mut HashMap<String, TtfFont>) {
    if fonts.contains_key(EMOJI_FALLBACK_KEY) {
        return;
    }

    // Always use the bundled Noto Emoji first — it has vector outlines
    // that our TTF parser can read. System emoji fonts (Apple Color Emoji,
    // Noto Color Emoji) use bitmap tables (CBDT/CBLC) which we can't parse.
    load_bundled_emoji_font(fonts);
    if fonts.contains_key(EMOJI_FALLBACK_KEY) {
        return;
    }

    // Fallback: try system fonts (may be bitmap-only)
    let db = system_fontdb();
    for family in EMOJI_FALLBACK_FAMILIES {
        let query = SystemFontQuery::new(family, FontVariant::new(false, false));
        if let Some(font) = query_fontdb_font(db, &query).or_else(|| query_fontconfig_font(&query))
        {
            fonts.insert(EMOJI_FALLBACK_KEY.to_string(), font);
            return;
        }
    }
}

/// Load the bundled Noto Emoji font (monochrome, vector outlines).
/// This ensures emoji rendering works on all platforms without requiring
/// a system emoji font to be installed.
fn load_bundled_emoji_font(fonts: &mut HashMap<String, TtfFont>) {
    static NOTO_EMOJI_DATA: &[u8] = include_bytes!("../assets/NotoEmoji-Regular.ttf");

    if let Ok(font) = crate::parser::ttf::parse_ttf(NOTO_EMOJI_DATA.to_vec()) {
        fonts.insert(EMOJI_FALLBACK_KEY.to_string(), font);
    }
}

struct BundledFont {
    key: &'static str,
    data: &'static [u8],
}

// Keys must match font_variant_key() format: lowercase + __bold/__italic/__bold_italic
static LIBERATION_FONTS: &[BundledFont] = &[
    BundledFont {
        key: "liberation serif",
        data: include_bytes!("../assets/LiberationSerif-Regular.ttf"),
    },
    BundledFont {
        key: "liberation serif__bold",
        data: include_bytes!("../assets/LiberationSerif-Bold.ttf"),
    },
    BundledFont {
        key: "liberation serif__italic",
        data: include_bytes!("../assets/LiberationSerif-Italic.ttf"),
    },
    BundledFont {
        key: "liberation serif__bold_italic",
        data: include_bytes!("../assets/LiberationSerif-BoldItalic.ttf"),
    },
    BundledFont {
        key: "liberation sans",
        data: include_bytes!("../assets/LiberationSans-Regular.ttf"),
    },
    BundledFont {
        key: "liberation sans__bold",
        data: include_bytes!("../assets/LiberationSans-Bold.ttf"),
    },
    BundledFont {
        key: "liberation sans__italic",
        data: include_bytes!("../assets/LiberationSans-Italic.ttf"),
    },
    BundledFont {
        key: "liberation sans__bold_italic",
        data: include_bytes!("../assets/LiberationSans-BoldItalic.ttf"),
    },
    BundledFont {
        key: "liberation mono",
        data: include_bytes!("../assets/LiberationMono-Regular.ttf"),
    },
    BundledFont {
        key: "liberation mono__bold",
        data: include_bytes!("../assets/LiberationMono-Bold.ttf"),
    },
    BundledFont {
        key: "liberation mono__italic",
        data: include_bytes!("../assets/LiberationMono-Italic.ttf"),
    },
    BundledFont {
        key: "liberation mono__bold_italic",
        data: include_bytes!("../assets/LiberationMono-BoldItalic.ttf"),
    },
];

/// Bundled Noto Sans for multilingual fallback (Hebrew, Greek, Cyrillic, etc.)
static NOTO_SANS_DATA: &[u8] = include_bytes!("../assets/NotoSans-Regular.ttf");

/// Bundled Noto Sans Arabic for Arabic script fallback.
static NOTO_ARABIC_DATA: &[u8] = include_bytes!("../assets/NotoSansArabic-Regular.ttf");

/// Key for the Arabic fallback font.
pub(crate) const ARABIC_FALLBACK_KEY: &str = "__arabic_fallback";

/// Key for the multilingual (Noto Sans) fallback font — covers Hebrew,
/// Greek, Cyrillic, and other non-CJK/non-Arabic scripts.
pub(crate) const MULTILINGUAL_FALLBACK_KEY: &str = "__multilingual_fallback";

/// Load bundled Liberation fonts as the default serif/sans-serif/monospace.
/// Liberation fonts are metrically identical to Times New Roman, Arial, and
/// Courier New, ensuring ironpress output matches Chromium rendering exactly.
/// Also loads Noto Sans as a multilingual fallback for Arabic, Hebrew, etc.
/// Cached parsed bundled fonts — parsed once on first use, then cloned
/// into each conversion's font map. This avoids re-parsing ~5MB of TTF
/// data on every `html_to_pdf()` call.
static BUNDLED_FONTS_CACHE: std::sync::OnceLock<Vec<(String, TtfFont)>> =
    std::sync::OnceLock::new();

/// Shared fontdb database of system fonts. `db.load_system_fonts()` walks the
/// filesystem (/usr/share/fonts, ~/Library/Fonts, etc.) which can take
/// hundreds of ms on Linux CI runners with many font packages installed.
/// Loading once per process — instead of per `html_to_pdf()` call — shaves
/// ~300-400 ms per render on Ubuntu CI.
static SYSTEM_FONTDB_CACHE: std::sync::OnceLock<fontdb::Database> = std::sync::OnceLock::new();

fn system_fontdb() -> &'static fontdb::Database {
    SYSTEM_FONTDB_CACHE.get_or_init(|| {
        let mut db = fontdb::Database::new();
        db.load_system_fonts();
        db
    })
}

fn parse_all_bundled_fonts() -> Vec<(String, TtfFont)> {
    let mut result = Vec::new();
    for bundled in LIBERATION_FONTS {
        if let Ok(font) = crate::parser::ttf::parse_ttf(bundled.data.to_vec()) {
            result.push((bundled.key.to_string(), font));
        }
    }
    if let Ok(font) = crate::parser::ttf::parse_ttf(NOTO_SANS_DATA.to_vec()) {
        result.push((MULTILINGUAL_FALLBACK_KEY.to_string(), font));
    }
    if let Ok(font) = crate::parser::ttf::parse_ttf(NOTO_ARABIC_DATA.to_vec()) {
        result.push((ARABIC_FALLBACK_KEY.to_string(), font));
    }
    result
}

/// Try to load the system's actual serif/sans-serif/monospace fonts
/// (Times New Roman, Arial, Courier New) so the output matches Chromium
/// exactly. Falls through to bundled Liberation fonts when unavailable.
pub(crate) fn load_system_default_fonts(fonts: &mut HashMap<String, TtfFont>) {
    let families = [
        ("Times New Roman", "serif"),
        ("Arial", "sans-serif"),
        ("Courier New", "monospace"),
    ];
    let db = system_fontdb();

    for (family, _generic) in &families {
        for variant in FONT_VARIANTS {
            let query = SystemFontQuery::new(family, *variant);
            let key = query.variant_key();
            if fonts.contains_key(&key) {
                continue;
            }
            if let Some(font) =
                query_fontdb_font(db, &query).or_else(|| query_fontconfig_font(&query))
            {
                fonts.insert(key, font);
            }
        }
    }
}

pub(crate) fn load_bundled_liberation_fonts(fonts: &mut HashMap<String, TtfFont>) {
    let cached = BUNDLED_FONTS_CACHE.get_or_init(parse_all_bundled_fonts);
    for (key, font) in cached {
        if !fonts.contains_key(key) {
            fonts.insert(key.clone(), font.clone());
        }
    }
}

pub(crate) fn load_requested_system_fonts(
    nodes: &[DomNode],
    rules: &[CssRule],
    fonts: &mut HashMap<String, TtfFont>,
) {
    let requested = requested_families(nodes, rules);
    if requested.is_empty() {
        return;
    }

    let db = system_fontdb();

    for family in requested {
        load_family_variants(db, &family, fonts);
    }
}

fn requested_families(nodes: &[DomNode], rules: &[CssRule]) -> BTreeSet<String> {
    let mut families = BTreeSet::new();

    for rule in rules {
        collect_style_map_family(&rule.declarations, &mut families);
    }

    collect_node_families(nodes, &mut families);
    families
}

fn collect_node_families(nodes: &[DomNode], families: &mut BTreeSet<String>) {
    for node in nodes {
        if let DomNode::Element(element) = node {
            if let Some(style_attr) = element.style_attr() {
                let style_map = parse_inline_style(style_attr);
                collect_style_map_family(&style_map, families);
            }
            collect_node_families(&element.children, families);
        }
    }
}

fn collect_style_map_family(
    style_map: &crate::parser::css::StyleMap,
    families: &mut BTreeSet<String>,
) {
    let Some(CssValue::Keyword(family)) = style_map.get("font-family") else {
        return;
    };

    for entry in parse_font_stack(family).families() {
        let FontFamily::Custom(name) = entry else {
            continue;
        };
        if should_try_system_font(name) {
            families.insert(name.to_ascii_lowercase());
        }
    }
}

fn should_try_system_font(family: &str) -> bool {
    !matches!(
        family.to_ascii_lowercase().as_str(),
        "serif" | "sans-serif" | "monospace" | "cursive" | "fantasy"
    )
}

fn load_family_variants(db: &fontdb::Database, family: &str, fonts: &mut HashMap<String, TtfFont>) {
    for variant in FONT_VARIANTS {
        let query = SystemFontQuery::new(family, *variant);
        match fonts.entry(query.variant_key()) {
            Entry::Occupied(_) => {}
            Entry::Vacant(slot) => {
                let Some(font) = load_system_font(db, &query) else {
                    continue;
                };
                slot.insert(font);
            }
        }
    }
}

fn load_system_font(db: &fontdb::Database, query: &SystemFontQuery<'_>) -> Option<TtfFont> {
    if query.prefers_ui_sans_resolution() {
        load_preferred_family_font(db, query, UI_SANS_FALLBACK_FAMILIES)
            .or_else(|| query_fontdb_font(db, query))
            .or_else(|| query_fontconfig_font(query))
    } else {
        // Prefer fontdb (fast, no subprocess) over fontconfig (fc-match can hang)
        query_fontdb_font(db, query).or_else(|| query_fontconfig_font(query))
    }
}

fn load_preferred_family_font(
    db: &fontdb::Database,
    query: &SystemFontQuery<'_>,
    families: &[&str],
) -> Option<TtfFont> {
    families.iter().find_map(|family| {
        let preferred = SystemFontQuery::new(family, query.variant);
        query_fontdb_font(db, &preferred).or_else(|| query_fontconfig_font(&preferred))
    })
}

fn query_fontconfig_font(query: &SystemFontQuery<'_>) -> Option<TtfFont> {
    let mut child = Command::new("fc-match")
        .args([
            query.fontconfig_pattern().as_str(),
            "-f",
            "%{family}\n%{file}",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .ok()?;

    // Timeout after 1 second to avoid blocking on slow/absent fontconfig.
    let timeout = std::time::Duration::from_secs(1);
    let start = std::time::Instant::now();
    loop {
        match child.try_wait() {
            Ok(Some(_)) => break,
            Ok(None) => {
                if start.elapsed() > timeout {
                    let _ = child.kill();
                    return None;
                }
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            Err(_) => return None,
        }
    }
    let output = child.wait_with_output().ok()?;
    if !output.status.success() {
        return None;
    }

    let output = String::from_utf8(output.stdout).ok()?;
    let (family, path) = output.split_once('\n')?;
    if !fontconfig_family_matches(query, family) {
        return None;
    }

    let path = path.trim();
    if path.is_empty() {
        return None;
    }

    parse_ttf(std::fs::read(path).ok()?).ok()
}

fn fontconfig_family_matches(query: &SystemFontQuery<'_>, family_output: &str) -> bool {
    let requested = query.normalized_family().trim();
    family_output
        .split(',')
        .map(str::trim)
        .any(|family| family.eq_ignore_ascii_case(requested))
}

#[cfg(test)]
fn build_fontconfig_pattern(query: &SystemFontQuery<'_>) -> String {
    query.fontconfig_pattern()
}

fn query_fontdb_font(db: &fontdb::Database, query: &SystemFontQuery<'_>) -> Option<TtfFont> {
    let families = query.fontdb_families();
    let face_id = db.query(&fontdb::Query {
        families: &families,
        weight: query.variant.weight(),
        stretch: fontdb::Stretch::Normal,
        style: query.variant.style(),
    })?;
    db.with_face_data(face_id, |data, face_index| {
        parse_ttf_with_index(data.to_vec(), face_index as usize).ok()
    })?
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::ttf::{FontVerticalMetrics, TtfFont};
    use crate::style::computed::{FontFamily, FontStack, parse_font_stack};

    fn stub_font(name: &str) -> TtfFont {
        let metrics = FontVerticalMetrics::new(800, -200, 0);
        TtfFont {
            font_name: name.to_string(),
            units_per_em: 1000,
            bbox: [0, -200, 1000, 800],
            pdf_metrics: metrics,
            layout_metrics: metrics,
            cmap: std::collections::HashMap::new(),
            glyph_widths: vec![500],
            num_h_metrics: 1,
            flags: 0,
            data: std::sync::Arc::new(vec![]),
        }
    }

    // ── find_font ────────────────────────────────────────────────────────────

    #[test]
    fn find_font_exact_match_regular() {
        let mut fonts = HashMap::new();
        fonts.insert("arial".to_string(), stub_font("Arial"));
        let (key, _) = find_font(&fonts, "Arial", false, false).unwrap();
        assert_eq!(key, "arial");
    }

    #[test]
    fn find_font_exact_match_bold() {
        let mut fonts = HashMap::new();
        fonts.insert("arial__bold".to_string(), stub_font("Arial Bold"));
        let (key, _) = find_font(&fonts, "Arial", true, false).unwrap();
        assert_eq!(key, "arial__bold");
    }

    #[test]
    fn find_font_exact_match_italic() {
        let mut fonts = HashMap::new();
        fonts.insert("arial__italic".to_string(), stub_font("Arial Italic"));
        let (key, _) = find_font(&fonts, "Arial", false, true).unwrap();
        assert_eq!(key, "arial__italic");
    }

    #[test]
    fn find_font_exact_match_bold_italic() {
        let mut fonts = HashMap::new();
        fonts.insert("arial__bold_italic".to_string(), stub_font("Arial BI"));
        let (key, _) = find_font(&fonts, "Arial", true, true).unwrap();
        assert_eq!(key, "arial__bold_italic");
    }

    #[test]
    fn find_font_case_insensitive_match() {
        let mut fonts = HashMap::new();
        fonts.insert("arial".to_string(), stub_font("Arial"));
        // Stored under lowercase key; look up with mixed case
        assert!(find_font(&fonts, "ARIAL", false, false).is_some());
        assert!(find_font(&fonts, "Arial", false, false).is_some());
    }

    #[test]
    fn find_font_bold_falls_back_to_regular() {
        let mut fonts = HashMap::new();
        // Only the regular variant is stored.
        fonts.insert("arial".to_string(), stub_font("Arial"));
        let (key, _) = find_font(&fonts, "Arial", true, false).unwrap();
        assert_eq!(key, "arial");
    }

    #[test]
    fn find_font_italic_falls_back_to_regular() {
        let mut fonts = HashMap::new();
        fonts.insert("arial".to_string(), stub_font("Arial"));
        let (key, _) = find_font(&fonts, "Arial", false, true).unwrap();
        assert_eq!(key, "arial");
    }

    #[test]
    fn find_font_returns_none_when_family_absent() {
        let fonts: HashMap<String, TtfFont> = HashMap::new();
        assert!(find_font(&fonts, "NonExistent", false, false).is_none());
    }

    // ── resolve_font_family ──────────────────────────────────────────────────

    #[test]
    fn resolve_font_family_returns_custom_when_font_loaded() {
        let mut fonts = HashMap::new();
        fonts.insert("roboto".to_string(), stub_font("Roboto"));
        let stack = parse_font_stack("Roboto, sans-serif");
        let result = resolve_font_family(&stack, &fonts, false, false);
        assert_eq!(result, FontFamily::Custom("roboto".to_string()));
    }

    #[test]
    fn resolve_font_family_returns_builtin_helvetica() {
        let fonts: HashMap<String, TtfFont> = HashMap::new();
        let stack = FontStack::from_family(FontFamily::Helvetica);
        let result = resolve_font_family(&stack, &fonts, false, false);
        assert_eq!(result, FontFamily::Helvetica);
    }

    #[test]
    fn resolve_font_family_returns_builtin_times_roman() {
        let fonts: HashMap<String, TtfFont> = HashMap::new();
        let stack = FontStack::from_family(FontFamily::TimesRoman);
        let result = resolve_font_family(&stack, &fonts, false, false);
        assert_eq!(result, FontFamily::TimesRoman);
    }

    #[test]
    fn resolve_font_family_returns_builtin_courier() {
        let fonts: HashMap<String, TtfFont> = HashMap::new();
        let stack = FontStack::from_family(FontFamily::Courier);
        let result = resolve_font_family(&stack, &fonts, false, false);
        assert_eq!(result, FontFamily::Courier);
    }

    #[test]
    fn resolve_font_family_skips_missing_custom_and_falls_back_to_builtin() {
        let fonts: HashMap<String, TtfFont> = HashMap::new();
        // "Roboto" is parsed as Custom; "serif" maps to TimesRoman.
        let stack = parse_font_stack("Roboto, serif");
        let result = resolve_font_family(&stack, &fonts, false, false);
        assert_eq!(result, FontFamily::TimesRoman);
    }

    #[test]
    fn resolve_font_family_defaults_to_helvetica_when_all_custom_missing() {
        let fonts: HashMap<String, TtfFont> = HashMap::new();
        let stack = FontStack::from_family(FontFamily::Custom("Roboto".to_string()));
        let result = resolve_font_family(&stack, &fonts, false, false);
        assert_eq!(result, FontFamily::Helvetica);
    }

    // ── should_try_system_font ───────────────────────────────────────────────

    #[test]
    fn should_try_system_font_rejects_cursive_and_fantasy() {
        assert!(!should_try_system_font("cursive"));
        assert!(!should_try_system_font("fantasy"));
    }

    #[test]
    fn should_try_system_font_is_case_insensitive() {
        assert!(!should_try_system_font("Serif"));
        assert!(!should_try_system_font("MONOSPACE"));
        assert!(should_try_system_font("Roboto"));
    }

    // ── font_variant_key with mixed-case / whitespace ────────────────────────

    #[test]
    fn font_variant_key_lowercases_input() {
        assert_eq!(font_variant_key("Arial", false, false), "arial");
        assert_eq!(font_variant_key("Arial", true, false), "arial__bold");
        assert_eq!(font_variant_key("Arial", false, true), "arial__italic");
        assert_eq!(font_variant_key("Arial", true, true), "arial__bold_italic");
    }

    #[test]
    fn font_variant_key_trims_whitespace() {
        assert_eq!(font_variant_key("  Arial  ", false, false), "arial");
        assert_eq!(
            font_variant_key("  Arial  ", true, true),
            "arial__bold_italic"
        );
    }

    // ── SystemFontQuery::normalized_family ───────────────────────────────────

    #[test]
    fn normalized_family_maps_ui_sans_aliases_to_sans_serif() {
        for alias in &[
            "ui-sans-serif",
            "system-ui",
            "-apple-system",
            "blinkmacsystemfont",
        ] {
            let q = SystemFontQuery::new(alias, FontVariant::new(false, false));
            assert_eq!(q.normalized_family(), "sans-serif", "failed for {alias}");
        }
    }

    #[test]
    fn normalized_family_maps_ui_serif_to_serif() {
        let q = SystemFontQuery::new("ui-serif", FontVariant::new(false, false));
        assert_eq!(q.normalized_family(), "serif");
    }

    #[test]
    fn normalized_family_maps_ui_monospace_to_monospace() {
        let q = SystemFontQuery::new("ui-monospace", FontVariant::new(false, false));
        assert_eq!(q.normalized_family(), "monospace");
    }

    #[test]
    fn normalized_family_passes_through_custom_name() {
        let q = SystemFontQuery::new("Roboto", FontVariant::new(false, false));
        assert_eq!(q.normalized_family(), "Roboto");
    }

    #[test]
    fn normalized_family_trims_surrounding_whitespace() {
        let q = SystemFontQuery::new("  Roboto  ", FontVariant::new(false, false));
        assert_eq!(q.normalized_family(), "Roboto");
    }

    // ── SystemFontQuery::prefers_ui_sans_resolution ──────────────────────────

    #[test]
    fn prefers_ui_sans_resolution_true_for_all_aliases() {
        for alias in &[
            "ui-sans-serif",
            "system-ui",
            "-apple-system",
            "blinkmacsystemfont",
        ] {
            let q = SystemFontQuery::new(alias, FontVariant::new(false, false));
            assert!(q.prefers_ui_sans_resolution(), "expected true for {alias}");
        }
    }

    #[test]
    fn prefers_ui_sans_resolution_false_for_other_families() {
        for family in &["ui-serif", "ui-monospace", "sans-serif", "Roboto"] {
            let q = SystemFontQuery::new(family, FontVariant::new(false, false));
            assert!(
                !q.prefers_ui_sans_resolution(),
                "expected false for {family}"
            );
        }
    }

    // ── SystemFontQuery::fontdb_families ─────────────────────────────────────

    #[test]
    fn fontdb_families_ui_sans_returns_fallback_list_plus_generic() {
        let q = SystemFontQuery::new("ui-sans-serif", FontVariant::new(false, false));
        let families = q.fontdb_families();
        // Should include the named fallbacks and the generic SansSerif sentinel.
        assert!(families.contains(&fontdb::Family::Name("DejaVu Sans")));
        assert!(families.contains(&fontdb::Family::Name("Arial")));
        assert!(families.contains(&fontdb::Family::SansSerif));
    }

    #[test]
    fn fontdb_families_sans_serif_returns_single_generic() {
        let q = SystemFontQuery::new("sans-serif", FontVariant::new(false, false));
        assert_eq!(q.fontdb_families(), vec![fontdb::Family::SansSerif]);
    }

    #[test]
    fn fontdb_families_serif_returns_single_generic() {
        let q = SystemFontQuery::new("serif", FontVariant::new(false, false));
        assert_eq!(q.fontdb_families(), vec![fontdb::Family::Serif]);
    }

    #[test]
    fn fontdb_families_monospace_returns_single_generic() {
        let q = SystemFontQuery::new("monospace", FontVariant::new(false, false));
        assert_eq!(q.fontdb_families(), vec![fontdb::Family::Monospace]);
    }

    #[test]
    fn fontdb_families_named_returns_name_family() {
        let q = SystemFontQuery::new("Roboto", FontVariant::new(false, false));
        assert_eq!(q.fontdb_families(), vec![fontdb::Family::Name("Roboto")]);
    }

    #[test]
    fn font_variant_key_suffixes_are_stable() {
        assert_eq!(
            font_variant_key("ui-sans-serif", false, false),
            "ui-sans-serif"
        );
        assert_eq!(
            font_variant_key("ui-sans-serif", true, false),
            "ui-sans-serif__bold"
        );
        assert_eq!(
            font_variant_key("ui-sans-serif", false, true),
            "ui-sans-serif__italic"
        );
        assert_eq!(
            font_variant_key("ui-sans-serif", true, true),
            "ui-sans-serif__bold_italic"
        );
    }

    #[test]
    fn generic_css_families_do_not_trigger_system_loading() {
        assert!(!should_try_system_font("serif"));
        assert!(!should_try_system_font("sans-serif"));
        assert!(!should_try_system_font("monospace"));
        assert!(should_try_system_font("ui-sans-serif"));
        assert!(should_try_system_font("roboto"));
    }

    #[test]
    fn fontconfig_pattern_maps_ui_generics() {
        let query = SystemFontQuery::new("ui-sans-serif", FontVariant::new(true, false));
        assert_eq!(build_fontconfig_pattern(&query), "sans-serif:style=Bold");
    }

    #[test]
    fn fontconfig_family_match_requires_requested_family() {
        let query = SystemFontQuery::new("MissingFont", FontVariant::new(false, false));
        assert!(!fontconfig_family_matches(&query, "Noto Sans"));
    }

    #[test]
    fn fontconfig_family_match_accepts_matching_alias_list() {
        let query = SystemFontQuery::new("DejaVu Sans", FontVariant::new(false, false));
        assert!(fontconfig_family_matches(
            &query,
            "DejaVu Sans,DejaVu Sans Condensed"
        ));
    }

    // ── load_unicode_fallback_font ──────────────────────────────────────────

    #[test]
    fn unicode_fallback_key_is_dunder_prefixed() {
        assert!(UNICODE_FALLBACK_KEY.starts_with("__"));
    }

    #[test]
    fn load_unicode_fallback_font_does_not_panic() {
        let mut fonts = HashMap::new();
        // Should not panic regardless of which system fonts are installed.
        load_unicode_fallback_font(&mut fonts);
    }

    #[test]
    fn load_unicode_fallback_font_is_idempotent() {
        let mut fonts = HashMap::new();
        load_unicode_fallback_font(&mut fonts);
        let count_after_first = fonts.len();
        load_unicode_fallback_font(&mut fonts);
        assert_eq!(
            fonts.len(),
            count_after_first,
            "calling load_unicode_fallback_font twice should not add a second entry"
        );
    }

    #[test]
    fn load_unicode_fallback_font_skips_when_key_already_present() {
        let mut fonts = HashMap::new();
        let sentinel = stub_font("Sentinel");
        fonts.insert(UNICODE_FALLBACK_KEY.to_string(), sentinel);
        load_unicode_fallback_font(&mut fonts);
        // The sentinel font should remain unchanged.
        assert_eq!(
            fonts.get(UNICODE_FALLBACK_KEY).unwrap().font_name,
            "Sentinel"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn load_unicode_fallback_font_loads_a_font_on_macos() {
        let mut fonts = HashMap::new();
        load_unicode_fallback_font(&mut fonts);
        assert!(
            fonts.contains_key(UNICODE_FALLBACK_KEY),
            "macOS should have at least one of the candidate Unicode fallback fonts"
        );
    }
}