rust-fontconfig 5.0.0

Pure-Rust alternative to font-loader and fontconfig w. minimal dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
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
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
//! # rust-fontconfig
//!
//! Pure-Rust rewrite of the Linux fontconfig library (no system dependencies). Enable the `parsing` feature to parse `.woff`, `.woff2`, `.ttc`, `.otf` and `.ttf` with allsorts.
//!
//! **NOTE**: Also works on Windows, macOS and WASM - without external dependencies!
//!
//! ## Usage
//!
//! ### Basic Font Query
//!
//! ```rust,no_run
//! use rust_fontconfig::{FcFontCache, FcPattern};
//!
//! fn main() {
//!     // Build the font cache
//!     let cache = FcFontCache::build();
//!
//!     // Query a font by name
//!     let results = cache.query(
//!         &FcPattern {
//!             name: Some(String::from("Arial")),
//!             ..Default::default()
//!         },
//!         &mut Vec::new() // Trace messages container
//!     );
//!
//!     if let Some(font_match) = results {
//!         println!("Font match ID: {:?}", font_match.id);
//!         println!("Font unicode ranges: {:?}", font_match.unicode_ranges);
//!     } else {
//!         println!("No matching font found");
//!     }
//! }
//! ```
//!
//! ### Resolve Font Chain and Query for Text
//!
//! ```rust,no_run
//! use rust_fontconfig::{FcFontCache, FcWeight, PatternMatch};
//!
//! fn main() {
//!     # #[cfg(feature = "std")]
//!     # {
//!     let cache = FcFontCache::build();
//!
//!     // Build font fallback chain (without text parameter)
//!     let font_chain = cache.resolve_font_chain(
//!         &["Arial".to_string(), "sans-serif".to_string()],
//!         FcWeight::Normal,
//!         PatternMatch::DontCare,
//!         PatternMatch::DontCare,
//!         &mut Vec::new(),
//!     );
//!
//!     // Query which fonts to use for specific text
//!     let text = "Hello 你好 Здравствуйте";
//!     let font_runs = font_chain.query_for_text(&cache, text);
//!
//!     println!("Text split into {} font runs:", font_runs.len());
//!     for run in font_runs {
//!         println!("  '{}' -> font {:?}", run.text, run.font_id);
//!     }
//!     # }
//! }
//! ```

#![allow(non_snake_case)]

extern crate alloc;

use alloc::collections::btree_map::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
#[cfg(all(feature = "std", feature = "parsing"))]
use allsorts::binary::read::ReadScope;
#[cfg(all(feature = "std", feature = "parsing"))]
use allsorts::get_name::fontcode_get_name;
#[cfg(all(feature = "std", feature = "parsing"))]
use allsorts::tables::os2::Os2;
#[cfg(all(feature = "std", feature = "parsing"))]
use allsorts::tables::{FontTableProvider, HheaTable, HmtxTable, MaxpTable};
#[cfg(all(feature = "std", feature = "parsing"))]
use allsorts::tag;
#[cfg(feature = "std")]
use std::path::PathBuf;

#[cfg(feature = "std")]
pub mod config;
pub mod fallback;
pub mod utils;
#[cfg(feature = "std")]
pub use config::{FcFallbackConfig, FcScriptFallback, GenericFamily};
#[cfg(feature = "std")]
use fallback::FontChainCacheKey;
#[cfg(feature = "std")]
pub use fallback::{CssFallbackGroup, FontFallbackChain, ScriptFallbackGroup};

#[cfg(feature = "ffi")]
pub mod ffi;

#[cfg(feature = "cache")]
pub mod disk_cache;
#[cfg(feature = "async-registry")]
pub mod multithread;
#[cfg(feature = "async-registry")]
pub mod registry;
#[cfg(feature = "async-registry")]
pub mod scoring;

#[cfg(all(target_os = "ios", feature = "std", feature = "parsing"))]
mod mobile_ios;

/// Operating system type for generic font family resolution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OperatingSystem {
    Windows,
    Linux,
    MacOS,
    IOS,
    Android,
    Wasm,
}

impl OperatingSystem {
    /// Detect the current operating system at compile time.
    pub fn current() -> Self {
        #[cfg(target_os = "windows")]
        return OperatingSystem::Windows;

        #[cfg(target_os = "linux")]
        return OperatingSystem::Linux;

        #[cfg(target_os = "macos")]
        return OperatingSystem::MacOS;

        #[cfg(target_os = "ios")]
        return OperatingSystem::IOS;

        #[cfg(target_os = "android")]
        return OperatingSystem::Android;

        #[cfg(target_family = "wasm")]
        return OperatingSystem::Wasm;

        #[cfg(not(any(
            target_os = "windows",
            target_os = "linux",
            target_os = "macos",
            target_os = "ios",
            target_os = "android",
            target_family = "wasm"
        )))]
        return OperatingSystem::Linux; // Default fallback
    }

    /// Built-in `serif` candidates for this OS, script-specific entries for.
    #[cfg(feature = "std")]
    #[deprecated(
        since = "5.0.0",
        note = "use `FcFallbackConfig::os_defaults(os).expand_generic(GenericFamily::Serif, ranges)`"
    )]
    pub fn get_serif_fonts(&self, unicode_ranges: &[UnicodeRange]) -> Vec<String> {
        FcFallbackConfig::os_defaults(*self).expand_generic(GenericFamily::Serif, unicode_ranges)
    }

    /// Built-in `sans-serif` candidates for this OS, script-specific entries.
    #[cfg(feature = "std")]
    #[deprecated(
        since = "5.0.0",
        note = "use `FcFallbackConfig::os_defaults(os).expand_generic(GenericFamily::SansSerif, ranges)`"
    )]
    pub fn get_sans_serif_fonts(&self, unicode_ranges: &[UnicodeRange]) -> Vec<String> {
        FcFallbackConfig::os_defaults(*self)
            .expand_generic(GenericFamily::SansSerif, unicode_ranges)
    }

    /// Built-in `monospace` candidates for this OS, script-specific entries.
    #[cfg(feature = "std")]
    #[deprecated(
        since = "5.0.0",
        note = "use `FcFallbackConfig::os_defaults(os).expand_generic(GenericFamily::Monospace, ranges)`"
    )]
    pub fn get_monospace_fonts(&self, unicode_ranges: &[UnicodeRange]) -> Vec<String> {
        FcFallbackConfig::os_defaults(*self)
            .expand_generic(GenericFamily::Monospace, unicode_ranges)
    }

    /// Expand one CSS family entry against the built-in tables for this OS.
    #[cfg(feature = "std")]
    #[deprecated(
        since = "5.0.0",
        note = "use `FcFallbackConfig::os_defaults(os).expand_family(family, ranges)`"
    )]
    pub fn expand_generic_family(
        &self,
        family: &str,
        unicode_ranges: &[UnicodeRange],
    ) -> Vec<String> {
        FcFallbackConfig::os_defaults(*self).expand_family(family, unicode_ranges)
    }
}

/// Expand a CSS font stack against the built-in per-OS tables.
#[cfg(feature = "std")]
#[deprecated(
    since = "5.0.0",
    note = "use `FcFallbackConfig::os_defaults(os).candidate_families(families, ranges)`"
)]
pub fn expand_font_families(
    families: &[String],
    os: OperatingSystem,
    unicode_ranges: &[UnicodeRange],
) -> Vec<String> {
    FcFallbackConfig::os_defaults(os).candidate_families(families, unicode_ranges)
}

/// UUID to identify a font (collections are broken up into separate fonts).
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
pub struct FontId(pub u128);

impl core::fmt::Debug for FontId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(self, f)
    }
}

impl core::fmt::Display for FontId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let id = self.0;
        write!(
            f,
            "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
            (id >> 96) & 0xFFFFFFFF,
            (id >> 80) & 0xFFFF,
            (id >> 64) & 0xFFFF,
            (id >> 48) & 0xFFFF,
            id & 0xFFFFFFFFFFFF
        )
    }
}

impl FontId {
    /// Generate a new unique FontId using an atomic counter.
    pub fn new() -> Self {
        use core::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(1);
        let id = COUNTER.fetch_add(1, Ordering::Relaxed) as u128;
        FontId(id)
    }
}

/// Whether a field is required to match (yes / no / don't care).
#[derive(Debug, Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
#[repr(C)]
pub enum PatternMatch {
    /// Default: don't particularly care whether the requirement matches.
    #[default]
    DontCare = 2,
    /// Requirement has to be true for the selected font.
    True = 0,
    /// Requirement has to be false for the selected font.
    False = 1,
}

impl PatternMatch {
    fn needs_to_match(&self) -> bool {
        matches!(self, PatternMatch::True | PatternMatch::False)
    }

    fn matches(&self, other: &PatternMatch) -> bool {
        match (self, other) {
            (PatternMatch::DontCare, _) => true,
            (_, PatternMatch::DontCare) => true,
            (a, b) => a == b,
        }
    }
}

/// Font weight values as defined in CSS specification.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
#[repr(C)]
pub enum FcWeight {
    Thin = 100,
    ExtraLight = 200,
    Light = 300,
    Normal = 400,
    Medium = 500,
    SemiBold = 600,
    Bold = 700,
    ExtraBold = 800,
    Black = 900,
}

impl FcWeight {
    pub fn from_u16(weight: u16) -> Self {
        match weight {
            0..=149 => FcWeight::Thin,
            150..=249 => FcWeight::ExtraLight,
            250..=349 => FcWeight::Light,
            350..=449 => FcWeight::Normal,
            450..=549 => FcWeight::Medium,
            550..=649 => FcWeight::SemiBold,
            650..=749 => FcWeight::Bold,
            750..=849 => FcWeight::ExtraBold,
            _ => FcWeight::Black,
        }
    }

    pub fn find_best_match(&self, available: &[FcWeight]) -> Option<FcWeight> {
        if available.is_empty() {
            return None;
        }

        // Exact match
        if available.contains(self) {
            return Some(*self);
        }

        // Get numeric value
        let self_value = *self as u16;

        match *self {
            FcWeight::Normal => {
                // For Normal (400), try Medium (500) first
                if available.contains(&FcWeight::Medium) {
                    return Some(FcWeight::Medium);
                }
                // Then try lighter weights
                for weight in &[FcWeight::Light, FcWeight::ExtraLight, FcWeight::Thin] {
                    if available.contains(weight) {
                        return Some(*weight);
                    }
                }
                // Last, try heavier weights
                for weight in &[
                    FcWeight::SemiBold,
                    FcWeight::Bold,
                    FcWeight::ExtraBold,
                    FcWeight::Black,
                ] {
                    if available.contains(weight) {
                        return Some(*weight);
                    }
                }
            }
            FcWeight::Medium => {
                // For Medium (500), try Normal (400) first
                if available.contains(&FcWeight::Normal) {
                    return Some(FcWeight::Normal);
                }
                // Then try lighter weights
                for weight in &[FcWeight::Light, FcWeight::ExtraLight, FcWeight::Thin] {
                    if available.contains(weight) {
                        return Some(*weight);
                    }
                }
                // Last, try heavier weights
                for weight in &[
                    FcWeight::SemiBold,
                    FcWeight::Bold,
                    FcWeight::ExtraBold,
                    FcWeight::Black,
                ] {
                    if available.contains(weight) {
                        return Some(*weight);
                    }
                }
            }
            FcWeight::Thin | FcWeight::ExtraLight | FcWeight::Light => {
                // For lightweight fonts (<400), first try lighter or equal weights
                let mut best_match = None;
                let mut smallest_diff = u16::MAX;

                // Find the closest lighter weight
                for weight in available {
                    let weight_value = *weight as u16;
                    // Only consider weights <= self (per test expectation)
                    if weight_value <= self_value {
                        let diff = self_value - weight_value;
                        if diff < smallest_diff {
                            smallest_diff = diff;
                            best_match = Some(*weight);
                        }
                    }
                }

                if best_match.is_some() {
                    return best_match;
                }

                // If no lighter weight, find the closest heavier weight
                best_match = None;
                smallest_diff = u16::MAX;

                for weight in available {
                    let weight_value = *weight as u16;
                    if weight_value > self_value {
                        let diff = weight_value - self_value;
                        if diff < smallest_diff {
                            smallest_diff = diff;
                            best_match = Some(*weight);
                        }
                    }
                }

                return best_match;
            }
            FcWeight::SemiBold | FcWeight::Bold | FcWeight::ExtraBold | FcWeight::Black => {
                // For heavyweight fonts (>500), first try heavier or equal weights
                let mut best_match = None;
                let mut smallest_diff = u16::MAX;

                // Find the closest heavier weight
                for weight in available {
                    let weight_value = *weight as u16;
                    // Only consider weights >= self
                    if weight_value >= self_value {
                        let diff = weight_value - self_value;
                        if diff < smallest_diff {
                            smallest_diff = diff;
                            best_match = Some(*weight);
                        }
                    }
                }

                if best_match.is_some() {
                    return best_match;
                }

                // If no heavier weight, find the closest lighter weight
                best_match = None;
                smallest_diff = u16::MAX;

                for weight in available {
                    let weight_value = *weight as u16;
                    if weight_value < self_value {
                        let diff = self_value - weight_value;
                        if diff < smallest_diff {
                            smallest_diff = diff;
                            best_match = Some(*weight);
                        }
                    }
                }

                return best_match;
            }
        }

        // If nothing matches by now, return the first available weight
        Some(available[0])
    }
}

impl Default for FcWeight {
    fn default() -> Self {
        FcWeight::Normal
    }
}

/// CSS font-stretch values.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
#[repr(C)]
pub enum FcStretch {
    UltraCondensed = 1,
    ExtraCondensed = 2,
    Condensed = 3,
    SemiCondensed = 4,
    Normal = 5,
    SemiExpanded = 6,
    Expanded = 7,
    ExtraExpanded = 8,
    UltraExpanded = 9,
}

impl FcStretch {
    pub fn is_condensed(&self) -> bool {
        use self::FcStretch::*;
        match self {
            UltraCondensed => true,
            ExtraCondensed => true,
            Condensed => true,
            SemiCondensed => true,
            Normal => false,
            SemiExpanded => false,
            Expanded => false,
            ExtraExpanded => false,
            UltraExpanded => false,
        }
    }
    pub fn from_u16(width_class: u16) -> Self {
        match width_class {
            1 => FcStretch::UltraCondensed,
            2 => FcStretch::ExtraCondensed,
            3 => FcStretch::Condensed,
            4 => FcStretch::SemiCondensed,
            5 => FcStretch::Normal,
            6 => FcStretch::SemiExpanded,
            7 => FcStretch::Expanded,
            8 => FcStretch::ExtraExpanded,
            9 => FcStretch::UltraExpanded,
            _ => FcStretch::Normal,
        }
    }

    /// Follows CSS spec for stretch matching.
    pub fn find_best_match(&self, available: &[FcStretch]) -> Option<FcStretch> {
        if available.is_empty() {
            return None;
        }

        if available.contains(self) {
            return Some(*self);
        }

        // For 'normal' or condensed values, narrower widths are checked first, then wider values
        if *self <= FcStretch::Normal {
            // Find narrower values first
            let mut closest_narrower = None;
            for stretch in available.iter() {
                if *stretch < *self
                    && (closest_narrower.is_none() || *stretch > closest_narrower.unwrap())
                {
                    closest_narrower = Some(*stretch);
                }
            }

            if closest_narrower.is_some() {
                return closest_narrower;
            }

            // Otherwise, find wider values
            let mut closest_wider = None;
            for stretch in available.iter() {
                if *stretch > *self
                    && (closest_wider.is_none() || *stretch < closest_wider.unwrap())
                {
                    closest_wider = Some(*stretch);
                }
            }

            return closest_wider;
        } else {
            // For expanded values, wider values are checked first, then narrower values
            let mut closest_wider = None;
            for stretch in available.iter() {
                if *stretch > *self
                    && (closest_wider.is_none() || *stretch < closest_wider.unwrap())
                {
                    closest_wider = Some(*stretch);
                }
            }

            if closest_wider.is_some() {
                return closest_wider;
            }

            // Otherwise, find narrower values
            let mut closest_narrower = None;
            for stretch in available.iter() {
                if *stretch < *self
                    && (closest_narrower.is_none() || *stretch > closest_narrower.unwrap())
                {
                    closest_narrower = Some(*stretch);
                }
            }

            return closest_narrower;
        }
    }
}

