f-office-docx 0.3.0

DOCX model and Word's layout rules.
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
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
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
use std::fmt::Write as _;

use compatifont::{Description, Item};
use f_office_fonts::environment::{FontEnvironment, Lacking, OwnFace, WordLine};
use f_office_fonts::{
    FamilyName, FontDb, FontId, KerningSource, NotReadCause, Os2Metrics, OutlineError,
};

use f_office_fonts::SymbolFont;

use super::{FontChoice, line_descent, sha256};
use crate::profile::Profile;
use crate::quirks::HelveticaLine;
use crate::{Fonts, KerningTable, OutlineCommand, SubstituteLayout};
use f_office_warnings::Name;

const CARLITO: &[u8] = include_bytes!(concat!(
    env!(
        "F_OFFICE_UNIT_TEST_FONTS",
        "set F_OFFICE_UNIT_TEST_FONTS to the folder of the test fonts, which holds Carlito-Regular.ttf"
    ),
    "/Carlito-Regular.ttf"
));

/// The base target's profile with Helvetica's line `line`.
fn with_line(line: HelveticaLine) -> Profile {
    Profile::base().with_variant(line)
}

/// An environment with only Word's lines of families and the other names of faces of the base
/// target's environment.
fn lines_and_names() -> FontEnvironment {
    let base = Profile::base();
    let environment = base.font_environment();
    FontEnvironment::default()
        .with_lines(environment.lines().to_vec())
        .with_face_names(environment.face_names().to_vec())
}

/// A description of the regular face `bytes` of `family` in `version`, with an entry from a
/// check against `matched` in `made_for` whose items are all equal, so that it reaches the
/// layout level.
fn described(bytes: &[u8], (family, version): (&str, &str), matched: (&str, &str)) -> Description {
    let items = Item::all().fold(String::new(), |mut items, item| {
        let _ = writeln!(items, "\"{}\" = \"equal\"", item.name());
        items
    });
    let text = format!(
        "format = 1\nfamily_name = \"{family}\"\nversion = \"{version}\"\n\n[[fonts]]\n\
         filename = \"{family}-Regular.ttf\"\nsubfamily_name = \"Regular\"\n\
         full_name = \"{family} Regular\"\npost_script_name = \"{family}-Regular\"\n\
         weight = 400\nstyle = \"normal\"\nsha256 = \"{}\"\n\n[[compatible_with]]\n\
         family_name = \"{}\"\nversion = \"{}\"\nbasis = \"check\"\n\
         reference = \"checks/test.toml\"\nsubfamilies = {{ Regular = \"Regular\" }}\n\n\
         [compatible_with.items]\n{items}",
        sha256(bytes),
        matched.0,
        matched.1
    );
    Description::from_toml(&text).unwrap()
}

/// Adds the face of Carlito renamed `family` in `version` to `db`, with a description that gives
/// it the layout of `matched`.
fn add_described(
    db: &mut FontDb,
    (family, version): (&str, &str),
    matched: (&str, &str),
) -> FontId {
    let bytes = with_names(CARLITO, family, &format!("Version {version}"));
    db.add_description(described(&bytes, (family, version), matched));
    db.add_font(bytes).unwrap()[0]
}

/// Adds Arimo CF 7.06.1, made for Arial 7.06, to `db`.
fn add_arimo_cf(db: &mut FontDb) -> FontId {
    add_described(db, ("Arimo CF", "7.06.1"), ("Arial", "7.06"))
}

#[test]
fn takes_pair_kerning_and_ligatures_from_the_font_store() {
    // The trait's defaults know no pair kerning and no standard ligatures, so a lost body of
    // the font choice would give them for every font.
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let glyph = |ch| choice.glyph(carlito, ch).unwrap();
    // Carlito kerns "AV" by -89 units, and joins "fi" into one glyph.
    let kerning = |table| choice.kerning(carlito, glyph('A'), glyph('V'), table);
    assert_eq!(kerning(KerningTable::FaceSource), -89);
    assert_eq!(
        kerning(KerningTable::KernTable),
        db.kerning_from(carlito, glyph('A'), glyph('V'), KerningSource::KernTable)
    );
    let fi = [glyph('f'), glyph('i')];
    let joined = choice.ligatures(carlito, &fi);
    assert_eq!(joined, db.ligatures(carlito, &fi));
    assert_eq!(joined.len(), 1);
}

#[test]
fn gives_the_ink_of_a_glyph_none_for_a_space_and_the_cause_of_an_outline_that_does_not_read() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let glyph = |ch| choice.glyph(carlito, ch).unwrap();
    // The ink of "x" stands on the baseline and reaches up; a space has none.
    let ink = choice.ink(carlito, glyph('x'));
    assert!(
        matches!(ink, Ok(Some((low, high))) if low <= 0 && high > 0),
        "{ink:?}"
    );
    assert_eq!(choice.ink(carlito, glyph(' ')), Ok(None));
    // The font store's cause reaches the layout, which warns of it.
    assert_eq!(
        choice.ink(carlito, u32::MAX),
        Err(OutlineError::UnknownGlyph)
    );
    let unknown = FontId::from_index(carlito.index() + 1);
    assert_eq!(choice.ink(unknown, 0), Err(OutlineError::UnknownFont));
}

#[test]
fn finds_the_families_that_draw_a_family_in_its_place() {
    let db = FontDb::new();
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    for (family, first) in [
        ("calibri", Some("Celeborn CF")),
        ("Aptos", Some("Intos CF")),
        ("Courier New", Some("Curunír CF")),
        ("arial narrow", Some("Arimo Narrow CF")),
        ("Book Antiqua", Some("P052")),
        ("Bookman Old Style", Some("URW Bookman")),
        ("Segoe UI", Some("Sindar CF")),
        ("Comic Sans MS", Some("Comic Relief CF")),
        ("Cambria Math", Some("Caladea Math CF")),
    ] {
        let drawn = choice.drawn_with(family);
        assert_eq!(drawn.first().map(String::as_str), first, "{family}");
    }
}

#[test]
fn draws_the_families_of_its_own_rule_with_their_compatible_fonts() {
    let db = FontDb::new();
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    // F-Office's own rule names a family, which its compatible fonts then draw.
    let arial = ["Arial", "Arimo CF", "Arimo", "Liberation Sans"];
    assert_eq!(choice.drawn_with("Helvetica"), arial);
    // A symbol font takes its symbol stand-in face instead.
    assert_eq!(choice.drawn_with("Symbol"), Vec::<String>::new());
    assert_eq!(
        choice.drawn_with("Times"),
        ["Times New Roman", "Tinos CF", "Liberation Serif", "Tinos"]
    );
}

#[test]
fn takes_words_line_of_a_family_from_the_base_environment() {
    let base = Profile::base();
    let line = |family| {
        base.font_environment()
            .line(family)
            .map(|l| (l.ascent, l.descent))
    };
    assert_eq!(line("Calibri"), None);
    assert_eq!(line("Cambria"), Some((960, 212)));
}

#[test]
fn draws_a_family_with_the_family_that_the_configuration_names_and_its_compatible_fonts() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let target = crate::Target::all().next().unwrap();
    let mut configuration = crate::Configuration::of(target);
    for (family, uses) in [
        ("Aptos", "Calibri"),
        ("Symbol", "Aptos"),
        ("Calibri", "Symbol"),
    ] {
        configuration
            .fonts
            .uses
            .insert(family.to_owned(), uses.to_owned());
    }
    let profile = Profile::resolve(&configuration, &crate::profile::Overrides::default()).unwrap();
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &profile);
    // A ring of families stops at the family that comes again.
    assert_eq!(choice.drawn_with("Aptos"), ["Calibri", "Symbol"]);
    assert_eq!(
        choice.drawn_with("Symbol"),
        ["Aptos", "Calibri", "Celeborn CF", "Carlito"]
    );
    let aptos = choice.face(&FamilyName::from_static("Aptos"), false, false);
    assert_eq!(aptos.map(|chosen| chosen.font), None);
    let symbol = choice.face(&FamilyName::from_static("Symbol"), false, false);
    assert_eq!(symbol.map(|chosen| chosen.font), Some(carlito));
}

#[test]
fn keeps_measured_line_metrics_over_the_own_file_only_for_named_fonts() {
    let mut db = FontDb::new();
    let helvetica = db
        .add_font(with_names(CARLITO, "Helvetica", "Version 1.0"))
        .unwrap()[0];
    let symbol = db
        .add_font(with_names(CARLITO, "Symbol", "Version 1.0"))
        .unwrap()[0];
    let environment = lines_and_names();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let metrics = |family, named| {
        let family = FamilyName::from_static(family);
        let chosen = if named {
            choice.face(&family, false, false)
        } else {
            choice.substitute(&family, false, false)
        };
        chosen.map(|chosen| chosen.metrics)
    };
    let own = choice.metrics(helvetica);
    assert_ne!(metrics("Helvetica", true), own);
    assert_eq!(metrics("Helvetica", false), own);
    assert_eq!(metrics("Symbol", true), choice.metrics(symbol));
}

