md-viewer 0.3.1

Fast, lightweight markdown viewer for Linux with tabs, file explorer, and live reload
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
use std::collections::HashSet;

use egui::{FontData, FontDefinitions, FontFamily};
use egui_commonmark_extended::STRONG_FONT_FAMILY;
use fontique::{
    Blob, Collection, CollectionOptions, FamilyId, FontStyle, FontWeight, GenericFamily, Script,
    SourceCache, SourceKind,
};
use serde::{Deserialize, Serialize};

/// Markdown font presets that emulate how popular markdown viewers pick fonts.
///
/// A preset reorders the app's font chains so the first installed face matches
/// what the emulated viewer would show on Linux. CSS-generic keywords
/// (`-apple-system`, `BlinkMacSystemFont`, `system-ui`, `ui-monospace`,
/// `sans-serif`, `monospace`) have no literal family behind them, so they are
/// transcribed to the concrete faces a Linux browser resolves them to:
/// `system-ui`/UI aliases become GNOME's Adwaita Sans / Cantarell, and generic
/// monospace becomes Noto Sans Mono / DejaVu Sans Mono. Anything still missing
/// falls through to the app's own fallback chain, so Unicode/CJK coverage and
/// bold rendering never regress when switching presets.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum FontPreset {
    /// The app's own look: best installed general-purpose sans for body text,
    /// egui's bundled monospace face for code.
    #[default]
    Current,
    /// github.com rendered markdown (Primer `.markdown-body`): body
    /// `"Mona Sans VF", -apple-system, BlinkMacSystemFont, "Segoe UI",
    /// "Noto Sans", Helvetica, Arial, sans-serif`; code `ui-monospace,
    /// SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono",
    /// monospace`.
    Github,
    /// VS Code markdown preview (`markdown.preview.fontFamily` default plus
    /// the Linux `editor.fontFamily` default for code): body `-apple-system,
    /// BlinkMacSystemFont, "Segoe WPC", "Segoe UI", system-ui, "Ubuntu",
    /// "Droid Sans", sans-serif`; code `'Droid Sans Mono', monospace`.
    Vscode,
}

impl FontPreset {
    pub(crate) const ALL: [FontPreset; 3] =
        [FontPreset::Current, FontPreset::Github, FontPreset::Vscode];

    /// Menu label for this preset.
    pub(crate) fn label(self) -> &'static str {
        match self {
            FontPreset::Current => "Default",
            FontPreset::Github => "GitHub",
            FontPreset::Vscode => "VS Code",
        }
    }

    /// One-line explanation of what the preset emulates, shown as menu hover text.
    pub(crate) fn description(self) -> &'static str {
        match self {
            FontPreset::Current => {
                "This app's default: best installed sans + bundled mono code font."
            }
            FontPreset::Github => {
                "github.com style: Mona Sans / Segoe UI / Noto Sans body, SF Mono / Liberation Mono code."
            }
            FontPreset::Vscode => {
                "VS Code preview style: Segoe UI / system UI body, Droid Sans Mono code."
            }
        }
    }

    /// `(body line-height, code line-height)` multipliers fed to the renderer.
    /// GitHub: `.markdown-body{line-height:1.5}`, `pre{line-height:1.45}`.
    /// VS Code preview default: `--markdown-line-height: 1.6`, code 1.357em.
    pub(crate) fn line_heights(self) -> (f32, f32) {
        match self {
            FontPreset::Current => (1.5, 1.3),
            FontPreset::Github => (1.5, 1.45),
            FontPreset::Vscode => (1.6, 1.36),
        }
    }

    /// Body families from the emulated viewer's CSS stack, in resolution
    /// order. `None` keeps the app's own primary sans selection.
    ///
    /// Pure macOS keywords (`-apple-system`, `BlinkMacSystemFont`) are skipped.
    /// `"Adwaita Sans"` directly follows `"Segoe UI"` because modern fontconfig
    /// setups substitute Segoe UI with GNOME's Adwaita Sans, which is what
    /// Linux browsers actually render for stacks asking for Segoe UI first.
    fn body_families(self) -> Option<&'static [&'static str]> {
        match self {
            FontPreset::Current => None,
            FontPreset::Github => Some(GITHUB_BODY_FAMILIES),
            FontPreset::Vscode => Some(VSCODE_BODY_FAMILIES),
        }
    }

    /// Code families from the emulated viewer's monospace stack, in resolution
    /// order. Empty keeps egui's bundled monospace first.
    fn mono_families(self) -> &'static [&'static str] {
        match self {
            // GitHub puts ui-monospace first; on Linux browsers that resolves
            // through fontconfig's generic monospace alias before any of the
            // named proprietary faces are reached, so the Linux defaults lead.
            FontPreset::Github => GITHUB_MONO_FAMILIES,
            // VS Code webviews always inject editor.fontFamily; its Linux
            // default is 'Droid Sans Mono', monospace.
            FontPreset::Vscode => VSCODE_MONO_FAMILIES,
            FontPreset::Current => &[],
        }
    }
}

/// Discrete base text sizes shared by every font preset. Unlike the presets
/// themselves — which only choose typefaces and line heights — the size class
/// is one app-wide setting with a single shared default, so switching presets
/// never changes the text size on its own.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum TextSizeClass {
    Small,
    #[default]
    Normal,
    Large,
    ExtraLarge,
    Huge,
}

impl TextSizeClass {
    pub(crate) const ALL: [TextSizeClass; 5] = [
        TextSizeClass::Small,
        TextSizeClass::Normal,
        TextSizeClass::Large,
        TextSizeClass::ExtraLarge,
        TextSizeClass::Huge,
    ];

    /// Menu label including the concrete pixel size.
    pub(crate) fn label(self) -> &'static str {
        match self {
            TextSizeClass::Small => "Small (14px)",
            TextSizeClass::Normal => "Normal (16px)",
            TextSizeClass::Large => "Large (18px)",
            TextSizeClass::ExtraLarge => "Extra large (20px)",
            TextSizeClass::Huge => "Huge (24px)",
        }
    }

    /// Base body size in px. Headings and code cascade from this because the
    /// renderer derives every document size from `TextStyle::Body`.
    pub(crate) fn px(self) -> f32 {
        match self {
            TextSizeClass::Small => 14.0,
            TextSizeClass::Normal => 16.0,
            TextSizeClass::Large => 18.0,
            TextSizeClass::ExtraLarge => 20.0,
            TextSizeClass::Huge => 24.0,
        }
    }
}