impl Default for FcStretch {
    fn default() -> Self {
        FcStretch::Normal
    }
}

/// Unicode range representation for font matching.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
pub struct UnicodeRange {
    pub start: u32,
    pub end: u32,
}

/// The default set of Unicode-block fallback scripts that.
pub const DEFAULT_UNICODE_FALLBACK_SCRIPTS: &[UnicodeRange] = &[
    UnicodeRange {
        start: 0x0400,
        end: 0x04FF,
    }, // Cyrillic
    UnicodeRange {
        start: 0x0600,
        end: 0x06FF,
    }, // Arabic
    UnicodeRange {
        start: 0x0900,
        end: 0x097F,
    }, // Devanagari
    UnicodeRange {
        start: 0x3040,
        end: 0x309F,
    }, // Hiragana
    UnicodeRange {
        start: 0x30A0,
        end: 0x30FF,
    }, // Katakana
    UnicodeRange {
        start: 0x4E00,
        end: 0x9FFF,
    }, // CJK Unified Ideographs
    UnicodeRange {
        start: 0xAC00,
        end: 0xD7A3,
    }, // Hangul Syllables
];

impl UnicodeRange {
    pub fn contains(&self, c: char) -> bool {
        let c = c as u32;
        c >= self.start && c <= self.end
    }

    pub fn overlaps(&self, other: &UnicodeRange) -> bool {
        self.start <= other.end && other.start <= self.end
    }

    pub fn is_subset_of(&self, other: &UnicodeRange) -> bool {
        self.start >= other.start && self.end <= other.end
    }
}

/// Check if any range covers CJK Unified Ideographs, Hiragana, Katakana, or Hangul.
pub fn has_cjk_ranges(ranges: &[UnicodeRange]) -> bool {
    const BLOCKS: [UnicodeRange; 4] = [
        UnicodeRange {
            start: 0x3040,
            end: 0x309F,
        }, // Hiragana
        UnicodeRange {
            start: 0x30A0,
            end: 0x30FF,
        }, // Katakana
        UnicodeRange {
            start: 0x4E00,
            end: 0x9FFF,
        }, // CJK Unified Ideographs
        UnicodeRange {
            start: 0xAC00,
            end: 0xD7AF,
        }, // Hangul Syllables
    ];
    ranges.iter().any(|r| BLOCKS.iter().any(|b| r.overlaps(b)))
}

/// Check if any range covers the Arabic block.
pub fn has_arabic_ranges(ranges: &[UnicodeRange]) -> bool {
    ranges.iter().any(|r| {
        r.overlaps(&UnicodeRange {
            start: 0x0600,
            end: 0x06FF,
        })
    })
}

/// Check if any range covers the Cyrillic block.
pub fn has_cyrillic_ranges(ranges: &[UnicodeRange]) -> bool {
    ranges.iter().any(|r| {
        r.overlaps(&UnicodeRange {
            start: 0x0400,
            end: 0x04FF,
        })
    })
}

/// Check if any range covers the Hebrew block.
pub fn has_hebrew_ranges(ranges: &[UnicodeRange]) -> bool {
    ranges.iter().any(|r| {
        r.overlaps(&UnicodeRange {
            start: 0x0590,
            end: 0x05FF,
        })
    })
}

/// Check if any range covers the Thai block.
pub fn has_thai_ranges(ranges: &[UnicodeRange]) -> bool {
    ranges.iter().any(|r| {
        r.overlaps(&UnicodeRange {
            start: 0x0E00,
            end: 0x0E7F,
        })
    })
}

/// Log levels for trace messages.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub enum TraceLevel {
    Debug,
    Info,
    Warning,
    Error,
}

/// Reason for font matching failure or success.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MatchReason {
    NameMismatch {
        requested: Option<String>,
        found: Option<String>,
    },
    FamilyMismatch {
        requested: Option<String>,
        found: Option<String>,
    },
    StyleMismatch {
        property: &'static str,
        requested: String,
        found: String,
    },
    WeightMismatch {
        requested: FcWeight,
        found: FcWeight,
    },
    StretchMismatch {
        requested: FcStretch,
        found: FcStretch,
    },
    UnicodeRangeMismatch {
        character: char,
        ranges: Vec<UnicodeRange>,
    },
    Success,
}

/// Trace message for debugging font matching.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceMsg {
    pub level: TraceLevel,
    pub path: String,
    pub reason: MatchReason,
}

/// Hinting style for font rendering.
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
pub enum FcHintStyle {
    #[default]
    None = 0,
    Slight = 1,
    Medium = 2,
    Full = 3,
}

/// Subpixel rendering order.
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
pub enum FcRgba {
    #[default]
    Unknown = 0,
    Rgb = 1,
    Bgr = 2,
    Vrgb = 3,
    Vbgr = 4,
    None = 5,
}

/// LCD filter mode for subpixel rendering.
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
pub enum FcLcdFilter {
    #[default]
    None = 0,
    Default = 1,
    Light = 2,
    Legacy = 3,
}

/// Per-font rendering configuration from system font config (Linux fonts.conf).
#[derive(Debug, Default, Clone)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
pub struct FcFontRenderConfig {
    pub antialias: Option<bool>,
    pub hinting: Option<bool>,
    pub hintstyle: Option<FcHintStyle>,
    pub autohint: Option<bool>,
    pub rgba: Option<FcRgba>,
    pub lcdfilter: Option<FcLcdFilter>,
    pub embeddedbitmap: Option<bool>,
    pub embolden: Option<bool>,
    pub dpi: Option<f64>,
    pub scale: Option<f64>,
    pub minspace: Option<bool>,
}

/// Helper newtype to provide Eq/Ord for Option<f64> via total-order bit comparison.
impl Eq for FcFontRenderConfig {}

// Manual PartialOrd/Ord for f64 field bit pattern consistency.
impl PartialEq for FcFontRenderConfig {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == core::cmp::Ordering::Equal
    }
}

impl PartialOrd for FcFontRenderConfig {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for FcFontRenderConfig {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        // Compare all non-f64 fields first
        let ord = self
            .antialias
            .cmp(&other.antialias)
            .then_with(|| self.hinting.cmp(&other.hinting))
            .then_with(|| self.hintstyle.cmp(&other.hintstyle))
            .then_with(|| self.autohint.cmp(&other.autohint))
            .then_with(|| self.rgba.cmp(&other.rgba))
            .then_with(|| self.lcdfilter.cmp(&other.lcdfilter))
            .then_with(|| self.embeddedbitmap.cmp(&other.embeddedbitmap))
            .then_with(|| self.embolden.cmp(&other.embolden))
            .then_with(|| self.minspace.cmp(&other.minspace));

        // For f64 fields, use to_bits() for total ordering
        let ord = ord.then_with(|| {
            let a = self.dpi.map(|v| v.to_bits());
            let b = other.dpi.map(|v| v.to_bits());
            a.cmp(&b)
        });
        ord.then_with(|| {
            let a = self.scale.map(|v| v.to_bits());
            let b = other.scale.map(|v| v.to_bits());
            a.cmp(&b)
        })
    }
}

/// Font pattern for matching.
#[derive(Default, Clone, PartialOrd, Ord, PartialEq, Eq)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
#[repr(C)]
pub struct FcPattern {
    // font name
    pub name: Option<String>,
    // family name
    pub family: Option<String>,
    // "italic" property
    pub italic: PatternMatch,
    // "oblique" property
    pub oblique: PatternMatch,
    // "bold" property
    pub bold: PatternMatch,
    // "monospace" property
    pub monospace: PatternMatch,
    // "condensed" property
    pub condensed: PatternMatch,
    // font weight
    pub weight: FcWeight,
    // font stretch
    pub stretch: FcStretch,
    // unicode ranges to match
    pub unicode_ranges: Vec<UnicodeRange>,
    // extended font metadata
    pub metadata: FcFontMetadata,
    // per-font rendering configuration (from system fonts.conf on Linux)
    pub render_config: FcFontRenderConfig,
}

impl core::fmt::Debug for FcPattern {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut d = f.debug_struct("FcPattern");

        if let Some(name) = &self.name {
            d.field("name", name);
        }

        if let Some(family) = &self.family {
            d.field("family", family);
        }

        if self.italic != PatternMatch::DontCare {
            d.field("italic", &self.italic);
        }

        if self.oblique != PatternMatch::DontCare {
            d.field("oblique", &self.oblique);
        }

        if self.bold != PatternMatch::DontCare {
            d.field("bold", &self.bold);
        }

        if self.monospace != PatternMatch::DontCare {
            d.field("monospace", &self.monospace);
        }

        if self.condensed != PatternMatch::DontCare {
            d.field("condensed", &self.condensed);
        }

        if self.weight != FcWeight::Normal {
            d.field("weight", &self.weight);
        }

        if self.stretch != FcStretch::Normal {
            d.field("stretch", &self.stretch);
        }

        if !self.unicode_ranges.is_empty() {
            d.field("unicode_ranges", &self.unicode_ranges);
        }

        // Only show non-empty metadata fields
        let empty_metadata = FcFontMetadata::default();
        if self.metadata != empty_metadata {
            d.field("metadata", &self.metadata);
        }

        // Only show render_config when it differs from default
        let empty_render_config = FcFontRenderConfig::default();
        if self.render_config != empty_render_config {
            d.field("render_config", &self.render_config);
        }

        d.finish()
    }
}

/// Font metadata from the OS/2 table.
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
pub struct FcFontMetadata {
    pub copyright: Option<String>,
    pub designer: Option<String>,
    pub designer_url: Option<String>,
    pub font_family: Option<String>,
    pub font_subfamily: Option<String>,
    pub full_name: Option<String>,
    pub id_description: Option<String>,
    pub license: Option<String>,
    pub license_url: Option<String>,
    pub manufacturer: Option<String>,
    pub manufacturer_url: Option<String>,
    pub postscript_name: Option<String>,
    pub preferred_family: Option<String>,
    pub preferred_subfamily: Option<String>,
    pub trademark: Option<String>,
    pub unique_id: Option<String>,
    pub version: Option<String>,
}

impl FcPattern {
    /// Check if this pattern would match the given character.
    pub fn contains_char(&self, c: char) -> bool {
        if self.unicode_ranges.is_empty() {
            return true; // No ranges specified means match all characters
        }

        for range in &self.unicode_ranges {
            if range.contains(c) {
                return true;
            }
        }

        false
    }
}

/// Font match result with UUID.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontMatch {
    pub id: FontId,
    pub unicode_ranges: Vec<UnicodeRange>,
    pub fallbacks: Vec<FontMatchNoFallback>,
}

/// Font match result with UUID (without fallback).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontMatchNoFallback {
    pub id: FontId,
    pub unicode_ranges: Vec<UnicodeRange>,
}

/// A run of text that uses the same font.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedFontRun {
    /// The text content of this run.
    pub text: String,
    /// Start byte index in the original text.
    pub start_byte: usize,
    /// End byte index in the original text (exclusive).
    pub end_byte: usize,
    /// The font to use for this run (None if no font found).
    pub font_id: Option<FontId>,
    /// Which CSS font-family this came from.
    pub css_source: String,
}

/// Path to a font file.
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
#[cfg_attr(feature = "cache", derive(serde::Serialize, serde::Deserialize))]
#[repr(C)]
pub struct FcFontPath {
    pub path: String,
    pub font_index: usize,
    /// 64-bit content hash of the file's bytes.
    #[cfg_attr(feature = "cache", serde(default))]
    pub bytes_hash: u64,
}

/// In-memory font data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct FcFont {
    pub bytes: Vec<u8>,
    pub font_index: usize,
    pub id: String, // For identification in tests
}

/// Owned font-source descriptor, returned by.
#[derive(Debug, Clone)]
pub enum OwnedFontSource {
    /// Font loaded from memory (small metadata + owned `Vec<u8>`).
    Memory(FcFont),
    /// Font loaded from disk.
    Disk(FcFontPath),
}

/// A handle to font bytes returned by [`FcFontCache::get_font_bytes`].
#[cfg(feature = "std")]
pub enum FontBytes {
    /// Heap-owned bytes.
    Owned(std::sync::Arc<[u8]>),
    /// File-backed mmap.
    #[cfg(not(target_family = "wasm"))]
    Mmapped(mmapio::Mmap),
}

#[cfg(feature = "std")]
impl FontBytes {
    /// Borrow the underlying byte slice.
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        match self {
            FontBytes::Owned(arc) => arc,
            #[cfg(not(target_family = "wasm"))]
            FontBytes::Mmapped(m) => &m[..],
        }
    }
}

#[cfg(feature = "std")]
impl core::ops::Deref for FontBytes {
    type Target = [u8];
    #[inline]
    fn deref(&self) -> &[u8] {
        self.as_slice()
    }
}

#[cfg(feature = "std")]
impl AsRef<[u8]> for FontBytes {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}

#[cfg(feature = "std")]
impl core::fmt::Debug for FontBytes {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let kind = match self {
            FontBytes::Owned(_) => "Owned",
            #[cfg(not(target_family = "wasm"))]
            FontBytes::Mmapped(_) => "Mmapped",
        };
        write!(f, "FontBytes::{}({} bytes)", kind, self.as_slice().len())
    }
}

/// Open a font file as an mmap-backed [`FontBytes`].
#[cfg(feature = "std")]
fn open_font_bytes_mmap(path: &str) -> Option<std::sync::Arc<FontBytes>> {
    use std::fs::File;
    use std::sync::Arc;

    #[cfg(not(target_family = "wasm"))]
    {
        if let Ok(file) = File::open(path) {
            // Safety: Mmap requires file is not mutated. For system fonts this is fine.
            if let Ok(mmap) = unsafe { mmapio::MmapOptions::new().map(&file) } {
                return Some(Arc::new(FontBytes::Mmapped(mmap)));
            }
        }
    }
    let bytes = std::fs::read(path).ok()?;
    Some(Arc::new(FontBytes::Owned(Arc::from(bytes))))
}

/// A named font to be added to the font cache from memory.
#[derive(Debug, Clone)]
pub struct NamedFont {
    /// Human-readable name for this font (e.g., "My Custom Font").
    pub name: String,
    /// The raw font file bytes (TTF, OTF, WOFF, WOFF2, TTC).
    pub bytes: Vec<u8>,
}

impl NamedFont {
    /// Create a new named font from bytes.
    pub fn new(name: impl Into<String>, bytes: Vec<u8>) -> Self {
        Self {
            name: name.into(),
            bytes,
        }
    }
}

/// Font cache, initialized at startup.
pub struct FcFontCache {
    pub(crate) shared: std::sync::Arc<FcFontCacheShared>,
}

/// Shared interior of `FcFontCache`.
// Internal lock wrapper: `RwLock` by default, or `UnsafeCell` under `single-thread-unsafe-locks` (WASM).

#[cfg(not(feature = "single-thread-unsafe-locks"))]
pub struct StLock<T> {
    lock: std::sync::RwLock<T>,
}
#[cfg(not(feature = "single-thread-unsafe-locks"))]
impl<T> core::fmt::Debug for StLock<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("StLock(..)")
    }
}
#[cfg(not(feature = "single-thread-unsafe-locks"))]
impl<T> StLock<T> {
    pub fn new(v: T) -> Self {
        Self {
            lock: std::sync::RwLock::new(v),
        }
    }
    pub fn read(&self) -> Result<StReadGuard<'_, T>, core::convert::Infallible> {
        Ok(StReadGuard {
            g: self.lock.read().unwrap_or_else(|e| e.into_inner()),
        })
    }
    pub fn write(&self) -> Result<StWriteGuard<'_, T>, core::convert::Infallible> {
        Ok(StWriteGuard {
            g: self.lock.write().unwrap_or_else(|e| e.into_inner()),
        })
    }
    pub fn lock(&self) -> Result<StWriteGuard<'_, T>, core::convert::Infallible> {
        self.write()
    }
}
#[cfg(not(feature = "single-thread-unsafe-locks"))]
pub struct StReadGuard<'a, T> {
    g: std::sync::RwLockReadGuard<'a, T>,
}
#[cfg(not(feature = "single-thread-unsafe-locks"))]
impl<'a, T> core::ops::Deref for StReadGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.g
    }
}
#[cfg(not(feature = "single-thread-unsafe-locks"))]
pub struct StWriteGuard<'a, T> {
    g: std::sync::RwLockWriteGuard<'a, T>,
}
#[cfg(not(feature = "single-thread-unsafe-locks"))]
impl<'a, T> core::ops::Deref for StWriteGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.g
    }
}
#[cfg(not(feature = "single-thread-unsafe-locks"))]
impl<'a, T> core::ops::DerefMut for StWriteGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.g
    }
}