#[test]
fn gives_helvetica_the_line_of_its_face_where_the_target_says_so() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let environment = lines_and_names();
    let metrics = |helvetica_line| {
        let choice = FontChoice::new(&db, &environment, &with_line(helvetica_line));
        let own = choice.metrics(carlito);
        let drawn_with = ["Carlito".to_owned()];
        let drawn = choice.draw_stand_in("Helvetica", &drawn_with, (false, false), &[]);
        (drawn.map(|chosen| chosen.metrics), own)
    };
    let (face, own) = metrics(HelveticaLine::TakesFaceLine);
    assert_eq!(face, own);
    let (mac, own) = metrics(HelveticaLine::TwelveTenthsEm);
    assert_ne!(mac, own);
    let lines = with_line(HelveticaLine::TakesFaceLine).stand_in_lines();
    assert!(lines.of_family("Symbol"));
}

#[test]
fn treats_a_family_that_the_target_lacks_as_missing() {
    let mut db = FontDb::new();
    db.add_font(CARLITO.to_vec()).unwrap();
    let lacking = Lacking {
        drawn_with: None,
        family: FamilyName::from_static("Carlito"),
    };
    let environment = FontEnvironment::default().with_lacking(vec![lacking]);
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let carlito = FamilyName::from_static("Carlito");
    assert!(choice.face(&carlito, false, false).is_none());
    assert!(choice.substitute(&carlito, true, false).is_none());
    let lower = FamilyName::from_static("carlito");
    assert!(choice.face(&lower, false, false).is_none());
}

#[test]
fn a_target_listing_blocks_local_names_before_stand_ins() {
    let mut db = FontDb::new();
    db.add_font(CARLITO.to_vec()).unwrap();
    let environment =
        FontEnvironment::default().with_available(vec![FamilyName::from_static("Calibri")]);
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let face = |family| choice.face(&FamilyName::from_static(family), false, false);
    assert!(face("Carlito").is_none());
    assert!(
        choice
            .substitute(&FamilyName::from_static("Carlito"), false, false)
            .is_none()
    );
    assert!(face("Calibri").is_some());
    assert!(face("CALIBRI").is_some());
}

/// The profile of `target` with a configuration that adds `family` to the fonts of Word's
/// machine.
fn with_installed(target: crate::Target, family: &str) -> Profile {
    let mut configuration = crate::Configuration::of(target);
    configuration
        .fonts
        .installed
        .insert(family.to_owned(), true);
    Profile::resolve(&configuration, &crate::profile::Overrides::default()).unwrap()
}

/// Whether the target's font environment has a full font listing.
fn listed(target: crate::Target) -> bool {
    !Profile::of(target)
        .unwrap()
        .font_environment()
        .available()
        .is_empty()
}

/// Whether the font choice of `profile` takes the face of Carlito in `db`.
fn takes_carlito(db: &FontDb, profile: &Profile) -> bool {
    FontChoice::new(db, profile.font_environment(), profile)
        .face(&FamilyName::from_static("Carlito"), false, false)
        .is_some()
}

#[test]
fn a_family_that_the_configuration_installs_counts_as_listed() {
    let mut db = FontDb::new();
    db.add_font(CARLITO.to_vec()).unwrap();
    let targets: Vec<_> = crate::Target::all()
        .filter(|target| listed(*target))
        .collect();
    assert_ne!(targets.len(), 0, "a target has a full font listing");
    for target in targets {
        assert!(
            !takes_carlito(&db, &Profile::of(target).unwrap()),
            "{target}"
        );
        let added = with_installed(target, "Carlito");
        assert!(takes_carlito(&db, &added), "{target}");
        assert!(added.font_environment().permits("carlito"), "{target}");
        assert_eq!(
            added.origin("configuration.fonts.installed.Carlito"),
            Some("configuration")
        );
        // A family that the configuration does not install stays outside the listing.
        assert!(
            !takes_carlito(&db, &with_installed(target, "Lato")),
            "{target}"
        );
    }
}

#[test]
fn a_target_without_a_full_listing_takes_an_added_family_as_every_other() {
    // A target without a full listing takes every name, and an added name changes nothing.
    let mut db = FontDb::new();
    db.add_font(CARLITO.to_vec()).unwrap();
    for target in crate::Target::all().filter(|target| !listed(*target)) {
        let added = with_installed(target, "Carlito");
        assert!(added.font_environment().available().is_empty(), "{target}");
        assert!(takes_carlito(&db, &added), "{target}");
    }
}

#[test]
fn a_reference_stand_in_needs_the_targets_family_style_and_version() {
    let mut db = FontDb::new();
    let id = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let mut info = db.info(id).unwrap().clone();
    info.family = "Helvetica".to_owned();
    let environment = FontEnvironment::new(vec![OwnFace {
        family: "Helvetica".to_owned(),
        style: info.subfamily.clone(),
        version: info.version.clone().unwrap(),
        kerning: None,
        units_per_em: None,
    }])
    .with_available(vec![FamilyName::from_static("Arial")]);
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TakesFaceLine));
    assert!(choice.permits_face(&info));
    info.version = Some("another version".to_owned());
    assert!(!choice.permits_face(&info));
}

#[test]
fn names_a_face_only_when_it_is_the_targets_own() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let info = db.info(carlito).unwrap();
    let (name, version) = (
        info.postscript_name.clone().unwrap(),
        info.version.clone().unwrap(),
    );
    let (family, style) = (info.family.clone(), info.subfamily.clone());
    let own = |style: &str, version: &str| {
        FontEnvironment::new(vec![OwnFace {
            family: family.clone(),
            style: style.to_owned(),
            version: version.to_owned(),
            kerning: None,
            units_per_em: None,
        }])
    };
    let named = |environment: &FontEnvironment| {
        let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
        choice.target_face(carlito)
    };
    // The face is named by the file's PostScript name.
    assert_eq!(
        named(&own(&style, &version)),
        Some((name.clone(), version.clone()))
    );
    assert_eq!(named(&own(&style, "Version 0.1")), None);
    assert_eq!(named(&own("Other", &version)), None);
    assert_eq!(named(&FontEnvironment::default()), None);
}

#[test]
fn takes_the_recorded_kerning_source_of_the_targets_file_over_its_own() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let info = db.info(carlito).unwrap();
    let (family, style, version) = (
        info.family.clone(),
        info.subfamily.clone(),
        info.version.clone().unwrap(),
    );
    let own = db.kerning_source(carlito);
    let other = match own {
        KerningSource::Gpos => KerningSource::KernTable,
        KerningSource::KernTable => KerningSource::Gpos,
    };
    let own_face = |version: &str, kerning| {
        FontEnvironment::new(vec![OwnFace {
            family: family.clone(),
            style: style.clone(),
            version: version.to_owned(),
            kerning,
            units_per_em: None,
        }])
    };
    let source = |environment: &FontEnvironment| {
        let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
        (
            choice.kerning_source(carlito),
            choice.kerning_source(carlito),
        )
    };
    assert_eq!(source(&own_face(&version, Some(other))), (other, other));
    assert_eq!(source(&own_face(&version, None)), (own, own));
    assert_eq!(source(&own_face("Version 0.1", Some(other))), (own, own));
    assert_eq!(source(&FontEnvironment::default()), (own, own));
}

/// `font` with a new `name` table that holds only the family, the style, the full name, the
/// version and the PostScript name, for Windows in US English; the table goes at the end of the
/// file, and its record points there.
fn with_names(font: &[u8], family: &str, version: &str) -> Vec<u8> {
    with_name_table(font, &regular_names(family, version))
}

/// The names of `with_names`: the family, the style, the full name, the version and the
/// PostScript name of the regular face of `family`.
fn regular_names(family: &str, version: &str) -> Vec<(u16, String)> {
    vec![
        (1, family.to_owned()),
        (2, "Regular".to_owned()),
        (4, format!("{family} Regular")),
        (5, version.to_owned()),
        (6, format!("{family}-Regular")),
    ]
}

/// `font` with a new `name` table that holds `names`, each as (name ID, text), for Windows in
/// US English; the table goes at the end of the file, and its record points there.
fn with_name_table(font: &[u8], names: &[(u16, String)]) -> Vec<u8> {
    let short = |n: usize| u16::try_from(n).unwrap();
    let mut strings = Vec::new();
    let mut table = Vec::new();
    table.extend_from_slice(&0_u16.to_be_bytes());
    table.extend_from_slice(&short(names.len()).to_be_bytes());
    table.extend_from_slice(&short(6 + 12 * names.len()).to_be_bytes());
    for (id, text) in names {
        let utf16: Vec<u8> = text.encode_utf16().flat_map(u16::to_be_bytes).collect();
        for value in [
            3_u16,
            1,
            0x409,
            *id,
            short(utf16.len()),
            short(strings.len()),
        ] {
            table.extend_from_slice(&value.to_be_bytes());
        }
        strings.extend(utf16);
    }
    table.extend(strings);
    let mut bytes = font.to_vec();
    while !bytes.len().is_multiple_of(4) {
        bytes.push(0);
    }
    let count = usize::from(u16::from_be_bytes([bytes[4], bytes[5]]));
    let record = (0..count)
        .map(|index| 12 + 16 * index)
        .find(|&at| &bytes[at..at + 4] == b"name")
        .unwrap();
    let (offset, length) = (
        u32::try_from(bytes.len()).unwrap(),
        u32::try_from(table.len()).unwrap(),
    );
    bytes[record + 8..record + 12].copy_from_slice(&offset.to_be_bytes());
    bytes[record + 12..record + 16].copy_from_slice(&length.to_be_bytes());
    bytes.extend(table);
    bytes
}