/// Primer `.markdown-body` body stack without macOS-only aliases; the generic
/// `sans-serif` tail is covered by the app's existing fallback chain.
///
/// GitHub prepends its open-source Mona Sans (primer/primitives#1332); it
/// renders only where installed locally because GitHub ships no markdown
/// webfont. `"Noto Sans Backtick Fix"` is intentionally skipped: it is a
/// `local()`-only `@font-face` shim covering just U+60, not a real family.
const GITHUB_BODY_FAMILIES: &[&str] = &[
    "Mona Sans VF",
    "Mona Sans",
    "Segoe UI",
    "Adwaita Sans", // fontconfig substitutes Segoe UI with Adwaita Sans on modern GNOME
    "Noto Sans",
    "Helvetica",
    "Arial",
];

/// Primer `.markdown-body` code stack. Generic monospace leads because
/// `ui-monospace` precedes every named face in the CSS and resolves on Linux.
const GITHUB_MONO_FAMILIES: &[&str] = &[
    "Noto Sans Mono",
    "DejaVu Sans Mono",
    "SFMono-Regular",
    "SF Mono",
    "Menlo",
    "Consolas",
    "Liberation Mono",
];

/// VS Code preview body stack without macOS-only aliases; `system-ui` is
/// transcribed to its common desktop resolutions and `sans-serif` remains
/// covered by the app's existing fallback chain.
const VSCODE_BODY_FAMILIES: &[&str] = &[
    "Segoe WPC",
    "Segoe UI",
    "Adwaita Sans", // system-ui on GNOME 47+
    "Cantarell",    // system-ui on older GNOME releases
    "Ubuntu",
    "Droid Sans",
];

/// VS Code preview code stack: the Linux `editor.fontFamily` default followed
/// by the generic monospace resolutions.
const VSCODE_MONO_FAMILIES: &[&str] = &["Droid Sans Mono", "Noto Sans Mono", "DejaVu Sans Mono"];

/// Apply the shared base text size class to the context styles. Headings and
/// code cascade because the renderer derives document sizes from
/// `TextStyle::Body`.
fn apply_text_size_class(ctx: &egui::Context, size: TextSizeClass) {
    let base = size.px();
    ctx.style_mut(|style| {
        use egui::{FontId, TextStyle};
        style
            .text_styles
            .insert(TextStyle::Body, FontId::proportional(base));
        style
            .text_styles
            .insert(TextStyle::Heading, FontId::proportional(base * 2.0));
        style
            .text_styles
            .insert(TextStyle::Monospace, FontId::monospace(base - 2.0));
    });
}

struct ScriptFallback {
    key: &'static str,
    script: [u8; 4],
    required_glyphs: &'static str,
}

// ISO 15924 identifiers and coverage samples describe scripts, not font
// families. The platform backend remains the sole source of family choices.
const SCRIPT_FALLBACKS: &[ScriptFallback] = &[
    ScriptFallback {
        key: "SystemHanFallback",
        script: *b"Hani",
        required_glyphs: "中文测试繁體",
    },
    ScriptFallback {
        key: "SystemHiraganaFallback",
        script: *b"Hira",
        required_glyphs: "かな",
    },
    ScriptFallback {
        key: "SystemKatakanaFallback",
        script: *b"Kana",
        required_glyphs: "カナ",
    },
    ScriptFallback {
        key: "SystemHangulFallback",
        script: *b"Hang",
        required_glyphs: "한글",
    },
    ScriptFallback {
        key: "SystemArabicFallback",
        script: *b"Arab",
        required_glyphs: "اب",
    },
    ScriptFallback {
        key: "SystemHebrewFallback",
        script: *b"Hebr",
        required_glyphs: "אב",
    },
    ScriptFallback {
        key: "SystemDevanagariFallback",
        script: *b"Deva",
        required_glyphs: "नमस्तेहिन्दी",
    },
    ScriptFallback {
        key: "SystemThaiFallback",
        script: *b"Thai",
        required_glyphs: "สวัสดีภาษาไทย",
    },
];

const GENERIC_FALLBACKS: &[(GenericFamily, &str, &str)] = &[
    (GenericFamily::Math, "SystemMathFallback", "→"),
    (GenericFamily::SansSerif, "SystemSymbolFallback", "⚠"),
];

#[derive(Clone)]
struct SelectedFont {
    blob: Blob<u8>,
    index: u32,
    family_id: FamilyId,
    family: String,
    source: String,
    weight: FontWeight,
}

impl SelectedFont {
    fn identity(&self) -> (u64, u32) {
        (self.blob.id(), self.index)
    }

    fn data(&self) -> FontData {
        let mut data = FontData::from_owned(self.blob.data().to_vec());
        data.index = self.index;
        data
    }
}

struct InstalledFont {
    key: String,
    selected: SelectedFont,
    required_glyphs: &'static str,
    primary: bool,
}

fn font_has_glyphs(blob: &Blob<u8>, index: u32, required_glyphs: &str) -> bool {
    ttf_parser::Face::parse(blob.data(), index)
        .map(|face| {
            required_glyphs
                .chars()
                .all(|c| face.glyph_index(c).is_some())
        })
        .unwrap_or(false)
}

fn source_description(source: &SourceKind) -> String {
    match source {
        SourceKind::Memory(_) => "<memory>".to_owned(),
        SourceKind::Path(path) => path.display().to_string(),
    }
}