#[cfg(feature = "single-thread-unsafe-locks")]
pub struct StLock<T> {
    cell: std::cell::UnsafeCell<T>,
}
#[cfg(feature = "single-thread-unsafe-locks")]
unsafe impl<T> Sync for StLock<T> {}
#[cfg(feature = "single-thread-unsafe-locks")]
unsafe impl<T> Send for StLock<T> {}
#[cfg(feature = "single-thread-unsafe-locks")]
impl<T> core::fmt::Debug for StLock<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("StLock(..)")
    }
}
#[cfg(feature = "single-thread-unsafe-locks")]
impl<T> StLock<T> {
    pub fn new(v: T) -> Self {
        Self {
            cell: std::cell::UnsafeCell::new(v),
        }
    }
    pub fn read(&self) -> Result<StReadGuard<'_, T>, core::convert::Infallible> {
        Ok(StReadGuard {
            r: unsafe { &*self.cell.get() },
        })
    }
    pub fn write(&self) -> Result<StWriteGuard<'_, T>, core::convert::Infallible> {
        Ok(StWriteGuard {
            r: unsafe { &mut *self.cell.get() },
        })
    }
    pub fn lock(&self) -> Result<StWriteGuard<'_, T>, core::convert::Infallible> {
        Ok(StWriteGuard {
            r: unsafe { &mut *self.cell.get() },
        })
    }
}
#[cfg(feature = "single-thread-unsafe-locks")]
pub struct StReadGuard<'a, T> {
    r: &'a T,
}
#[cfg(feature = "single-thread-unsafe-locks")]
impl<'a, T> core::ops::Deref for StReadGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.r
    }
}
#[cfg(feature = "single-thread-unsafe-locks")]
pub struct StWriteGuard<'a, T> {
    r: &'a mut T,
}
#[cfg(feature = "single-thread-unsafe-locks")]
impl<'a, T> core::ops::Deref for StWriteGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.r
    }
}
#[cfg(feature = "single-thread-unsafe-locks")]
impl<'a, T> core::ops::DerefMut for StWriteGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.r
    }
}

pub(crate) struct FcFontCacheShared {
    /// Main pattern/metadata state, guarded by a reader-writer lock.
    pub(crate) state: StLock<FcFontCacheInner>,
    /// Font fallback chain cache.
    pub(crate) chain_cache: StLock<std::collections::HashMap<FontChainCacheKey, FontFallbackChain>>,
    /// Shared file-bytes cache: content-hash → weak [`FontBytes`].
    pub(crate) shared_bytes: StLock<std::collections::HashMap<u64, std::sync::Weak<FontBytes>>>,
}

/// The actual font-pattern state, held behind the RwLock in.
#[derive(Default, Debug)]
pub(crate) struct FcFontCacheInner {
    /// Disk font path -> the ids of its faces.
    pub(crate) by_path: BTreeMap<String, Vec<FontId>>,
    /// On-disk font paths.
    pub(crate) disk_fonts: BTreeMap<FontId, FcFontPath>,
    /// In-memory fonts.
    pub(crate) memory_fonts: BTreeMap<FontId, FcFont>,
    /// Metadata cache (patterns stored by ID for quick lookup).
    pub(crate) metadata: BTreeMap<FontId, FcPattern>,
    /// Normalized family/name -> the fonts that carry it.
    pub(crate) family_index: BTreeMap<String, alloc::vec::Vec<FontId>>,
    /// What generic families, missing named families, script blocks and.
    pub(crate) fallback_config: FcFallbackConfig,
}

impl FcFontCacheInner {
    /// Record `id` under the normalized spellings of its family and name.
    pub(crate) fn index_pattern_family(&mut self, pattern: &FcPattern, id: FontId) {
        for key in [pattern.family.as_deref(), pattern.name.as_deref()]
            .into_iter()
            .flatten()
            .map(crate::utils::normalize_family_name)
            .filter(|k| !k.is_empty())
        {
            let slot = self.family_index.entry(key).or_default();
            if !slot.contains(&id) {
                slot.push(id);
            }
        }
    }

    /// Register a font backed by a file.
    pub(crate) fn insert_disk_font(
        &mut self,
        mut pattern: FcPattern,
        id: FontId,
        path: FcFontPath,
    ) -> FontId {
        pattern.unicode_ranges =
            FcFontCache::normalize_unicode_ranges(core::mem::take(&mut pattern.unicode_ranges));
        if let Some(existing) = self.by_path.get(&path.path).and_then(|ids| {
            ids.iter().copied().find(|existing| {
                self.disk_fonts
                    .get(existing)
                    .is_some_and(|p| p.font_index == path.font_index)
                    && self.metadata.get(existing) == Some(&pattern)
            })
        }) {
            return existing;
        }
        self.index_pattern_family(&pattern, id);
        self.by_path.entry(path.path.clone()).or_default().push(id);
        self.disk_fonts.insert(id, path);
        self.metadata.insert(id, pattern);
        id
    }

    /// Register a font held in memory.
    pub(crate) fn insert_memory_font(
        &mut self,
        mut pattern: FcPattern,
        id: FontId,
        font: FcFont,
    ) -> FontId {
        pattern.unicode_ranges =
            FcFontCache::normalize_unicode_ranges(core::mem::take(&mut pattern.unicode_ranges));
        let hash = crate::utils::content_dedup_hash_u64(&font.bytes);
        if let Some(existing) = self.memory_fonts.iter().find_map(|(existing, f)| {
            (f.font_index == font.font_index
                && self.metadata.get(existing) == Some(&pattern)
                && crate::utils::content_dedup_hash_u64(&f.bytes) == hash)
                .then_some(*existing)
        }) {
            return existing;
        }
        self.index_pattern_family(&pattern, id);
        self.memory_fonts.insert(id, font);
        self.metadata.insert(id, pattern);
        id
    }
}

impl Clone for FcFontCache {
    /// Shallow clone — the returned handle shares the same underlying.
    fn clone(&self) -> Self {
        Self {
            shared: std::sync::Arc::clone(&self.shared),
        }
    }
}

impl core::fmt::Debug for FcFontCache {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let state = self.state_read();
        f.debug_struct("FcFontCache")
            .field("fonts", &state.metadata.len())
            .field("metadata_len", &state.metadata.len())
            .field("disk_fonts_len", &state.disk_fonts.len())
            .field("memory_fonts_len", &state.memory_fonts.len())
            .finish()
    }
}

impl Default for FcFontCache {
    fn default() -> Self {
        Self {
            shared: std::sync::Arc::new(FcFontCacheShared {
                state: StLock::new(FcFontCacheInner::default()),
                chain_cache: StLock::new(std::collections::HashMap::new()),
                shared_bytes: StLock::new(std::collections::HashMap::new()),
            }),
        }
    }
}

impl FcFontCache {
    /// The fallback configuration this cache resolves with (a copy).
    pub fn fallback_config(&self) -> FcFallbackConfig {
        self.state_read().fallback_config.clone()
    }

    /// Replace the fallback configuration.
    pub fn set_fallback_config(&self, config: FcFallbackConfig) -> &Self {
        self.state_write().fallback_config = config;
        self.clear_chain_cache();
        self
    }

    /// Builder-style [`set_fallback_config`](Self::set_fallback_config).
    pub fn with_fallback_config(self, config: FcFallbackConfig) -> Self {
        self.set_fallback_config(config);
        self
    }

    /// Drop every memoized chain.
    pub(crate) fn clear_chain_cache(&self) {
        match self.shared.chain_cache.lock() {
            Ok(mut memo) => memo.clear(),
            Err(e) => match e {},
        }
    }