/// The target's own regular face of `family` in `version`, with the kerning source `kerning`.
fn own_regular(family: &str, version: &str, kerning: Option<KerningSource>) -> FontEnvironment {
    FontEnvironment::new(vec![OwnFace {
        family: family.to_owned(),
        style: "Regular".to_owned(),
        version: version.to_owned(),
        kerning,
        units_per_em: None,
    }])
}

#[test]
fn lays_out_a_described_face_as_the_targets_own_face_of_the_same_version() {
    let mut db = FontDb::new();
    let arimo_cf = add_arimo_cf(&mut db);
    let arimo = db
        .add_font(with_names(CARLITO, "Arimo", "Version 7.06.1"))
        .unwrap()[0];
    let tinos_cf = add_described(&mut db, ("Tinos CF", "7.12.1"), ("Times New Roman", "7.12"));
    // A file of the described family and version that is not the described file.
    let changed = db
        .add_font(with_weight(
            &with_names(CARLITO, "Arimo CF", "Version 7.06.1"),
            500,
        ))
        .unwrap()[0];
    let own = db.kerning_source(arimo_cf);
    let other = match own {
        KerningSource::Gpos => KerningSource::KernTable,
        KerningSource::KernTable => KerningSource::Gpos,
    };
    let answers = |environment: &FontEnvironment, font| {
        let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
        (choice.target_face(font), choice.kerning_source(font))
    };
    let arial = own_regular("Arial", "Version 7.06", Some(other));
    let as_own = Some(("Arimo CF-Regular".to_owned(), "Version 7.06.1".to_owned()));
    assert_eq!(answers(&arial, arimo_cf), (as_own, other));
    // Another version of the own face than the description's entry, a face without a
    // description, a face of another family and a file other than the described one draw as
    // ordinary faces.
    for environment in [
        own_regular("Arial", "Version 5.01", Some(other)),
        own_regular("Arial", "Version 7.0", Some(other)),
        own_regular("Arial", "Version 7.06.1", None),
        FontEnvironment::default(),
    ] {
        assert_eq!(answers(&environment, arimo_cf), (None, own));
    }
    assert_eq!(answers(&arial, arimo), (None, own));
    assert_eq!(answers(&arial, tinos_cf), (None, own));
    assert_eq!(answers(&arial, changed).0, None);
}

#[test]
fn says_whether_a_described_face_has_the_layout_of_the_targets_face() {
    let mut db = FontDb::new();
    let arimo_cf = add_arimo_cf(&mut db);
    let sans = db
        .add_font(with_names(CARLITO, "Liberation Sans", "Version 2.1"))
        .unwrap()[0];
    let answers = |environment: &FontEnvironment, asked: &str, font| {
        let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
        (
            choice.face_version(font),
            choice.substitute_layout(&FamilyName::new(asked), font),
        )
    };
    let version = |text: &str| Some(text.to_owned());
    let windows = own_regular("Arial", "Version 7.06", None);
    let mac = own_regular("Arial", "Version 5.01.2x", None);
    assert_eq!(
        answers(&windows, "Arial", arimo_cf),
        (version("7.06.1"), SubstituteLayout::Exact)
    );
    // An uninstalled custom font falling back to an exact stand-in for Arial is Fallback, not Exact.
    assert_eq!(
        answers(&windows, "MyBrandFont", arimo_cf),
        (version("7.06.1"), SubstituteLayout::Fallback)
    );
    let other = SubstituteLayout::OtherVersion {
        family: Name::new("Arial"),
        made_for: Name::new("7.06"),
        target: Name::new("5.01.2x"),
    };
    assert_eq!(answers(&mac, "Arial", arimo_cf), (version("7.06.1"), other));
    let nothing = FontEnvironment::default();
    assert_eq!(
        answers(&nothing, "Arial", arimo_cf),
        (version("7.06.1"), SubstituteLayout::Widths)
    );
    assert_eq!(
        answers(&windows, "Arial", sans),
        (version("2.1"), SubstituteLayout::Widths)
    );
    assert_eq!(
        answers(&windows, "MyBrandFont", sans),
        (version("2.1"), SubstituteLayout::Fallback)
    );
}

#[test]
fn distinguishes_verified_metric_stand_ins_from_unverified_widths_and_fallbacks() {
    let mut db = FontDb::new();
    let bytes = with_names(CARLITO, "Intos CF", "Version 2.01.1");
    let items = Item::all().fold(String::new(), |mut out, item| {
        let value = if matches!(item, Item::GposKern | Item::Gsub | Item::Gpos) {
            "differs"
        } else {
            "equal"
        };
        let _ = writeln!(out, "\"{}\" = \"{value}\"", item.name());
        out
    });
    let desc_toml = format!(
        "format = 1\nfamily_name = \"Intos CF\"\nversion = \"2.01.1\"\n\n[[fonts]]\n\
         filename = \"IntosCF-Regular.ttf\"\nsubfamily_name = \"Regular\"\n\
         full_name = \"Intos CF Regular\"\npost_script_name = \"IntosCF-Regular\"\n\
         weight = 400\nstyle = \"normal\"\nsha256 = \"{}\"\n\n[[compatible_with]]\n\
         family_name = \"Aptos\"\nversion = \"2.01\"\nbasis = \"check\"\n\
         reference = \"checks/test.toml\"\nsubfamilies = {{ Regular = \"Regular\" }}\n\n\
         [compatible_with.items]\n{items}",
        sha256(&bytes)
    );
    db.add_description(Description::from_toml(&desc_toml).unwrap());
    let intos_cf = db.add_font(bytes).unwrap()[0];

    let windows = own_regular("Aptos", "Version 2.01", None);
    let older = own_regular("Aptos", "Version 1.00", None);
    let choice_win = FontChoice::new(&db, &windows, &with_line(HelveticaLine::TwelveTenthsEm));
    let choice_old = FontChoice::new(&db, &older, &with_line(HelveticaLine::TwelveTenthsEm));

    assert_eq!(
        choice_win.substitute_layout(&FamilyName::new("Aptos"), intos_cf),
        SubstituteLayout::Metrics
    );
    assert_eq!(
        choice_win.substitute_layout(&FamilyName::new("MyBrandFont"), intos_cf),
        SubstituteLayout::Fallback
    );
    assert_eq!(
        choice_old.substitute_layout(&FamilyName::new("Aptos"), intos_cf),
        SubstituteLayout::OtherVersion {
            family: Name::new("Aptos"),
            made_for: Name::new("2.01"),
            target: Name::new("1.00"),
        }
    );
}

#[test]
fn matches_typographic_family_faces_for_legacy_compatifont_targets() {
    let mut db = FontDb::new();
    let display_bytes = with_names(CARLITO, "Intos Display CF", "Version 2.01.1");
    let metric_items = Item::all().fold(String::new(), |mut out, item| {
        let value = if matches!(item, Item::GposKern | Item::Gsub | Item::Gpos) {
            "differs"
        } else {
            "equal"
        };
        let _ = writeln!(out, "\"{}\" = \"{value}\"", item.name());
        out
    });
    let display_desc = format!(
        "format = 1\nfamily_name = \"Intos Display CF\"\nversion = \"2.01.1\"\n\n[[fonts]]\n\
         filename = \"IntosDisplayCF-Regular.ttf\"\nsubfamily_name = \"Regular\"\n\
         full_name = \"Intos Display CF Regular\"\npost_script_name = \"IntosDisplayCF-Regular\"\n\
         weight = 400\nstyle = \"normal\"\nsha256 = \"{}\"\n\n[[compatible_with]]\n\
         family_name = \"Aptos Display\"\nversion = \"2.01\"\nbasis = \"check\"\n\
         reference = \"checks/test.toml\"\nsubfamilies = {{ Regular = \"Regular\" }}\n\n\
         [compatible_with.items]\n{metric_items}",
        sha256(&display_bytes)
    );
    db.add_description(Description::from_toml(&display_desc).unwrap());
    let intos_display = db.add_font(display_bytes).unwrap()[0];
    let arimo_narrow = add_described(
        &mut db,
        ("Arimo Narrow CF", "2.40.1"),
        ("Arial Narrow", "2.40"),
    );

    let environment = FontEnvironment::new(vec![
        OwnFace {
            family: "Aptos".to_owned(),
            style: "Display".to_owned(),
            version: "Version 2.01;O365".to_owned(),
            kerning: None,
            units_per_em: None,
        },
        OwnFace {
            family: "Arial".to_owned(),
            style: "Narrow".to_owned(),
            version: "Version 2.40".to_owned(),
            kerning: None,
            units_per_em: None,
        },
    ]);
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));

    assert_eq!(
        choice.substitute_layout(&FamilyName::new("Aptos Display"), intos_display),
        SubstituteLayout::Metrics
    );
    assert_eq!(
        choice.substitute_layout(&FamilyName::new("MyBrandFont"), intos_display),
        SubstituteLayout::Fallback
    );
    assert_eq!(
        choice.substitute_layout(&FamilyName::new("Arial Narrow"), arimo_narrow),
        SubstituteLayout::Exact
    );
    assert_eq!(
        choice.layout_family(arimo_narrow).as_deref(),
        Some("Arial Narrow")
    );
    assert_eq!(
        choice.substitute_layout(&FamilyName::new("Arial"), arimo_narrow),
        SubstituteLayout::Fallback
    );
}