fn select_from_families(
    collection: &mut Collection,
    source_cache: &mut SourceCache,
    family_ids: &[FamilyId],
    weight: FontWeight,
    required_glyphs: &str,
    require_true_bold: bool,
) -> Option<SelectedFont> {
    for family_id in family_ids {
        let Some(family) = collection.family(*family_id) else {
            continue;
        };
        let mut candidates: Vec<_> = family
            .fonts()
            .iter()
            .filter(|font| {
                font.style() == FontStyle::Normal
                    && (!require_true_bold || font.weight() >= FontWeight::BOLD)
            })
            .collect();
        candidates.sort_by(|left, right| {
            let left_distance = (left.weight().value() - weight.value()).abs();
            let right_distance = (right.weight().value() - weight.value()).abs();
            left_distance.total_cmp(&right_distance)
        });

        for font in candidates {
            let Some(blob) = font.load(Some(source_cache)) else {
                continue;
            };
            if !font_has_glyphs(&blob, font.index(), required_glyphs) {
                continue;
            }
            return Some(SelectedFont {
                blob,
                index: font.index(),
                family_id: *family_id,
                family: family.name().to_owned(),
                source: source_description(font.source().kind()),
                weight: font.weight(),
            });
        }
    }
    None
}

fn fallback_family_ids(
    collection: &mut Collection,
    script: [u8; 4],
    locale: Option<&str>,
) -> Vec<FamilyId> {
    let script = Script::from_bytes(script);
    match locale {
        Some(locale) => collection.fallback_families((script, locale)).collect(),
        None => collection.fallback_families(script).collect(),
    }
}

fn installed_fonts_cover(installed: &[InstalledFont], glyphs: &str) -> bool {
    installed
        .iter()
        .any(|font| font_has_glyphs(&font.selected.blob, font.selected.index, glyphs))
}

fn install_regular_font(
    definitions: &mut FontDefinitions,
    installed: &mut Vec<InstalledFont>,
    loaded_faces: &mut HashSet<(u64, u32)>,
    key: &'static str,
    selected: SelectedFont,
    required_glyphs: &'static str,
    primary: bool,
) {
    if !loaded_faces.insert(selected.identity()) {
        return;
    }
    log::info!(
        "Loaded system font {} ({}, weight {}) from {} (face index {})",
        key,
        selected.family,
        selected.weight.value(),
        selected.source,
        selected.index
    );
    definitions
        .font_data
        .insert(key.to_owned(), selected.data().into());
    if let Some(family) = definitions.families.get_mut(&FontFamily::Proportional) {
        if primary {
            family.insert(0, key.to_owned())
        } else {
            family.push(key.to_owned())
        }
    }
    if let Some(family) = definitions.families.get_mut(&FontFamily::Monospace) {
        family.push(key.to_owned());
    }
    installed.push(InstalledFont {
        key: key.to_owned(),
        selected,
        required_glyphs,
        primary,
    });
}

fn install_regular_fonts(
    collection: &mut Collection,
    source_cache: &mut SourceCache,
    definitions: &mut FontDefinitions,
    locale: Option<&str>,
    preferred_family: Option<&str>,
    preset_body_families: Option<&'static [&'static str]>,
) -> Vec<InstalledFont> {
    let mut installed = Vec::new();
    let mut loaded_faces = HashSet::new();

    if let Some(name) = preferred_family {
        match collection.family_id(name) {
            Some(family_id) => {
                if let Some(selected) = select_from_families(
                    collection,
                    source_cache,
                    &[family_id],
                    FontWeight::NORMAL,
                    "Aa",
                    false,
                ) {
                    install_regular_font(
                        definitions,
                        &mut installed,
                        &mut loaded_faces,
                        "SystemSans",
                        selected,
                        "Aa",
                        true,
                    );
                } else {
                    log::warn!(
                        "Preferred font '{name}' has no usable regular face; falling back to system default."
                    );
                }
            }
            None => {
                log::warn!("Preferred font '{name}' not found; falling back to system default.");
            }
        }
    }

    // A preset's body families lead the primary sans chain when no user-picked
    // family was installed (the picker's choice outranks the preset's emulated
    // stack). Each stack name is tried in the emulated viewer's resolution
    // order; a total miss falls through to the app's own auto-detection.
    if installed.is_empty() {
        if let Some(preset_families) = preset_body_families {
            let family_ids: Vec<FamilyId> = preset_families
                .iter()
                .filter_map(|name| collection.family_id(name))
                .collect();
            if let Some(selected) = select_from_families(
                collection,
                source_cache,
                &family_ids,
                FontWeight::NORMAL,
                "Aa",
                false,
            ) {
                install_regular_font(
                    definitions,
                    &mut installed,
                    &mut loaded_faces,
                    "SystemSans",
                    selected,
                    "Aa",
                    true,
                );
            } else {
                log::warn!(
                    "Preset body families {preset_families:?} had no usable regular face; falling back to system default."
                );
            }
        }
    }

    // Auto-detect the system sans-serif only if no preferred family was
    // requested, or the preferred family couldn't be installed above.
    if installed.is_empty() {
        let families: Vec<_> = collection
            .generic_families(GenericFamily::SansSerif)
            .collect();
        if let Some(selected) = select_from_families(
            collection,
            source_cache,
            &families,
            FontWeight::NORMAL,
            "Aa",
            false,
        ) {
            install_regular_font(
                definitions,
                &mut installed,
                &mut loaded_faces,
                "SystemSans",
                selected,
                "Aa",
                true,
            );
        }
    }

    for spec in SCRIPT_FALLBACKS {
        if installed_fonts_cover(&installed, spec.required_glyphs) {
            continue;
        }
        let families = fallback_family_ids(collection, spec.script, locale);
        let Some(selected) = select_from_families(
            collection,
            source_cache,
            &families,
            FontWeight::NORMAL,
            spec.required_glyphs,
            false,
        ) else {
            continue;
        };
        install_regular_font(
            definitions,
            &mut installed,
            &mut loaded_faces,
            spec.key,
            selected,
            spec.required_glyphs,
            false,
        );
    }

    for &(generic, key, glyphs) in GENERIC_FALLBACKS {
        if installed_fonts_cover(&installed, glyphs) {
            continue;
        }
        let families: Vec<_> = collection.generic_families(generic).collect();
        let Some(selected) = select_from_families(
            collection,
            source_cache,
            &families,
            FontWeight::NORMAL,
            glyphs,
            false,
        ) else {
            continue;
        };
        install_regular_font(
            definitions,
            &mut installed,
            &mut loaded_faces,
            key,
            selected,
            glyphs,
            false,
        );
    }
    installed
}