    /// The configured candidates for `family`: a generic keyword's base.
    #[deprecated(
        since = "5.0.0",
        note = "read `fallback_config().generic_candidates(..)` / `substitutions_for(..)`"
    )]
    pub fn system_alias_prefs(&self, family: &str) -> Vec<String> {
        let state = self.state_read();
        match GenericFamily::from_css(family) {
            Some(generic) => state.fallback_config.generic_candidates(generic).to_vec(),
            None => state.fallback_config.substitutions_for(family).to_vec(),
        }
    }

    /// Expand a CSS stack through this cache's configuration, filling gaps.
    #[deprecated(
        since = "5.0.0",
        note = "use `fallback_config().candidate_families(families, ranges)`"
    )]
    pub fn expand_font_families_config_first(
        &self,
        families: &[String],
        os: OperatingSystem,
        unicode_ranges: &[UnicodeRange],
    ) -> Vec<String> {
        let mut config = self.fallback_config();
        config.merge_defaults(&FcFallbackConfig::os_defaults(os));
        config.candidate_families(families, unicode_ranges)
    }

    /// Acquire a read guard on the cache's state.
    #[inline]
    pub(crate) fn state_read(&self) -> StReadGuard<'_, FcFontCacheInner> {
        // [az-web-lift] StLock::read() is Infallible (never poisons/spins).
        match self.shared.state.read() {
            Ok(g) => g,
            Err(e) => match e {},
        }
    }

    /// Acquire a write guard on the cache's state.
    #[inline]
    pub(crate) fn state_write(&self) -> StWriteGuard<'_, FcFontCacheInner> {
        // [az-web-lift] StLock::write() is Infallible (never poisons/spins).
        match self.shared.state.write() {
            Ok(g) => g,
            Err(e) => match e {},
        }
    }

    /// Adds in-memory font files.
    pub fn with_memory_fonts(&self, fonts: Vec<(FcPattern, FcFont)>) -> &Self {
        // Auto-detect Unicode coverage for naively-registered fonts before locking.
        let fonts: Vec<(FcPattern, FcFont)> = fonts
            .into_iter()
            .map(|(pattern, font)| (Self::populate_memory_font_ranges(pattern, &font), font))
            .collect();
        let mut state = self.state_write();
        for (pattern, font) in fonts {
            let id = FontId::new();
            state.insert_memory_font(pattern, id, font);
        }
        self
    }

    /// Adds a memory font with a specific ID (for testing).
    pub fn with_memory_font_with_id(&self, id: FontId, pattern: FcPattern, font: FcFont) -> &Self {
        let pattern = Self::populate_memory_font_ranges(pattern, &font);
        let mut state = self.state_write();
        state.insert_memory_font(pattern, id, font);
        self
    }

    /// Fill in a memory font's `unicode_ranges` from its raw bytes when the.
    #[cfg(all(feature = "std", feature = "parsing"))]
    fn populate_memory_font_ranges(mut pattern: FcPattern, font: &FcFont) -> FcPattern {
        if !pattern.unicode_ranges.is_empty() {
            return pattern;
        }
        if let Some(faces) = FcParseFontBytes(&font.bytes, &font.id) {
            // Pick face matching index, else fallback to first.
            let ranges = faces
                .iter()
                .find(|(_, f)| f.font_index == font.font_index)
                .or_else(|| faces.first())
                .map(|(p, _)| p.unicode_ranges.clone())
                .unwrap_or_default();
            if !ranges.is_empty() {
                pattern.unicode_ranges = ranges;
            }
        }
        pattern
    }

    /// Without the `parsing` feature there is no cmap/OS2 parser available,.
    #[cfg(not(all(feature = "std", feature = "parsing")))]
    fn populate_memory_font_ranges(pattern: FcPattern, _font: &FcFont) -> FcPattern {
        pattern
    }

    /// Register a newly-parsed on-disk font.
    pub fn insert_builder_font(&self, pattern: FcPattern, path: FcFontPath) {
        let id = FontId::new();
        {
            let mut state = self.state_write();
            state.insert_disk_font(pattern, id, path);
        }
        // Invalidate chain cache so callers see the new font.
        self.clear_chain_cache();
    }

    #[cfg(feature = "std")]
    #[doc(hidden)]
    pub fn chain_cache_len(&self) -> usize {
        self.shared.chain_cache.lock().map(|c| c.len()).unwrap_or(0)
    }

    /// Insert a *fast-probed* pattern into the cache and return its.
    pub fn insert_fast_pattern(&self, pattern: FcPattern, path: FcFontPath) -> FontId {
        let id = {
            let mut state = self.state_write();
            state.insert_disk_font(pattern, FontId::new(), path)
        };
        self.clear_chain_cache();
        id
    }

    /// Every `FontId` registered from the file at `path` (one per face and.
    pub fn lookup_paths_cached(&self, path: &str) -> Option<Vec<FontId>> {
        self.state_read()
            .by_path
            .get(path)
            .cloned()
            .filter(|ids| !ids.is_empty())
    }

    /// Get font data for a given font ID.
    pub fn get_font_by_id(&self, id: &FontId) -> Option<OwnedFontSource> {
        let state = self.state_read();
        if let Some(font) = state.memory_fonts.get(id) {
            return Some(OwnedFontSource::Memory(font.clone()));
        }
        if let Some(path) = state.disk_fonts.get(id) {
            return Some(OwnedFontSource::Disk(path.clone()));
        }
        None
    }

    /// Get metadata for a font ID.
    pub fn get_metadata_by_id(&self, id: &FontId) -> Option<FcPattern> {
        self.state_read().metadata.get(id).cloned()
    }

    /// Get the font bytes for `id` as a shared [`FontBytes`].
    #[cfg(feature = "std")]
    pub fn get_font_bytes(&self, id: &FontId) -> Option<std::sync::Arc<FontBytes>> {
        use std::sync::Arc;
        match self.get_font_by_id(id)? {
            OwnedFontSource::Memory(font) => {
                Some(Arc::new(FontBytes::Owned(Arc::from(font.bytes.as_slice()))))
            }
            OwnedFontSource::Disk(path) => {
                let hash = path.bytes_hash;
                if hash != 0 {
                    let guard = self.shared.shared_bytes.lock().unwrap();
                    {
                        if let Some(weak) = guard.get(&hash) {
                            if let Some(arc) = weak.upgrade() {
                                return Some(arc);
                            }
                        }
                    }
                }

                let arc = open_font_bytes_mmap(&path.path)?;
                if hash != 0 {
                    let mut guard = self.shared.shared_bytes.lock().unwrap();
                    {
                        // Overwrite any stale weak ref that failed to upgrade.
                        guard.insert(hash, Arc::downgrade(&arc));
                    }
                }
                Some(arc)
            }
        }
    }

    /// Returns an empty font cache (no_std / no filesystem).
    #[cfg(not(feature = "std"))]
    pub fn build() -> Self {
        Self::default()
    }

    /// Scans system font directories using filename heuristics (no allsorts).
    #[cfg(all(feature = "std", not(feature = "parsing")))]
    pub fn build() -> Self {
        Self::build_from_filenames()
    }

    /// Scans and parses all system fonts via allsorts for full metadata.
    #[cfg(all(feature = "std", feature = "parsing"))]
    pub fn build() -> Self {
        Self::build_inner(None)
    }

    /// Filename-only scan: discovers fonts on disk, guesses metadata from.
    #[cfg(all(feature = "std", not(feature = "parsing")))]
    fn build_from_filenames() -> Self {
        let cache = Self::default();
        {
            let mut state = cache.state_write();
            state.fallback_config = FcFallbackConfig::os_defaults(OperatingSystem::current());
            for dir in crate::config::font_directories(OperatingSystem::current()) {
                for path in FcCollectFontFilesRecursive(dir) {
                    let pattern = match pattern_from_filename(&path) {
                        Some(p) => p,
                        None => continue,
                    };
                    state.insert_disk_font(
                        pattern,
                        FontId::new(),
                        FcFontPath {
                            path: path.to_string_lossy().to_string(),
                            font_index: 0,
                            // Filename-only scan — we never read the bytes,
                            // so there's no dedup key. Leave as 0.
                            bytes_hash: 0,
                        },
                    );
                }
            }
        }
        cache
    }

    /// Builds a font cache with only specific font families (and their fallbacks).
    #[cfg(all(feature = "std", feature = "parsing"))]
    pub fn build_with_families(families: &[impl AsRef<str>]) -> Self {
        // Expand generic families to OS-specific names using built-in lists.
        let os = OperatingSystem::current();
        let mut target_families: Vec<String> = Vec::new();

        for family in families {
            let family_str = family.as_ref();
            let expanded = FcFallbackConfig::os_defaults(os)
                .expand_family(family_str, DEFAULT_UNICODE_FALLBACK_SCRIPTS);
            if expanded.is_empty() || (expanded.len() == 1 && expanded[0] == family_str) {
                target_families.push(family_str.to_string());
            } else {
                target_families.extend(expanded);
            }
        }

        Self::build_inner(Some(&target_families))
    }

    /// Inner build function that handles both filtered and unfiltered font loading.
    #[cfg(all(feature = "std", feature = "parsing"))]
    fn build_inner(family_filter: Option<&[String]>) -> Self {
        let cache = FcFontCache::default();

        // Normalize filter families for matching
        let filter_normalized: Option<Vec<String>> = family_filter.map(|families| {
            families
                .iter()
                .map(|f| crate::utils::normalize_family_name(f))
                .collect()
        });

        // Helper closure to check if a pattern matches the filter
        let matches_filter = |pattern: &FcPattern| -> bool {
            match &filter_normalized {
                None => true, // No filter = accept all
                Some(targets) => {
                    pattern.name.as_ref().map_or(false, |name| {
                        let name_norm = crate::utils::normalize_family_name(name);
                        targets.iter().any(|target| name_norm.contains(target))
                    }) || pattern.family.as_ref().map_or(false, |family| {
                        let family_norm = crate::utils::normalize_family_name(family);
                        targets.iter().any(|target| family_norm.contains(target))
                    })
                }
            }
        };

        let mut state = cache.state_write();
        state.fallback_config = FcFallbackConfig::os_defaults(OperatingSystem::current());

        #[cfg(target_os = "linux")]
        {
            if let Some((font_entries, render_configs, system_aliases)) = FcScanDirectories() {
                // The platform configuration is the authority; the built-in
                // tables only fill what it leaves unsaid.
                let mut config = FcFallbackConfig::default();
                config.absorb_system_aliases(system_aliases);
                config.merge_defaults(&state.fallback_config);
                state.fallback_config = config;
                for (mut pattern, path) in font_entries {
                    if matches_filter(&pattern) {
                        // Apply per-font render config if a matching family rule exists
                        if let Some(family) = pattern.name.as_ref().or(pattern.family.as_ref()) {
                            if let Some(rc) = render_configs.get(family) {
                                pattern.render_config = rc.clone();
                            }
                        }
                        let id = FontId::new();
                        state.insert_disk_font(pattern, id, path);
                    }
                }
            }
        }

        #[cfg(target_os = "windows")]
        {
            let system_root = std::env::var("SystemRoot")
                .or_else(|_| std::env::var("WINDIR"))
                .unwrap_or_else(|_| "C:\\Windows".to_string());

            let user_profile =
                std::env::var("USERPROFILE").unwrap_or_else(|_| "C:\\Users\\Default".to_string());

            let font_dirs = vec![
                (None, format!("{}\\Fonts\\", system_root)),
                (
                    None,
                    format!(
                        "{}\\AppData\\Local\\Microsoft\\Windows\\Fonts\\",
                        user_profile
                    ),
                ),
            ];

            let font_entries = FcScanDirectoriesInner(&font_dirs);
            for (pattern, path) in font_entries {
                if matches_filter(&pattern) {
                    let id = FontId::new();
                    state.insert_disk_font(pattern, id, path);
                }
            }
        }

        #[cfg(target_os = "macos")]
        {
            let font_dirs = vec![
                (None, "~/Library/Fonts".to_owned()),
                (None, "/System/Library/Fonts".to_owned()),
                (None, "/Library/Fonts".to_owned()),
                (None, "/System/Library/AssetsV2".to_owned()),
            ];

            let font_entries = FcScanDirectoriesInner(&font_dirs);
            for (pattern, path) in font_entries {
                if matches_filter(&pattern) {
                    let id = FontId::new();
                    state.insert_disk_font(pattern, id, path);
                }
            }
        }

        // iOS: Enumerate fonts via CoreText to bypass sandbox read_dir restrictions.
        #[cfg(target_os = "ios")]
        {
            let font_files = crate::mobile_ios::copy_available_font_urls();
            let font_entries = FcParseFontFiles(&font_files);
            for (pattern, path) in font_entries {
                if matches_filter(&pattern) {
                    let id = FontId::new();
                    state.insert_disk_font(pattern, id, path);
                }
            }
        }

        // Android: Enumerate world-readable system and vendor font directories.
        #[cfg(target_os = "android")]
        {
            let font_dirs = vec![
                (None, "/system/fonts".to_owned()),
                (None, "/product/fonts".to_owned()),
                (None, "/system_ext/fonts".to_owned()),
                (None, "/data/fonts".to_owned()),
            ];

            let font_entries = FcScanDirectoriesInner(&font_dirs);
            for (pattern, path) in font_entries {
                if matches_filter(&pattern) {
                    let id = FontId::new();
                    state.insert_disk_font(pattern, id, path);
                }
            }
        }

        drop(state);
        cache
    }

    /// Check if a font ID is a memory font (preferred over disk fonts).
    pub fn is_memory_font(&self, id: &FontId) -> bool {
        self.state_read().memory_fonts.contains_key(id)
    }

    /// Every registered font with its pattern, in registration order.
    pub fn list(&self) -> Vec<(FcPattern, FontId)> {
        self.state_read()
            .metadata
            .iter()
            .map(|(id, pattern)| (pattern.clone(), *id))
            .collect()
    }

    /// Visit every registered font without cloning.
    pub fn for_each_pattern<F: FnMut(&FcPattern, &FontId)>(&self, mut f: F) {
        let state = self.state_read();
        for (id, pattern) in &state.metadata {
            f(pattern, id);
        }
    }

    pub fn is_empty(&self) -> bool {
        self.state_read().metadata.is_empty()
    }

    /// Number of registered fonts (one per face and name record).
    pub fn len(&self) -> usize {
        self.state_read().metadata.len()
    }

    /// Like [`FcFontCache::query`], but **total**: it returns `None` only when the.
    pub fn query_with_fallback(
        &self,
        pattern: &FcPattern,
        trace: &mut Vec<TraceMsg>,
    ) -> Option<FontMatch> {
        if let Some(m) = self.query(pattern, trace) {
            return Some(m);
        }

        // 2. Drop the family/name constraint, keep how it should LOOK.
        if pattern.name.is_some() || pattern.family.is_some() {
            let relaxed = FcPattern {
                name: None,
                family: None,
                ..pattern.clone()
            };
            if let Some(m) = self.query(&relaxed, trace) {
                return Some(m);
            }
        }

        // 3. Coverage only. Anything that can render the requested ranges.
        let bare = FcPattern {
            unicode_ranges: pattern.unicode_ranges.clone(),
            ..FcPattern::default()
        };
        self.query(&bare, trace)
    }

    /// Queries a font from the in-memory cache, returns the first found font (early return).
    pub fn query(&self, pattern: &FcPattern, trace: &mut Vec<TraceMsg>) -> Option<FontMatch> {
        let state = self.state_read();

        // Sort by memory vs disk, then fallback::RankKey (style, coverage, width, name).
        let mut matches: Vec<(bool, fallback::RankKey, FontId, &FcPattern)> = Vec::new();

        for (id, metadata) in &state.metadata {
            if Self::query_matches_internal(metadata, pattern, trace) {
                let is_disk = !state.memory_fonts.contains_key(id);
                matches.push((
                    is_disk,
                    fallback::RankKey::for_request(pattern, metadata, &pattern.unicode_ranges),
                    *id,
                    metadata,
                ));
            }
        }

        matches.sort();

        matches.first().map(|(_, _, id, metadata)| FontMatch {
            id: *id,
            unicode_ranges: metadata.unicode_ranges.clone(),
            fallbacks: Vec::new(),
        })
    }

    /// Get in-memory font data (cloned out of the shared state).
    pub fn get_memory_font(&self, id: &FontId) -> Option<FcFont> {
        self.state_read().memory_fonts.get(id).cloned()
    }

    /// Check if a pattern matches the query, with detailed tracing.
    fn trace_path(k: &FcPattern) -> String {
        k.name
            .as_ref()
            .cloned()
            .unwrap_or_else(|| "<unknown>".to_string())
    }

    pub fn query_matches_internal(
        k: &FcPattern,
        pattern: &FcPattern,
        trace: &mut Vec<TraceMsg>,
    ) -> bool {
        // Check name - substring match
        if let Some(ref name) = pattern.name {
            if !k.name.as_ref().map_or(false, |kn| kn.contains(name)) {
                trace.push(TraceMsg {
                    level: TraceLevel::Info,
                    path: Self::trace_path(k),
                    reason: MatchReason::NameMismatch {
                        requested: pattern.name.clone(),
                        found: k.name.clone(),
                    },
                });
                return false;
            }
        }

        // Check family - substring match
        if let Some(ref family) = pattern.family {
            if !k.family.as_ref().map_or(false, |kf| kf.contains(family)) {
                trace.push(TraceMsg {
                    level: TraceLevel::Info,
                    path: Self::trace_path(k),
                    reason: MatchReason::FamilyMismatch {
                        requested: pattern.family.clone(),
                        found: k.family.clone(),
                    },
                });
                return false;
            }
        }

        // Check style properties
        let style_properties = [
            (
                "italic",
                pattern.italic.needs_to_match(),
                pattern.italic.matches(&k.italic),
            ),
            (
                "oblique",
                pattern.oblique.needs_to_match(),
                pattern.oblique.matches(&k.oblique),
            ),
            (
                "bold",
                pattern.bold.needs_to_match(),
                pattern.bold.matches(&k.bold),
            ),
            (
                "monospace",
                pattern.monospace.needs_to_match(),
                pattern.monospace.matches(&k.monospace),
            ),
            (
                "condensed",
                pattern.condensed.needs_to_match(),
                pattern.condensed.matches(&k.condensed),
            ),
        ];

        for (property_name, needs_to_match, matches) in style_properties {
            if needs_to_match && !matches {
                let (requested, found) = match property_name {
                    "italic" => (format!("{:?}", pattern.italic), format!("{:?}", k.italic)),
                    "oblique" => (format!("{:?}", pattern.oblique), format!("{:?}", k.oblique)),
                    "bold" => (format!("{:?}", pattern.bold), format!("{:?}", k.bold)),
                    "monospace" => (
                        format!("{:?}", pattern.monospace),
                        format!("{:?}", k.monospace),
                    ),
                    "condensed" => (
                        format!("{:?}", pattern.condensed),
                        format!("{:?}", k.condensed),
                    ),
                    _ => (String::new(), String::new()),
                };

                trace.push(TraceMsg {
                    level: TraceLevel::Info,
                    path: Self::trace_path(k),
                    reason: MatchReason::StyleMismatch {
                        property: property_name,
                        requested,
                        found,
                    },
                });
                return false;
            }
        }

        // Check weight - hard filter if non-normal weight is requested
        if pattern.weight != FcWeight::Normal && pattern.weight != k.weight {
            trace.push(TraceMsg {
                level: TraceLevel::Info,
                path: Self::trace_path(k),
                reason: MatchReason::WeightMismatch {
                    requested: pattern.weight,
                    found: k.weight,
                },
            });
            return false;
        }

        // Check stretch - hard filter if non-normal stretch is requested
        if pattern.stretch != FcStretch::Normal && pattern.stretch != k.stretch {
            trace.push(TraceMsg {
                level: TraceLevel::Info,
                path: Self::trace_path(k),
                reason: MatchReason::StretchMismatch {
                    requested: pattern.stretch,
                    found: k.stretch,
                },
            });
            return false;
        }

        // Check unicode ranges if specified
        if !pattern.unicode_ranges.is_empty() {
            let mut has_overlap = false;

            for p_range in &pattern.unicode_ranges {
                for k_range in &k.unicode_ranges {
                    if p_range.overlaps(k_range) {
                        has_overlap = true;
                        break;
                    }
                }
                if has_overlap {
                    break;
                }
            }

            if !has_overlap {
                trace.push(TraceMsg {
                    level: TraceLevel::Info,
                    path: Self::trace_path(k),
                    reason: MatchReason::UnicodeRangeMismatch {
                        character: '\0', // No specific character to report
                        ranges: k.unicode_ranges.clone(),
                    },
                });
                return false;
            }
        }

        true
    }

    /// Extract tokens from a font name.
    pub fn extract_font_name_tokens(name: &str) -> Vec<String> {
        let mut tokens = Vec::new();
        let mut current_token = String::new();
        let mut last_was_lower = false;

        for c in name.chars() {
            if c.is_whitespace() || c == '-' || c == '_' {
                // Word separator
                if !current_token.is_empty() {
                    tokens.push(current_token.clone());
                    current_token.clear();
                }
                last_was_lower = false;
            } else if c.is_uppercase() && last_was_lower && !current_token.is_empty() {
                // CamelCase boundary (e.g., "Noto" | "Sans")
                tokens.push(current_token.clone());
                current_token.clear();
                current_token.push(c);
                last_was_lower = false;
            } else {
                current_token.push(c);
                last_was_lower = c.is_lowercase();
            }
        }

        if !current_token.is_empty() {
            tokens.push(current_token);
        }

        tokens
    }

    /// Total coverage of `ranges` in codepoints (widths summed; callers.
    // Helper to calculate total unicode coverage
    pub fn calculate_unicode_coverage(ranges: &[UnicodeRange]) -> u64 {
        ranges
            .iter()
            .map(|range| (range.end - range.start + 1) as u64)
            .sum()
    }

    /// Coalesce ranges into a sorted, **disjoint** set.
    pub fn normalize_unicode_ranges(mut ranges: Vec<UnicodeRange>) -> Vec<UnicodeRange> {
        if ranges.len() < 2 {
            return ranges;
        }

        ranges.sort_unstable();

        let mut out: Vec<UnicodeRange> = Vec::with_capacity(ranges.len());
        for range in ranges {
            match out.last_mut() {
                // Overlapping or touching: extend. `saturating_add` so an `end` of
                // u32::MAX cannot wrap around into a bogus failure-to-merge.
                Some(prev) if range.start <= prev.end.saturating_add(1) => {
                    prev.end = prev.end.max(range.end);
                }
                _ => out.push(range),
            }
        }
        out
    }

    /// Calculate how well a font's Unicode ranges cover the requested ranges.
    pub fn calculate_unicode_compatibility(
        requested: &[UnicodeRange],
        available: &[UnicodeRange],
    ) -> i32 {
        if requested.is_empty() {
            // No specific requirements, return total coverage
            return Self::calculate_unicode_coverage(available) as i32;
        }

        let mut total_coverage = 0u32;

        for req_range in requested {
            for avail_range in available {
                // Calculate overlap between requested and available ranges
                let overlap_start = req_range.start.max(avail_range.start);
                let overlap_end = req_range.end.min(avail_range.end);

                if overlap_start <= overlap_end {
                    // There is overlap
                    let overlap_size = overlap_end - overlap_start + 1;
                    total_coverage += overlap_size;
                }
            }
        }

        total_coverage as i32
    }

    pub fn calculate_style_score(original: &FcPattern, candidate: &FcPattern) -> i32 {
        let mut score = 0_i32;

        // Weight calculation with special handling for bold property
        if (original.bold == PatternMatch::True && candidate.weight == FcWeight::Bold)
            || (original.bold == PatternMatch::False && candidate.weight != FcWeight::Bold)
        {
            // No weight penalty when bold is requested and font has Bold weight
            // No weight penalty when non-bold is requested and font has non-Bold weight
        } else {
            // Apply normal weight difference penalty
            let weight_diff = (original.weight as i32 - candidate.weight as i32).abs();
            score += weight_diff as i32;
        }

        // Exact weight match bonus: reward fonts whose weight matches the request exactly,
        // with an extra bonus when both are Normal (the most common case for body text)
        if original.weight == candidate.weight {
            score -= 15;
            if original.weight == FcWeight::Normal {
                score -= 10; // Extra bonus for Normal-Normal match
            }
        }

        // Stretch calculation with special handling for condensed property
        if (original.condensed == PatternMatch::True && candidate.stretch.is_condensed())
            || (original.condensed == PatternMatch::False && !candidate.stretch.is_condensed())
        {
            // No stretch penalty when condensed is requested and font has condensed stretch
            // No stretch penalty when non-condensed is requested and font has non-condensed stretch
        } else {
            // Apply normal stretch difference penalty
            let stretch_diff = (original.stretch as i32 - candidate.stretch as i32).abs();
            score += (stretch_diff * 100) as i32;
        }

        // Handle style properties with standard penalties and bonuses
        let style_props = [
            (original.italic, candidate.italic, 300, 150),
            (original.oblique, candidate.oblique, 200, 100),
            (original.bold, candidate.bold, 300, 150),
            (original.monospace, candidate.monospace, 100, 50),
            (original.condensed, candidate.condensed, 100, 50),
        ];

        for (orig, cand, mismatch_penalty, dontcare_penalty) in style_props {
            if orig.needs_to_match() {
                if orig == PatternMatch::False && cand == PatternMatch::DontCare {
                    // Requesting non-italic but font doesn't declare: small penalty
                    // (less than a full mismatch but more than a perfect match)
                    score += dontcare_penalty / 2;
                } else if !orig.matches(&cand) {
                    if cand == PatternMatch::DontCare {
                        score += dontcare_penalty;
                    } else {
                        score += mismatch_penalty;
                    }
                } else if orig == PatternMatch::True && cand == PatternMatch::True {
                    // Give bonus for exact True match
                    score -= 20;
                } else if orig == PatternMatch::False && cand == PatternMatch::False {
                    // Give bonus for exact False match (prefer explicitly non-italic
                    // over fonts with unknown/DontCare italic status)
                    score -= 20;
                }
            } else {
                // orig == DontCare: prefer "normal" fonts over styled ones.
                if cand == PatternMatch::True {
                    score += dontcare_penalty / 3;
                }
            }
        }

        // ── Name-based "base font" detection ──
        // Shorter font names relative to their family imply a more "basic" variant.
        if let (Some(name), Some(family)) = (&candidate.name, &candidate.family) {
            let name_lower = name.to_ascii_lowercase();
            let family_lower = family.to_ascii_lowercase();

            // Strip the family prefix from the name to get the "extra" part
            let extra = if name_lower.starts_with(&family_lower) {
                name_lower[family_lower.len()..].to_string()
            } else {
                String::new()
            };

            // Strip common neutral descriptors that don't indicate a style variant
            let stripped = extra
                .replace("regular", "")
                .replace("normal", "")
                .replace("book", "")
                .replace("roman", "");
            let stripped = stripped.trim();

            if stripped.is_empty() {
                // This is a "base font" – name is just the family (± "Regular")
                score -= 50;
            } else {
                // Name has extra style descriptors – add a penalty per extra word
                let extra_words = stripped.split_whitespace().count();
                score += (extra_words as i32) * 25;
            }
        }

        // ── Subfamily "Regular" bonus ──
        if let Some(ref subfamily) = candidate.metadata.font_subfamily {
            let sf_lower = subfamily.to_ascii_lowercase();
            if sf_lower == "regular" {
                score -= 30;
            }
        }

        score
    }
}