#[test]
fn draws_arial_and_times_new_roman_with_the_fonts_of_their_layout_first() {
    let environment = FontEnvironment::default();
    let mut db = FontDb::new();
    let sans = db
        .add_font(with_names(CARLITO, "Liberation Sans", "Version 2.1"))
        .unwrap()[0];
    let serif = db
        .add_font(with_names(CARLITO, "Liberation Serif", "Version 2.1"))
        .unwrap()[0];
    let fonts = |db: &FontDb| {
        let choice = FontChoice::new(db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
        ["Arial", "Times New Roman", "Helvetica", "Times"].map(|family| {
            let chosen = choice
                .face(&FamilyName::from_static(family), false, false)
                .unwrap();
            assert!(chosen.stands_in, "{family}");
            chosen.font
        })
    };
    assert_eq!(fonts(&db), [sans, serif, sans, serif]);
    let arimo_cf = add_arimo_cf(&mut db);
    let tinos_cf = add_described(&mut db, ("Tinos CF", "7.12.1"), ("Times New Roman", "7.12"));
    assert_eq!(fonts(&db), [arimo_cf, tinos_cf, arimo_cf, tinos_cf]);
}

#[test]
fn draws_a_missing_family_with_its_compatible_font_before_a_face_of_its_typographic_family() {
    let environment = FontEnvironment::default();
    let mut names = regular_names("Arial Narrow", "Version 2.40");
    names.push((16, "Arial".to_owned()));
    let mut db = FontDb::new();
    let narrow = db.add_font(with_name_table(CARLITO, &names)).unwrap()[0];
    let arial = |db: &FontDb| {
        let choice = FontChoice::new(db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
        let chosen = choice
            .face(&FamilyName::from_static("Arial"), false, false)
            .unwrap();
        (chosen.font, chosen.stands_in)
    };
    // With no stand-in, the face of the typographic family Arial draws Arial.
    assert_eq!(arial(&db), (narrow, false));
    let arimo_cf = add_arimo_cf(&mut db);
    assert_eq!(arial(&db), (arimo_cf, true));
    let own = db
        .add_font(with_names(CARLITO, "Arial", "Version 7.06"))
        .unwrap()[0];
    assert_eq!(arial(&db), (own, false));
}

#[test]
fn draws_a_target_face_named_by_its_full_or_postscript_name_with_its_compatible_font() {
    let environment = lines_and_names();
    let mut db = FontDb::new();
    let arimo_cf = add_arimo_cf(&mut db);
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let chosen = |name, bold| {
        let chosen = choice
            .face(&FamilyName::from_static(name), bold, false)
            .unwrap();
        (chosen.font, chosen.stands_in, chosen.synthetic_bold)
    };
    assert_eq!(chosen("Arial Bold", false), (arimo_cf, true, false));
    assert_eq!(chosen("ArialMT", false), (arimo_cf, true, false));
    // The open font has no bold face here, so a bold run of the regular face's name is bold
    // by synthesis, as the target's regular face found by that name is.
    assert_eq!(chosen("Arial-ItalicMT", true), (arimo_cf, true, true));
    assert!(
        choice
            .face(&FamilyName::from_static("TimesNewRomanPSMT"), false, false)
            .is_none()
    );
    let nameless = FontEnvironment::default();
    let choice = FontChoice::new(&db, &nameless, &with_line(HelveticaLine::TwelveTenthsEm));
    assert!(
        choice
            .face(&FamilyName::from_static("ArialMT"), false, false)
            .is_none()
    );
}

#[test]
fn a_described_face_lays_out_as_the_family_of_the_targets_face() {
    let mut db = FontDb::new();
    let arimo_cf = add_arimo_cf(&mut db);
    let family = |environment: &FontEnvironment| {
        let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
        (choice.family_name(arimo_cf), choice.layout_family(arimo_cf))
    };
    let named = |name: &str| Some(name.to_owned());
    assert_eq!(
        family(&own_regular("Arial", "Version 7.06", None)),
        (named("Arimo CF"), named("Arial"))
    );
    assert_eq!(
        family(&own_regular("Arial", "Version 5.01", None)),
        (named("Arimo CF"), named("Arimo CF"))
    );
}

#[test]
fn finds_faces_by_family_and_through_stand_ins() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let font = |family| {
        choice
            .face(&FamilyName::from_static(family), false, false)
            .map(|f| f.font)
    };
    assert_eq!(font("Carlito"), Some(carlito));
    assert_eq!(font("Calibri"), Some(carlito));
    assert_eq!(font("Aptos"), None);
    let chosen = choice
        .face(&FamilyName::from_static("Calibri"), false, false)
        .unwrap();
    assert_eq!(Some(chosen.metrics), choice.metrics(carlito));
    assert_eq!(font("Symbol"), None);
}

#[test]
fn finds_one_face_for_a_family_in_any_case_of_ascii_letters() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    for family in ["Calibri", "CALIBRI", "Carlito", "carlito"] {
        let face = choice.face(&FamilyName::from_static(family), false, false);
        assert_eq!(face.map(|f| f.font), Some(carlito), "{family}");
    }
    // The cache keeps one answer for each family name key.
    assert_eq!(choice.chosen.borrow().len(), 2);
}

#[test]
fn finds_older_builds_by_names_without_mt_or_ms() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let font = |family| {
        choice
            .face(&FamilyName::from_static(family), false, false)
            .map(|f| f.font)
    };
    // A PostScript name with "MT" and a family name with " MS" find the build without it.
    assert_eq!(font("Carlito-RegularMT"), Some(carlito));
    assert_eq!(font("Carlito MS"), Some(carlito));
    assert_eq!(font("MT"), None);
    assert_eq!(font(" MS"), None);
}

#[test]
fn keeps_the_answer_of_each_family_and_request_and_gives_it_again() {
    let mut db = FontDb::new();
    db.add_font(CARLITO.to_vec()).unwrap();
    // A full target listing makes the choice check each face against the font environment.
    let environment =
        FontEnvironment::default().with_available(vec![FamilyName::from_static("Calibri")]);
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let families = ["Calibri", "Carlito", "Aptos", "Symbol", "Carlito MS"];
    let requests = (0..8_u8).map(|bits| (bits & 1 != 0, bits & 2 != 0, bits & 4 != 0));
    for (family, (bold, italic, named)) in families
        .iter()
        .flat_map(|family| requests.clone().map(move |request| (*family, request)))
    {
        let family = FamilyName::from_static(family);
        let anew = choice.choose_anew(&family, bold, italic, named, &[]);
        let first = choice.choose(&family, bold, italic, named);
        let again = choice.choose(&family, bold, italic, named);
        assert_eq!((first, again), (anew, anew), "{}", family.as_str());
    }
    // One answer for each family and request, kept once.
    let chosen = choice.chosen.borrow();
    assert_eq!(chosen.len(), families.len());
    assert!(chosen.values().all(|answers| answers.len() == 8));
}

#[test]
fn draws_a_missing_symbol_font_with_its_measured_metrics() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let environment = FontEnvironment::default().with_lines(vec![WordLine {
        family: FamilyName::from_static("Test Symbols"),
        ascent: 1005,
        descent: 215,
        over_own_file: false,
    }]);
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let drawn_with = |families: &[&str]| -> Vec<String> {
        families.iter().map(|family| (*family).to_owned()).collect()
    };
    let draw = |family, families: &[&str], bold| {
        choice.draw_stand_in(family, &drawn_with(families), (bold, false), &[])
    };
    let chosen = draw("Test Symbols", &["Missing", "Carlito"], true).unwrap();
    assert_eq!(chosen.font, carlito);
    let m = chosen.metrics;
    // Carlito has 2048 units per em, which also measure its advances, so the line
    // metrics are 1.005 and 0.215 em in those units.
    assert_eq!((m.units_per_em, m.hhea_line_gap), (2048, 0));
    assert_eq!(
        (m.hhea_ascender, m.hhea_descender, m.descent),
        (2058, -440, 440)
    );
    let own = choice.metrics(carlito).unwrap();
    assert_eq!(m.underline_position, own.underline_position);
    assert!(draw("Test Symbols", &["Missing"], false).is_none());
    let chosen = draw("Other Symbols", &["Carlito"], false).unwrap();
    assert_eq!(Some(chosen.metrics), choice.metrics(carlito));
}

#[test]
fn takes_the_typo_descent_only_from_fonts_that_ask_for_typo_metrics() {
    let mut db = FontDb::new();
    let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
    let os2 = db.metrics(carlito).unwrap().os2.unwrap();
    let with = |use_typo_metrics, descender| Os2Metrics {
        use_typo_metrics,
        typo: f_office_fonts::LineMetrics {
            descender,
            ..os2.typo
        },
        win_descent: 550,
        ..os2
    };
    assert_eq!(line_descent(&with(false, -400)), 550);
    assert_eq!(line_descent(&with(true, -400)), 400);
    // Also when it goes deeper than `usWinDescent`, as in Aptos.
    assert_eq!(line_descent(&with(true, -600)), 600);
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    assert_eq!(choice.metrics(carlito).unwrap().descent, line_descent(&os2));
}