fn push_unique(
    destination: &mut Vec<String>,
    seen: &mut HashSet<String>,
    names: impl IntoIterator<Item = String>,
) {
    for name in names {
        if seen.insert(name.clone()) {
            destination.push(name)
        }
    }
}

fn build_strong_family(
    primary_regular: Option<&str>,
    primary_bold: Option<&str>,
    default_proportional: &[String],
    fallback_bold: &[String],
    proportional: &[String],
) -> Vec<String> {
    let mut family = Vec::new();
    let mut seen = HashSet::new();
    push_unique(
        &mut family,
        &mut seen,
        primary_bold.into_iter().map(str::to_owned),
    );
    push_unique(
        &mut family,
        &mut seen,
        primary_regular.into_iter().map(str::to_owned),
    );
    push_unique(&mut family, &mut seen, default_proportional.iter().cloned());
    push_unique(&mut family, &mut seen, fallback_bold.iter().cloned());
    push_unique(&mut family, &mut seen, proportional.iter().cloned());
    family
}

fn install_strong_font_family(
    collection: &mut Collection,
    source_cache: &mut SourceCache,
    definitions: &mut FontDefinitions,
    installed: &[InstalledFont],
    default_proportional: &[String],
) -> usize {
    let mut loaded_faces: HashSet<_> = installed
        .iter()
        .map(|font| font.selected.identity())
        .collect();
    let mut primary_regular = None;
    let mut primary_bold = None;
    let mut fallback_bold = Vec::new();
    let mut count = 0;

    for regular in installed {
        if regular.primary {
            primary_regular = Some(regular.key.clone())
        }
        let Some(selected) = select_from_families(
            collection,
            source_cache,
            &[regular.selected.family_id],
            FontWeight::BOLD,
            regular.required_glyphs,
            true,
        ) else {
            continue;
        };
        if !loaded_faces.insert(selected.identity()) {
            continue;
        }
        let key = format!("{}Bold", regular.key);
        log::info!(
            "Loaded strong font {} ({}, weight {}) from {} (face index {})",
            key,
            selected.family,
            selected.weight.value(),
            selected.source,
            selected.index
        );
        definitions
            .font_data
            .insert(key.clone(), selected.data().into());
        count += 1;
        if regular.primary {
            primary_bold = Some(key)
        } else {
            fallback_bold.push(key)
        }
    }

    let proportional = definitions
        .families
        .get(&FontFamily::Proportional)
        .cloned()
        .unwrap_or_default();
    let strong = build_strong_family(
        primary_regular.as_deref(),
        primary_bold.as_deref(),
        default_proportional,
        &fallback_bold,
        &proportional,
    );
    if primary_regular.is_some() && primary_bold.is_none() {
        log::warn!("No true bold face found for the primary system sans; using regular fallback.");
    }
    definitions
        .families
        .insert(FontFamily::Name(STRONG_FONT_FAMILY.into()), strong);
    count
}

/// Load fonts through platform generic-family and script/locale fallback rules.
///
/// Fontique delegates to fontconfig on Linux/FreeBSD, DirectWrite on Windows,
/// CoreText on Apple platforms, and the system configuration on Android.
///
/// `preferred_family` optionally names a specific installed family (matched
/// case-insensitively) to use as the primary proportional font instead of the
/// auto-detected system sans-serif; an unset or unresolvable preference falls
/// back to today's auto-detect behavior.
/// Lead the monospace chain with the preset's code face, keeping egui's
/// bundled monospace (and any installed fallbacks) as fallback. Returns
/// whether a preset face was installed.
fn install_preset_mono_font(
    collection: &mut Collection,
    source_cache: &mut SourceCache,
    definitions: &mut FontDefinitions,
    mono_families: &'static [&'static str],
) -> bool {
    let family_ids: Vec<FamilyId> = mono_families
        .iter()
        .filter_map(|name| collection.family_id(name))
        .collect();
    let Some(selected) = select_from_families(
        collection,
        source_cache,
        &family_ids,
        FontWeight::NORMAL,
        "{}",
        false,
    ) else {
        log::warn!(
            "Preset mono families {mono_families:?} had no usable face; keeping the bundled monospace."
        );
        return false;
    };
    definitions
        .font_data
        .insert("PresetMono".to_owned(), selected.data().into());
    if let Some(family) = definitions.families.get_mut(&FontFamily::Monospace) {
        family.insert(0, "PresetMono".to_owned());
    }
    true
}

/// Bundled monochrome emoji face, appended last to both family chains.
///
/// Color-emoji coverage comes first via the system NotoColorEmoji face (see
/// `install_emoji_fonts`); this monochrome face fills any emoji codepoints
/// the color font lacks. Appended last so it only supplies glyphs nothing
/// else covers.
/// (See docs/devlog/014-font-fallback.md.)
///
/// Embedded in the binary. It used to be read at runtime from
/// `concat!(env!("CARGO_MANIFEST_DIR"), …)`, which is the *build machine's*
/// checkout path, so every distributed binary silently lacked it.
const EMOJI_FONT_BYTES: &[u8] = include_bytes!("../assets/fonts/NotoEmoji-Regular.ttf");

/// System color-emoji face (CBDT/CBLC bitmap font), appended after the
/// regular system fallbacks but before the monochrome emoji face.
/// Only the CBDT `NotoColorEmoji.ttf` builds belong here; Fedora's COLRv1
/// `Noto-COLRv1.ttf` is not handled by the swash bitmap path.
#[cfg(feature = "color-emoji")]
const COLOR_EMOJI_FONT_PATHS: &[&str] = &[
    "/usr/share/fonts/noto/NotoColorEmoji.ttf", // Arch (noto-fonts-emoji)
    "/usr/share/fonts/TTF/NotoColorEmoji.ttf",  // Arch (older layout)
    "/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf", // Debian/Ubuntu (fonts-noto-color-emoji)
];