#[cfg(all(feature = "std", feature = "parsing"))]
#[allow(non_snake_case, dead_code)]
fn FcScanDirectories() -> Option<(
    Vec<(FcPattern, FcFontPath)>,
    BTreeMap<String, FcFontRenderConfig>,
    BTreeMap<String, Vec<String>>,
)> {
    let config = FcSystemConfig::from_system()?;
    if config.font_dirs.is_empty() {
        return None;
    }
    let dirs: Vec<(Option<String>, String)> = config
        .font_dirs
        .iter()
        .map(|dir| (None, dir.to_string_lossy().into_owned()))
        .collect();
    Some((
        FcScanDirectoriesInner(&dirs),
        config.render_configs,
        config.aliases,
    ))
}

/// Deepest chain of `<include>`s [`FcSystemConfig::parse_tree`] follows.
#[cfg(all(feature = "std", feature = "parsing"))]
const MAX_INCLUDE_DEPTH: usize = 64;

/// What a fontconfig configuration tree says, as far as this crate reads.
#[cfg(all(feature = "std", feature = "parsing"))]
#[derive(Debug, Clone, Default, PartialEq)]
pub struct FcSystemConfig {
    /// `<dir>` entries, resolved (prefixes and `~` expanded), in order,.
    pub font_dirs: Vec<PathBuf>,
    /// `<match target="font">` rendering settings keyed by family.
    pub render_configs: BTreeMap<String, FcFontRenderConfig>,
    /// `<alias><family>X</family><prefer>…</prefer></alias>` entries keyed by.
    pub aliases: BTreeMap<String, Vec<String>>,
    /// Every configuration file that was read, in the order it was read.
    pub files: Vec<PathBuf>,
}

#[cfg(all(feature = "std", feature = "parsing"))]
impl FcSystemConfig {
    /// The platform configuration: `$FONTCONFIG_FILE` when set and.
    pub fn from_system() -> Option<Self> {
        let root = std::env::var("FONTCONFIG_FILE")
            .ok()
            .filter(|p| !p.is_empty())
            .unwrap_or_else(|| "/etc/fonts/fonts.conf".to_string());
        let root = PathBuf::from(root);
        if !root.is_file() {
            return None;
        }
        Self::parse_tree(&root)
    }

    /// Parse `root` and everything it includes, the way fontconfig does:.
    pub fn parse_tree(root: &std::path::Path) -> Option<Self> {
        use std::collections::VecDeque;

        let root_dir = root.parent().map(|d| d.to_path_buf()).unwrap_or_default();
        let search_dirs: Vec<PathBuf> = std::env::var_os("FONTCONFIG_PATH")
            .map(|v| std::env::split_paths(&v).collect::<Vec<_>>())
            .unwrap_or_default()
            .into_iter()
            .chain(core::iter::once(root_dir))
            .collect();

        let mut config = Self::default();
        let mut visited: alloc::collections::BTreeSet<PathBuf> =
            alloc::collections::BTreeSet::new();
        let mut queue: VecDeque<(PathBuf, usize)> = VecDeque::new();
        queue.push_back((root.to_path_buf(), 0));

        while let Some((path, depth)) = queue.pop_front() {
            if depth > MAX_INCLUDE_DEPTH {
                continue;
            }
            let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
            if !visited.insert(identity) {
                continue;
            }
            let Ok(metadata) = std::fs::metadata(&path) else {
                continue;
            };

            if metadata.is_dir() {
                // The directory's files come next, before anything queued
                // after the include that named the directory.
                let mut entries: Vec<PathBuf> = std::fs::read_dir(&path)
                    .ok()?
                    .filter_map(|entry| entry.ok().map(|e| e.path()))
                    .filter(|p| std::fs::metadata(p).map(|m| m.is_file()).unwrap_or(false))
                    .filter(|p| {
                        p.file_name().map(|n| n.to_string_lossy()).is_some_and(|n| {
                            n.starts_with(|c: char| c.is_ascii_digit()) && n.ends_with(".conf")
                        })
                    })
                    .collect();
                entries.sort();
                for (i, entry) in entries.into_iter().enumerate() {
                    queue.insert(i, (entry, depth));
                }
                continue;
            }
            if !metadata.is_file() {
                continue;
            }

            let Ok(xml) = std::fs::read_to_string(&path) else {
                continue;
            };
            let mut includes: Vec<(Option<String>, PathBuf)> = Vec::new();
            let mut dirs: Vec<(Option<String>, String)> = Vec::new();
            if ParseFontsConf(&xml, &mut includes, &mut dirs).is_none() {
                continue;
            }
            ParseFontsConfRenderConfig(&xml, &mut config.render_configs);
            ParseFontsConfAliases(&xml, &mut config.aliases);
            config.files.push(path.clone());

            let here = path.parent().map(|d| d.to_path_buf()).unwrap_or_default();
            for (prefix, dir) in dirs {
                let resolved = match prefix.as_deref() {
                    Some("relative") => Some(here.join(dir)),
                    _ => process_path(&prefix, PathBuf::from(dir), false),
                };
                if let Some(dir) = resolved {
                    if !config.font_dirs.contains(&dir) {
                        config.font_dirs.push(dir);
                    }
                }
            }

            // This file's includes come next, in document order, before
            // whatever was queued by the file that included this one.
            let mut position = 0;
            for (prefix, include) in includes {
                let resolved = match prefix.as_deref() {
                    Some("relative") => Some(here.join(include)),
                    Some(_) => process_path(&prefix, include, true),
                    None => process_path(&None, include, true).map(|expanded| {
                        if expanded.is_absolute() {
                            expanded
                        } else {
                            search_dirs
                                .iter()
                                .map(|dir| dir.join(&expanded))
                                .find(|candidate| candidate.exists())
                                .unwrap_or_else(|| {
                                    search_dirs
                                        .last()
                                        .map(|dir| dir.join(&expanded))
                                        .unwrap_or(expanded)
                                })
                        }
                    }),
                };
                if let Some(resolved) = resolved {
                    queue.insert(position, (resolved, depth + 1));
                    position += 1;
                }
            }
        }

        // A root that could not be read (or parsed) yields no files at all.
        if config.files.is_empty() {
            return None;
        }
        Some(config)
    }
}