/// The name and cause of each file that the font choice names as not read.
fn files_not_read(choice: &FontChoice<'_>) -> Vec<(String, NotReadCause)> {
    let files = choice.files_not_read().into_iter();
    files.map(|file| (file.file, file.cause)).collect()
}

#[test]
fn a_face_whose_file_does_not_load_counts_as_missing_and_its_file_is_named_once() {
    let name = format!("f-office-docx-choice-{}", std::process::id());
    let folder = std::env::temp_dir().join(name);
    std::fs::create_dir_all(&folder).unwrap();
    std::fs::write(folder.join("carlito.ttf"), CARLITO).unwrap();
    let mut db = FontDb::new();
    db.add_files(&[folder.join("carlito.ttf")]).unwrap();
    std::fs::remove_file(folder.join("carlito.ttf")).unwrap();
    std::fs::remove_dir(&folder).unwrap();
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    assert_eq!(choice.files_not_read(), []);
    // The family's own face and the stand-in that it would draw count as missing.
    assert_eq!(choice.face(&FamilyName::new("Carlito"), false, false), None);
    assert_eq!(choice.face(&FamilyName::new("Calibri"), false, false), None);
    let gone = NotReadCause::Unreadable(std::io::ErrorKind::NotFound);
    assert_eq!(files_not_read(&choice), [("carlito.ttf".to_owned(), gone)]);
}

/// The bytes of `font` with every name `from` made `to`, in single bytes and in UTF-16BE, the
/// two encodings of a `name` table. The two names have as many letters, so no offset moves.
fn renamed(font: &[u8], from: &str, to: &str) -> Vec<u8> {
    assert_eq!(from.len(), to.len());
    let utf16 =
        |name: &str| -> Vec<u8> { name.encode_utf16().flat_map(u16::to_be_bytes).collect() };
    let mut bytes = font.to_vec();
    for (from, to) in [
        (from.as_bytes().to_vec(), to.as_bytes().to_vec()),
        (utf16(from), utf16(to)),
    ] {
        let mut start = 0;
        while let Some(found) = bytes[start..].windows(from.len()).position(|w| w == from) {
            let at = start + found;
            bytes[at..at + to.len()].copy_from_slice(&to);
            start = at + to.len();
        }
    }
    bytes
}

#[test]
fn the_search_goes_on_past_a_face_whose_file_does_not_load_to_the_stand_in() {
    let name = format!("f-office-docx-choice-search-{}", std::process::id());
    let folder = std::env::temp_dir().join(name);
    std::fs::create_dir_all(&folder).unwrap();
    let calibri_file = renamed(CARLITO, "Carlito", "Calibri");
    std::fs::write(folder.join("calibri.ttf"), calibri_file).unwrap();
    std::fs::write(folder.join("carlito.ttf"), CARLITO).unwrap();
    let mut db = FontDb::new();
    db.add_files(&[folder.join("calibri.ttf"), folder.join("carlito.ttf")])
        .unwrap();
    std::fs::remove_file(folder.join("calibri.ttf")).unwrap();
    let calibri = FamilyName::new("Calibri");
    // The folder's own Calibri face comes first, and its file does not load.
    let own = db.query(&calibri, false, false).unwrap();
    assert_eq!(db.info(own).unwrap().family, "Calibri");
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    // The face counts as missing, so Carlito stands in, as for a folder without Calibri.
    let chosen = choice.face(&calibri, false, false).unwrap();
    assert!(chosen.stands_in);
    assert_eq!(db.info(chosen.font).unwrap().family, "Carlito");
    assert_eq!(choice.face(&calibri, false, false), Some(chosen));
    std::fs::remove_file(folder.join("carlito.ttf")).unwrap();
    std::fs::remove_dir(&folder).unwrap();
    let gone = NotReadCause::Unreadable(std::io::ErrorKind::NotFound);
    assert_eq!(files_not_read(&choice), [("calibri.ttf".to_owned(), gone)]);
}

/// The bytes of `font` with the weight class `weight` in its `OS/2` table.
fn with_weight(font: &[u8], weight: u16) -> Vec<u8> {
    let number = |at: usize, len: usize| {
        font[at..at + len]
            .iter()
            .fold(0_usize, |value, byte| value << 8 | usize::from(*byte))
    };
    let os2 = (0..number(4, 2))
        .map(|index| 12 + 16 * index)
        .find(|&at| &font[at..at + 4] == b"OS/2")
        .unwrap();
    let table = number(os2 + 8, 4);
    let mut bytes = font.to_vec();
    bytes[table + 4..table + 6].copy_from_slice(&weight.to_be_bytes());
    bytes
}

#[test]
fn a_bold_face_whose_file_does_not_load_gives_the_regular_face_of_its_family() {
    let name = format!("f-office-docx-choice-bold-{}", std::process::id());
    let folder = std::env::temp_dir().join(name);
    std::fs::create_dir_all(&folder).unwrap();
    std::fs::write(folder.join("carlito-bold.ttf"), with_weight(CARLITO, 700)).unwrap();
    std::fs::write(folder.join("carlito.ttf"), CARLITO).unwrap();
    let mut db = FontDb::new();
    db.add_files(&[folder.join("carlito-bold.ttf"), folder.join("carlito.ttf")])
        .unwrap();
    std::fs::remove_file(folder.join("carlito-bold.ttf")).unwrap();
    let carlito = FamilyName::new("Carlito");
    // The bold face comes first for bold, and its file does not load.
    let bold = db.query(&carlito, true, false).unwrap();
    assert_eq!(db.info(bold).unwrap().weight, 700);
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
    let chosen = choice.face(&carlito, true, false).unwrap();
    std::fs::remove_file(folder.join("carlito.ttf")).unwrap();
    std::fs::remove_dir(&folder).unwrap();
    // The regular face draws the family, as in a folder without a bold face.
    let mut regular_only = FontDb::new();
    let regular = regular_only.add_font(CARLITO.to_vec()).unwrap()[0];
    let alone = FontChoice::new(
        &regular_only,
        &environment,
        &with_line(HelveticaLine::TwelveTenthsEm),
    );
    let expected = alone.face(&carlito, true, false).unwrap();
    assert_eq!(db.info(chosen.font), regular_only.info(regular));
    assert_eq!(
        (chosen.metrics, chosen.synthetic_bold, chosen.stands_in),
        (expected.metrics, expected.synthetic_bold, false)
    );
    // The family has no italic face either: its upright face draws italic, slanted.
    let italic = alone.face(&carlito, false, true).unwrap();
    assert_eq!(regular_only.info(italic.font), regular_only.info(regular));
    assert!(italic.synthetic_italic && !expected.synthetic_italic);
    let gone = NotReadCause::Unreadable(std::io::ErrorKind::NotFound);
    assert_eq!(
        files_not_read(&choice),
        [("carlito-bold.ttf".to_owned(), gone)]
    );
}

#[test]
fn gives_the_metafile_face_of_the_font_environment() {
    use f_office_fonts::environment::MetafileFaces;
    let db = FontDb::new();
    let environment = FontEnvironment::default()
        .with_available(vec![FamilyName::from_static("Calibri")])
        .with_metafile_faces(vec![MetafileFaces {
            charset: 255,
            faces: (0..18).map(|index| format!("Face {index}")).collect(),
        }]);
    let profile = with_line(HelveticaLine::TwelveTenthsEm);
    let choice = FontChoice::new(&db, &environment, &profile);
    let mapped = |family| choice.metafile_face(&FamilyName::new(family), 255, 0x31);
    // The modern family (3) with fixed pitch (1) is the eleventh face.
    assert_eq!(mapped("Missing"), Some(FamilyName::new("Face 10")));
    assert_eq!(mapped("Calibri"), None);
}

/// A font database of the open fonts of the build, which holds Noto Symbols CF and no symbol
/// font, with the face of Noto Symbols CF.
fn open_fonts() -> (FontDb, FontId) {
    let mut db = FontDb::new();
    f_office_fonts::open_fonts::add_missing(&mut db).expect("the open fonts read");
    let family = FamilyName::from_static(SymbolFont::DRAWING_FAMILY);
    let noto = db
        .query(&family, false, false)
        .expect("the build holds Noto Symbols CF");
    (db, noto)
}

/// The targets whose font environment holds Word's numbers of `font`, with their profiles and
/// those numbers' units per em, advance of `code` and device width of `code` at 100 dots per em.
fn with_symbol_widths(font: SymbolFont, code: u32) -> Vec<(crate::Target, Profile, u16, u16, i32)> {
    let profiles: Vec<_> = (crate::Target::all())
        .filter_map(|target| {
            let profile = Profile::of(target).ok()?;
            let fonts = profile.symbol_fonts();
            let (_, widths) = fonts.get(font)?;
            let numbers = (
                widths.units_per_em(),
                widths.advance(code)?,
                widths.device_width(code, 100)?,
            );
            Some((target, profile.clone(), numbers.0, numbers.1, numbers.2))
        })
        .collect();
    assert!(
        !profiles.is_empty(),
        "a target holds Word's numbers of {font:?}"
    );
    profiles
}

/// The font of the symbol stand-in face that `choice` gives the regular face of `family`.
fn stand_in(choice: &FontChoice<'_>, family: &'static str) -> FontId {
    choice
        .substitute(&FamilyName::from_static(family), false, false)
        .expect("a stand-in face")
        .font
}