/// Install emoji faces into the fallback chains.
///
/// The color face is only useful with the vendored epaint patch that
/// rasterizes color-bitmap glyphs via swash (ab_glyph alone renders them
/// blank). With the patch, emoji render in full color; without it, the
/// monochrome face still provides visible glyphs. Builds without the
/// `color-emoji` feature (the crates.io package) only get the monochrome face.
fn install_emoji_fonts(definitions: &mut FontDefinitions) {
    // `emoji_only` exists only in the vendored epaint (`[patch.crates-io]`),
    // which `cargo publish` ignores; see the `color-emoji` feature in Cargo.toml.
    #[cfg(feature = "color-emoji")]
    for path in COLOR_EMOJI_FONT_PATHS {
        match std::fs::read(path) {
            Ok(bytes) => {
                let mut data = FontData::from_owned(bytes);
                // Restrict to default-emoji characters so the color face
                // never claims general symbols (▶ ⚠ ✔ …) used by the UI.
                data.emoji_only = true;
                definitions
                    .font_data
                    .insert("ColorEmoji".to_owned(), data.into());
                for family in [FontFamily::Proportional, FontFamily::Monospace] {
                    if let Some(chain) = definitions.families.get_mut(&family) {
                        // Insert ahead of epaint's built-in monochrome emoji
                        // faces, which would otherwise claim the glyph first.
                        let pos = chain
                            .iter()
                            .position(|n| n == "NotoEmoji-Regular" || n == "emoji-icon-font")
                            .unwrap_or(chain.len());
                        chain.insert(pos, "ColorEmoji".to_owned());
                    }
                }
                log::info!("Loaded system color emoji font from {path}");
                break;
            }
            Err(e) => log::debug!("Color emoji font {path} unavailable: {e}"),
        }
    }
    definitions.font_data.insert(
        "NotoEmoji".to_owned(),
        FontData::from_static(EMOJI_FONT_BYTES).into(),
    );
    for family in [FontFamily::Proportional, FontFamily::Monospace] {
        if let Some(chain) = definitions.families.get_mut(&family) {
            chain.push("NotoEmoji".to_owned());
        }
    }
}

pub(crate) fn setup_fonts(
    ctx: &egui::Context,
    preferred_family: Option<&str>,
    preset: FontPreset,
    size: TextSizeClass,
) {
    let started = std::time::Instant::now();
    let mut collection = Collection::new(CollectionOptions::default());
    let family_count = collection.family_names().count();
    let mut source_cache = SourceCache::default();
    let locale = sys_locale::get_locale();
    let mut definitions = FontDefinitions::default();
    let defaults = definitions
        .families
        .get(&FontFamily::Proportional)
        .cloned()
        .unwrap_or_default();
    let installed = install_regular_fonts(
        &mut collection,
        &mut source_cache,
        &mut definitions,
        locale.as_deref(),
        preferred_family,
        preset.body_families(),
    );
    let bold_count = install_strong_font_family(
        &mut collection,
        &mut source_cache,
        &mut definitions,
        &installed,
        &defaults,
    );
    let preset_mono_families = preset.mono_families();
    let preset_mono = if preset_mono_families.is_empty() {
        false
    } else {
        install_preset_mono_font(
            &mut collection,
            &mut source_cache,
            &mut definitions,
            preset_mono_families,
        )
    };
    install_emoji_fonts(&mut definitions);
    if installed.is_empty() {
        log::warn!("No suitable system font fallbacks found; using egui defaults.");
    } else {
        log::info!(
            "Selected {} font faces from {} families for locale {:?} in {:.1} ms",
            installed.len() + bold_count + usize::from(preset_mono),
            family_count,
            locale,
            started.elapsed().as_secs_f64() * 1000.0
        );
    }
    ctx.set_fonts(definitions);
    apply_text_size_class(ctx, size);
}

/// Enumerate the family names the font picker should offer: one canonical
/// name per family, filtered to families that can actually serve as the
/// document body font.
///
/// Fontique's raw `family_names()` is unusable for a picker. On a stock Arch
/// system it reports 742 names for only 317 distinct families — every
/// localized name and weight-instance name ("Noto Sans Black", …) is a
/// separate entry that resolves to the base family and would pick the very
/// same regular face — and roughly two thirds of the listed names
/// (script-specific families such as "Noto Sans Devanagari", emoji and
/// symbol faces) have no basic-Latin coverage, so picking them silently fell
/// back to the auto-detected default. The body-font gate here is the same
/// one `install_regular_fonts` applies when installing a picked family, so
/// every listed name is guaranteed to take effect.
///
/// Costs one face load per candidate (every face of script-only families is
/// probed and rejected) — around half a second on a stock Arch system — so
/// callers run this off the UI thread (see the egui workflow's async phase).
pub(crate) fn scan_pickable_font_families() -> Vec<String> {
    let mut collection = Collection::new(CollectionOptions::default());
    let mut source_cache = SourceCache::default();
    pickable_family_names(&mut collection, &mut source_cache)
}