/// Parse `<alias><family>NAME</family><prefer><family>...</family>...</prefer></alias>`.
#[cfg(all(feature = "std", feature = "parsing"))]
fn ParseFontsConfAliases(input: &str, aliases: &mut BTreeMap<String, Vec<String>>) {
    use xmlparser::Token::*;
    use xmlparser::Tokenizer;

    #[derive(Clone, Copy, PartialEq)]
    enum State {
        Idle,
        InAlias,
        InAliasFamily,
        InPrefer,
        InPreferFamily,
    }

    let mut state = State::Idle;
    let mut alias_key: Option<String> = None;
    let mut preferred: Vec<String> = Vec::new();
    let mut text_buf = String::new();

    for token_result in Tokenizer::from(input) {
        let token = match token_result {
            Ok(token) => token,
            Err(_) => continue,
        };
        match token {
            ElementStart { local, .. } => match local.as_str() {
                "alias" => {
                    state = State::InAlias;
                    alias_key = None;
                    preferred.clear();
                }
                "family" if state == State::InAlias => {
                    state = State::InAliasFamily;
                    text_buf.clear();
                }
                "prefer" if state == State::InAlias => {
                    state = State::InPrefer;
                }
                "family" if state == State::InPrefer => {
                    state = State::InPreferFamily;
                    text_buf.clear();
                }
                _ => {}
            },
            Text { text } => {
                if state == State::InAliasFamily || state == State::InPreferFamily {
                    text_buf.push_str(text.as_str());
                }
            }
            ElementEnd { end, .. } => {
                use xmlparser::ElementEnd;
                let closed = match end {
                    ElementEnd::Close(_, local) => Some(local.as_str().to_owned()),
                    _ => None,
                };
                let Some(closed) = closed else { continue };
                match closed.as_str() {
                    "family" => match state {
                        State::InAliasFamily => {
                            let t = text_buf.trim();
                            if !t.is_empty() && alias_key.is_none() {
                                alias_key = Some(t.to_owned());
                            }
                            state = State::InAlias;
                        }
                        State::InPreferFamily => {
                            let t = text_buf.trim();
                            if !t.is_empty() {
                                preferred.push(t.to_owned());
                            }
                            state = State::InPrefer;
                        }
                        _ => {}
                    },
                    "prefer" if state == State::InPrefer => {
                        state = State::InAlias;
                    }
                    "alias" => {
                        if let Some(key) = alias_key.take() {
                            if !preferred.is_empty() {
                                let norm = crate::utils::normalize_family_name(&key);
                                let entry = aliases.entry(norm).or_default();
                                for fam in preferred.drain(..) {
                                    if !entry.iter().any(|e| e == &fam) {
                                        entry.push(fam);
                                    }
                                }
                            }
                        }
                        state = State::Idle;
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }
}

// Parses the fonts.conf file
#[cfg(all(feature = "std", feature = "parsing"))]
fn ParseFontsConf(
    input: &str,
    paths_to_visit: &mut Vec<(Option<String>, PathBuf)>,
    font_paths: &mut Vec<(Option<String>, String)>,
) -> Option<()> {
    use xmlparser::Token::*;
    use xmlparser::Tokenizer;

    const TAG_INCLUDE: &str = "include";
    const TAG_DIR: &str = "dir";
    const ATTRIBUTE_PREFIX: &str = "prefix";

    let mut current_prefix: Option<&str> = None;
    let mut current_path: Option<&str> = None;
    let mut is_in_include = false;
    let mut is_in_dir = false;

    for token_result in Tokenizer::from(input) {
        let token = match token_result {
            Ok(token) => token,
            Err(_) => return None,
        };

        match token {
            ElementStart { local, .. } => {
                if is_in_include || is_in_dir {
                    return None; /* error: nested tags */
                }

                match local.as_str() {
                    TAG_INCLUDE => {
                        is_in_include = true;
                    }
                    TAG_DIR => {
                        is_in_dir = true;
                    }
                    _ => continue,
                }

                current_path = None;
            }
            Text { text, .. } => {
                let text = text.as_str().trim();
                if text.is_empty() {
                    continue;
                }
                if is_in_include || is_in_dir {
                    current_path = Some(text);
                }
            }
            Attribute { local, value, .. } => {
                if !is_in_include && !is_in_dir {
                    continue;
                }
                // attribute on <include> or <dir> node
                if local.as_str() == ATTRIBUTE_PREFIX {
                    current_prefix = Some(value.as_str());
                }
            }
            ElementEnd { end, .. } => {
                let end_tag = match end {
                    xmlparser::ElementEnd::Close(_, a) => a,
                    _ => continue,
                };

                match end_tag.as_str() {
                    TAG_INCLUDE => {
                        if !is_in_include {
                            continue;
                        }

                        if let Some(current_path) = current_path.as_ref() {
                            paths_to_visit.push((
                                current_prefix.map(ToOwned::to_owned),
                                PathBuf::from(*current_path),
                            ));
                        }
                    }
                    TAG_DIR => {
                        if !is_in_dir {
                            continue;
                        }

                        if let Some(current_path) = current_path.as_ref() {
                            font_paths.push((
                                current_prefix.map(ToOwned::to_owned),
                                (*current_path).to_owned(),
                            ));
                        }
                    }
                    _ => continue,
                }

                is_in_include = false;
                is_in_dir = false;
                current_path = None;
                current_prefix = None;
            }
            _ => {}
        }
    }

    Some(())
}

/// Parses `<match target="font">` blocks from fonts.conf XML and returns.
#[cfg(all(feature = "std", feature = "parsing"))]
fn ParseFontsConfRenderConfig(input: &str, configs: &mut BTreeMap<String, FcFontRenderConfig>) {
    use xmlparser::Token::*;
    use xmlparser::Tokenizer;

    // Parser state machine
    #[derive(Clone, Copy, PartialEq)]
    enum State {
        /// Outside any relevant block.
        Idle,
        /// Inside <match target="font">.
        InMatchFont,
        /// Inside <test name="family"> within a match block.
        InTestFamily,
        /// Inside <edit name="..."> within a match block.
        InEdit,
    }

    let mut state = State::Idle;
    let mut match_is_font_target = false;
    let mut current_family: Option<String> = None;
    let mut current_edit_name: Option<String> = None;
    let mut current_value: Option<String> = None;
    let mut value_tag: Option<String> = None;
    let mut config = FcFontRenderConfig::default();
    let mut in_test = false;
    let mut test_name: Option<String> = None;

    for token_result in Tokenizer::from(input) {
        let token = match token_result {
            Ok(token) => token,
            Err(_) => continue,
        };

        match token {
            ElementStart { local, .. } => {
                let tag = local.as_str();
                match tag {
                    "match" => {
                        // Reset state for a new match block
                        match_is_font_target = false;
                        current_family = None;
                        config = FcFontRenderConfig::default();
                    }
                    "test" if state == State::InMatchFont => {
                        in_test = true;
                        test_name = None;
                    }
                    "edit" if state == State::InMatchFont => {
                        current_edit_name = None;
                    }
                    "bool" | "double" | "const" | "string" | "int" => {
                        if state == State::InTestFamily || state == State::InEdit {
                            value_tag = Some(tag.to_owned());
                            current_value = None;
                        }
                    }
                    _ => {}
                }
            }
            Attribute { local, value, .. } => {
                let attr_name = local.as_str();
                let attr_value = value.as_str();

                match attr_name {
                    "target" => {
                        if attr_value == "font" {
                            match_is_font_target = true;
                        }
                    }
                    "name" => {
                        if in_test && state == State::InMatchFont {
                            test_name = Some(attr_value.to_owned());
                        } else if state == State::InMatchFont {
                            current_edit_name = Some(attr_value.to_owned());
                        }
                    }
                    _ => {}
                }
            }
            Text { text, .. } => {
                let text = text.as_str().trim();
                if !text.is_empty() && (state == State::InTestFamily || state == State::InEdit) {
                    current_value = Some(text.to_owned());
                }
            }
            ElementEnd { end, .. } => {
                match end {
                    xmlparser::ElementEnd::Open => {
                        // Tag just opened (after attributes processed)
                        if match_is_font_target && state == State::Idle {
                            state = State::InMatchFont;
                            match_is_font_target = false;
                        } else if in_test {
                            if test_name.as_deref() == Some("family") {
                                state = State::InTestFamily;
                            }
                            in_test = false;
                        } else if current_edit_name.is_some() && state == State::InMatchFont {
                            state = State::InEdit;
                        }
                    }
                    xmlparser::ElementEnd::Close(_, local) => {
                        let tag = local.as_str();
                        match tag {
                            "match" => {
                                // End of match block: store config if we have a family
                                if let Some(family) = current_family.take() {
                                    let empty = FcFontRenderConfig::default();
                                    if config != empty {
                                        configs.insert(family, config.clone());
                                    }
                                }
                                state = State::Idle;
                                config = FcFontRenderConfig::default();
                            }
                            "test" => {
                                if state == State::InTestFamily {
                                    // Extract the family name from the value we collected
                                    if let Some(ref val) = current_value {
                                        current_family = Some(val.clone());
                                    }
                                    state = State::InMatchFont;
                                }
                                current_value = None;
                                value_tag = None;
                            }
                            "edit" => {
                                if state == State::InEdit {
                                    // Apply the collected value to the config
                                    if let (Some(ref name), Some(ref val)) =
                                        (&current_edit_name, &current_value)
                                    {
                                        apply_edit_value(
                                            &mut config,
                                            name,
                                            val,
                                            value_tag.as_deref(),
                                        );
                                    }
                                    state = State::InMatchFont;
                                }
                                current_edit_name = None;
                                current_value = None;
                                value_tag = None;
                            }
                            "bool" | "double" | "const" | "string" | "int" => {
                                // value_tag and current_value already set by Text handler
                            }
                            _ => {}
                        }
                    }
                    xmlparser::ElementEnd::Empty => {
                        // Self-closing tags: nothing to do
                    }
                }
            }
            _ => {}
        }
    }
}

/// Apply a parsed edit value to the render config.
#[cfg(all(feature = "std", feature = "parsing"))]
fn apply_edit_value(
    config: &mut FcFontRenderConfig,
    edit_name: &str,
    value: &str,
    _value_tag: Option<&str>,
) {
    match edit_name {
        "antialias" => {
            config.antialias = parse_bool_value(value);
        }
        "hinting" => {
            config.hinting = parse_bool_value(value);
        }
        "autohint" => {
            config.autohint = parse_bool_value(value);
        }
        "embeddedbitmap" => {
            config.embeddedbitmap = parse_bool_value(value);
        }
        "embolden" => {
            config.embolden = parse_bool_value(value);
        }
        "minspace" => {
            config.minspace = parse_bool_value(value);
        }
        "hintstyle" => {
            config.hintstyle = parse_hintstyle_const(value);
        }
        "rgba" => {
            config.rgba = parse_rgba_const(value);
        }
        "lcdfilter" => {
            config.lcdfilter = parse_lcdfilter_const(value);
        }
        "dpi" => {
            if let Ok(v) = value.parse::<f64>() {
                config.dpi = Some(v);
            }
        }
        "scale" => {
            if let Ok(v) = value.parse::<f64>() {
                config.scale = Some(v);
            }
        }
        _ => {
            // Unknown edit property, ignore
        }
    }
}

#[cfg(all(feature = "std", feature = "parsing"))]
fn parse_bool_value(value: &str) -> Option<bool> {
    match value {
        "true" => Some(true),
        "false" => Some(false),
        _ => None,
    }
}

#[cfg(all(feature = "std", feature = "parsing"))]
fn parse_hintstyle_const(value: &str) -> Option<FcHintStyle> {
    match value {
        "hintnone" => Some(FcHintStyle::None),
        "hintslight" => Some(FcHintStyle::Slight),
        "hintmedium" => Some(FcHintStyle::Medium),
        "hintfull" => Some(FcHintStyle::Full),
        _ => None,
    }
}

#[cfg(all(feature = "std", feature = "parsing"))]
fn parse_rgba_const(value: &str) -> Option<FcRgba> {
    match value {
        "unknown" => Some(FcRgba::Unknown),
        "rgb" => Some(FcRgba::Rgb),
        "bgr" => Some(FcRgba::Bgr),
        "vrgb" => Some(FcRgba::Vrgb),
        "vbgr" => Some(FcRgba::Vbgr),
        "none" => Some(FcRgba::None),
        _ => None,
    }
}

#[cfg(all(feature = "std", feature = "parsing"))]
fn parse_lcdfilter_const(value: &str) -> Option<FcLcdFilter> {
    match value {
        "lcdnone" => Some(FcLcdFilter::None),
        "lcddefault" => Some(FcLcdFilter::Default),
        "lcdlight" => Some(FcLcdFilter::Light),
        "lcdlegacy" => Some(FcLcdFilter::Legacy),
        _ => None,
    }
}

/// Intermediate parsed data from a single font face within a font file.
#[cfg(all(feature = "std", feature = "parsing"))]
struct ParsedFontFace {
    pattern: FcPattern,
    font_index: usize,
}

/// Parse all font table data from a single font face and return the extracted patterns.
#[cfg(all(feature = "std", feature = "parsing"))]
fn parse_font_faces(font_bytes: &[u8]) -> Option<Vec<ParsedFontFace>> {
    use allsorts::{
        binary::read::ReadScope,
        font_data::FontData,
        get_name::fontcode_get_name,
        post::PostTable,
        tables::{os2::Os2, HeadTable, NameTable},
        tag,
    };
    use std::collections::BTreeSet;

    const FONT_SPECIFIER_NAME_ID: u16 = 4;
    const FONT_SPECIFIER_FAMILY_ID: u16 = 1;

    let max_fonts = if font_bytes.len() >= 12 && &font_bytes[0..4] == b"ttcf" {
        // Read numFonts from TTC header (offset 8, 4 bytes)
        let num_fonts =
            u32::from_be_bytes([font_bytes[8], font_bytes[9], font_bytes[10], font_bytes[11]]);
        // Cap at a reasonable maximum as a safety measure
        std::cmp::min(num_fonts as usize, 100)
    } else {
        // Not a collection, just one font
        1
    };

    let scope = ReadScope::new(font_bytes);
    let font_file = scope.read::<FontData<'_>>().ok()?;

    // Handle collections properly by iterating through all fonts
    let mut results = Vec::new();

    for font_index in 0..max_fonts {
        let provider = font_file.table_provider(font_index).ok()?;
        let head_data = provider.table_data(tag::HEAD).ok()??.into_owned();
        let head_table = ReadScope::new(&head_data).read::<HeadTable>().ok()?;

        let is_bold = head_table.is_bold();
        let is_italic = head_table.is_italic();
        let mut detected_monospace = None;

        let post_data = provider.table_data(tag::POST).ok()??;
        if let Ok(post_table) = ReadScope::new(&post_data).read::<PostTable>() {
            // isFixedPitch here - https://learn.microsoft.com/en-us/typography/opentype/spec/post#header
            detected_monospace = Some(post_table.header.is_fixed_pitch != 0);
        }

        // OS/2 table is optional; get properties if present.
        let os2_data = provider.table_data(tag::OS_2).ok().flatten();
        let os2_table = os2_data
            .as_deref()
            .and_then(|data| ReadScope::new(data).read_dep::<Os2>(data.len()).ok());

        // Extract additional style information
        let is_oblique = os2_table.as_ref().is_some_and(|os2| {
            os2.fs_selection
                .contains(allsorts::tables::os2::FsSelectionFlag::OBLIQUE)
        });
        // Without OS/2 the only weight signal is the `head.macStyle` bold bit, so
        // the face lands on Bold or Normal rather than a precise class.
        let weight = os2_table.as_ref().map_or(
            if is_bold {
                FcWeight::Bold
            } else {
                FcWeight::Normal
            },
            |os2| FcWeight::from_u16(os2.us_weight_class),
        );
        let stretch = os2_table.as_ref().map_or(FcStretch::Normal, |os2| {
            FcStretch::from_u16(os2.us_width_class)
        });

        // Coverage comes from the cmap and nothing else: every codepoint the
        // face maps to a real glyph, exactly. See `cmap_coverage`.
        let unicode_ranges = cmap_coverage(&provider).unwrap_or_default();

        // Use the shared detect_monospace helper for PANOSE + hmtx fallback
        let is_monospace =
            detect_monospace(&provider, os2_table.as_ref(), detected_monospace).unwrap_or(false);

        let name_data = provider.table_data(tag::NAME).ok()??.into_owned();
        let name_table = ReadScope::new(&name_data).read::<NameTable>().ok()?;

        // Extract metadata from name table
        let mut metadata = FcFontMetadata::default();

        const NAME_ID_COPYRIGHT: u16 = 0;
        const NAME_ID_FAMILY: u16 = 1;
        const NAME_ID_SUBFAMILY: u16 = 2;
        const NAME_ID_UNIQUE_ID: u16 = 3;
        const NAME_ID_FULL_NAME: u16 = 4;
        const NAME_ID_VERSION: u16 = 5;
        const NAME_ID_POSTSCRIPT_NAME: u16 = 6;
        const NAME_ID_TRADEMARK: u16 = 7;
        const NAME_ID_MANUFACTURER: u16 = 8;
        const NAME_ID_DESIGNER: u16 = 9;
        const NAME_ID_DESCRIPTION: u16 = 10;
        const NAME_ID_VENDOR_URL: u16 = 11;
        const NAME_ID_DESIGNER_URL: u16 = 12;
        const NAME_ID_LICENSE: u16 = 13;
        const NAME_ID_LICENSE_URL: u16 = 14;
        const NAME_ID_PREFERRED_FAMILY: u16 = 16;
        const NAME_ID_PREFERRED_SUBFAMILY: u16 = 17;

        metadata.copyright = get_name_string(&name_data, NAME_ID_COPYRIGHT);
        metadata.font_family = get_name_string(&name_data, NAME_ID_FAMILY);
        metadata.font_subfamily = get_name_string(&name_data, NAME_ID_SUBFAMILY);
        metadata.full_name = get_name_string(&name_data, NAME_ID_FULL_NAME);
        metadata.unique_id = get_name_string(&name_data, NAME_ID_UNIQUE_ID);
        metadata.version = get_name_string(&name_data, NAME_ID_VERSION);
        metadata.postscript_name = get_name_string(&name_data, NAME_ID_POSTSCRIPT_NAME);
        metadata.trademark = get_name_string(&name_data, NAME_ID_TRADEMARK);
        metadata.manufacturer = get_name_string(&name_data, NAME_ID_MANUFACTURER);
        metadata.designer = get_name_string(&name_data, NAME_ID_DESIGNER);
        metadata.id_description = get_name_string(&name_data, NAME_ID_DESCRIPTION);
        metadata.designer_url = get_name_string(&name_data, NAME_ID_DESIGNER_URL);
        metadata.manufacturer_url = get_name_string(&name_data, NAME_ID_VENDOR_URL);
        metadata.license = get_name_string(&name_data, NAME_ID_LICENSE);
        metadata.license_url = get_name_string(&name_data, NAME_ID_LICENSE_URL);
        metadata.preferred_family = get_name_string(&name_data, NAME_ID_PREFERRED_FAMILY);
        metadata.preferred_subfamily = get_name_string(&name_data, NAME_ID_PREFERRED_SUBFAMILY);

        // One font can support multiple patterns
        let mut f_family = None;

        let patterns = name_table
            .name_records
            .iter()
            .filter_map(|name_record| {
                let name_id = name_record.name_id;
                if name_id == FONT_SPECIFIER_FAMILY_ID {
                    if let Ok(Some(family)) =
                        fontcode_get_name(&name_data, FONT_SPECIFIER_FAMILY_ID)
                    {
                        f_family = Some(family);
                    }
                    None
                } else if name_id == FONT_SPECIFIER_NAME_ID {
                    let family = f_family.as_ref()?;
                    let name = fontcode_get_name(&name_data, FONT_SPECIFIER_NAME_ID).ok()??;
                    if name.to_bytes().is_empty() {
                        None
                    } else {
                        let mut name_str = String::from_utf8_lossy(name.to_bytes()).to_string();
                        let mut family_str = String::from_utf8_lossy(family.as_bytes()).to_string();
                        if name_str.starts_with('.') {
                            name_str = name_str[1..].to_string();
                        }
                        if family_str.starts_with('.') {
                            family_str = family_str[1..].to_string();
                        }
                        Some((
                            FcPattern {
                                name: Some(name_str),
                                family: Some(family_str),
                                bold: if is_bold {
                                    PatternMatch::True
                                } else {
                                    PatternMatch::False
                                },
                                italic: if is_italic {
                                    PatternMatch::True
                                } else {
                                    PatternMatch::False
                                },
                                oblique: if is_oblique {
                                    PatternMatch::True
                                } else {
                                    PatternMatch::False
                                },
                                monospace: if is_monospace {
                                    PatternMatch::True
                                } else {
                                    PatternMatch::False
                                },
                                condensed: if stretch <= FcStretch::Condensed {
                                    PatternMatch::True
                                } else {
                                    PatternMatch::False
                                },
                                weight,
                                stretch,
                                unicode_ranges: unicode_ranges.clone(),
                                metadata: metadata.clone(),
                                render_config: FcFontRenderConfig::default(),
                            },
                            font_index,
                        ))
                    }
                } else {
                    None
                }
            })
            .collect::<BTreeSet<_>>();

        results.extend(patterns.into_iter().map(|(pat, idx)| ParsedFontFace {
            pattern: pat,
            font_index: idx,
        }));
    }

    if results.is_empty() {
        None
    } else {
        Some(results)
    }
}

// Remaining implementation for font scanning, parsing, etc.
#[cfg(all(feature = "std", feature = "parsing"))]
pub(crate) fn FcParseFont(filepath: &PathBuf) -> Option<Vec<(FcPattern, FcFontPath)>> {
    #[cfg(all(not(target_family = "wasm"), feature = "std"))]
    use mmapio::MmapOptions;
    use std::fs::File;

    // Try parsing the font file and see if the postscript name matches
    let file = File::open(filepath).ok()?;

    #[cfg(all(not(target_family = "wasm"), feature = "std"))]
    let font_bytes = unsafe { MmapOptions::new().map(&file).ok()? };

    #[cfg(not(all(not(target_family = "wasm"), feature = "std")))]
    let font_bytes = std::fs::read(filepath).ok()?;

    let faces = parse_font_faces(&font_bytes[..])?;
    let path_str = filepath.to_string_lossy().to_string();
    // Hash once per file using cheap sampled hash to avoid full file page-fault.
    let bytes_hash = crate::utils::content_dedup_hash_u64(&font_bytes[..]);

    Some(
        faces
            .into_iter()
            .map(|face| {
                (
                    face.pattern,
                    FcFontPath {
                        path: path_str.clone(),
                        font_index: face.font_index,
                        bytes_hash,
                    },
                )
            })
            .collect(),
    )
}

/// Coverage info returned by a fast-probe parse.
#[cfg(all(feature = "std", feature = "parsing"))]
#[derive(Debug, Clone)]
pub struct FastCoverage {
    /// Metadata pattern with `unicode_ranges` populated from the.
    pub pattern: FcPattern,
    /// Subset of the input codepoints that this face covers (maps.
    pub covered: alloc::collections::BTreeSet<char>,
    /// `head.macStyle.bold` (bit 0).
    pub is_bold: bool,
    /// `head.macStyle.italic` (bit 1).
    pub is_italic: bool,
}

/// Fast per-face coverage probe.
#[cfg(all(feature = "std", feature = "parsing"))]
#[allow(non_snake_case)]
pub fn FcParseFontFaceFast(
    font_bytes: &[u8],
    font_index: usize,
    codepoints: &alloc::collections::BTreeSet<char>,
) -> Option<FastCoverage> {
    use allsorts::{
        binary::read::ReadScope,
        font_data::FontData,
        tables::{
            cmap::{Cmap, CmapSubtable},
            FontTableProvider, HeadTable,
        },
        tag,
    };

    let scope = ReadScope::new(font_bytes);
    let font_file = scope.read::<FontData<'_>>().ok()?;
    let provider = font_file.table_provider(font_index).ok()?;

    // head — 54 bytes, macStyle at offset 44. Cheap.
    let head_data = provider.table_data(tag::HEAD).ok()??;
    let head_table = ReadScope::new(&head_data).read::<HeadTable>().ok()?;
    let is_bold = head_table.is_bold();
    let is_italic = head_table.is_italic();

    // cmap — find the best Unicode subtable, probe each codepoint.
    // The mmap page-cache only faults in the bytes we touch.
    let cmap_data = provider.table_data(tag::CMAP).ok()??;
    let cmap = ReadScope::new(&cmap_data).read::<Cmap<'_>>().ok()?;
    let encoding_record = find_best_cmap_subtable(&cmap)?;
    let cmap_subtable = ReadScope::new(&cmap_data)
        .offset(encoding_record.offset as usize)
        .read::<CmapSubtable<'_>>()
        .ok()?;

    let mut covered: alloc::collections::BTreeSet<char> = alloc::collections::BTreeSet::new();
    for ch in codepoints {
        if matches!(cmap_subtable.map_glyph(*ch as u32), Ok(Some(gid)) if gid != 0) {
            covered.insert(*ch);
        }
    }
    // Full coverage from subtable segments, matching scan path storage.
    let covered_ranges =
        coverage_from_subtable(&cmap_subtable, &cmap_data, encoding_record.offset as usize)
            .unwrap_or_default();

    let weight = if is_bold {
        FcWeight::Bold
    } else {
        FcWeight::Normal
    };
    let italic_match = if is_italic {
        PatternMatch::True
    } else {
        PatternMatch::False
    };

    let pattern = FcPattern {
        name: None,
        family: None,
        weight,
        italic: italic_match,
        oblique: PatternMatch::DontCare,
        monospace: PatternMatch::DontCare,
        unicode_ranges: covered_ranges,
        ..Default::default()
    };

    Some(FastCoverage {
        pattern,
        covered,
        is_bold,
        is_italic,
    })
}

/// Count the number of faces inside a TTC, or `1` for a single-face.
#[cfg(all(feature = "std", feature = "parsing"))]
#[allow(non_snake_case)]
pub fn FcCountFontFaces(font_bytes: &[u8]) -> usize {
    if font_bytes.len() >= 12 && &font_bytes[0..4] == b"ttcf" {
        let num_fonts =
            u32::from_be_bytes([font_bytes[8], font_bytes[9], font_bytes[10], font_bytes[11]]);
        // Same cap as parse_font_faces, for safety.
        std::cmp::min(num_fonts as usize, 100).max(1)
    } else {
        1
    }
}

/// Parse font bytes and extract font patterns for in-memory fonts.
#[cfg(all(feature = "std", feature = "parsing"))]
#[allow(non_snake_case)]
pub fn FcParseFontBytes(font_bytes: &[u8], font_id: &str) -> Option<Vec<(FcPattern, FcFont)>> {
    FcParseFontBytesInner(font_bytes, font_id)
}

/// Internal implementation for parsing font bytes.
#[cfg(all(feature = "std", feature = "parsing"))]
fn FcParseFontBytesInner(font_bytes: &[u8], font_id: &str) -> Option<Vec<(FcPattern, FcFont)>> {
    let faces = parse_font_faces(font_bytes)?;
    let id = font_id.to_string();
    let bytes = font_bytes.to_vec();

    Some(
        faces
            .into_iter()
            .map(|face| {
                (
                    face.pattern,
                    FcFont {
                        bytes: bytes.clone(),
                        font_index: face.font_index,
                        id: id.clone(),
                    },
                )
            })
            .collect(),
    )
}

#[cfg(all(feature = "std", feature = "parsing"))]
fn FcScanDirectoriesInner(paths: &[(Option<String>, String)]) -> Vec<(FcPattern, FcFontPath)> {
    #[cfg(all(feature = "multithreading", not(target_family = "wasm")))]
    {
        use rayon::prelude::*;

        // scan directories in parallel
        paths
            .par_iter()
            .filter_map(|(prefix, p)| {
                process_path(prefix, PathBuf::from(p), false).map(FcScanSingleDirectoryRecursive)
            })
            .flatten()
            .collect()
    }
    // wasm has no rayon (it's target-gated off), so even with `multithreading`
    // enabled wasm falls back to the sequential path.
    #[cfg(not(all(feature = "multithreading", not(target_family = "wasm"))))]
    {
        paths
            .iter()
            .filter_map(|(prefix, p)| {
                process_path(prefix, PathBuf::from(p), false).map(FcScanSingleDirectoryRecursive)
            })
            .flatten()
            .collect()
    }
}

/// Font files under `dir`: see [`crate::utils::collect_font_files`] (cycle-safe,.
#[cfg(feature = "std")]
#[allow(non_snake_case)]
fn FcCollectFontFilesRecursive(dir: PathBuf) -> Vec<PathBuf> {
    crate::utils::collect_font_files(&dir)
}

#[cfg(all(feature = "std", feature = "parsing"))]
fn FcScanSingleDirectoryRecursive(dir: PathBuf) -> Vec<(FcPattern, FcFontPath)> {
    let files = FcCollectFontFilesRecursive(dir);
    FcParseFontFiles(&files)
}

#[cfg(all(feature = "std", feature = "parsing"))]
fn FcParseFontFiles(files_to_parse: &[PathBuf]) -> Vec<(FcPattern, FcFontPath)> {
    let result = {
        #[cfg(all(feature = "multithreading", not(target_family = "wasm")))]
        {
            use rayon::prelude::*;

            files_to_parse
                .par_iter()
                .filter_map(|file| FcParseFont(file))
                .collect::<Vec<Vec<_>>>()
        }
        #[cfg(not(all(feature = "multithreading", not(target_family = "wasm"))))]
        {
            files_to_parse
                .iter()
                .filter_map(|file| FcParseFont(file))
                .collect::<Vec<Vec<_>>>()
        }
    };

    result.into_iter().flat_map(|f| f.into_iter()).collect()
}

#[cfg(all(feature = "std", feature = "parsing"))]
/// Takes a path & prefix and resolves them to a usable path, or `None` if they're unsupported/unavailable.
fn process_path(
    prefix: &Option<String>,
    mut path: PathBuf,
    is_include_path: bool,
) -> Option<PathBuf> {
    use std::env::var;

    const HOME_SHORTCUT: &str = "~";
    const CWD_PATH: &str = ".";

    const HOME_ENV_VAR: &str = "HOME";
    const XDG_CONFIG_HOME_ENV_VAR: &str = "XDG_CONFIG_HOME";
    const XDG_CONFIG_HOME_DEFAULT_PATH_SUFFIX: &str = ".config";
    const XDG_DATA_HOME_ENV_VAR: &str = "XDG_DATA_HOME";
    const XDG_DATA_HOME_DEFAULT_PATH_SUFFIX: &str = ".local/share";

    const PREFIX_CWD: &str = "cwd";
    const PREFIX_DEFAULT: &str = "default";
    const PREFIX_XDG: &str = "xdg";

    // These three could, in theory, be cached, but the work required to do so outweighs the minor benefits
    fn get_home_value() -> Option<PathBuf> {
        var(HOME_ENV_VAR).ok().map(PathBuf::from)
    }
    fn get_xdg_config_home_value() -> Option<PathBuf> {
        var(XDG_CONFIG_HOME_ENV_VAR)
            .ok()
            .map(PathBuf::from)
            .or_else(|| {
                get_home_value()
                    .map(|home_path| home_path.join(XDG_CONFIG_HOME_DEFAULT_PATH_SUFFIX))
            })
    }
    fn get_xdg_data_home_value() -> Option<PathBuf> {
        var(XDG_DATA_HOME_ENV_VAR)
            .ok()
            .map(PathBuf::from)
            .or_else(|| {
                get_home_value().map(|home_path| home_path.join(XDG_DATA_HOME_DEFAULT_PATH_SUFFIX))
            })
    }

    // Resolve the tilde character in the path, if present
    if path.starts_with(HOME_SHORTCUT) {
        if let Some(home_path) = get_home_value() {
            path = home_path.join(
                path.strip_prefix(HOME_SHORTCUT)
                    .expect("already checked that it starts with the prefix"),
            );
        } else {
            return None;
        }
    }

    // Resolve prefix values
    match prefix {
        Some(prefix) => match prefix.as_str() {
            PREFIX_CWD | PREFIX_DEFAULT => {
                let mut new_path = PathBuf::from(CWD_PATH);
                new_path.push(path);

                Some(new_path)
            }
            PREFIX_XDG => {
                if is_include_path {
                    get_xdg_config_home_value()
                        .map(|xdg_config_home_path| xdg_config_home_path.join(path))
                } else {
                    get_xdg_data_home_value()
                        .map(|xdg_data_home_path| xdg_data_home_path.join(path))
                }
            }
            _ => None, // Unsupported prefix
        },
        None => Some(path),
    }
}

// Helper function to extract a string from the name table
#[cfg(all(feature = "std", feature = "parsing"))]
fn get_name_string(name_data: &[u8], name_id: u16) -> Option<String> {
    fontcode_get_name(name_data, name_id)
        .ok()
        .flatten()
        .map(|name| String::from_utf8_lossy(name.to_bytes()).to_string())
}

/// Find the best Unicode CMAP subtable from a font provider.
#[cfg(all(feature = "std", feature = "parsing"))]
fn find_best_cmap_subtable<'a>(
    cmap: &allsorts::tables::cmap::Cmap<'a>,
) -> Option<allsorts::tables::cmap::EncodingRecord> {
    use allsorts::tables::cmap::{EncodingId, PlatformId};

    // Full-repertoire subtables first, BMP-only ones after.
    cmap.find_subtable(PlatformId::UNICODE, EncodingId(4))
        .or_else(|| cmap.find_subtable(PlatformId::WINDOWS, EncodingId(10)))
        .or_else(|| cmap.find_subtable(PlatformId::UNICODE, EncodingId(3)))
        .or_else(|| cmap.find_subtable(PlatformId::WINDOWS, EncodingId(1)))
        .or_else(|| cmap.find_subtable(PlatformId::UNICODE, EncodingId(0)))
        .or_else(|| cmap.find_subtable(PlatformId::UNICODE, EncodingId(1)))
}

/// Exact coverage of a font face: every codepoint its best Unicode cmap.
#[cfg(all(feature = "std", feature = "parsing"))]
fn cmap_coverage(provider: &impl FontTableProvider) -> Option<Vec<UnicodeRange>> {
    use allsorts::binary::read::ReadScope;
    use allsorts::tables::cmap::{Cmap, CmapSubtable};

    let cmap_data = provider.table_data(tag::CMAP).ok()??;
    let cmap = ReadScope::new(&cmap_data).read::<Cmap<'_>>().ok()?;
    let record = find_best_cmap_subtable(&cmap)?;
    let subtable = ReadScope::new(&cmap_data)
        .offset(record.offset as usize)
        .read::<CmapSubtable<'_>>()
        .ok()?;
    coverage_from_subtable(&subtable, &cmap_data, record.offset as usize)
}

/// See [`cmap_coverage`].
#[cfg(all(feature = "std", feature = "parsing"))]
fn coverage_from_subtable(
    subtable: &allsorts::tables::cmap::CmapSubtable<'_>,
    cmap_data: &[u8],
    offset: usize,
) -> Option<Vec<UnicodeRange>> {
    use allsorts::tables::cmap::CmapSubtable;

    let mut ranges: Vec<UnicodeRange> = Vec::new();
    let mut push = |start: u32, end: u32| {
        if start > end {
            return;
        }
        match ranges.last_mut() {
            Some(last) if start <= last.end.saturating_add(1) => last.end = last.end.max(end),
            _ => ranges.push(UnicodeRange { start, end }),
        }
    };

    match subtable {
        CmapSubtable::Format4(f4) => {
            let seg_count = f4.start_codes.len();
            let glyph_ids: Vec<u16> = f4.glyph_id_array.iter().collect();
            let segments = f4
                .start_codes
                .iter()
                .zip(f4.end_codes.iter())
                .zip(f4.id_deltas.iter())
                .zip(f4.id_range_offsets.iter())
                .enumerate();
            for (i, (((start, end), delta), range_offset)) in segments {
                if start == 0xFFFF {
                    continue; // the mandatory terminal segment
                }
                let (start, end) = (start as u32, end as u32);
                if range_offset == 0 {
                    // gid = code + delta (mod 2^16): exactly one code of the
                    // segment can land on glyph 0.
                    let zero_code = (delta as u16).wrapping_neg() as u32;
                    if zero_code >= start && zero_code <= end {
                        if zero_code > start {
                            push(start, zero_code - 1);
                        }
                        if zero_code < end {
                            push(zero_code + 1, end);
                        }
                    } else {
                        push(start, end);
                    }
                } else {
                    // glyphIdArray-indexed segment (OpenType cmap format 4).
                    let base = (range_offset as usize / 2).wrapping_sub(seg_count - i);
                    for code in start..=end {
                        let index = base.wrapping_add((code - start) as usize);
                        let Some(&value) = glyph_ids.get(index) else {
                            continue;
                        };
                        if value != 0 && value.wrapping_add(delta as u16) != 0 {
                            push(code, code);
                        }
                    }
                }
            }
        }
        CmapSubtable::Format12 { .. } => {
            for (start, end, start_gid) in format12_groups(cmap_data, offset)? {
                // gid = start_gid + (code - start): only the first code of a
                // group that starts at glyph 0 maps to .notdef.
                let first = if start_gid == 0 {
                    start.saturating_add(1)
                } else {
                    start
                };
                push(first, end.min(0x10FFFF));
            }
        }
        CmapSubtable::Format0 { glyph_id_array, .. } => {
            for (code, gid) in glyph_id_array.iter().enumerate() {
                if gid != 0 {
                    push(code as u32, code as u32);
                }
            }
        }
        CmapSubtable::Format6 {
            first_code,
            glyph_id_array,
            ..
        } => {
            for (i, gid) in glyph_id_array.iter().enumerate() {
                if gid != 0 {
                    let code = *first_code as u32 + i as u32;
                    push(code, code);
                }
            }
        }
        CmapSubtable::Format10 {
            start_char_code,
            glyph_id_array,
            ..
        } => {
            for (i, gid) in glyph_id_array.iter().enumerate() {
                if gid != 0 {
                    let code = *start_char_code + i as u32;
                    push(code, code);
                }
            }
        }
        CmapSubtable::Format2 { .. } => {
            // Legacy mixed 8/16-bit CJK encodings — never a Unicode subtable,
            // but if it is all the font has, enumerate it.
            let mut codes: Vec<u32> = Vec::new();
            subtable
                .mappings_fn(|code, gid| {
                    if gid != 0 {
                        codes.push(code);
                    }
                })
                .ok()?;
            codes.sort_unstable();
            for code in codes {
                push(code, code);
            }
        }
    }

    if ranges.is_empty() {
        None
    } else {
        Some(FcFontCache::normalize_unicode_ranges(ranges))
    }
}

/// The `(startCharCode, endCharCode, startGlyphID)` groups of the format-12.
#[cfg(all(feature = "std", feature = "parsing"))]
fn format12_groups(cmap_data: &[u8], offset: usize) -> Option<Vec<(u32, u32, u32)>> {
    let table = cmap_data.get(offset..)?;
    let u16_at = |at: usize| {
        table
            .get(at..at + 2)
            .map(|b| u16::from_be_bytes([b[0], b[1]]))
    };
    let u32_at = |at: usize| {
        table
            .get(at..at + 4)
            .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
    };
    if u16_at(0)? != 12 {
        return None;
    }
    let num_groups = u32_at(12)? as usize;
    let mut groups = Vec::with_capacity(num_groups.min(1 << 16));
    for i in 0..num_groups {
        let at = 16 + i * 12;
        groups.push((u32_at(at)?, u32_at(at + 4)?, u32_at(at + 8)?));
    }
    Some(groups)
}

// Helper function to detect if a font is monospace
#[cfg(all(feature = "std", feature = "parsing"))]
fn detect_monospace(
    provider: &impl FontTableProvider,
    os2_table: Option<&Os2>,
    detected_monospace: Option<bool>,
) -> Option<bool> {
    if let Some(is_monospace) = detected_monospace {
        return Some(is_monospace);
    }

    // Try using PANOSE classification, when there is an OS/2 table to read it
    // from; otherwise fall straight through to the hmtx width check.
    if let Some(os2_table) = os2_table {
        if os2_table.panose[0] == 2 {
            // 2 = Latin Text
            return Some(os2_table.panose[3] == 9); // 9 = Monospaced
        }
    }

    // Check glyph widths in hmtx table
    let hhea_data = provider.table_data(tag::HHEA).ok()??;
    let hhea_table = ReadScope::new(&hhea_data).read::<HheaTable>().ok()?;
    let maxp_data = provider.table_data(tag::MAXP).ok()??;
    let maxp_table = ReadScope::new(&maxp_data).read::<MaxpTable>().ok()?;
    let hmtx_data = provider.table_data(tag::HMTX).ok()??;
    let hmtx_table = ReadScope::new(&hmtx_data)
        .read_dep::<HmtxTable<'_>>((
            usize::from(maxp_table.num_glyphs),
            usize::from(hhea_table.num_h_metrics),
        ))
        .ok()?;

    let mut monospace = true;
    let mut last_advance = 0;

    // Check if all advance widths are the same
    for i in 0..hhea_table.num_h_metrics as usize {
        let advance = hmtx_table.h_metrics.read_item(i).ok()?.advance_width;
        if i > 0 && advance != last_advance {
            monospace = false;
            break;
        }
        last_advance = advance;
    }

    Some(monospace)
}

/// Guess font metadata from a filename using the existing tokenizer.
#[cfg(all(feature = "std", not(feature = "parsing")))]
fn pattern_from_filename(path: &std::path::Path) -> Option<FcPattern> {
    let ext = path.extension()?.to_str()?.to_ascii_lowercase();
    match ext.as_str() {
        "ttf" | "otf" | "ttc" | "woff" | "woff2" => {}
        _ => return None,
    }

    let stem = path.file_stem()?.to_str()?;
    let all_tokens = crate::config::tokenize_lowercase(stem);

    // Style detection: check if any token matches a known style keyword
    let has_token = |kw: &str| all_tokens.iter().any(|t| t == kw);
    let is_bold = has_token("bold") || has_token("heavy");
    let is_italic = has_token("italic");
    let is_oblique = has_token("oblique");
    let is_mono = has_token("mono") || has_token("monospace");
    let is_condensed = has_token("condensed");

    // Family = non-style tokens joined
    let family_tokens = crate::config::tokenize_font_stem(stem);
    if family_tokens.is_empty() {
        return None;
    }
    let family = family_tokens.join(" ");

    Some(FcPattern {
        name: Some(stem.to_string()),
        family: Some(family),
        bold: if is_bold {
            PatternMatch::True
        } else {
            PatternMatch::False
        },
        italic: if is_italic {
            PatternMatch::True
        } else {
            PatternMatch::False
        },
        oblique: if is_oblique {
            PatternMatch::True
        } else {
            PatternMatch::DontCare
        },
        monospace: if is_mono {
            PatternMatch::True
        } else {
            PatternMatch::DontCare
        },
        condensed: if is_condensed {
            PatternMatch::True
        } else {
            PatternMatch::DontCare
        },
        weight: if is_bold {
            FcWeight::Bold
        } else {
            FcWeight::Normal
        },
        stretch: if is_condensed {
            FcStretch::Condensed
        } else {
            FcStretch::Normal
        },
        unicode_ranges: Vec::new(),
        metadata: FcFontMetadata::default(),
        render_config: FcFontRenderConfig::default(),
    })
}

#[cfg(all(test, feature = "std", feature = "parsing"))]
mod system_alias_tests {
    use super::*;

    const SAMPLE: &str = r#"<?xml version="1.0"?>
<fontconfig>
  <alias>
    <family>sans-serif</family>
    <prefer>
      <family>Noto Sans</family>
      <family>DejaVu Sans</family>
    </prefer>
  </alias>
  <alias>
    <family>Arial</family>
    <prefer><family>Liberation Sans</family></prefer>
  </alias>
  <alias binding="same">
    <family>monospace</family>
    <prefer><family>Noto Sans Mono</family></prefer>
  </alias>
</fontconfig>"#;

    const SECOND_FILE: &str = r#"<fontconfig>
  <alias>
    <family>sans-serif</family>
    <prefer>
      <family>Ubuntu</family>
      <family>Noto Sans</family>
    </prefer>
  </alias>
</fontconfig>"#;

    #[test]
    fn alias_blocks_parse_with_order_and_dedup_across_files() {
        let mut aliases = BTreeMap::new();
        ParseFontsConfAliases(SAMPLE, &mut aliases);
        ParseFontsConfAliases(SECOND_FILE, &mut aliases);
        let key = crate::utils::normalize_family_name("sans-serif");
        assert_eq!(
            aliases.get(&key).map(Vec::as_slice),
            Some(
                &[
                    "Noto Sans".to_string(),
                    "DejaVu Sans".to_string(),
                    "Ubuntu".to_string()
                ][..]
            ),
            "prefer entries append across files in include order, deduplicated"
        );
        assert_eq!(
            aliases.get("arial").map(Vec::as_slice),
            Some(&["Liberation Sans".to_string()][..]),
            "named-family aliases parse too (key normalized)"
        );
        assert_eq!(
            aliases.get("monospace").map(Vec::as_slice),
            Some(&["Noto Sans Mono".to_string()][..]),
            "alias attributes (binding=...) do not confuse the parser"
        );
    }

    #[test]
    fn config_first_expansion_beats_the_builtin_lists() {
        // What `build_inner` does on Linux: the parsed aliases are the
        // authority, the built-in tables only fill what they leave unsaid.
        let mut aliases = BTreeMap::new();
        ParseFontsConfAliases(SAMPLE, &mut aliases);
        let mut config = FcFallbackConfig::default();
        config.absorb_system_aliases(aliases);
        config.merge_defaults(&FcFallbackConfig::os_defaults(OperatingSystem::Linux));

        let cache = FcFontCache::default().with_fallback_config(config);
        let out = cache
            .fallback_config()
            .candidate_families(&["Arial".to_string(), "sans-serif".to_string()], &[]);
        assert_eq!(
            out,
            vec![
                "Arial".to_string(),           // named family keeps itself first
                "Liberation Sans".to_string(), // its configured substitution
                "Noto Sans".to_string(),       // sans-serif configured prefer list
                "DejaVu Sans".to_string(),
            ],
            "configured preferences resolve the stack; no built-in list entries leak in"
        );
    }

    #[test]
    fn generic_family_without_config_falls_back_to_builtin_lists() {
        let mut config = FcFallbackConfig::default();
        config.merge_defaults(&FcFallbackConfig::os_defaults(OperatingSystem::Linux));
        let out = config.candidate_families(&["sans-serif".to_string()], &[]);
        assert!(
            !out.is_empty() && out.iter().any(|f| f == "DejaVu Sans"),
            "no configuration parsed -> the built-in candidates are the last resort: {out:?}"
        );
    }
}

#[cfg(all(test, feature = "std", feature = "parsing"))]
mod coverage_tests {
    use super::*;
    use allsorts::binary::read::ReadScope;
    use allsorts::font_data::FontData;
    use allsorts::tables::cmap::{Cmap, CmapSubtable};
    use allsorts::tables::FontTableProvider;

    const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/InstrumentSerif-Regular.ttf");

    /// Every codepoint up to `max` the face's best subtable maps to a real.
    fn brute_force(bytes: &[u8], face: usize, max: u32) -> Vec<UnicodeRange> {
        let font = ReadScope::new(bytes)
            .read::<FontData<'_>>()
            .expect("font data");
        let provider = font.table_provider(face).expect("face");
        let cmap_data = provider
            .table_data(tag::CMAP)
            .expect("cmap")
            .expect("cmap present");
        let cmap = ReadScope::new(&cmap_data)
            .read::<Cmap<'_>>()
            .expect("cmap header");
        let record = find_best_cmap_subtable(&cmap).expect("a Unicode subtable");
        let subtable = ReadScope::new(&cmap_data)
            .offset(record.offset as usize)
            .read::<CmapSubtable<'_>>()
            .expect("subtable");
        // allsorts' format-12 `map_glyph` is a linear scan over the groups,
        // so enumerate those subtables once instead of probing per codepoint.
        let mut codes: Vec<u32> = Vec::new();
        if matches!(subtable, CmapSubtable::Format12 { .. }) {
            subtable
                .mappings_fn(|cp, gid| {
                    if gid != 0 && cp <= max {
                        codes.push(cp);
                    }
                })
                .expect("format-12 mappings");
            codes.sort_unstable();
            codes.dedup();
        } else {
            for cp in 0..=max {
                if (0xD800..=0xDFFF).contains(&cp) {
                    continue;
                }
                if matches!(subtable.map_glyph(cp), Ok(Some(gid)) if gid != 0) {
                    codes.push(cp);
                }
            }
        }
        let mut out: Vec<UnicodeRange> = Vec::new();
        for cp in codes {
            match out.last_mut() {
                Some(last) if last.end + 1 == cp => last.end = cp,
                _ => out.push(UnicodeRange { start: cp, end: cp }),
            }
        }
        out
    }

    fn clipped(ranges: &[UnicodeRange], max: u32) -> Vec<UnicodeRange> {
        ranges
            .iter()
            .filter(|r| r.start <= max)
            .map(|r| UnicodeRange {
                start: r.start,
                end: r.end.min(max),
            })
            .collect()
    }

    #[test]
    fn format12_groups_are_read_from_the_raw_table() {
        let mut table = Vec::new();
        table.extend_from_slice(&12u16.to_be_bytes()); // format
        table.extend_from_slice(&0u16.to_be_bytes()); // reserved
        table.extend_from_slice(&(16u32 + 2 * 12).to_be_bytes()); // length
        table.extend_from_slice(&0u32.to_be_bytes()); // language
        table.extend_from_slice(&2u32.to_be_bytes()); // numGroups
        for (start, end, gid) in [(0x20u32, 0x7Eu32, 3u32), (0x1F600, 0x1F64F, 200)] {
            table.extend_from_slice(&start.to_be_bytes());
            table.extend_from_slice(&end.to_be_bytes());
            table.extend_from_slice(&gid.to_be_bytes());
        }
        // Embedded at an offset, as inside a real cmap table.
        let mut cmap = vec![0u8; 40];
        cmap.extend_from_slice(&table);

        assert_eq!(
            format12_groups(&cmap, 40),
            Some(vec![(0x20, 0x7E, 3), (0x1F600, 0x1F64F, 200)])
        );
        assert_eq!(
            format12_groups(&cmap, 0),
            None,
            "offset 0 is not a format-12 subtable"
        );
        assert_eq!(
            format12_groups(&cmap[..50], 40),
            None,
            "a truncated table is rejected"
        );
    }

    /// The parsed coverage of the bundled fixture is exactly the set of.
    #[test]
    fn fixture_coverage_equals_the_cmap_exactly() {
        let faces = FcParseFontBytes(FIXTURE, "fixture").expect("the fixture parses");
        let parsed = &faces[0].0.unicode_ranges;
        assert!(!parsed.is_empty());
        assert_eq!(
            *parsed,
            FcFontCache::normalize_unicode_ranges(parsed.clone()),
            "stored coverage is normalized"
        );

        let exact = brute_force(FIXTURE, 0, 0x10FFFF);
        assert_eq!(
            *parsed, exact,
            "segment walk and per-codepoint lookup disagree"
        );

        // Sanity on the shape: a Latin text face, not a block-rounded one.
        assert!(crate::fallback::covers(parsed, 'A' as u32));
        assert!(!crate::fallback::covers(parsed, 0x4E00));
        let latin_ext_a = UnicodeRange {
            start: 0x0100,
            end: 0x017F,
        };
        let overlap = crate::fallback::overlap_size(parsed, &latin_ext_a);
        assert!(
            overlap > 0 && overlap < 128,
            "the fixture covers part of Latin Extended-A ({overlap} of 128); a block-rounded \
             coverage would report all or nothing"
        );
    }

    fn with_best_subtable<R>(
        bytes: &[u8],
        face: usize,
        f: impl FnOnce(&CmapSubtable<'_>, &[u8], usize) -> R,
    ) -> Option<R> {
        let font = ReadScope::new(bytes).read::<FontData<'_>>().ok()?;
        let provider = font.table_provider(face).ok()?;
        let cmap_data = provider.table_data(tag::CMAP).ok()??;
        let cmap = ReadScope::new(&cmap_data).read::<Cmap<'_>>().ok()?;
        let record = find_best_cmap_subtable(&cmap)?;
        let subtable = ReadScope::new(&cmap_data)
            .offset(record.offset as usize)
            .read::<CmapSubtable<'_>>()
            .ok()?;
        Some(f(&subtable, &cmap_data, record.offset as usize))
    }

    /// Every installed face: each parsed range starts and ends on a mapped.
    #[test]
    #[ignore]
    fn every_installed_font_coverage_matches_its_cmap_at_every_boundary() {
        fn walk(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
            let Ok(entries) = std::fs::read_dir(dir) else {
                return;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    walk(&path, out);
                } else if crate::utils::is_font_file(&path) {
                    out.push(path);
                }
            }
        }
        let mut files = Vec::new();
        for dir in crate::config::font_directories(OperatingSystem::current()) {
            walk(&dir, &mut files);
        }
        // Bounded sample to keep tests fast (set RFC_COVERAGE_CHECK_ALL for all files).
        if std::env::var_os("RFC_COVERAGE_CHECK_ALL").is_none() {
            files.truncate(400);
        }
        let surrogate = |cp: u32| (0xD800..=0xDFFF).contains(&cp);
        let (mut faces_checked, mut skipped) = (0usize, 0usize);
        for path in &files {
            let Ok(bytes) = std::fs::read(path) else {
                continue;
            };
            let Some(faces) = FcParseFontBytes(&bytes, &path.to_string_lossy()) else {
                skipped += 1;
                continue;
            };
            let mut seen_faces = alloc::collections::BTreeSet::new();
            for (pattern, font) in &faces {
                if !seen_faces.insert(font.font_index) {
                    continue;
                }
                let where_ = format!("{}#{}", path.display(), font.font_index);
                let checked =
                    with_best_subtable(&bytes, font.font_index, |subtable, cmap_data, offset| {
                        // allsorts' format-12 `map_glyph` scans the groups linearly;
                        // a CJK face has thousands, so look those up by binary search.
                        let groups = match subtable {
                            CmapSubtable::Format12 { .. } => format12_groups(cmap_data, offset),
                            _ => None,
                        };
                        let mapped = |cp: u32| match &groups {
                            Some(groups) => {
                                let i = groups.partition_point(|g| g.1 < cp);
                                groups.get(i).is_some_and(|&(start, end, gid)| {
                                    start <= cp && cp <= end && (gid != 0 || cp != start)
                                })
                            }
                            None => matches!(subtable.map_glyph(cp), Ok(Some(gid)) if gid != 0),
                        };
                        for r in &pattern.unicode_ranges {
                            assert!(
                                mapped(r.start) && mapped(r.end),
                                "{where_}: {r:?} does not end on mapped codepoints"
                            );
                            if r.start > 0 && !surrogate(r.start - 1) {
                                assert!(!mapped(r.start - 1), "{where_}: {r:?} starts late");
                            }
                            if r.end < 0x10FFFF && !surrogate(r.end + 1) {
                                assert!(!mapped(r.end + 1), "{where_}: {r:?} ends early");
                            }
                        }
                    });
                if checked.is_some() {
                    faces_checked += 1;
                }
            }
        }
        println!(
            "checked {faces_checked} faces in {} files ({skipped} unparsable)",
            files.len()
        );
        assert!(faces_checked > 0, "no fonts found to check");
    }
}