/// `outline` with each point at `place` of it.
fn placed(
    outline: Vec<OutlineCommand>,
    place: impl Fn([i32; 2]) -> [i32; 2],
) -> Vec<OutlineCommand> {
    (outline.into_iter())
        .map(|command| match command {
            OutlineCommand::MoveTo(p) => OutlineCommand::MoveTo(place(p)),
            OutlineCommand::LineTo(p) => OutlineCommand::LineTo(place(p)),
            OutlineCommand::QuadTo(c, p) => OutlineCommand::QuadTo(place(c), place(p)),
            OutlineCommand::CubicTo(c, d, p) => {
                OutlineCommand::CubicTo(place(c), place(d), place(p))
            }
            OutlineCommand::Close => OutlineCommand::Close,
        })
        .collect()
}

#[test]
fn gives_a_missing_symbol_font_a_stand_in_face_with_the_metrics_of_its_file() {
    let (db, _) = open_fonts();
    let first = u32::try_from(db.len()).unwrap();
    let wingdings = FamilyName::from_static("Wingdings");
    for (_, profile, ..) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
        let choice = FontChoice::of(&db, &profile);
        let chosen = (choice.substitute(&wingdings, true, true)).expect("a stand-in face");
        let fonts = profile.symbol_fonts();
        let (_, widths) = fonts.get(SymbolFont::Wingdings).unwrap();
        // Its ID lies past the faces of the database, and it makes bold and italic itself.
        let flags = (
            chosen.stands_in,
            chosen.synthetic_bold,
            chosen.synthetic_italic,
        );
        assert_eq!(
            (chosen.font.index() >= first, flags),
            (true, (true, true, true))
        );
        assert_eq!(chosen.metrics, super::metrics_of(&widths.metrics));
        // The same face answers each later query of the family.
        assert_eq!(choice.substitute(&wingdings, true, true), Some(chosen));
    }
}

#[test]
fn gives_the_stand_in_face_of_a_symbol_font_to_the_postscript_name_of_its_file() {
    let (db, _) = open_fonts();
    for (_, profile, ..) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
        let choice = FontChoice::of(&db, &profile);
        let fonts = profile.symbol_fonts();
        let (_, widths) = fonts.get(SymbolFont::Symbol).unwrap();
        let postscript = FamilyName::new(&widths.postscript_name);
        let chosen = choice
            .face(&postscript, false, false)
            .map(|chosen| chosen.font);
        assert_eq!(chosen, Some(stand_in(&choice, "Symbol")));
    }
}

#[test]
fn gives_the_codes_of_a_symbol_stand_in_face_the_widths_of_words_file() {
    let (db, _) = open_fonts();
    for (_, profile, _, advance, device_width) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
        let choice = FontChoice::of(&db, &profile);
        let font = stand_in(&choice, "Wingdings");
        let fonts = profile.symbol_fonts();
        let (_, widths) = fonts.get(SymbolFont::Wingdings).unwrap();
        // A code of one byte and its private use form are the same code.
        let glyphs = ['\u{F0FC}', '\u{FC}', '\u{2713}'].map(|ch| choice.glyph(font, ch));
        assert_eq!(glyphs, [Some(0xFC), Some(0xFC), None]);
        let numbers = (
            choice.advance(font, 0xFC),
            choice.device_width(font, 0xFC, 100),
            choice.bi_level_advance(font, 0xFC, 1000),
            choice.device_heights(font, 8),
        );
        let expected = (
            Some(advance),
            Some(device_width),
            widths.written(0xFC).map(i32::from),
            widths.heights(8),
        );
        assert_eq!(numbers, expected);
        // It has no kerning and no ligatures.
        let joins = (
            choice.kerning(font, 0xFC, 0xFC, KerningTable::FaceSource),
            choice.ligatures(font, &[0xFC, 0xFC]).len(),
        );
        assert_eq!(joins, (0, 0));
    }
}

#[test]
fn lays_out_a_symbol_stand_in_face_as_its_font_and_names_the_face_that_draws_it() {
    let (db, noto) = open_fonts();
    for (_, profile, ..) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
        let choice = FontChoice::of(&db, &profile);
        let font = stand_in(&choice, "Wingdings");
        let fonts = profile.symbol_fonts();
        let (_, widths) = fonts.get(SymbolFont::Wingdings).unwrap();
        // It lays out as the target's file of the font.
        let family = choice.layout_family(font);
        let layout = (
            family.as_deref(),
            choice.substitute_layout(&FamilyName::new("Wingdings"), font),
            choice.classification(font),
        );
        let expected = (
            Some("Wingdings"),
            SubstituteLayout::Exact,
            Some(widths.classification),
        );
        assert_eq!(layout, expected);
        assert_eq!(
            choice.substitute_layout(&FamilyName::new("MyCustomSymbol"), font),
            SubstituteLayout::Fallback
        );
        // A warning names the face that draws it.
        let names = (choice.family_name(font), choice.face_version(font));
        assert_eq!(names, (choice.family_name(noto), choice.face_version(noto)));
    }
}

#[test]
fn steps_a_symbol_stand_in_face_as_an_own_face_only_where_the_file_of_its_font_is_one() {
    let (db, _) = open_fonts();
    for (_, profile, ..) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
        let choice = FontChoice::of(&db, &profile);
        let fonts = profile.symbol_fonts();
        let environment = profile.font_environment();
        let own: Vec<_> = (SymbolFont::ALL.into_iter())
            .filter_map(|font| {
                let (_, widths) = fonts.get(font)?;
                let file = environment.is_target_file(font.family(), "Regular", &widths.version);
                let face = choice.target_face(stand_in(&choice, font.family()));
                Some((font, face.is_some(), file))
            })
            .collect();
        assert!(own.iter().all(|(_, face, file)| face == file), "{own:?}");
    }
}

#[test]
fn gives_the_missing_glyph_of_a_symbol_stand_in_face_the_widths_of_the_files_missing_glyph() {
    use f_office_fonts::{ShapeDirection, ShapeRequest, ShapedScript};
    let (db, _) = open_fonts();
    for (_, profile, _, advance, device_width) in with_symbol_widths(SymbolFont::Symbol, 0) {
        let choice = FontChoice::of(&db, &profile);
        let font = stand_in(&choice, "Symbol");
        let fonts = profile.symbol_fonts();
        let (_, widths) = fonts.get(SymbolFont::Symbol).unwrap();
        // A code that the file does not map takes the missing glyph, glyph 0.
        let code = (0x20..=0xFF)
            .find(|&code| widths.advance(code).is_none())
            .expect("a code that the file does not map");
        let text = char::from_u32(0xF000 + code).unwrap().to_string();
        let request = ShapeRequest {
            text: &text,
            script: ShapedScript::Arabic,
            direction: ShapeDirection::LeftToRight,
            language: None,
        };
        let shaped = choice.shape(font, &request).unwrap();
        let glyphs: Vec<_> = shaped.iter().map(|g| (g.glyph, g.advance)).collect();
        assert_eq!(glyphs, [(0, i32::from(advance))]);
        assert_eq!(choice.device_width(font, 0, 100), Some(device_width));
    }
}

#[test]
fn gives_no_stand_in_face_without_the_face_that_draws_it() {
    let db = FontDb::new();
    for (_, profile, ..) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
        let choice = FontChoice::of(&db, &profile);
        let wingdings = FamilyName::from_static("Wingdings");
        assert_eq!(choice.substitute(&wingdings, false, false), None);
    }
}

#[test]
fn shapes_the_codes_of_a_symbol_stand_in_face_without_substitutions() {
    use f_office_fonts::{ShapeDirection, ShapeRequest, ShapedScript};
    let (db, _) = open_fonts();
    for (_, profile, _, advance, _) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
        let choice = FontChoice::of(&db, &profile);
        let font = stand_in(&choice, "Symbol");
        let request = ShapeRequest {
            text: "a\u{F062}",
            script: ShapedScript::Arabic,
            direction: ShapeDirection::RightToLeft,
            language: None,
        };
        let shaped = choice.shape(font, &request).unwrap();
        let glyphs: Vec<_> = (shaped.iter())
            .map(|g| (g.glyph, g.cluster, g.offset))
            .collect();
        assert_eq!(glyphs, [(0x62, 1, (0, 0)), (0x61, 0, (0, 0))]);
        assert_eq!(shaped.last().map(|g| g.advance), Some(i32::from(advance)));
    }
}

#[test]
fn outlines_a_code_of_a_symbol_stand_in_face_with_the_drawing_faces_glyph_in_its_middle() {
    let (db, noto) = open_fonts();
    for (_, profile, em, advance, _) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
        let choice = FontChoice::of(&db, &profile);
        let font = stand_in(&choice, "Symbol");
        // Symbol's code 61 is alpha, drawn with the open font's alpha at the code's units per
        // em, moved right by half the difference of the code's width and the drawn glyph's.
        let alpha = db.glyph_id(noto, '\u{3B1}').unwrap();
        let drawn = i64::from(db.advance(noto, alpha).unwrap());
        let noto_em = i64::from(db.metrics(noto).unwrap().units_per_em);
        let (em, advance) = (i64::from(em), i64::from(advance));
        let height =
            |y: i32| i32::try_from(f_office_units::div_round(i64::from(y) * em, noto_em)).unwrap();
        let place = |[x, y]: [i32; 2]| {
            let twice = 2 * i64::from(x) * em + advance * noto_em - drawn * em;
            let x = f_office_units::div_round(twice, 2 * noto_em);
            [i32::try_from(x).unwrap(), height(y)]
        };
        let expected = placed(choice.outline(noto, alpha).unwrap(), place);
        assert_eq!(choice.outline(font, 0x61).unwrap(), expected);
        let ink = choice.ink(noto, alpha).unwrap();
        let expected = ink.map(|(low, high)| (height(low), height(high)));
        assert_eq!(choice.ink(font, 0x61).unwrap(), expected);
    }
}