fn pickable_family_names(
    collection: &mut Collection,
    source_cache: &mut SourceCache,
) -> Vec<String> {
    let mut names: Vec<String> = collection.family_names().map(str::to_owned).collect();
    names.sort_by_key(|name| name.to_lowercase());
    names.dedup();
    names.retain(|name| {
        let Some(id) = collection.family_id(name) else {
            return false;
        };
        // Keep only each family's canonical (first-seen) name so aliases —
        // localized names and weight-instance names — collapse into a single
        // entry instead of five rows that all pick the same regular face.
        let canonical = collection.family_name(id).map(str::to_owned);
        if canonical.as_deref() != Some(name.as_str()) {
            return false;
        }
        select_from_families(
            collection,
            source_cache,
            &[id],
            FontWeight::NORMAL,
            "Aa",
            false,
        )
        .is_some()
    });
    names
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reported_scripts_use_full_coverage_samples() {
        let sample = |script| {
            SCRIPT_FALLBACKS
                .iter()
                .find(|fallback| fallback.script == script)
                .unwrap()
                .required_glyphs
        };
        assert_eq!(sample(*b"Deva"), "नमस्तेहिन्दी");
        assert_eq!(sample(*b"Thai"), "สวัสดีภาษาไทย");
        assert!(sample(*b"Hani").contains('测'));
        assert!(sample(*b"Hani").contains('體'));
    }

    #[test]
    fn default_latin_precedes_script_bold_without_primary_system_sans() {
        let strong = build_strong_family(
            None,
            None,
            &["DefaultLatin".into()],
            &["HanBold".into()],
            &["DefaultLatin".into(), "Han".into()],
        );
        assert_eq!(strong, ["DefaultLatin", "HanBold", "Han"]);
    }

    #[test]
    fn primary_regular_and_bold_stay_together() {
        let strong = build_strong_family(
            Some("SystemSans"),
            Some("SystemSansBold"),
            &["DefaultLatin".into()],
            &["HanBold".into()],
            &["SystemSans".into(), "Han".into()],
        );
        assert_eq!(
            strong,
            [
                "SystemSansBold",
                "SystemSans",
                "DefaultLatin",
                "HanBold",
                "Han"
            ]
        );
    }

    #[test]
    #[ignore = "requires installed system fonts"]
    fn unknown_preferred_family_falls_back_to_auto_detect() {
        let mut collection = Collection::new(CollectionOptions::default());
        let mut source_cache = SourceCache::default();
        let mut definitions = FontDefinitions::default();
        let installed = install_regular_fonts(
            &mut collection,
            &mut source_cache,
            &mut definitions,
            None,
            Some("Definitely Not An Installed Font Name 12345"),
            None,
        );
        assert!(
            installed.iter().any(|f| f.primary),
            "auto-detect fallback should still install a primary font"
        );
    }

    #[test]
    #[ignore = "requires installed system fonts"]
    fn known_preferred_family_becomes_primary() {
        let mut collection = Collection::new(CollectionOptions::default());
        let mut source_cache = SourceCache::default();

        // Discover whatever the system's default sans-serif family is, then
        // request it explicitly by name and confirm it round-trips as
        // primary. Avoids hardcoding a font name that may not exist on every
        // machine/CI image.
        let mut baseline_definitions = FontDefinitions::default();
        let baseline = install_regular_fonts(
            &mut collection,
            &mut source_cache,
            &mut baseline_definitions,
            None,
            None,
            None,
        );
        let Some(baseline_primary) = baseline.iter().find(|f| f.primary) else {
            return; // no system fonts available in this environment
        };
        let family_name = baseline_primary.selected.family.clone();

        let mut definitions = FontDefinitions::default();
        let installed = install_regular_fonts(
            &mut collection,
            &mut source_cache,
            &mut definitions,
            None,
            Some(&family_name),
            None,
        );
        let primary = installed
            .iter()
            .find(|f| f.primary)
            .expect("primary font installed");
        assert_eq!(primary.selected.family, family_name);
    }

    #[test]
    #[ignore = "requires installed system fonts"]
    fn pickable_family_list_is_deduplicated_and_body_capable() {
        let names = scan_pickable_font_families();
        assert!(!names.is_empty(), "no pickable families found");

        // Sorted case-insensitively, no duplicate names.
        let mut sorted = names.clone();
        sorted.sort_by_key(|name| name.to_lowercase());
        assert_eq!(names, sorted, "pickable family list must stay sorted");

        // One canonical name per family, and every listed family must pass
        // the same body-font gate used when installing a picked family —
        // otherwise picking it silently falls back to the default again.
        let mut collection = Collection::new(CollectionOptions::default());
        let total = collection.family_names().count();
        let mut source_cache = SourceCache::default();
        let mut seen_ids = HashSet::new();
        for name in &names {
            let id = collection
                .family_id(name)
                .unwrap_or_else(|| panic!("listed family {name:?} does not resolve"));
            assert!(
                seen_ids.insert(id),
                "duplicate family id behind {name:?} — alias leak"
            );
            assert_eq!(
                collection.family_name(id).map(str::to_owned).as_deref(),
                Some(name.as_str()),
                "{name:?} is an alias, not the family's canonical name"
            );
            assert!(
                select_from_families(
                    &mut collection,
                    &mut source_cache,
                    &[id],
                    FontWeight::NORMAL,
                    "Aa",
                    false,
                )
                .is_some(),
                "listed family {name:?} cannot serve as a body font"
            );
        }
        assert!(
            names.len() < total,
            "aliases and script-only families should be filtered ({}/{})",
            names.len(),
            total
        );
    }

    #[test]
    #[ignore = "requires installed multilingual regular and bold fonts"]
    fn installed_fonts_cover_reported_scripts() {
        let context = egui::Context::default();
        setup_fonts(
            &context,
            None,
            FontPreset::default(),
            TextSizeClass::default(),
        );
        context.begin_pass(Default::default());
        let regular = egui::FontId::proportional(16.0);
        let strong = egui::FontId::new(16.0, FontFamily::Name(STRONG_FONT_FAMILY.into()));
        let samples = [
            "中文测试繁體",
            "かなカナ",
            "한글",
            "नमस्तेहिन्दी",
            "สวัสดีภาษาไทย",
        ];
        let missing_regular: Vec<_> = samples
            .iter()
            .filter(|sample| !context.fonts_mut(|fonts| fonts.has_glyphs(&regular, sample)))
            .collect();
        let missing_strong: Vec<_> = samples
            .iter()
            .filter(|sample| !context.fonts_mut(|fonts| fonts.has_glyphs(&strong, sample)))
            .collect();
        let _ = context.end_pass();
        assert!(
            missing_regular.is_empty(),
            "regular chain lacks {missing_regular:?}"
        );
        assert!(
            missing_strong.is_empty(),
            "strong chain lacks {missing_strong:?}"
        );
    }

    #[test]
    fn preset_family_lists_follow_the_emulated_css_stacks() {
        // GitHub (Primer .markdown-body) leads with its locally-installed Mona
        // Sans, asks for Segoe UI before Noto Sans, and ends the named part of
        // its body stack at Arial.
        let github_body = FontPreset::Github
            .body_families()
            .expect("github body list");
        assert_eq!(github_body[..3], ["Mona Sans VF", "Mona Sans", "Segoe UI"]);
        assert!(github_body.contains(&"Noto Sans"));
        assert_eq!(*github_body.last().expect("non-empty"), "Arial");

        // VS Code preview lists Ubuntu and Droid Sans behind the system-ui
        // resolutions.
        let vscode_body = FontPreset::Vscode
            .body_families()
            .expect("vscode body list");
        let ubuntu_pos = vscode_body
            .iter()
            .position(|f| *f == "Ubuntu")
            .expect("ubuntu in vscode stack");
        let adwaita_pos = vscode_body
            .iter()
            .position(|f| *f == "Adwaita Sans")
            .expect("adwaita sans in vscode stack");
        assert!(adwaita_pos < ubuntu_pos, "system-ui precedes Ubuntu");

        // The default preset keeps the app's own sans selection.
        assert_eq!(FontPreset::Current.body_families(), None);
        assert!(FontPreset::Current.mono_families().is_empty());
    }

    /// The bundled monochrome face must be registered on every machine, not
    /// only on the one that built the binary. Runs without system fonts.
    #[test]
    fn bundled_emoji_face_is_always_registered_last() {
        let mut definitions = FontDefinitions::default();
        install_emoji_fonts(&mut definitions);
        assert!(
            definitions.font_data.contains_key("NotoEmoji"),
            "bundled emoji face missing from font_data"
        );
        for family in [FontFamily::Proportional, FontFamily::Monospace] {
            assert_eq!(
                definitions.families[&family].last().map(String::as_str),
                Some("NotoEmoji"),
                "bundled emoji face must be the last fallback in {family:?}"
            );
        }
    }

    /// The bundled face on its own covers and inks the document emoji.
    /// Runs without system fonts, so CI exercises the fallback path.
    #[test]
    fn bundled_emoji_face_alone_renders_doc_emoji() {
        let mut definitions = FontDefinitions::default();
        install_emoji_fonts(&mut definitions);
        definitions.font_data.retain(|k, _| k == "NotoEmoji");
        *definitions
            .families
            .get_mut(&FontFamily::Proportional)
            .unwrap() = vec!["NotoEmoji".to_owned()];
        let ctx = egui::Context::default();
        ctx.set_fonts(definitions);
        ctx.run(egui::RawInput::default(), |_ctx| {});
        let font_id = egui::FontId::proportional(16.0);
        for ch in [
            '\u{1F7E2}',
            '\u{1F534}',
            '\u{1F535}',
            '\u{26AA}',
            '\u{2705}',
        ] {
            assert!(
                ctx.fonts_mut(|f| f.has_glyph(&font_id, ch)),
                "bundled emoji face lacks {ch}"
            );
            let job = egui::text::LayoutJob::simple(
                ch.to_string(),
                font_id.clone(),
                egui::Color32::WHITE,
                f32::INFINITY,
            );
            let ink = ctx.fonts_mut(|f| {
                let galley = f.layout_job(job);
                let uv = galley.rows[0].glyphs[0].uv_rect;
                let image = f.image();
                let [w, h] = image.size;
                let mut count = 0usize;
                for y in (uv.min[1] as usize).min(h)..(uv.max[1] as usize).min(h) {
                    for x in (uv.min[0] as usize).min(w)..(uv.max[0] as usize).min(w) {
                        if image[(x, y)].a() > 16 {
                            count += 1;
                        }
                    }
                }
                count
            });
            assert!(ink > 20, "bundled emoji {ch} rasterized blank ({ink} px)");
        }
    }

    #[test]
    #[cfg(feature = "color-emoji")]
    #[ignore = "requires installed system fonts"]
    fn emoji_fallback_face_resolves_for_doc_emoji() {
        // Build the same definitions setup_fonts() would install: egui
        // defaults + the bundled monochrome emoji face appended last.
        let mut definitions = FontDefinitions::default();
        install_emoji_fonts(&mut definitions);

        let ctx = egui::Context::default();
        ctx.set_fonts(definitions);
        // Fonts aren't built until the first Context::run() pass.
        ctx.run(egui::RawInput::default(), |_ctx| {});
        let font_id = egui::FontId::proportional(16.0);
        // Debug: font_data keys and family list as egui sees them.
        ctx.fonts(|f| {
            let defs = f.definitions();
            eprintln!(
                "font_data keys: {:?}",
                defs.font_data.keys().collect::<Vec<_>>()
            );
            eprintln!(
                "Proportional chain: {:?}",
                defs.families.get(&FontFamily::Proportional)
            );
            eprintln!(
                "Monospace chain: {:?}",
                defs.families.get(&FontFamily::Monospace)
            );
        });
        // Isolate which individual face supplies each glyph: one font per chain.
        let defaults = FontDefinitions::default();
        let mut with_ours = FontDefinitions::default();
        install_emoji_fonts(&mut with_ours);
        for (label, defs_source) in [
            ("builtin:NotoEmoji-Regular", &defaults),
            ("bundled:NotoEmoji", &with_ours),
        ] {
            let name = label.split(':').nth(1).unwrap();
            let mut single = defs_source.clone();
            single.font_data.retain(|k, _| k == name);
            *single.families.get_mut(&FontFamily::Proportional).unwrap() = vec![name.to_owned()];
            let ctx2 = egui::Context::default();
            ctx2.set_fonts(single);
            ctx2.run(egui::RawInput::default(), |_ctx| {});
            let font_id = egui::FontId::proportional(16.0);
            let results: Vec<bool> = ctx2.fonts_mut(|f| {
                [
                    '\u{1F7E2}',
                    '\u{1F534}',
                    '\u{1F535}',
                    '\u{26AA}',
                    '\u{2705}',
                ]
                .iter()
                .map(|&ch| f.has_glyph(&font_id, ch))
                .collect()
            });
            eprintln!("face {label}: 🟢🔴🔵⚪✅ = {results:?}");
        }

        for ch in [
            '\u{1F7E2}',
            '\u{1F534}',
            '\u{1F535}',
            '\u{26AA}',
            '\u{2705}',
        ] {
            let resolved = ctx.fonts_mut(|f| f.has_glyph(&font_id, ch));
            assert!(
                resolved,
                "emoji {ch} should resolve through the fallback chain to NotoEmoji"
            );
        }

        // End-to-end ink check: rasterize each emoji and require actual
        // coverage in the atlas, so a cmap hit with an empty outline fails.
        for ch in ['\u{1F7E2}', '\u{1F534}', '\u{2705}'] {
            let job = egui::text::LayoutJob::simple(
                ch.to_string(),
                font_id.clone(),
                egui::Color32::WHITE,
                f32::INFINITY,
            );
            let ink = ctx.fonts_mut(|f| {
                let galley = f.layout_job(job);
                let glyph = &galley.rows[0].glyphs[0];
                let uv = glyph.uv_rect;
                let image = f.image(); // full atlas
                let [w, h] = image.size;
                let (x0, y0) = (uv.min[0] as usize, uv.min[1] as usize);
                let (x1, y1) = (uv.max[0] as usize, uv.max[1] as usize);
                let mut count = 0usize;
                for y in y0.min(h)..y1.min(h) {
                    for x in x0.min(w)..x1.min(w) {
                        if image[(x, y)].a() > 16 {
                            count += 1;
                        }
                    }
                }
                count
            });
            eprintln!("ink pixels for {ch:?}: {ink}");
            assert!(
                ink > 20,
                "emoji {ch} rasterized blank (only {ink} ink pixels)"
            );
        }

        // Color check (requires vendored epaint with the swash patch): each
        // doc emoji must resolve to the ColorEmoji face and produce genuinely
        // colored atlas pixels — saturated red/green RGB channels.
        for (ch, want_channel) in [('\u{1F7E2}', "green"), ('\u{1F534}', "red")] {
            let job = egui::text::LayoutJob::simple(
                ch.to_string(),
                font_id.clone(),
                egui::Color32::WHITE,
                f32::INFINITY,
            );
            let (colored, channel_peak) = ctx.fonts_mut(|f| {
                let galley = f.layout_job(job);
                let glyph = &galley.rows[0].glyphs[0];
                let uv = glyph.uv_rect;
                let image = f.image();
                let [w, h] = image.size;
                let mut peak = 0u8;
                for y in uv.min[1] as usize..(uv.max[1] as usize).min(h) {
                    for x in uv.min[0] as usize..(uv.max[0] as usize).min(w) {
                        let px = image[(x, y)];
                        let m = match want_channel {
                            "green" => px.g(),
                            _ => px.r(),
                        };
                        // Require the color channel to dominate its counterpart.
                        let other = match want_channel {
                            "green" => px.r(),
                            _ => px.g(),
                        };
                        if px.a() > 32 && m > 48 && m as u16 > other as u16 + 16 {
                            peak = peak.max(m);
                        }
                    }
                }
                (uv.colored, peak)
            });
            eprintln!(
                "{ch:?}: colored flag = {colored}, {want_channel} channel peak = {channel_peak}"
            );
            // Debug: dump first few atlas pixels from the glyph region.
            ctx.fonts(|f| {
                let _ = f;
            });
            let job2 = egui::text::LayoutJob::simple(
                ch.to_string(),
                font_id.clone(),
                egui::Color32::WHITE,
                f32::INFINITY,
            );
            ctx.fonts_mut(|f| {
                let galley = f.layout_job(job2);
                let uv = galley.rows[0].glyphs[0].uv_rect;
                let image = f.image();
                let mut shown = 0;
                for y in uv.min[1] as usize..uv.max[1] as usize {
                    for x in uv.min[0] as usize..uv.max[0] as usize {
                        let px = image[(x, y)];
                        if px.a() > 0 && shown < 8 {
                            eprintln!("  atlas px ({x},{y}) = {:?}", px);
                            shown += 1;
                        }
                    }
                }
            });
            assert!(colored, "emoji {ch} did not take the color-glyph path");
            assert!(
                channel_peak > 128,
                "emoji {ch} rendered without color (peak {want_channel} = {channel_peak})"
            );
        }
    }

    #[test]
    #[cfg(feature = "color-emoji")]
    #[ignore = "requires installed system fonts"]
    fn color_emoji_face_never_claims_ui_symbols() {
        let mut definitions = FontDefinitions::default();
        install_emoji_fonts(&mut definitions);
        definitions.font_data.retain(|k, _| k == "ColorEmoji");
        *definitions
            .families
            .get_mut(&FontFamily::Proportional)
            .unwrap() = vec!["ColorEmoji".to_owned()];
        let ctx = egui::Context::default();
        ctx.set_fonts(definitions);
        ctx.run(egui::RawInput::default(), |_ctx| {});
        let font_id = egui::FontId::proportional(16.0);
        // Default-emoji characters resolve through the color face...
        for ch in ['\u{1F7E2}', '\u{1F534}', '\u{26AA}', '\u{2705}'] {
            let ok = ctx.fonts_mut(|f| f.has_glyph(&font_id, ch));
            assert!(ok, "{ch} should come from ColorEmoji");
        }
        // ...but general UI symbols must not, even though Noto Color Emoji
        // maps them — they belong to regular text faces.
        for ch in [
            '\u{25B6}', '\u{25BC}', '\u{26A0}', '\u{2714}', '\u{2192}', '\u{2713}',
        ] {
            let claimed = ctx.fonts_mut(|f| f.has_glyph(&font_id, ch));
            assert!(
                !claimed,
                "{ch} (UI symbol) must not be claimed by the color emoji face"
            );
        }
    }

    #[test]
    fn preset_mono_lists_lead_with_linux_generic_monospace_resolutions() {
        assert_eq!(
            FontPreset::Github.mono_families()[..2],
            ["Noto Sans Mono", "DejaVu Sans Mono"]
        );
        assert_eq!(
            FontPreset::Vscode.mono_families(),
            ["Droid Sans Mono", "Noto Sans Mono", "DejaVu Sans Mono"]
        );
    }

    #[test]
    #[ignore = "requires installed system fonts"]
    fn github_preset_resolves_its_body_stack_when_fonts_exist() {
        let mut collection = Collection::new(CollectionOptions::default());
        let mut source_cache = SourceCache::default();
        let mut definitions = FontDefinitions::default();
        let installed = install_regular_fonts(
            &mut collection,
            &mut source_cache,
            &mut definitions,
            None,
            None,
            FontPreset::Github.body_families(),
        );
        let Some(primary) = installed.iter().find(|f| f.primary) else {
            return; // no system fonts available in this environment
        };
        let stack = FontPreset::Github
            .body_families()
            .expect("github body list");
        assert!(
            stack.contains(&primary.selected.family.as_str()),
            "preset lead {:?} must come from the emulated stack",
            primary.selected.family
        );
    }
}