/// A run of the face `font` with the glyph `id` at 12 pt, 72 pt from the page's corner, and the
/// run that `choice` draws from it.
fn drawn_run(
    choice: &FontChoice<'_>,
    font: FontId,
    id: u32,
) -> (f_office_paint::GlyphRun, f_office_paint::GlyphRun) {
    use f_office_paint::{DisplayList, Glyph, GlyphRun, Item, Orientation, Page, Rgb};
    use f_office_units::Length;
    let size = Length::from_units(12 * Length::UNITS_PER_POINT);
    let x = Length::from_units(72 * Length::UNITS_PER_POINT);
    let run = GlyphRun {
        font,
        size,
        color: Rgb { r: 0, g: 0, b: 0 },
        text: "\u{3B1}".to_owned(),
        glyphs: vec![Glyph {
            id,
            x,
            y: x,
            text_start: 0,
            text_end: 2,
        }],
        outline: None,
        filled: true,
        effect: false,
        turn: None,
    };
    let page = Page::new(
        size,
        size,
        Orientation::Portrait,
        vec![Item::Glyphs(run.clone())],
    );
    let list = choice.draw_symbol_stand_ins(DisplayList::new(vec![page]));
    let [page] = list.pages() else {
        panic!("one page");
    };
    let [Item::Glyphs(drawn)] = page.items() else {
        panic!("one glyph run");
    };
    (run, drawn.clone())
}

/// The glyph, place across and place down of each glyph of `run`.
fn glyph_places(
    run: &f_office_paint::GlyphRun,
) -> Vec<(u32, f_office_units::Length, f_office_units::Length)> {
    run.glyphs.iter().map(|g| (g.id, g.x, g.y)).collect()
}

/// The shift that puts a glyph of the drawing face `noto` with the advance `drawn` in the
/// middle of a code of the advance `advance` in an em of `em` units, at the size of `run`.
fn middle_shift(
    db: &FontDb,
    noto: FontId,
    (advance, em): (u16, u16),
    drawn: u16,
    run: &f_office_paint::GlyphRun,
) -> f_office_units::Length {
    let noto_em = i64::from(db.metrics(noto).unwrap().units_per_em);
    let (em, advance, drawn) = (i64::from(em), i64::from(advance), i64::from(drawn));
    f_office_units::Length::from_units(f_office_units::div_round(
        (advance * noto_em - drawn * em) * run.size.units(),
        2 * em * noto_em,
    ))
}

#[test]
fn draws_the_runs_of_a_symbol_stand_in_face_with_its_drawing_face_in_the_middle_of_each_width() {
    let (db, noto) = open_fonts();
    for (_, profile, em, advance, _) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
        let choice = FontChoice::of(&db, &profile);
        let font = stand_in(&choice, "Symbol");
        let (run, drawn) = drawn_run(&choice, font, 0x61);
        let alpha = db.glyph_id(noto, '\u{3B1}').unwrap();
        let noto_advance = db.advance(noto, alpha).unwrap();
        let shift = middle_shift(&db, noto, (advance, em), noto_advance, &run);
        assert_eq!((drawn.font, &drawn.text), (noto, &run.text));
        let [(_, x, y)] = glyph_places(&run)[..] else {
            panic!("one glyph");
        };
        assert_eq!(glyph_places(&drawn), [(alpha, x + shift, y)]);
    }
}

#[test]
fn draws_the_missing_glyph_of_a_symbol_stand_in_face_with_the_drawing_faces_missing_glyph() {
    let (db, noto) = open_fonts();
    for (_, profile, em, advance, _) in with_symbol_widths(SymbolFont::Symbol, 0) {
        let choice = FontChoice::of(&db, &profile);
        let font = stand_in(&choice, "Symbol");
        let (run, drawn) = drawn_run(&choice, font, 0);
        // Both missing glyphs draw a box, so it stands in the middle of the file's.
        let shift = middle_shift(&db, noto, (advance, em), db.advance(noto, 0).unwrap(), &run);
        let [(_, x, y)] = glyph_places(&run)[..] else {
            panic!("one glyph");
        };
        assert_eq!(glyph_places(&drawn), [(0, x + shift, y)]);
    }
}

#[test]
fn lays_out_a_missing_symbol_font_with_its_stand_in_and_draws_it_with_its_drawing_face() {
    use crate::testing::WordParts as _;
    use f_office_paint::Item;
    let (db, noto) = open_fonts();
    let first = u32::try_from(db.len()).unwrap();
    let body = r#"<w:p><w:r><w:sym w:font="Wingdings" w:char="F0FC"/><w:sym w:font="Wingdings" w:char="F0FC"/></w:r></w:p>"#;
    let bytes = crate::testing::docx(body).plain_styles().zip().unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let check = SymbolFont::Wingdings.character('\u{F0FC}').unwrap();
    let tick = db.glyph_id(noto, check).unwrap();
    for (target, ..) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let laid_out = crate::layout_lines(&package, (&db, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let runs: Vec<_> = (laid_out.list.pages().iter())
            .flat_map(f_office_paint::Page::items)
            .filter_map(|item| match item {
                Item::Glyphs(run) => Some(run),
                _ => None,
            })
            .collect();
        assert!(runs.iter().all(|run| run.font.index() < first));
        let ticks: Vec<u32> = (runs.iter())
            .filter(|run| run.font == noto)
            .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.id))
            .collect();
        assert_eq!(ticks, [tick, tick]);
    }
}

/// Office families with the open font of the build that carries the layout of each, and the
/// PostScript name of Word's regular file of the family.
const OPEN_FONTS_OF_FAMILIES: [(&str, &str, &str); 9] = [
    ("Cambria", "Caladea CF", "Cambria"),
    ("Cambria Math", "Caladea Math CF", "CambriaMath"),
    ("Aptos", "Intos CF", "Aptos"),
    ("Aptos Display", "Intos Display CF", "AptosDisplay"),
    ("Arial Narrow", "Arimo Narrow CF", "ArialNarrow"),
    ("Courier New", "Curunír CF", "CourierNewPSMT"),
    ("Georgia", "Gelasio CF", "Georgia"),
    ("Segoe UI", "Sindar CF", "SegoeUI"),
    ("Comic Sans MS", "Comic Relief CF", "ComicSansMS"),
];

/// The family of `font` in `db`.
fn family_of(db: &FontDb, font: FontId) -> Option<String> {
    (db.faces()).find_map(|(id, face)| (id == font).then(|| face.family.clone()))
}

/// The face of `family` in `db` that is bold and italic as asked, if the family has one.
fn styled_face(db: &FontDb, family: &str, (bold, italic): (bool, bool)) -> Option<FontId> {
    (db.faces()).find_map(|(id, face)| {
        (face.family == family && face.bold() == bold && face.italic == italic).then_some(id)
    })
}

#[test]
fn draws_a_missing_family_with_the_open_font_that_carries_its_layout() {
    let (db, _) = open_fonts();
    let styles = [(false, false), (true, false), (false, true), (true, true)];
    for target in crate::Target::all() {
        let profile = Profile::of(target).unwrap();
        let choice = FontChoice::of(&db, &profile);
        for ((closed, open, _), (bold, italic)) in
            (OPEN_FONTS_OF_FAMILIES.iter()).flat_map(|font| styles.map(|style| (font, style)))
        {
            // The layout asks for the family's face, then for a face in its place.
            let family = FamilyName::from_static(closed);
            let chosen = (choice.face(&family, bold, italic))
                .or_else(|| choice.substitute(&family, bold, italic))
                .expect("an open font");
            let asked = format!("{target:?} {closed} bold {bold} italic {italic}");
            assert_eq!(
                family_of(&db, chosen.font).as_deref(),
                Some(*open),
                "{asked}"
            );
            // A face of the open font in the asked style draws it without a synthetic style;
            // styles the open font does not ship synthesize bold/italic like the target face does.
            let info = db.info(chosen.font).unwrap();
            let synthetic = (chosen.synthetic_bold, chosen.synthetic_italic);
            if let Some(face) = styled_face(&db, open, (bold, italic)) {
                assert_eq!((chosen.font, synthetic), (face, (false, false)), "{asked}");
            } else {
                assert_eq!(
                    synthetic,
                    (bold && info.light(), italic && !info.italic),
                    "{asked}"
                );
            }
        }
    }
}

#[test]
fn draws_a_family_that_the_fonts_hold_with_its_own_file_and_not_with_its_open_font() {
    // A file of each family, with the PostScript name of Word's file, then the open fonts.
    let mut db = FontDb::new();
    let own: Vec<FontId> = (OPEN_FONTS_OF_FAMILIES.iter())
        .map(|(closed, _, postscript_name)| {
            let mut names = regular_names(closed, "Version 0.01");
            names[4].1 = (*postscript_name).to_owned();
            db.add_font(with_name_table(CARLITO, &names)).unwrap()[0]
        })
        .collect();
    f_office_fonts::open_fonts::add_missing(&mut db).expect("the open fonts read");
    for target in crate::Target::all() {
        let profile = Profile::of(target).unwrap();
        let choice = FontChoice::of(&db, &profile);
        for ((closed, ..), &font) in OPEN_FONTS_OF_FAMILIES.iter().zip(&own) {
            let family = FamilyName::from_static(closed);
            let chosen = choice.face(&family, false, false).map(|chosen| chosen.font);
            assert_eq!(chosen, Some(font), "{target:?} {closed}");
        }
    }
}

#[test]
fn lays_out_an_equation_with_the_math_table_of_caladea_math_cf_where_cambria_math_is_missing() {
    use crate::testing::WordParts as _;
    use f_office_paint::Item;
    use f_office_units::Length;
    let (db, _) = open_fonts();
    let query = |family| db.query(&FamilyName::from_static(family), false, false);
    let caladea_math = query("Caladea Math CF").expect("the build holds Caladea Math CF");
    // An overbar takes its lengths from the bars' values of a MATH table, which Caladea Math
    // CF has and Caladea CF has not.
    assert!(db.math_bars(caladea_math).is_some());
    assert_eq!(db.math_bars(query("Caladea CF").unwrap()), None);
    let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
    let body = format!(
        r#"<w:p><m:oMath xmlns:m="{math}"><m:bar><m:barPr><m:pos m:val="top"/></m:barPr><m:e><m:r><m:t>x</m:t></m:r></m:e></m:bar></m:oMath></w:p>"#
    );
    let bytes = crate::testing::docx(&body).plain_styles().zip().unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    for target in crate::Target::all() {
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let laid_out = crate::layout_lines(&package, (&db, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let items: Vec<_> = (laid_out.list.pages().iter())
            .flat_map(f_office_paint::Page::items)
            .collect();
        // The equation's glyphs take Caladea Math CF in the place of Cambria Math.
        let fonts: Vec<FontId> = (items.iter())
            .filter_map(|item| match item {
                Item::Glyphs(run) => Some(run.font),
                _ => None,
            })
            .collect();
        assert!(!fonts.is_empty(), "{target:?}");
        assert!(fonts.iter().all(|&font| font == caladea_math), "{target:?}");
        // The overbar, which the layout draws only from the bars' values of a MATH table.
        let rects: Vec<_> = (items.iter())
            .filter_map(|item| match item {
                Item::Rect(rect) => Some((rect.width, rect.height)),
                _ => None,
            })
            .collect();
        let [(width, height)] = rects[..] else {
            panic!("{target:?} {rects:?}");
        };
        assert!(width > Length::ZERO && height > Length::ZERO, "{target:?}");
    }
}

#[test]
fn reads_skewed_fraction_gaps_from_caladea_math_cf() {
    let (db, _) = open_fonts();
    let query = |family| db.query(&FamilyName::from_static(family), false, false);
    let caladea_math = query("Caladea Math CF").expect("the build holds Caladea Math CF");
    let gaps = db
        .math_skewed_fraction(caladea_math)
        .expect("Caladea Math CF has MATH skewed fraction gaps");
    assert!(gaps.horizontal_gap > 0 && gaps.vertical_gap > 0, "{gaps:?}");
    assert_eq!(db.math_skewed_fraction(query("Caladea CF").unwrap()), None);
}

#[test]
fn reads_limit_gaps_from_caladea_math_cf() {
    let (db, _) = open_fonts();
    let query = |family| db.query(&FamilyName::from_static(family), false, false);
    let caladea_math = query("Caladea Math CF").expect("the build holds Caladea Math CF");
    let gaps = db
        .math_limit_gaps(caladea_math)
        .expect("Caladea Math CF has MATH limit gaps");
    assert!(
        gaps.lower_limit_gap_min > 0 && gaps.upper_limit_gap_min > 0,
        "{gaps:?}"
    );
    assert_eq!(db.math_limit_gaps(query("Caladea CF").unwrap()), None);
}

#[test]
fn synthesizes_missing_bold_and_italic_on_stand_in_faces() {
    let mut db = FontDb::new();
    // Single-weight family (Regular only, e.g. SimSun -> Noto Serif SC CF).
    let single_reg = db
        .add_font(with_names(CARLITO, "Single Stand-In", "Version 1.0"))
        .unwrap()[0];
    // Regular + Bold family with no Italic (e.g. Microsoft YaHei -> Noto Sans SC CF).
    let two_reg = db
        .add_font(with_names(CARLITO, "Two Weight Stand-In", "Version 1.0"))
        .unwrap()[0];
    let two_bold = db
        .add_font(with_weight(
            &with_names(CARLITO, "Two Weight Stand-In", "Version 1.0"),
            700,
        ))
        .unwrap()[0];

    let mut configuration = crate::Configuration::of(crate::Target::all().next().unwrap());
    configuration
        .fonts
        .uses
        .insert("Single Target".to_owned(), "Single Stand-In".to_owned());
    configuration.fonts.uses.insert(
        "Two Weight Target".to_owned(),
        "Two Weight Stand-In".to_owned(),
    );
    let profile = Profile::resolve(&configuration, &crate::profile::Overrides::default()).unwrap();
    let environment = FontEnvironment::default();
    let choice = FontChoice::new(&db, &environment, &profile);

    // Single-weight stand-in synthesizes both bold and italic beyond Regular; Regular+Bold
    // stand-in uses real Bold without synthetic bold and synthesizes italic on both.
    let cases = [
        (("Single Target", false, false), (single_reg, false, false)),
        (("Single Target", true, false), (single_reg, true, false)),
        (("Single Target", false, true), (single_reg, false, true)),
        (("Single Target", true, true), (single_reg, true, true)),
        (("Two Weight Target", false, false), (two_reg, false, false)),
        (("Two Weight Target", true, false), (two_bold, false, false)),
        (("Two Weight Target", false, true), (two_reg, false, true)),
        (("Two Weight Target", true, true), (two_bold, false, true)),
    ];
    for ((family, bold, italic), (font, synth_bold, synth_italic)) in cases {
        let chosen = choice
            .face(&FamilyName::from_static(family), bold, italic)
            .unwrap();
        assert_eq!(
            (
                chosen.font,
                chosen.stands_in,
                chosen.synthetic_bold,
                chosen.synthetic_italic,
            ),
            (font, true, synth_bold, synth_italic),
            "{family} bold={bold} italic={italic}"
        );
    }
}

#[test]
fn carries_target_units_per_em_onto_stand_in_metrics_when_em_grids_differ() {
    let mut db = FontDb::new();
    // Carlito has 2048 units per em.
    db.add_font(with_names(CARLITO, "SimSun Stand-In", "Version 1.0"))
        .unwrap();
    let mut configuration = crate::Configuration::of(crate::Target::all().next().unwrap());
    configuration
        .fonts
        .uses
        .insert("SimSun".to_owned(), "SimSun Stand-In".to_owned());
    configuration
        .fonts
        .uses
        .insert("YaHei".to_owned(), "SimSun Stand-In".to_owned());
    let profile = Profile::resolve(&configuration, &crate::profile::Overrides::default()).unwrap();
    let environment = FontEnvironment::new(vec![
        OwnFace {
            family: "SimSun".to_owned(),
            style: "Regular".to_owned(),
            version: "Version 5.24".to_owned(),
            kerning: None,
            units_per_em: Some(256),
        },
        OwnFace {
            family: "YaHei".to_owned(),
            style: "Regular".to_owned(),
            version: "Version 6.26".to_owned(),
            kerning: None,
            units_per_em: Some(2048),
        },
    ]);
    let choice = FontChoice::new(&db, &environment, &profile);

    let simsun = choice
        .face(&FamilyName::from_static("SimSun"), false, false)
        .unwrap();
    assert_eq!(simsun.metrics.units_per_em, 2048);
    assert_eq!(simsun.metrics.target_units_per_em, Some(256));

    // When the target face already uses the same 2048 em grid, target_units_per_em stays None.
    let yahei = choice
        .face(&FamilyName::from_static("YaHei"), false, false)
        .unwrap();
    assert_eq!(yahei.metrics.units_per_em, 2048);
    assert_eq!(yahei.metrics.target_units_per_em, None);
}

#[test]
fn resolves_wave_1_east_asian_stand_ins_from_compatifont_known() {
    let db = FontDb::new();
    let profile = Profile::base();
    let choice = FontChoice::of(&db, &profile);
    for (target, expected) in [
        ("SimSun", "Noto Serif SC CF"),
        ("SimHei", "Noto Hei SC CF"),
        ("Microsoft YaHei", "Noto Sans SC CF"),
        ("DengXian", "Noto Clean SC CF"),
        ("PMingLiU", "Noto Serif TC CF"),
        ("Microsoft JhengHei", "Noto Sans TC CF"),
        ("Yu Gothic", "Noto Sans JP CF"),
        ("MS Gothic", "Noto Gothic JP CF"),
        ("MS Mincho", "Noto Serif JP CF"),
        ("Malgun Gothic", "Noto Sans KR CF"),
    ] {
        assert_eq!(
            choice.drawn_with(target).first().map(String::as_str),
            Some(expected),
            "{target}"
        );
    }
}