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
//! Font parsing, metrics extraction, and subsetting.
//!
//! This module provides the core font infrastructure for text layout and PDF generation:
//! - `loading`: System font cache construction and font reload errors
//! - `mock`: Mock font implementation for testing without real font files
//! - `parsed`: Full font parsing via allsorts (outlines, metrics, shaping tables, subsetting)
#![cfg(feature = "font_loading")]
use azul_css::{AzString, U8Vec};
use rust_fontconfig::{FcFontCache, OwnedFontSource};
pub mod loading {
#![cfg(feature = "std")]
#![cfg(feature = "font_loading")]
#![cfg_attr(not(feature = "std"), no_std)]
use std::io::Error as IoError;
use azul_css::{AzString, StringVec, U8Vec};
use rust_fontconfig::FcFontCache;
#[cfg(not(miri))]
#[must_use] pub fn build_font_cache() -> FcFontCache {
FcFontCache::build()
}
#[cfg(miri)]
pub fn build_font_cache() -> FcFontCache {
FcFontCache::default()
}
#[derive(Debug)]
pub enum FontReloadError {
Io(IoError, AzString),
FontNotFound(AzString),
FontLoadingNotActive(AzString),
}
impl Clone for FontReloadError {
fn clone(&self) -> Self {
use self::FontReloadError::{Io, FontNotFound, FontLoadingNotActive};
match self {
Io(err, path) => Io(IoError::new(err.kind(), "Io Error"), path.clone()),
FontNotFound(id) => FontNotFound(id.clone()),
FontLoadingNotActive(id) => FontLoadingNotActive(id.clone()),
}
}
}
azul_core::impl_display!(FontReloadError, {
Io(err, path_buf) => format!("Could not load \"{}\" - IO error: {}", path_buf.as_str(), err),
FontNotFound(id) => format!("Could not locate system font: \"{:?}\" found", id),
FontLoadingNotActive(id) => format!("Could not load system font: \"{:?}\": crate was not compiled with --features=\"font_loading\"", id)
});
}
pub mod mock {
//! Mock font implementation for testing text layout.
//!
//! Provides a `MockFont` that simulates font behavior without requiring
//! actual font files, useful for unit testing text layout functionality.
use std::collections::BTreeMap;
use crate::text3::cache::LayoutFontMetrics;
/// A mock font implementation for testing text layout without real fonts.
///
/// This allows testing text shaping, layout, and rendering code paths
/// without needing to load actual TrueType/OpenType font files.
#[derive(Debug, Clone)]
pub struct MockFont {
/// Font metrics (ascent, descent, etc.).
pub font_metrics: LayoutFontMetrics,
/// Width of the space character in font units.
pub space_width: Option<usize>,
/// Horizontal advance widths keyed by glyph ID.
pub glyph_advances: BTreeMap<u16, u16>,
/// Glyph bounding box sizes (width, height) keyed by glyph ID.
pub glyph_sizes: BTreeMap<u16, (i32, i32)>,
/// Unicode codepoint to glyph ID mapping.
pub glyph_indices: BTreeMap<u32, u16>,
}
impl MockFont {
/// Creates a new `MockFont` with the given font metrics.
#[must_use] pub const fn new(font_metrics: LayoutFontMetrics) -> Self {
Self {
font_metrics,
space_width: Some(10),
glyph_advances: BTreeMap::new(),
glyph_sizes: BTreeMap::new(),
glyph_indices: BTreeMap::new(),
}
}
/// Sets the space character width.
#[must_use] pub const fn with_space_width(mut self, width: usize) -> Self {
self.space_width = Some(width);
self
}
/// Adds a horizontal advance value for a glyph.
#[must_use] pub fn with_glyph_advance(mut self, glyph_index: u16, advance: u16) -> Self {
self.glyph_advances.insert(glyph_index, advance);
self
}
/// Adds a bounding box size for a glyph.
#[must_use] pub fn with_glyph_size(mut self, glyph_index: u16, size: (i32, i32)) -> Self {
self.glyph_sizes.insert(glyph_index, size);
self
}
/// Adds a Unicode codepoint to glyph ID mapping.
#[must_use] pub fn with_glyph_index(mut self, unicode: u32, index: u16) -> Self {
self.glyph_indices.insert(unicode, index);
self
}
}
}
pub mod parsed {
use core::fmt;
use std::{collections::BTreeMap, sync::Arc};
use allsorts::{
binary::read::ReadScope,
font_data::FontData,
layout::{GDEFTable, LayoutCache, LayoutCacheData, GPOS, GSUB},
outline::{OutlineBuilder, OutlineSink},
pathfinder_geometry::{line_segment::LineSegment2F, vector::Vector2F},
subset::{subset as allsorts_subset, whole_font, CmapTarget, SubsetProfile},
tables::{
cmap::owned::CmapSubtable as OwnedCmapSubtable,
glyf::{
Glyph, GlyfVisitorContext, LocaGlyf, Point,
VariableGlyfContext, VariableGlyfContextStore,
},
kern::owned::KernTable,
FontTableProvider, HheaTable, MaxpTable,
},
tag,
};
use azul_core::resources::{
GlyphOutline, GlyphOutlineOperation, OutlineCubicTo, OutlineLineTo, OutlineMoveTo,
OutlineQuadTo, OwnedGlyphBoundingBox,
};
use azul_css::props::basic::FontMetrics as CssFontMetrics;
// Mock font module for testing
pub use crate::font::mock::MockFont;
use crate::text3::cache::LayoutFontMetrics;
/// Cached GSUB table for glyph substitution operations.
pub type GsubCache = Arc<LayoutCacheData<GSUB>>;
/// Cached GPOS table for glyph positioning operations.
pub type GposCache = Arc<LayoutCacheData<GPOS>>;
/// The `wght` variation axis `(min, default, max)` in user units.
///
/// `None` when the font has no variable `wght` axis. Used to expand a
/// variable font into per-weight STATIC instances so the ordinary (static)
/// weight-selection path can pick the right one — no changes to
/// shaping/decode/PDF needed.
#[must_use]
pub fn read_wght_axis(bytes: &[u8], index: usize) -> Option<(f32, f32, f32)> {
let font_file = ReadScope::new(bytes).read::<FontData<'_>>().ok()?;
let provider = font_file.table_provider(index).ok()?;
let fvar_data = provider.read_table_data(tag::FVAR).ok()?;
let fvar = ReadScope::new(&fvar_data)
.read::<allsorts::tables::variable_fonts::fvar::FvarTable<'_>>()
.ok()?;
// Bind before returning so the (borrowing) axes() iterator is dropped at
// the end of this statement, not after `provider`/`fvar` at block end.
let axis = fvar.axes().find(|a| a.axis_tag == tag::WGHT);
axis.map(|a| {
(
f32::from(a.min_value),
f32::from(a.default_value),
f32::from(a.max_value),
)
})
}
/// Bake a self-contained STATIC instance of a variable font at `wght`.
///
/// All other axes are left at their default. Returns fresh TTF bytes that
/// parse and embed exactly like any static font, or `None` if the font is
/// not a bakeable variable font.
#[must_use]
pub fn bake_weight_instance(bytes: &[u8], index: usize, wght: f32) -> Option<Vec<u8>> {
use allsorts::tables::Fixed;
let font_file = ReadScope::new(bytes).read::<FontData<'_>>().ok()?;
let provider = font_file.table_provider(index).ok()?;
let fvar_data = provider.read_table_data(tag::FVAR).ok()?;
let fvar = ReadScope::new(&fvar_data)
.read::<allsorts::tables::variable_fonts::fvar::FvarTable<'_>>()
.ok()?;
let user: Vec<Fixed> = fvar
.axes()
.map(|a| {
if a.axis_tag == tag::WGHT {
Fixed::from(wght)
} else {
a.default_value
}
})
.collect();
allsorts::variations::instance(&provider, &user)
.ok()
.map(|(baked, _tuple)| baked)
}
/// Monotonic-clock nanos since process start. Used to timestamp
/// `ParsedFont.last_used` for LRU eviction. Cheap (single
/// `Instant::now`); resolution is plenty fine for "did this
/// face get touched in the last N seconds" decisions. Exposed
/// `pub(crate)` so `FontManager::evict_unused` reads from the
/// same clock as `last_used` writes.
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
#[cfg(not(target_family = "wasm"))]
pub(crate) fn monotonic_now_nanos() -> u64 {
// Safe: `Instant::elapsed` against the same launch instant is
// monotonic and never overflows in any realistic process
// lifetime (>500 years).
use std::sync::OnceLock;
use std::time::Instant;
static LAUNCH: OnceLock<Instant> = OnceLock::new();
let start = LAUNCH.get_or_init(Instant::now);
start.elapsed().as_nanos() as u64
}
/// On browser wasm `std::time::Instant::now()` panics ("time not
/// implemented on this platform") — it took the whole printpdf wasm demo
/// down with it on the first shaped glyph: every `last_used` store on a
/// font touch aborted the module. LRU eviction only needs *ordering*, not
/// wall time, and a shared atomic counter is exactly as monotonic.
#[cfg(target_family = "wasm")]
pub(crate) fn monotonic_now_nanos() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static TICK: AtomicU64 = AtomicU64::new(1);
TICK.fetch_add(1, Ordering::Relaxed)
}
/// Glyph-outline decoder state. See the
/// [`ParsedFont::loca_glyf`] field docs for the full description.
#[derive(Clone)]
pub(crate) enum LocaGlyfState {
/// Ready to decode immediately, or known to have no outline
/// data. `None` covers both CFF fonts and fonts where the
/// loca+glyf parse failed.
///
/// This variant *cannot* be evicted by
/// [`crate::text3::cache::FontManager::evict_unused`]: there
/// are no source bytes retained to re-decode from. The eager
/// `from_bytes` path (tests, `with_source_bytes` PDF callers)
/// produces this variant.
Loaded(Option<Arc<std::sync::Mutex<LocaGlyf>>>),
/// Font bytes retained for lazy `LocaGlyf` construction.
///
/// `loaded` is `Mutex<Option<…>>` (not `OnceLock`) so an
/// idle eviction can clear it back to `None`; the next
/// `get_or_decode_glyph` will re-parse from `bytes`. Two-step
/// double-check pattern in `resolve_loca_glyf` keeps the
/// expensive `LocaGlyf::load` outside the critical section.
Deferred {
bytes: Arc<rust_fontconfig::FontBytes>,
font_index: usize,
loaded: Arc<std::sync::Mutex<Option<Arc<std::sync::Mutex<LocaGlyf>>>>>,
},
}
/// Adapter that collects allsorts outline commands into our `GlyphOutline` format.
///
/// Implements `OutlineSink` so it can be passed to `GlyfVisitorContext::visit()`.
/// This handles composite glyph resolution, transforms, and variable font
/// deltas automatically via allsorts internals.
struct GlyphOutlineCollector {
contours: Vec<GlyphOutline>,
current_contour: Vec<GlyphOutlineOperation>,
}
impl GlyphOutlineCollector {
const fn new() -> Self {
Self {
contours: Vec::new(),
current_contour: Vec::new(),
}
}
fn into_outlines(mut self) -> Vec<GlyphOutline> {
if !self.current_contour.is_empty() {
self.contours.push(GlyphOutline {
operations: std::mem::take(&mut self.current_contour).into(),
});
}
self.contours
}
}
impl OutlineSink for GlyphOutlineCollector {
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
fn move_to(&mut self, to: Vector2F) {
if !self.current_contour.is_empty() {
self.contours.push(GlyphOutline {
operations: std::mem::take(&mut self.current_contour).into(),
});
}
self.current_contour.push(GlyphOutlineOperation::MoveTo(OutlineMoveTo {
x: to.x() as i16,
y: to.y() as i16,
}));
}
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
fn line_to(&mut self, to: Vector2F) {
self.current_contour.push(GlyphOutlineOperation::LineTo(OutlineLineTo {
x: to.x() as i16,
y: to.y() as i16,
}));
}
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
fn quadratic_curve_to(&mut self, ctrl: Vector2F, to: Vector2F) {
self.current_contour.push(GlyphOutlineOperation::QuadraticCurveTo(
OutlineQuadTo {
ctrl_1_x: ctrl.x() as i16,
ctrl_1_y: ctrl.y() as i16,
end_x: to.x() as i16,
end_y: to.y() as i16,
},
));
}
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
fn cubic_curve_to(&mut self, ctrl: LineSegment2F, to: Vector2F) {
self.current_contour.push(GlyphOutlineOperation::CubicCurveTo(
OutlineCubicTo {
ctrl_1_x: ctrl.from_x() as i16,
ctrl_1_y: ctrl.from_y() as i16,
ctrl_2_x: ctrl.to_x() as i16,
ctrl_2_y: ctrl.to_y() as i16,
end_x: to.x() as i16,
end_y: to.y() as i16,
},
));
}
fn close(&mut self) {
self.current_contour.push(GlyphOutlineOperation::ClosePath);
self.contours.push(GlyphOutline {
operations: std::mem::take(&mut self.current_contour).into(),
});
}
}
/// Parsed font data with all required tables for text layout and PDF generation.
///
/// This struct holds the parsed representation of a TrueType/OpenType font,
/// including glyph outlines, metrics, and shaping tables. It's used for:
/// - Text layout (via GSUB/GPOS tables)
/// - Glyph rendering (via glyf/CFF outlines)
/// - PDF font embedding (via font metrics and subsetting)
pub struct ParsedFont {
/// Hash of the font bytes for caching and equality checks.
pub hash: u64,
/// Layout-specific font metrics (ascent, descent, line gap).
pub font_metrics: LayoutFontMetrics,
/// PDF-specific detailed font metrics from HEAD, HHEA, OS/2 tables.
pub pdf_font_metrics: PdfFontMetrics,
/// Total number of glyphs in the font (from maxp table).
pub num_glyphs: u16,
/// Horizontal header table (hhea) containing global horizontal metrics.
pub hhea_table: HheaTable,
/// Offset+length into `original_bytes` for hmtx table (lazy: no copy).
pub hmtx_range: (usize, usize),
/// Offset+length into `original_bytes` for vmtx table (lazy: no copy).
pub vmtx_range: (usize, usize),
/// Vertical header table (vhea), same format as hhea. None if font has no vertical metrics.
pub vhea_table: Option<HheaTable>,
/// Maximum profile table (maxp) containing glyph count and memory hints.
pub maxp_table: MaxpTable,
/// Raw GSUB table bytes, kept as a `Vec<u8>` (tens to low-hundreds
/// of KiB) so the parsed `GsubCache` can be built on first shape
/// call instead of up-front. Access via [`ParsedFont::gsub`] —
/// that getter populates `gsub_cache_lazy` via `OnceLock` and
/// returns a borrow.
pub(crate) gsub_bytes: Option<Vec<u8>>,
/// Lazy GSUB cache: populated on first [`ParsedFont::gsub`] call.
/// `None` means "font has no GSUB table" *after* init attempt;
/// the `OnceLock` wrapper distinguishes "not yet initialised"
/// from "initialised to None".
pub(crate) gsub_cache_lazy: std::sync::OnceLock<Option<GsubCache>>,
/// Raw GPOS table bytes. Same lazy-parse arrangement as
/// `gsub_bytes` — see [`ParsedFont::gpos`].
pub(crate) gpos_bytes: Option<Vec<u8>>,
/// Lazy GPOS cache, populated on first [`ParsedFont::gpos`] call.
pub(crate) gpos_cache_lazy: std::sync::OnceLock<Option<GposCache>>,
/// Glyph definition table (GDEF) for glyph classification.
pub opt_gdef_table: Option<Arc<GDEFTable>>,
/// Legacy kerning table (kern) for fonts without GPOS.
pub opt_kern_table: Option<Arc<KernTable>>,
/// Monotonic-clock nanos at the most recent
/// [`ParsedFont::get_or_decode_glyph`] / `gsub()` / `gpos()`
/// call. `0` means "never touched". Used by
/// [`crate::text3::cache::FontManager::evict_unused`] to
/// decide which `LocaGlyfState::Deferred` faces to release.
pub(crate) last_used: Arc<std::sync::atomic::AtomicU64>,
/// `true` if this font is a variable font (carries a `gvar`
/// table). Cached at parse time so [`decode_glyph_inner`]
/// can short-circuit the variable-context construction for
/// the common non-variable case. Variable-glyph delta
/// application requires the source bytes to be retained,
/// so it only fires on the `LocaGlyfState::Deferred` path.
pub(crate) is_variable_font: bool,
/// Lazy outline cache. Populated on first
/// [`ParsedFont::get_or_decode_glyph`] call per `gid`; entries
/// are wrapped in `Arc` so callers can hold them without
/// keeping the lock. The space glyph (and `.notdef` when
/// present) are pre-inserted by `from_bytes_internal` so the
/// shaper's cmap-miss path has something to render without
/// racing with a decode.
///
/// Tests that previously walked the public `glyph_records_decoded`
/// `BTreeMap` field now call
/// [`ParsedFont::prime_glyph_cache`] (decodes every glyph into
/// this cache) followed by
/// [`ParsedFont::for_each_decoded_glyph`] /
/// [`ParsedFont::glyph_cache_snapshot`] to walk the result.
// [az-web-lift] queue RwLock spins in lock_contended in single-threaded lifted wasm
// (only the pure-Rust queue RwLock is lifted; Mutex is Leaf-stubbed). Reuse
// rust_fontconfig::StLock (no-atomic single-threaded bypass). One of the 3 RwLocks total.
pub(crate) glyph_cache: Arc<rust_fontconfig::StLock<BTreeMap<u16, Arc<OwnedGlyph>>>>,
/// Glyph outline decoder state.
///
/// - `Loaded(Some(arc))`: `LocaGlyf` is already loaded (owning
/// its own `Box<[u8]>` copy of the loca+glyf tables) and
/// ready to decode glyphs. Produced by the eager `from_bytes`
/// constructor path (tests).
/// - `Loaded(None)`: the font has no usable loca+glyf (CFF, or
/// a parse failure). Glyph outlines won't decode; the hmtx
/// advance fallback fills in the blanks.
/// - `Deferred`: we retain an `Arc<[u8]>` to the full font file
/// and the `font_index`; the first `get_or_decode_glyph` call
/// parses a fresh `FontData` / `TableProvider` from those
/// bytes and loads `LocaGlyf`, storing the result in the
/// `OnceLock`. Fonts that get resolved into a chain but are
/// never actually rasterized pay zero decode cost — this is
/// the big win for pages like `excel.html` where 20+ fallback
/// faces load but only a handful are touched.
pub(crate) loca_glyf: LocaGlyfState,
/// Cached width of the space character in font units.
pub space_width: Option<usize>,
/// Character-to-glyph mapping (cmap subtable).
pub cmap_subtable: Option<OwnedCmapSubtable>,
/// Mock font data for testing (replaces real font behavior).
pub mock: Option<Box<MockFont>>,
/// Reverse mapping: `glyph_id` -> cluster text (handles ligatures like "fi").
pub reverse_glyph_cache: BTreeMap<u16, String>,
/// Original font bytes — only retained for callers that need to
/// reconstruct or subset the font (PDF export). Layout / shaping /
/// raster never read this, so `ParsedFont::from_bytes` leaves it
/// as `None` by default and callers opt in via
/// [`ParsedFont::with_source_bytes`]. Shared across faces of the
/// same `.ttc` via the `Arc<FontBytes>` that
/// [`rust_fontconfig::FcFontCache::get_font_bytes`] returns —
/// for disk fonts the backing is an mmap so untouched pages
/// don't count toward RSS.
pub original_bytes: Option<Arc<rust_fontconfig::FontBytes>>,
/// Font index within collection (0 for single-font files).
pub original_index: usize,
/// GID to CID mapping for CFF fonts (required for PDF embedding).
pub index_to_cid: BTreeMap<u16, u16>,
/// Font type (TrueType outlines or OpenType CFF).
pub font_type: FontType,
/// PostScript font name from the NAME table.
pub font_name: Option<String>,
/// TrueType bytecode hinting instance (mutable interpreter state).
/// Wrapped in Mutex because hinting mutates internal state.
/// None for CFF fonts or fonts without hinting data.
pub hint_instance: Option<std::sync::Mutex<allsorts::hinting::HintInstance>>,
}
impl Clone for ParsedFont {
fn clone(&self) -> Self {
Self {
hash: self.hash,
font_metrics: self.font_metrics,
pdf_font_metrics: self.pdf_font_metrics,
num_glyphs: self.num_glyphs,
hhea_table: self.hhea_table.clone(),
hmtx_range: self.hmtx_range,
vmtx_range: self.vmtx_range,
vhea_table: self.vhea_table.clone(),
maxp_table: self.maxp_table.clone(),
// OnceLock<T: Clone>: Clone preserves the init state, so
// a clone of a parsed cache skips re-parse on first
// access. The raw bytes we keep around for lazy init
// are cloned too.
gsub_bytes: self.gsub_bytes.clone(),
gsub_cache_lazy: self.gsub_cache_lazy.clone(),
gpos_bytes: self.gpos_bytes.clone(),
gpos_cache_lazy: self.gpos_cache_lazy.clone(),
opt_gdef_table: self.opt_gdef_table.clone(),
opt_kern_table: self.opt_kern_table.clone(),
// Share the lazy cache and loca_glyf across clones: cheap
// Arc bump, amortises glyph decode across clones of the
// same face.
last_used: Arc::clone(&self.last_used),
is_variable_font: self.is_variable_font,
glyph_cache: Arc::clone(&self.glyph_cache),
// `LocaGlyfState` is `Clone` — for `Loaded` this is an
// `Arc::clone`; for `Deferred` it's an `Arc::clone` of
// the bytes + the `OnceLock`, so a clone of a face
// that's already decoded glyphs carries the decode.
loca_glyf: self.loca_glyf.clone(),
space_width: self.space_width,
cmap_subtable: self.cmap_subtable.clone(),
mock: self.mock.clone(),
reverse_glyph_cache: self.reverse_glyph_cache.clone(),
// Arc clone — O(1), just bumps refcount; no byte copy.
original_bytes: self.original_bytes.clone(),
original_index: self.original_index,
index_to_cid: self.index_to_cid.clone(),
font_type: self.font_type.clone(),
font_name: self.font_name.clone(),
// HintInstance has mutable interpreter state and is not Clone.
// Clones are used for PDF/serialization where hinting isn't needed.
hint_instance: None,
}
}
}
/// Distinguishes TrueType fonts from OpenType CFF fonts.
///
/// This affects how glyph outlines are extracted and how the font
/// is embedded in PDF documents.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FontType {
/// TrueType font with quadratic Bézier outlines in glyf table.
TrueType,
/// OpenType font with cubic Bézier outlines in CFF table.
/// Contains the serialized CFF data for PDF embedding.
OpenTypeCFF(Vec<u8>),
}
/// PDF-specific font metrics from HEAD, HHEA, and OS/2 tables.
///
/// These metrics are used for PDF font descriptors and accurate
/// text positioning in generated PDF documents.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct PdfFontMetrics {
// -- HEAD table fields --
/// Font units per em-square (typically 1000 or 2048).
pub units_per_em: u16,
/// Font flags (italic, bold, fixed-pitch, etc.).
pub font_flags: u16,
/// Minimum x-coordinate across all glyphs.
pub x_min: i16,
/// Minimum y-coordinate across all glyphs.
pub y_min: i16,
/// Maximum x-coordinate across all glyphs.
pub x_max: i16,
/// Maximum y-coordinate across all glyphs.
pub y_max: i16,
// -- HHEA table fields --
/// Typographic ascender (distance above baseline).
pub ascender: i16,
/// Typographic descender (distance below baseline, usually negative).
pub descender: i16,
/// Recommended line gap between lines of text.
pub line_gap: i16,
/// Maximum horizontal advance width across all glyphs.
pub advance_width_max: u16,
/// Caret slope rise for italic angle calculation.
pub caret_slope_rise: i16,
/// Caret slope run for italic angle calculation.
pub caret_slope_run: i16,
// -- OS/2 table fields (0 if table not present) --
/// Average width of lowercase letters.
pub x_avg_char_width: i16,
/// Visual weight class (100-900, 400=normal, 700=bold).
pub us_weight_class: u16,
/// Visual width class (1-9, 5=normal).
pub us_width_class: u16,
/// Thickness of strikeout stroke in font units.
pub y_strikeout_size: i16,
/// Vertical position of strikeout stroke.
pub y_strikeout_position: i16,
}
impl Default for PdfFontMetrics {
fn default() -> Self {
Self::zero()
}
}
impl PdfFontMetrics {
/// Returns zeroed metrics with `units_per_em` set to 1000 (standard PostScript default)
/// to avoid division-by-zero in scaling calculations.
#[must_use] pub const fn zero() -> Self {
Self {
units_per_em: 1000,
font_flags: 0,
x_min: 0,
y_min: 0,
x_max: 0,
y_max: 0,
ascender: 0,
descender: 0,
line_gap: 0,
advance_width_max: 0,
caret_slope_rise: 0,
caret_slope_run: 0,
x_avg_char_width: 0,
us_weight_class: 0,
us_width_class: 0,
y_strikeout_size: 0,
y_strikeout_position: 0,
}
}
}
/// Result of font subsetting operation.
///
/// Contains the subsetted font bytes and a mapping from original
/// glyph IDs to new glyph IDs in the subset.
#[derive(Debug, Clone)]
pub struct SubsetFont {
/// The subsetted font file bytes (smaller than original).
pub bytes: Vec<u8>,
/// Mapping: original glyph ID -> (new subset glyph ID, source character).
pub glyph_mapping: BTreeMap<u16, (u16, char)>,
}
impl SubsetFont {
/// Return the changed text so that when rendering with the subset font (instead of the
/// original) the renderer will end up at the same glyph IDs as if we used the original text
/// on the original font
#[must_use] pub fn subset_text(&self, text: &str) -> String {
text.chars()
.filter_map(|c| {
self.glyph_mapping.values().find_map(|(ngid, ch)| {
if *ch == c {
char::from_u32(u32::from(*ngid))
} else {
None
}
})
})
.collect()
}
}
/// Hash-based equality: two fonts are considered equal if their content hash matches.
/// This is a performance optimization — hash collisions are possible but vanishingly
/// unlikely (~1/2^64).
impl PartialEq for ParsedFont {
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash
}
}
impl Eq for ParsedFont {}
const FONT_B64_START: &str = "data:font/ttf;base64,";
impl serde::Serialize for ParsedFont {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use base64::Engine;
let s = format!(
"{FONT_B64_START}{}",
base64::prelude::BASE64_STANDARD.encode(self.to_bytes(None).unwrap_or_default())
);
s.serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for ParsedFont {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Self, D::Error> {
use base64::Engine;
let s = String::deserialize(deserializer)?;
let b64 = s.strip_prefix(FONT_B64_START).and_then(|b| base64::prelude::BASE64_STANDARD.decode(b).ok());
let mut warnings = Vec::new();
Self::from_bytes(&b64.unwrap_or_default(), 0, &mut warnings).ok_or_else(|| {
serde::de::Error::custom(format!("Font deserialization error: {warnings:?}"))
})
}
}
impl fmt::Debug for ParsedFont {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ParsedFont")
.field("hash", &self.hash)
.field("font_metrics", &self.font_metrics)
.field("num_glyphs", &self.num_glyphs)
.field("hhea_table", &self.hhea_table)
.field(
"hmtx_range",
&format_args!("<{} bytes>", self.hmtx_range.1),
)
.field("maxp_table", &self.maxp_table)
.field(
"glyph_cache",
&format_args!(
"{} entries (lazy)",
self.glyph_cache.read().map(|m| m.len()).unwrap_or(0),
),
)
.field("space_width", &self.space_width)
.field("cmap_subtable", &self.cmap_subtable)
.finish_non_exhaustive()
}
}
/// Warning or error message generated during font parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontParseWarning {
/// Severity level of this warning.
pub severity: FontParseWarningSeverity,
/// Human-readable description of the issue.
pub message: String,
}
/// Severity level for font parsing warnings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontParseWarningSeverity {
/// Informational message (not an error).
Info,
/// Warning that may affect font rendering.
Warning,
/// Error that prevents proper font usage.
Error,
}
impl FontParseWarning {
/// Creates an info-level message.
#[must_use] pub const fn info(message: String) -> Self {
Self {
severity: FontParseWarningSeverity::Info,
message,
}
}
/// Creates a warning-level message.
#[must_use] pub const fn warning(message: String) -> Self {
Self {
severity: FontParseWarningSeverity::Warning,
message,
}
}
/// Creates an error-level message.
#[must_use] pub const fn error(message: String) -> Self {
Self {
severity: FontParseWarningSeverity::Error,
message,
}
}
}
// WEB-LIFT FIX (2026-06-02): a `FontTableProvider` that scans the sfnt table directory
// by hand from the raw font bytes. allsorts' `OffsetTableFontProvider` produces garbage
// on the remill/web backend: (1) `ReadArray::read_item`'s nested-tuple `TableRecord` read
// returns `table_tag = 0` for EVERY record (proven: tags[7]=0x0000 while the bytes there
// are 0x68656164 'head'); (2) even a hand-rolled scan added to the *allsorts crate* sees a
// bad `self.scope.data()` (the ReadScope fat-pointer mis-lifts through provider
// construction, or allsorts-crate code lifts differently). This provider lives in
// azul-layout — whose identical byte reads PROVABLY work (the `from_provider` probe read
// num_tables=15 from these same `font_bytes`) — and reads the slice directly. KEEP.
#[inline]
fn manual_be16(d: &[u8], o: usize) -> u32 {
(u32::from(d[o]) << 8) | u32::from(d[o + 1])
}
#[inline]
fn manual_be32(d: &[u8], o: usize) -> u32 {
(u32::from(d[o]) << 24)
| (u32::from(d[o + 1]) << 16)
| (u32::from(d[o + 2]) << 8)
| u32::from(d[o + 3])
}
struct ManualTableProvider<'a> {
data: &'a [u8],
dir: usize, // byte offset of the first table record (offset-table base + 12)
num: usize, // number of table records
}
impl<'a> ManualTableProvider<'a> {
fn new(data: &'a [u8], font_index: usize) -> Option<Self> {
if data.len() < 12 {
return None;
}
let base = if manual_be32(data, 0) == 0x7474_6366 {
// 'ttcf' (TrueType Collection): the font_index'th offset-table offset.
let num_fonts = manual_be32(data, 8) as usize;
if font_index >= num_fonts || 12 + font_index * 4 + 4 > data.len() {
return None;
}
manual_be32(data, 12 + font_index * 4) as usize
} else {
0 // single font: offset table at the start
};
if base + 12 > data.len() {
return None;
}
Some(ManualTableProvider {
data,
dir: base + 12,
num: manual_be16(data, base + 4) as usize,
})
}
}
impl FontTableProvider for ManualTableProvider<'_> {
fn table_data(
&self,
tag: u32,
) -> Result<Option<std::borrow::Cow<'_, [u8]>>, allsorts::error::ParseError> {
let mut i = 0;
while i < self.num {
let r = self.dir + i * 16;
if r + 16 > self.data.len() {
break;
}
if manual_be32(self.data, r) == tag {
let off = manual_be32(self.data, r + 8) as usize;
let len = manual_be32(self.data, r + 12) as usize;
return Ok(off
.checked_add(len)
.filter(|&e| e <= self.data.len())
.map(|e| std::borrow::Cow::Borrowed(&self.data[off..e])));
}
i += 1;
}
Ok(None)
}
fn has_table(&self, tag: u32) -> bool {
self.table_data(tag).ok().flatten().is_some()
}
fn table_tags(&self) -> Option<Vec<u32>> {
// DIAG (REVERT): sentinel 0xFADE as tags[0] proves THIS provider ran; then
// self.num pushes let me see if the usize field survived; then the real reads
// show if self.data (slice field) survived the struct move through generics.
let mut tags = Vec::with_capacity(self.num + 1);
tags.push(0x0000_FADE);
let mut i = 0;
while i < self.num {
let r = self.dir + i * 16;
if r + 4 > self.data.len() {
break;
}
tags.push(manual_be32(self.data, r));
i += 1;
}
Some(tags)
}
}
impl allsorts::tables::SfntVersion for ManualTableProvider<'_> {
fn sfnt_version(&self) -> u32 {
let base = self.dir.saturating_sub(12);
if base + 4 <= self.data.len() {
manual_be32(self.data, base)
} else {
0
}
}
}
impl ParsedFont {
/// Parse a font from bytes using allsorts
///
/// # Arguments
/// * `font_bytes` - The font file data
/// * `font_index` - Index of the font in a font collection (0 for single fonts)
/// * `warnings` - Optional vector to collect parsing warnings
///
/// # Returns
/// `Some(ParsedFont)` if parsing succeeds, `None` otherwise
///
/// Note: Outlines are decoded lazily by `get_or_decode_glyph`;
/// `LocaGlyf::load` runs eagerly here. Use `from_bytes_shared`
/// for the lazy-LocaGlyf production path.
pub fn from_bytes(
font_bytes: &[u8],
font_index: usize,
warnings: &mut Vec<FontParseWarning>,
) -> Option<Self> {
// `from_bytes` keeps the eager-LocaGlyf behaviour for the
// small number of callers (mainly tests) that don't have
// an `Arc<[u8]>` to keep alive for the lazy path.
let mut font = Self::from_bytes_internal(font_bytes, font_index, warnings, false)?;
// Retain an owned copy of the source bytes so the face can later be
// subset/embedded (PDF export, save->parse roundtrips). Callers pass a
// borrowed slice that may not outlive us, so we own it here. Mirrors
// `from_bytes_shared`, which retains the caller's `Arc<FontBytes>`.
if font.original_bytes.is_none() {
font.original_bytes = Some(Arc::new(
rust_fontconfig::FontBytes::Owned(Arc::from(font_bytes.to_vec())),
));
}
Some(font)
}
/// Shared implementation of `from_bytes` / `from_bytes_shared`.
///
/// `defer_loca_glyf = true` skips the `LocaGlyf::load` call
/// here so the caller (`from_bytes_shared`) can install a
/// `LocaGlyfState::Deferred` slot that re-parses on first
/// glyph decode. Saves the load-then-drop cycle the previous
/// arrangement paid (`from_bytes_shared` used to call
/// `from_bytes` and immediately replace the loaded `LocaGlyf`
/// with a Deferred slot, throwing away ~hundreds of KiB of
/// loca+glyf bytes per face for fonts in the chain that get
/// loaded but never rasterized).
fn from_bytes_internal(
font_bytes: &[u8],
font_index: usize,
warnings: &mut Vec<FontParseWarning>,
defer_loca_glyf: bool,
) -> Option<Self> {
use allsorts::{binary::read::ReadScope, font_data::FontData};
fn provider_err(font_index: usize, e: impl fmt::Display) -> FontParseWarning {
FontParseWarning::error(format!(
"Failed to get table provider for font index {font_index}: {e}"
))
}
let scope = ReadScope::new(font_bytes);
let font_file = match scope.read::<FontData<'_>>() {
Ok(ff) => ff,
Err(e) => {
warnings.push(FontParseWarning::error(format!(
"Failed to read font data: {e}"
)));
return None;
}
};
// FIX (2026-06-02): route OpenType fonts through the CONCRETE provider
// (`OffsetTableFontProvider`) instead of `FontData::table_provider`'s
// `Box<dyn FontTableProvider>`. On the lifted/web backend the trait-object
// VTABLE dispatch (allsorts font_data.rs:45 `self.provider.table_data(tag)`)
// mis-lifts: the vtable's fn-pointers are untranslated native addresses, so the
// indirect-call dispatcher routes the dyn call to the WRONG `table_data` impl,
// which returns a `Cow::Owned` garbage buffer → `HeadTable::read` errors → font
// parse returns None → text measures height 0. A concrete provider makes every
// `table_data` a DIRECT (monomorphized) call, which lifts correctly. Woff/Woff2
// keep the dyn path (they're not used on the web backend's embedded TTF).
match font_file {
FontData::OpenType(otf) => {
// Prefer the hand-rolled provider (reads font_bytes directly) over
// allsorts' OffsetTableFontProvider, whose lifted table reads are garbage
// on the web backend. Fall back to allsorts only if the manual layout
// parse can't recognise the sfnt (e.g. an unusual TTC).
if let Some(mp) = ManualTableProvider::new(font_bytes, font_index) {
Self::from_provider(mp, font_bytes, font_index, warnings, defer_loca_glyf)
} else {
match otf.table_provider(font_index) {
Ok(p) => Self::from_provider(
p,
font_bytes,
font_index,
warnings,
defer_loca_glyf,
),
Err(e) => {
warnings.push(provider_err(font_index, e));
None
}
}
}
}
other => match other.table_provider(font_index) {
Ok(p) => {
Self::from_provider(p, font_bytes, font_index, warnings, defer_loca_glyf)
}
Err(e) => {
warnings.push(provider_err(font_index, e));
None
}
},
}
}
/// Build a `ParsedFont` from a concrete [`FontTableProvider`]. Split out of
/// `from_bytes_internal` (2026-06-02) so OpenType fonts use the concrete
/// `OffsetTableFontProvider` (direct `table_data` calls that lift correctly on
/// the web backend) rather than `FontData::table_provider`'s `Box<dyn>`, whose
/// trait-object vtable dispatch mis-lifts (wrong impl → Owned garbage → parse fail).
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
fn from_provider<P: FontTableProvider>(
provider: P,
font_bytes: &[u8],
font_index: usize,
warnings: &mut Vec<FontParseWarning>,
defer_loca_glyf: bool,
) -> Option<Self> {
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use allsorts::{
binary::read::ReadScope,
tables::{
cmap::{owned::CmapSubtable as OwnedCmapSubtable, CmapSubtable},
FontTableProvider, HeadTable, HheaTable, MaxpTable,
},
tag,
};
// Extract font name from NAME table early (before provider is moved).
// WEB-LIFT FIX (2026-06-02): NameTable::string_for_id decodes the NAME strings via
// `encoding_rs` (Mac Roman / UTF-16 charset state machines), whose jump-tables
// are NOT devirt'd by the remill lift → MISSING_BLOCK trap (proven: trap in
// encoding_rs::Decoder::decode_to_utf8). font_name is OPTIONAL metadata (NOT used
// for layout/metrics/shaping — those are binary head/hhea/maxp/cmap/glyf), so skip
// the NAME-string decode on the web backend to avoid encoding_rs entirely.
#[cfg(feature = "web_lift")]
let font_name: Option<String> = None;
#[cfg(not(feature = "web_lift"))]
let font_name = provider.table_data(tag::NAME).ok().and_then(|name_data| {
ReadScope::new(&name_data?)
.read::<allsorts::tables::NameTable<'_>>()
.ok()
.and_then(|name_table| {
name_table.string_for_id(allsorts::tables::NameTable::POSTSCRIPT_NAME)
})
});
// DIAG (2026-06-02, REVERT): pinpoint the web font-parse-fails root — does HEAD
// fail because table_data can't find/return the table (directory mis-lift) or
// because HeadTable::read errors (table-read mis-lift)? Surfaced via warnings.
let head_table = match provider.table_data(tag::HEAD) {
Ok(Some(head_cow)) => {
// DIAG: is the HEAD table data CORRECT (magicNumber 0x5F0F3CF5 @ off 12 →
// HeadTable::read mis-lifts) or WRONG bytes (directory offset mis-lift)?
let bb = head_cow.as_ref();
let magic = if bb.len() >= 16 {
(u32::from(bb[12]) << 24) | (u32::from(bb[13]) << 16)
| (u32::from(bb[14]) << 8) | u32::from(bb[15])
} else { 0 };
if let Ok(h) = ReadScope::new(&head_cow).read::<HeadTable>() { h } else {
// DIAG: surface the sliced offset (how wrong) as hex — "HO" + 8 hex
// of (head_cow.ptr - font_bytes.ptr). garbage→offset-read mis-lift;
// 00000000→base; plausible-but-wrong→record mapping. "RF"=bytes-OK.
let m = if magic == 0x5F0F_3CF5 {
"RF000000".to_string()
} else {
let off = (head_cow.as_ref().as_ptr() as usize)
.wrapping_sub(font_bytes.as_ptr() as usize);
let mut msg = String::new();
// B=Borrowed(slice of font_bytes, ptr-arith/base mis-lift) vs
// O=Owned(decompressed/copied Vec — wrong path for plain TTF).
msg.push(if matches!(head_cow, std::borrow::Cow::Borrowed(_)) { 'B' } else { 'O' });
msg.push_str("HO");
let mut sh: i32 = 28;
while sh >= 0 {
let d = ((off >> sh) & 0xf) as u8;
msg.push((if d < 10 { b'0' + d } else { b'a' + d - 10 }) as char);
sh -= 4;
}
msg
};
warnings.push(FontParseWarning::error(m));
return None;
}
}
Ok(None) => {
// DIAG (REVERT): bytes+len+read_item-count+dir all proved OK (N0fr0fc0fg1)
// yet find_table_record(HEAD)=None though 'head' is rec[7] on disk. So
// either read_item's table_tag FIELD is garbage, or tag::HEAD mis-lifts, or
// the u32 == mis-lifts. t7 = tags[7] (should be 0x68656164 'head' low16
// =6164); H = tag::HEAD low16 (should be 6164); f = ANY tag==HEAD via an
// indexed compare loop (NOT .iter().any). "T<4h t7>H<4h HEAD>f<0|1>".
// T6164 H6164 f1 → values+compare OK (won't reach here — HEAD found)
// T6164 H6164 f0 → the u32 == comparison mis-lifts
// T!=6164 → read_item table_tag FIELD garbage (tuple read mis-lift)
// H!=6164 → tag::HEAD const mis-lifts
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
fn hx(m: &mut String, val: u32, nibbles: i32) {
let mut sh = (nibbles - 1) * 4;
while sh >= 0 {
let d = ((val >> sh) & 0xf) as u8;
m.push((if d < 10 { b'0' + d } else { b'a' + d - 10 }) as char);
sh -= 4;
}
}
// DECISIVE: tags[8] (head, file off 124) reads 0 but tags[2] (off 28) is OK.
// Read the SAME offsets from from_provider's LOCAL font_bytes param (proven
// correct at off 4/12). If local@124 = 0x6865 'he' but provider tags[8]=0 ⇒
// STORED-SLICE issue (provider self.data fat-ptr mis-lifts) → read locally.
// If local@124 = 0 ⇒ the font CONST is only PARTIALLY MIRRORED into the wasm
// (deep data-mirror gap) → table data is simply absent. local@93596 (=0x16f9c,
// head TABLE data start) further maps the mirror: 'he'/nonzero vs 0.
let loc124 = if font_bytes.len() >= 126 {
(u32::from(font_bytes[124]) << 8) | u32::from(font_bytes[125])
} else {
0xEEEE
};
let loc_head = if font_bytes.len() >= 93598 {
(u32::from(font_bytes[93596]) << 8) | u32::from(font_bytes[93597])
} else {
0xEEEE
};
let mut m = String::from("L"); // local font_bytes[124..126] (head dir record):
hx(&mut m, loc124 & 0xffff, 4); // 6865 'he' = mirrored; 0000 = not
m.push('H'); // local font_bytes[93596..] (head TABLE data, deep):
hx(&mut m, loc_head & 0xffff, 4);
warnings.push(FontParseWarning::error(m));
return None;
}
Err(_) => {
warnings.push(FontParseWarning::error("HEAD_DATAERR".to_string()));
return None;
}
};
let maxp_table = provider
.table_data(tag::MAXP)
.ok()
.and_then(|maxp_data| ReadScope::new(&maxp_data?).read::<MaxpTable>().ok())
.unwrap_or(MaxpTable {
num_glyphs: 0,
version1_sub_table: None,
});
let num_glyphs = maxp_table.num_glyphs as usize;
// Compute byte offset+length into font_bytes for hmtx/vmtx
// instead of copying the table data. The provider returns a
// borrowed slice for OpenType fonts, so we can derive the
// offset via pointer arithmetic.
let hmtx_range = provider
.table_data(tag::HMTX)
.ok()
.and_then(|cow_opt| {
let cow = cow_opt?;
match cow {
std::borrow::Cow::Borrowed(slice) => {
let base = font_bytes.as_ptr() as usize;
let ptr = slice.as_ptr() as usize;
let offset = ptr.checked_sub(base)?;
if offset + slice.len() <= font_bytes.len() {
Some((offset, slice.len()))
} else {
None
}
}
std::borrow::Cow::Owned(_) => None,
}
})
.unwrap_or((0, 0));
let vmtx_range = provider
.table_data(tag::VMTX)
.ok()
.and_then(|s| {
let slice = s?;
let base = font_bytes.as_ptr() as usize;
let ptr = slice.as_ptr() as usize;
let offset = ptr.checked_sub(base)?;
if offset + slice.len() <= font_bytes.len() {
Some((offset, slice.len()))
} else {
None
}
})
.unwrap_or((0, 0));
// Parse vhea table (same format as hhea, used for vertical metrics)
let vhea_table = provider
.table_data(tag::VHEA)
.ok()
.and_then(|vhea_data| ReadScope::new(&vhea_data?).read::<HheaTable>().ok());
// hhea is required per the OpenType spec; return None if missing
let hhea_table = provider
.table_data(tag::HHEA)
.ok()
.and_then(|hhea_data| ReadScope::new(&hhea_data?).read::<HheaTable>().ok())?;
// Build layout-specific font metrics
let font_metrics = LayoutFontMetrics {
units_per_em: if head_table.units_per_em == 0 {
1000
} else {
head_table.units_per_em
},
ascent: f32::from(hhea_table.ascender),
descent: f32::from(hhea_table.descender),
line_gap: f32::from(hhea_table.line_gap),
x_height: None, // will be populated from OS/2 table via from_font_metrics if available
cap_height: None,
};
// Build PDF-specific font metrics
let pdf_font_metrics =
Self::parse_pdf_font_metrics(font_bytes, font_index, &head_table, &hhea_table);
// Use allsorts LocaGlyf for on-demand outline extraction. We
// *load* LocaGlyf eagerly (it owns ~tens of KiB of loca +
// ~hundreds of KiB of glyf bytes) but we *don't* decode any
// glyph outlines up front — that's the big RSS win. Glyphs
// are decoded by `ParsedFont::get_or_decode_glyph` on first
// access from the CPU/GPU rasterizer.
//
// When `defer_loca_glyf` is set (production lazy path via
// `from_bytes_shared`), we skip `LocaGlyf::load` here too —
// the caller will overwrite the slot with
// `LocaGlyfState::Deferred` carrying the source bytes
// `Arc<[u8]>`, and the load happens on the first
// `get_or_decode_glyph` call. This avoids parsing
// ~hundreds of KiB per face for fonts that get resolved
// into a chain but never actually rasterized (typical
// for fallback fonts in CSS chains).
let has_glyf = provider.has_table(tag::GLYF) && provider.has_table(tag::LOCA);
// Cache `has_gvar` before `provider` gets moved into
// `allsorts::font::Font::new(provider)` further down —
// it's the cheapest way to detect a variable font and
// avoids the borrow-after-move that a later
// `provider.has_table(tag::GVAR)` would incur.
let has_gvar = provider.has_table(tag::GVAR);
let loca_glyf_opt: Option<Arc<std::sync::Mutex<LocaGlyf>>> = if has_glyf
&& !defer_loca_glyf
{
match LocaGlyf::load(&provider) {
Ok(lg) => Some(Arc::new(std::sync::Mutex::new(lg))),
Err(e) => {
warnings.push(FontParseWarning::warning(format!(
"Failed to load LocaGlyf: {e} — falling back to hmtx-only"
)));
None
}
}
} else {
None
};
// Lazy `glyph_cache` starts empty; the space-glyph stub
// below pre-inserts gid 0 / space so the shaper's
// cmap-miss fallback has something to render without
// racing with a decode.
let mut font_data_impl = allsorts::font::Font::new(provider).ok()?;
// Create TrueType hinting instance from font tables.
// [az-web-lift] Skip on the web build. The lifted layout never grid-fits glyphs to a
// pixel raster (it measures + ships a display list to JS), so hinting is never used.
// Building it (HintInstance::new) runs the allsorts bytecode Interpreter
// (Interpreter::new + ::dispatch — a large un-devirt'd opcode jump table the remill
// lift can't resolve, plus ~700 op_* fns of closure bloat). This is INDEPENDENT of the
// lift's jump-table devirt: even with a perfect lift, web has no use for hinting, and
// hinted advances are lower-quality output than the plain scaled advance. Native keeps
// real hinting unchanged.
#[cfg(feature = "web_lift")]
let hint_instance: Option<std::sync::Mutex<allsorts::hinting::HintInstance>> = None;
#[cfg(not(feature = "web_lift"))]
let hint_instance = allsorts::hinting::HintInstance::new(
&font_data_impl.font_table_provider
).ok().flatten().map(std::sync::Mutex::new);
// Stash raw GSUB/GPOS bytes for lazy parse. Typical fonts
// have ~tens of KiB of GSUB + a few-to-tens of KiB of GPOS —
// dwarfed by glyph outlines — so we keep the bytes around
// and only spend `LayoutTable::read` + `new_layout_cache`
// cycles when the shaper actually needs them (via
// `ParsedFont::gsub` / `::gpos`). For an ASCII run where no
// substitution / kerning is required, we skip both entirely.
let gsub_bytes = font_data_impl
.font_table_provider
.table_data(tag::GSUB)
.ok()
.flatten()
.map(std::borrow::Cow::into_owned);
let gpos_bytes = font_data_impl
.font_table_provider
.table_data(tag::GPOS)
.ok()
.flatten()
.map(std::borrow::Cow::into_owned);
let opt_gdef_table = font_data_impl.gdef_table().ok().and_then(|o| o);
let num_glyphs = font_data_impl.num_glyphs();
let opt_kern_table = font_data_impl
.kern_table()
.ok()
.and_then(|s| s);
let cmap_data = font_data_impl.cmap_subtable_data();
let cmap_subtable = ReadScope::new(cmap_data);
let cmap_subtable = cmap_subtable
.read::<CmapSubtable<'_>>()
.ok()
.and_then(|s| s.to_owned());
// Font identity hash — used by `PartialEq` for ParsedFont.
//
// Previously we did `font_bytes.hash(&mut hasher)` over
// the full mmap. That touched every page of the file
// (a 40 MiB `.ttc` walked byte-for-byte) so the "lazy
// mmap" ended up *fully resident* the moment we built
// a `ParsedFont`. Cold RSS jumped ~40 MiB from this
// single line.
//
// The hash doesn't need to be cryptographic — it just
// has to disambiguate two `ParsedFont`s. `(len, first
// 4 KiB, last 4 KiB, font_index)` is plenty unique and
// only faults in the two header / trailer pages, which
// shaping is going to need anyway.
let mut hasher = DefaultHasher::new();
(font_bytes.len() as u64).hash(&mut hasher);
let head_len = font_bytes.len().min(4096);
font_bytes[..head_len].hash(&mut hasher);
let tail_start = font_bytes.len().saturating_sub(4096);
font_bytes[tail_start..].hash(&mut hasher);
font_index.hash(&mut hasher);
let hash = hasher.finish();
let mut font = Self {
hash,
font_metrics,
pdf_font_metrics,
num_glyphs,
hhea_table,
hmtx_range,
vmtx_range,
vhea_table,
maxp_table,
gsub_bytes,
gsub_cache_lazy: std::sync::OnceLock::new(),
gpos_bytes,
gpos_cache_lazy: std::sync::OnceLock::new(),
opt_gdef_table,
opt_kern_table,
cmap_subtable,
last_used: Arc::new(std::sync::atomic::AtomicU64::new(0)),
is_variable_font: has_gvar,
glyph_cache: Arc::new(rust_fontconfig::StLock::new(BTreeMap::new())),
// Eager path: `from_bytes` loaded LocaGlyf immediately
// (or set None if the font has no loca+glyf). Lazy
// callers use `from_bytes_shared` which replaces this
// with `LocaGlyfState::Deferred` before returning.
loca_glyf: LocaGlyfState::Loaded(loca_glyf_opt),
space_width: None,
mock: None,
reverse_glyph_cache: BTreeMap::new(),
// Don't retain the source bytes by default — layout and
// raster don't need them. PDF subsetting / `to_bytes`
// callers opt in via `with_source_bytes`.
original_bytes: None,
original_index: font_index,
index_to_cid: BTreeMap::new(), // Will be filled for CFF fonts
font_type: FontType::TrueType, // Default, will be updated if CFF
font_name,
hint_instance,
};
// Calculate space width
let space_width = font.get_space_width_internal();
// Pre-decode the space glyph straight into the lazy
// `glyph_cache`. Space typically has no outline, so the
// decoder's outline visitor returns nothing useful and
// we'd spin re-decoding it every shape — short-circuit
// here with a hand-rolled record carrying the hmtx
// advance.
let _ = (|| {
let space_gid = font.lookup_glyph_index(' ' as u32)?;
{
// StLock::read() is infallible (Result<_, Infallible>);
// kept in a tight block so the guard drops at scope end.
let Ok(cache) = font.glyph_cache.read();
if cache.contains_key(&space_gid) {
return None;
}
}
let space_width_val = space_width?;
// Only pre-cache when we actually know a non-zero advance. During
// `from_bytes_internal` the source bytes are not attached yet, so
// `hmtx` is unreadable and `get_space_width_internal` reads back 0;
// caching that would pin every space to a 0 advance for the life of
// the face. Skip it and let the space decode lazily once bytes are
// attached (mock fonts that carry a real space width still cache).
if space_width_val == 0 {
return None;
}
let space_record = OwnedGlyph {
bounding_box: OwnedGlyphBoundingBox {
max_x: 0,
max_y: 0,
min_x: 0,
min_y: 0,
},
horz_advance: space_width_val as u16,
outline: Vec::new(),
phantom_points: None,
raw_points: None,
raw_on_curve: None,
raw_contour_ends: None,
instructions: None,
};
{
// StLock::write() is infallible (Result<_, Infallible>).
let Ok(mut cache) = font.glyph_cache.write();
cache.insert(space_gid, Arc::new(space_record));
}
Some(())
})();
font.space_width = space_width;
Some(font)
}
/// Attach the source font bytes to this `ParsedFont`, enabling
/// [`ParsedFont::to_bytes`] and [`ParsedFont::subset`] (both of
/// which the layout / shaping path never calls).
///
/// Takes an `Arc<FontBytes>` so the same file's bytes can be
/// shared across every face of a `.ttc` at zero extra cost —
/// pair with [`rust_fontconfig::FcFontCache::get_font_bytes`].
/// For ad-hoc PDF callers that have raw heap bytes, wrap them
/// via `Arc::new(FontBytes::Owned(Arc::from(vec)))`.
#[must_use]
pub fn with_source_bytes(mut self, bytes: Arc<rust_fontconfig::FontBytes>) -> Self {
self.original_bytes = Some(bytes);
self
}
/// Lazy-friendly constructor — identical to
/// [`ParsedFont::from_bytes`] except that `LocaGlyf` is
/// **not** loaded during the call. Instead, the supplied
/// `Arc<[u8]>` is retained and `LocaGlyf::load` runs the first
/// time [`get_or_decode_glyph`] needs glyph outlines for this
/// face.
///
/// Fonts that get resolved into a CSS fallback chain but are
/// never actually rasterized (common on desktop — e.g. every
/// face of HelveticaNeue.ttc loads, but only one or two are
/// shaped) then pay zero loca/glyf cost.
///
/// Production callers (the reftest harness, `LayoutWindow`,
/// `cpurender`) should prefer this constructor. Tests that
/// inspect `glyph_records_decoded` directly and don't want
/// a lazy path keep using `from_bytes`.
pub fn from_bytes_shared(
bytes: Arc<rust_fontconfig::FontBytes>,
font_index: usize,
warnings: &mut Vec<FontParseWarning>,
) -> Option<Self> {
// Skip the eager LocaGlyf::load via `defer_loca_glyf=true`
// — saves the load-then-drop cycle the prior arrangement
// paid (when this called `from_bytes`, allocated
// ~hundreds of KiB of loca+glyf bytes, then immediately
// replaced the slot with `Deferred` and dropped them).
// `bytes.as_ref()` derefs FontBytes → &[u8] (mmap or owned
// — same code path).
let mut font = Self::from_bytes_internal(bytes.as_ref(), font_index, warnings, true)?;
font.original_bytes = Some(bytes.clone());
font.loca_glyf = LocaGlyfState::Deferred {
bytes,
font_index,
loaded: Arc::new(std::sync::Mutex::new(None)),
};
Some(font)
}
/// Resolve the current face's `LocaGlyf`, loading it lazily
/// on first call when `loca_glyf` is `Deferred`. Returns
/// `None` when the font has no usable loca+glyf (CFF fonts
/// or parse failures).
fn resolve_loca_glyf(&self) -> Option<Arc<std::sync::Mutex<LocaGlyf>>> {
use allsorts::{
binary::read::ReadScope,
font_data::FontData,
tables::FontTableProvider,
};
match &self.loca_glyf {
LocaGlyfState::Loaded(inner) => inner.clone(),
LocaGlyfState::Deferred { bytes, font_index, loaded } => {
// Fast path: cached LocaGlyf is present.
if let Ok(guard) = loaded.lock() {
if let Some(arc) = guard.as_ref() {
return Some(Arc::clone(arc));
}
}
let _p = crate::probe::Probe::span("resolve_loca_glyf");
// Slow path: parse provider + load LocaGlyf without
// holding the slot's lock (allsorts can take a
// millisecond or two on a fresh load). Re-check
// after acquiring the write lock so a parallel
// decoder doesn't double-load.
let scope = ReadScope::new(bytes.as_slice());
let font_data = scope.read::<FontData<'_>>().ok()?;
let provider = font_data.table_provider(*font_index).ok()?;
// Gate on table presence to match the `from_bytes`
// has_glyf check; avoids a spurious warning on
// CFF fonts that sneak into the Deferred path.
if !provider.has_table(tag::GLYF) || !provider.has_table(tag::LOCA) {
return None;
}
// Zero-copy: keep `glyf` as a view into the already-resident
// (mmap'd) font bytes instead of copying the whole table
// (~20 MB for a large font) onto the heap. `bytes` is the
// exact buffer `provider` reads from, so load_shared can
// anchor the glyf range inside it (falling back to an owned
// copy if it ever can't). Audit §3.3a.
let owner: Arc<dyn AsRef<[u8]> + Send + Sync> = bytes.clone();
let new_arc = LocaGlyf::load_shared(&provider, owner)
.ok()
.map(|lg| Arc::new(std::sync::Mutex::new(lg)))?;
if let Ok(mut guard) = loaded.lock() {
if let Some(existing) = guard.as_ref() {
return Some(Arc::clone(existing));
}
*guard = Some(Arc::clone(&new_arc));
}
Some(new_arc)
}
}
}
/// Source bytes for PDF subsetting / table extraction.
///
/// Looks in two places:
/// - `original_bytes` (set by [`ParsedFont::with_source_bytes`]
/// for legacy PDF-first construction).
/// - `LocaGlyfState::Deferred.bytes` (set by
/// [`ParsedFont::from_bytes_shared`] — the production lazy
/// path, which already retains an `Arc<[u8]>` for the lazy
/// loca/glyf loader).
///
/// Returns `None` only for `ParsedFont`s built via the eager
/// `from_bytes` path without an explicit `with_source_bytes`
/// call — i.e. unit tests that load a font and don't touch
/// PDF.
pub fn source_bytes_for_subset(&self) -> Option<Arc<rust_fontconfig::FontBytes>> {
if let Some(bytes) = &self.original_bytes {
return Some(Arc::clone(bytes));
}
if let LocaGlyfState::Deferred { bytes, .. } = &self.loca_glyf {
return Some(Arc::clone(bytes));
}
None
}
/// Read the monotonic-clock nanos timestamp of the most
/// recent [`get_or_decode_glyph`] call on this face, or `0`
/// if it's never been touched.
pub fn last_used_nanos(&self) -> u64 {
self.last_used.load(std::sync::atomic::Ordering::Relaxed)
}
/// Drop the cached `LocaGlyf` for this face if it's
/// `Deferred`-with-bytes-retained — so the next
/// [`get_or_decode_glyph`] re-parses from `bytes`. No-op for
/// `Loaded` faces (no source bytes to fall back to).
///
/// Used by [`crate::text3::cache::FontManager::evict_unused`]
/// and exposed publicly so embedders can free memory under
/// pressure on fonts they no longer need to render.
pub fn evict_loca_glyf(&self) -> bool {
match &self.loca_glyf {
LocaGlyfState::Deferred { loaded, .. } => {
if let Ok(mut guard) = loaded.lock() {
if guard.is_some() {
*guard = None;
return true;
}
}
false
}
LocaGlyfState::Loaded(_) => false,
}
}
/// Fetch the parsed GSUB cache if this font has one, parsing
/// it from the retained `gsub_bytes` on first access.
///
/// Moved out of the eager `from_bytes` path because most text
/// runs never trigger GSUB — plain ASCII without ligatures is
/// handled entirely by the cmap + hmtx fast path. Building
/// `LayoutCacheData<GSUB>` up front reserved ~0.5–2 MiB per
/// face just to throw it away on pages that don't shape
/// complex scripts.
pub fn gsub(&self) -> Option<&GsubCache> {
self.gsub_cache_lazy
.get_or_init(|| {
use allsorts::{
binary::read::ReadScope,
layout::{new_layout_cache, LayoutTable, GSUB},
};
let bytes = self.gsub_bytes.as_ref()?;
ReadScope::new(bytes)
.read::<LayoutTable<GSUB>>()
.ok()
.map(new_layout_cache)
})
.as_ref()
}
/// Fetch the parsed GPOS cache if this font has one, parsing
/// it from the retained `gpos_bytes` on first access. See
/// [`ParsedFont::gsub`] for the motivation.
pub fn gpos(&self) -> Option<&GposCache> {
self.gpos_cache_lazy
.get_or_init(|| {
use allsorts::{
binary::read::ReadScope,
layout::{new_layout_cache, LayoutTable, GPOS},
};
let bytes = self.gpos_bytes.as_ref()?;
ReadScope::new(bytes)
.read::<LayoutTable<GPOS>>()
.ok()
.map(new_layout_cache)
})
.as_ref()
}
/// Fetch an `OwnedGlyph` for `gid`, decoding it on first access.
///
/// Cached in the `Arc<RwLock<…>>` `glyph_cache` so subsequent
/// calls (including across clones of this `ParsedFont`) hit the
/// cache. Returns `None` when `gid >= num_glyphs` or the font
/// has no loca+glyf and no hmtx entry for the glyph. For CFF
/// fonts the returned record has an empty outline and an advance
/// pulled from hmtx — matching the pre-lazy behaviour.
///
/// Called on the rasterizer hot path; performance budget is a
/// few µs per unique glyph (first hit) and an Arc bump + `BTreeMap`
/// lookup (cache hits). The write lock is held only across the
/// decode, not across the caller's use of the returned Arc.
pub fn get_or_decode_glyph(&self, gid: u16) -> Option<Arc<OwnedGlyph>> {
use std::sync::Arc;
if usize::from(gid) >= self.num_glyphs as usize {
return None;
}
// Bump the LRU timestamp so `FontManager::evict_unused`
// can tell this face is still in use. Cheap atomic store
// (Relaxed — eviction reads the same atomic and tolerates
// a slightly stale value, which only causes "evict, then
// re-load on next access" — never an incorrect render).
self.last_used
.store(monotonic_now_nanos(), std::sync::atomic::Ordering::Relaxed);
// Fast path: cache hit.
{
// StLock::read() is infallible; tight block drops the read
// guard before the write lock below (deadlock avoidance).
let Ok(cache) = self.glyph_cache.read();
if let Some(existing) = cache.get(&gid) {
return Some(Arc::clone(existing));
}
}
// Miss: decode. We drop the read lock before taking the
// write lock to avoid deadlock, and we re-check on the way
// in because another thread may have decoded the same glyph
// in between.
let record = self.decode_glyph_inner(gid);
let arc = Arc::new(record);
{
// StLock::write() is infallible (Result<_, Infallible>).
let Ok(mut cache) = self.glyph_cache.write();
cache
.entry(gid)
.or_insert_with(|| Arc::clone(&arc));
// If another thread beat us to the insert, return theirs
// so all callers observe the same Arc.
if let Some(winner) = cache.get(&gid) {
return Some(Arc::clone(winner));
}
}
Some(arc)
}
/// Eagerly decode every glyph into the lazy `glyph_cache`,
/// restoring the pre-lazy "every glyph is materialised at
/// construction time" behaviour. Used by tests that iterate
/// or compare against reference tooling, and by embedders
/// that want a walkable view without driving every shape
/// through `get_or_decode_glyph`.
///
/// After `prime_glyph_cache`, callers can use
/// [`ParsedFont::for_each_decoded_glyph`] or
/// [`ParsedFont::glyph_cache_snapshot`] to observe the
/// populated cache.
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
pub fn prime_glyph_cache(&mut self) {
let n = self.num_glyphs as usize;
for glyph_index in 0..n {
let gid = glyph_index as u16;
drop(self.get_or_decode_glyph(gid));
}
}
/// Walk every entry currently in the lazy `glyph_cache`,
/// invoking `f(gid, &OwnedGlyph)` for each. Holds a read
/// lock for the duration; do not call back into the font
/// from `f`. The cache is populated on demand by
/// [`ParsedFont::get_or_decode_glyph`] (and bulk-prefilled
/// by [`ParsedFont::prime_glyph_cache`]).
pub fn for_each_decoded_glyph<F: FnMut(u16, &OwnedGlyph)>(&self, mut f: F) {
{
// StLock::read() is infallible (Result<_, Infallible>).
let Ok(cache) = self.glyph_cache.read();
for (gid, glyph) in cache.iter() {
f(*gid, glyph.as_ref());
}
}
}
/// Snapshot of the currently-decoded glyphs as a
/// `BTreeMap<u16, Arc<OwnedGlyph>>`. Cheap (clones the
/// Arcs, not the records). Used by callers that want to
/// hand the map off across an API boundary; for in-place
/// iteration prefer [`ParsedFont::for_each_decoded_glyph`].
pub fn glyph_cache_snapshot(&self) -> BTreeMap<u16, Arc<OwnedGlyph>> {
self.glyph_cache
.read()
.map(|c| c.clone())
.unwrap_or_default()
}
/// Core decode routine: produces one `OwnedGlyph` for `gid` by
/// locking `loca_glyf` and running allsorts' outline visitor +
/// raw-simple-glyph extraction. Factored out so both
/// [`get_or_decode_glyph`] and [`prime_glyph_cache`] share it.
///
/// Always returns an `OwnedGlyph` — if anything in the decode
/// chain fails, falls back to an empty-outline record with the
/// `hmtx` advance. This mirrors the pre-lazy behaviour where
/// every gid ended up in `glyph_records_decoded`.
fn hmtx_bytes(&self) -> &[u8] {
let (off, len) = self.hmtx_range;
if len == 0 { return &[]; }
self.original_bytes.as_ref()
.map_or(&[], |b| &b.as_ref()[off..off+len])
}
fn vmtx_bytes(&self) -> &[u8] {
let (off, len) = self.vmtx_range;
if len == 0 { return &[]; }
self.original_bytes.as_ref()
.map_or(&[], |b| &b.as_ref()[off..off+len])
}
#[allow(clippy::cast_possible_wrap)] // bounded graphics/coord/font/fixed-point/debug-marker cast
fn decode_glyph_inner(&self, gid: u16) -> OwnedGlyph {
let _p = crate::probe::Probe::span("decode_glyph");
// [az-web-lift] use get_horizontal_advance (reads hmtx directly on the web build)
// instead of allsorts::glyph_info::advance, whose lifted ReadArray parse has an
// un-devirt'd jump table → MISSING_BLOCK → OOB during measure.
let horz_advance = self.get_horizontal_advance(gid);
let mut record = OwnedGlyph {
horz_advance,
bounding_box: OwnedGlyphBoundingBox {
min_x: 0,
min_y: 0,
max_x: horz_advance as i16,
max_y: 0,
},
outline: Vec::new(),
phantom_points: None,
raw_points: None,
raw_on_curve: None,
raw_contour_ends: None,
instructions: None,
};
// Resolve the `LocaGlyf` for this face. For `Loaded` that's
// a cheap `Arc::clone`; for `Deferred` this is where the
// actual `LocaGlyf::load` happens on first access, paid once
// per face that ever decodes a glyph.
let Some(loca_glyf_arc) = self.resolve_loca_glyf() else {
// No usable loca+glyf → CFF / OpenType-PostScript font
// (Noto Sans/Serif CJK and most .otf). Decode the glyph
// from the `CFF ` table instead; the TrueType-only glyf
// path below can't see these, which left every CFF glyph
// blank on the cpurender/headless path (CJK rendered as
// empty space with the hmtx advance still reserved).
self.decode_cff_glyph_into(gid, &mut record);
return record;
};
let Ok(mut loca_glyf) = loca_glyf_arc.lock() else {
return record;
};
// Visit the outline. If this is a variable font (gvar
// table present) AND we still have source bytes (only
// the `LocaGlyfState::Deferred` path retains them), we
// re-derive a `VariableGlyfContext` here so default-
// instance vs designed-instance differences land in
// the decoded outline. The chained `if let` pattern
// keeps `provider` and `store` in scope for the
// visit, which the borrow checker requires (the
// store's `Cow::Borrowed(&[u8])` tables tie its
// lifetime to the provider).
//
// Eager-`from_bytes` faces (no retained bytes) and
// non-variable fonts skip the var-context machinery
// and decode the default instance — same behaviour as
// before R4.
// [az-web-lift] The lifted web layout NEVER rasterizes (it measures + positions, then
// ships a display list to JS) — so glyph OUTLINES + TrueType hinting raw-points are
// never needed in wasm. Decoding them (allsorts GlyfVisitorContext::visit +
// GlyphOutlineCollector::into_outlines, whose GlyphOutlineOperation match is a 5-arm
// jump table the remill lift doesn't devirtualize → MISSING_BLOCK → OOB) crashes the
// measure pass. Skip BOTH decode passes on the web build; the record keeps its hmtx
// advance/metrics (set above) which is all text measurement needs.
if !cfg!(feature = "web_lift") {
let mut outline_done = false;
if self.is_variable_font {
if let LocaGlyfState::Deferred { bytes, .. } = &self.loca_glyf {
let scope = ReadScope::new(bytes);
if let Ok(font_data) =
scope.read::<FontData<'_>>()
{
if let Ok(provider) = font_data.table_provider(self.original_index) {
if let Ok(store) = VariableGlyfContextStore::read(&provider) {
if let Ok(var_ctx) = VariableGlyfContext::new(&store) {
let mut visitor = GlyfVisitorContext::new(
&mut loca_glyf,
Some(var_ctx),
);
let mut collector = GlyphOutlineCollector::new();
if visitor.visit(gid, None, &mut collector).is_ok() {
record.outline = collector.into_outlines();
let (min_x, min_y, max_x, max_y) =
compute_outline_bbox(&record.outline);
record.bounding_box = OwnedGlyphBoundingBox {
min_x,
min_y,
max_x,
max_y,
};
outline_done = true;
}
}
}
}
}
}
}
if !outline_done {
let mut visitor =
GlyfVisitorContext::new(&mut loca_glyf, None);
let mut collector = GlyphOutlineCollector::new();
if visitor.visit(gid, None, &mut collector).is_ok() {
record.outline = collector.into_outlines();
let (min_x, min_y, max_x, max_y) =
compute_outline_bbox(&record.outline);
record.bounding_box = OwnedGlyphBoundingBox {
min_x,
min_y,
max_x,
max_y,
};
}
}
// Second pass: pull raw SimpleGlyph data for TrueType
// bytecode hinting. LocaGlyf caches the `Arc<Glyph>`
// internally so this lookup is cheap after the first call.
if let Ok(glyph_arc) = loca_glyf.glyph(gid) {
// `is_on_curve` moved onto the `SimpleGlyphFlagExt` trait in
// allsorts 0.17 (SimpleGlyphFlags is now a BitFlags alias).
use allsorts::tables::glyf::SimpleGlyphFlagExt;
if let allsorts::tables::glyf::Glyph::Simple(sg) = glyph_arc.as_ref() {
record.raw_points = Some(
sg.coordinates.iter().map(|(_, pt)| (pt.0, pt.1)).collect(),
);
record.raw_on_curve = Some(
sg.coordinates.iter().map(|(f, _)| f.is_on_curve()).collect(),
);
record.raw_contour_ends = Some(sg.end_pts_of_contours.clone());
record.instructions = Some(sg.instructions.to_vec());
}
}
} // [az-web-lift] end skip glyph outline/hinting decode on web
record
}
/// Decode a single glyph outline from the `CFF ` (OpenType
/// PostScript) table into `record`. Used for fonts with no `glyf`
/// table — `decode_glyph_inner`'s TrueType path returns an empty
/// outline for them, so without this every CFF glyph rasterised as
/// blank on the CPU renderer. Notably this hit ALL CJK text: the
/// installed Noto Sans/Serif CJK fonts are CID-keyed CFF. allsorts'
/// `CFFOutlines` feeds the same `GlyphOutlineCollector` the glyf
/// path uses and resolves CID-keyed local subrs internally.
fn decode_cff_glyph_into(&self, gid: u16, record: &mut OwnedGlyph) {
use allsorts::cff::{outline::CFFOutlines, CFF};
let Some(ref original) = self.original_bytes else {
return;
};
let bytes: &[u8] = original.as_slice();
let Ok(font_data) = ReadScope::new(bytes).read::<FontData<'_>>() else {
return;
};
let Ok(provider) = font_data.table_provider(self.original_index) else {
return;
};
let Ok(Some(cff_data)) = provider.table_data(tag::CFF) else {
return;
};
let Ok(cff) = ReadScope::new(&cff_data).read::<CFF<'_>>() else {
return;
};
let mut outlines = CFFOutlines { table: &cff };
let mut collector = GlyphOutlineCollector::new();
if outlines.visit(gid, None, &mut collector).is_ok() {
record.outline = collector.into_outlines();
let (min_x, min_y, max_x, max_y) = compute_outline_bbox(&record.outline);
record.bounding_box = OwnedGlyphBoundingBox {
min_x,
min_y,
max_x,
max_y,
};
}
}
/// Parse PDF-specific font metrics from HEAD, HHEA, and OS/2 tables
fn parse_pdf_font_metrics(
font_bytes: &[u8],
font_index: usize,
head_table: &allsorts::tables::HeadTable,
hhea_table: &HheaTable,
) -> PdfFontMetrics {
use allsorts::{
binary::read::ReadScope,
font_data::FontData,
tables::{os2::Os2, FontTableProvider},
tag,
};
let scope = ReadScope::new(font_bytes);
let font_file = scope.read::<FontData<'_>>().ok();
let provider = font_file
.as_ref()
.and_then(|ff| ff.table_provider(font_index).ok());
let os2_table = provider
.as_ref()
.and_then(|p| p.table_data(tag::OS_2).ok())
.and_then(|os2_data| {
let data = os2_data?;
let scope = ReadScope::new(&data);
scope.read_dep::<Os2>(data.len()).ok()
});
// Base metrics from HEAD and HHEA (always present)
let base = PdfFontMetrics {
units_per_em: head_table.units_per_em,
font_flags: head_table.flags,
x_min: head_table.x_min,
y_min: head_table.y_min,
x_max: head_table.x_max,
y_max: head_table.y_max,
ascender: hhea_table.ascender,
descender: hhea_table.descender,
line_gap: hhea_table.line_gap,
advance_width_max: hhea_table.advance_width_max,
caret_slope_rise: hhea_table.caret_slope_rise,
caret_slope_run: hhea_table.caret_slope_run,
..PdfFontMetrics::zero()
};
// Add OS/2 metrics if available
os2_table
.map_or(base, |os2| PdfFontMetrics {
x_avg_char_width: os2.x_avg_char_width,
us_weight_class: os2.us_weight_class,
us_width_class: os2.us_width_class,
y_strikeout_size: os2.y_strikeout_size,
y_strikeout_position: os2.y_strikeout_position,
..base
})
}
/// Returns the width of the space character in font units.
///
/// This is used internally for text layout calculations.
/// Returns `None` if the font has no space glyph or its width cannot be determined.
fn get_space_width_internal(&self) -> Option<usize> {
if let Some(mock) = self.mock.as_ref() {
return mock.space_width;
}
let glyph_index = self.lookup_glyph_index(' ' as u32)?;
// [az-web-lift] use get_horizontal_advance (direct hmtx on web) instead of
// allsorts::glyph_info::advance (un-devirt'd jump table → OOB).
Some(self.get_horizontal_advance(glyph_index) as usize)
}
/// Look up the glyph index for a Unicode codepoint
pub fn lookup_glyph_index(&self, codepoint: u32) -> Option<u16> {
let cmap = self.cmap_subtable.as_ref()?;
cmap.map_glyph(codepoint).ok().flatten()
}
/// Get the horizontal advance width for a glyph in font units.
///
/// Pulled straight from the `hmtx` table — no glyph-outline
/// decode. Called once per shaped glyph per layout pass, so
/// avoiding the lazy decode here is a meaningful win over
/// routing through `get_or_decode_glyph`.
pub fn get_horizontal_advance(&self, glyph_index: u16) -> u16 {
if let Some(mock) = self.mock.as_ref() {
return mock.glyph_advances.get(&glyph_index).copied().unwrap_or(0);
}
// [az-web-lift] Read the hmtx advance DIRECTLY (a plain longHorMetric table lookup)
// instead of allsorts::glyph_info::advance, whose lifted binary `ReadArray` parse has
// an un-devirt'd jump table → MISSING_BLOCK → OOB during text measure. Identical result
// for non-variable fonts (the web fallback font is non-variable); native keeps the
// allsorts path (variable-font deltas etc.).
#[cfg(feature = "web_lift")]
{
let hmtx = self.hmtx_bytes();
let num = usize::from(self.hhea_table.num_h_metrics);
if num == 0 {
return 0;
}
let idx = (glyph_index as usize).min(num - 1);
let off = idx * 4;
return if off + 2 <= hmtx.len() {
((hmtx[off] as u16) << 8) | (hmtx[off + 1] as u16)
} else {
0
};
}
#[cfg(not(feature = "web_lift"))]
{
allsorts::glyph_info::advance(
&self.maxp_table,
&self.hhea_table,
self.hmtx_bytes(),
glyph_index,
)
.unwrap_or_default()
}
}
/// Get the hinted advance width in pixels for a glyph at the given ppem.
///
/// For glyphs with outlines, runs TrueType bytecode hinting to get the
/// grid-fitted advance from phantom points. For glyphs without outlines
/// (e.g. space), rounds the scaled advance to the pixel grid, matching
/// `FreeType`'s behavior.
///
/// Returns `None` if hinting is not available or fails.
#[allow(clippy::cast_precision_loss)] // bounded graphics/coord/font/fixed-point/debug-marker cast
pub fn get_hinted_advance_px(&self, glyph_index: u16, ppem: u16) -> Option<f32> {
// [az-web-lift] No pixel grid-fitting on the web (measure-only): return None so the
// caller falls back to the plain scaled advance. Hard-cfg (not a runtime `if cfg!`)
// so the whole hinting body — get_or_decode_glyph's outline path AND set_ppem →
// allsorts Interpreter::dispatch (opcode jump table → OOB) — is removed from the lift
// closure entirely. SEPARATE concern from the transpiler's jump-table devirt: web has
// no use for hinted advances regardless of lift quality. Native is unchanged.
#[cfg(feature = "web_lift")]
{
let _ = (glyph_index, ppem);
None
}
#[cfg(not(feature = "web_lift"))]
{
use allsorts::hinting::f26dot6::{compute_scale, F26Dot6};
let glyph = self.get_or_decode_glyph(glyph_index)?;
let upem = self.font_metrics.units_per_em;
if upem == 0 || ppem == 0 {
return None;
}
// Check if we even have a hint instance
let hint_mutex = self.hint_instance.as_ref()?;
let scale = compute_scale(ppem, upem);
// Round the LIVE hmtx advance, not the decoded glyph's cached
// `horz_advance`. The space glyph is eagerly pre-cached during
// `from_bytes_internal` before `original_bytes` is attached, so its
// cached advance can be a stale 0; and this function only ever rounds
// the scaled hmtx advance to the pixel grid anyway (see below), never
// the hinted phantom point. For every correctly-decoded glyph the two
// are identical, so this is a no-op except for the stale-space case.
let hmtx_advance = self.get_horizontal_advance(glyph_index);
let adv_f26dot6 = F26Dot6::from_funits(i32::from(hmtx_advance), scale);
// For glyphs with outline data, run bytecode hinting
if let (Some(raw_points), Some(raw_on_curve), Some(raw_contour_ends)) = (
glyph.raw_points.as_ref(),
glyph.raw_on_curve.as_ref(),
glyph.raw_contour_ends.as_ref(),
) {
let instructions = glyph.instructions.as_deref().unwrap_or(&[]);
let mut hint = hint_mutex.lock().ok()?;
hint.set_ppem(ppem, f64::from(ppem)).ok()?;
drop(hint);
let points_f26dot6: Vec<(i32, i32)> = raw_points
.iter()
.map(|&(x, y)| {
let sx = F26Dot6::from_funits(i32::from(x), scale);
let sy = F26Dot6::from_funits(i32::from(y), scale);
(sx.to_bits(), sy.to_bits())
})
.collect();
}
// Use the scaled advance rounded to pixel grid, NOT the hinted
// phantom point. Some glyph programs apply ClearType-specific SHPIX
// adjustments to the advance phantom point that are wrong for
// non-ClearType rendering. The rounded scaled advance matches
// FreeType's DEFAULT mode advance output (and, for glyphs without an
// outline such as space, FreeType's phantom-point pre-rounding).
let rounded = (adv_f26dot6.to_bits() + 32) & !63;
Some(rounded as f32 / 64.0)
} // [az-web-lift] end #[cfg(not(web_lift))] hinting body
}
/// Get the number of glyphs in this font
pub const fn num_glyphs(&self) -> u16 {
self.num_glyphs
}
/// Check if this font has a glyph for the given codepoint
pub fn has_glyph(&self, codepoint: u32) -> bool {
self.lookup_glyph_index(codepoint).is_some()
}
/// Get vertical metrics for a glyph (for vertical text layout).
///
/// Uses vhea+vmtx tables (same binary format as hhea+hmtx).
/// Returns None if font has no vertical metrics tables.
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
pub fn get_vertical_metrics(
&self,
glyph_id: u16,
) -> Option<crate::text3::cache::VerticalMetrics> {
let vhea = self.vhea_table.as_ref()?;
if self.vmtx_range.1 == 0 {
return None;
}
let vert_advance = f32::from(allsorts::glyph_info::advance(
&self.maxp_table, vhea, self.vmtx_bytes(), glyph_id,
).ok()?);
let units_per_em = f32::from(self.font_metrics.units_per_em);
let scale = if units_per_em > 0.0 { 1.0 / units_per_em } else { 0.001 };
// Vertical bearing: approximate from glyph bbox if available
let (bearing_x, bearing_y) = self.get_or_decode_glyph(glyph_id)
.map_or((0.0, 0.0), |g| {
let bbox = &g.bounding_box;
// tsb (top side bearing): origin_y - max_y
// lsb for vertical: center the glyph horizontally
let width = f32::from(bbox.max_x - bbox.min_x);
(-(width / 2.0) * scale, (vert_advance * scale) - (f32::from(bbox.max_y) * scale))
});
Some(crate::text3::cache::VerticalMetrics {
advance: vert_advance * scale,
bearing_x,
bearing_y,
origin_y: self.font_metrics.ascent * scale,
})
}
/// Get layout-specific font metrics
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
pub fn get_font_metrics(&self) -> LayoutFontMetrics {
// Ensure descent is positive (OpenType may have negative descent)
let descent = if self.font_metrics.descent > 0.0 {
self.font_metrics.descent
} else {
-self.font_metrics.descent
};
LayoutFontMetrics {
ascent: self.font_metrics.ascent,
descent,
line_gap: self.font_metrics.line_gap,
units_per_em: self.font_metrics.units_per_em,
x_height: self.font_metrics.x_height,
cap_height: self.font_metrics.cap_height,
}
}
/// Convert the `ParsedFont` back to bytes using `allsorts::whole_font`
/// This reconstructs the entire font from the parsed data
///
/// Source bytes come from either the explicit
/// [`ParsedFont::with_source_bytes`] handle (PDF-first
/// construction) *or* the `LocaGlyfState::Deferred` slot
/// installed by [`ParsedFont::from_bytes_shared`]. The
/// production lazy path retains bytes for the lazy `LocaGlyf`
/// loader, so PDF subsetting Just Works without an extra
/// `with_source_bytes` call.
///
/// # Arguments
/// * `tags` - Optional list of specific table tags to include (None = all tables)
/// # Errors
///
/// Returns an error string if serializing the font fails.
pub fn to_bytes(&self, tags: Option<&[u32]>) -> Result<Vec<u8>, String> {
let source = self.source_bytes_for_subset().ok_or_else(|| {
"ParsedFont::to_bytes requires source bytes; construct via \
ParsedFont::from_bytes_shared (production lazy path) or \
attach via ParsedFont::with_source_bytes"
.to_string()
})?;
let scope = ReadScope::new(source.as_slice());
let font_file = scope.read::<FontData<'_>>().map_err(|e| e.to_string())?;
let provider = font_file
.table_provider(self.original_index)
.map_err(|e| e.to_string())?;
let tags_to_use = tags.unwrap_or(&[
tag::CMAP,
tag::HEAD,
tag::HHEA,
tag::HMTX,
tag::MAXP,
tag::NAME,
tag::OS_2,
tag::POST,
tag::GLYF,
tag::LOCA,
]);
whole_font(&provider, tags_to_use).map_err(|e| e.to_string())
}
/// Create a subset font containing only the specified glyph IDs
/// Returns the subset font bytes and a mapping from old to new glyph IDs
///
/// # Arguments
/// * `glyph_ids` - The glyph IDs to include in the subset (glyph 0/.notdef is always
/// included)
/// * `cmap_target` - Target cmap format (Unicode for web, `MacRoman` for compatibility)
///
/// # Returns
/// A tuple of (`subset_font_bytes`, `glyph_mapping`) where `glyph_mapping` maps
/// `original_glyph_id` -> (`new_glyph_id`, `original_char`)
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
/// # Errors
///
/// Returns an error string if subsetting the font fails.
pub fn subset(
&self,
glyph_ids: &[(u16, char)],
cmap_target: CmapTarget,
) -> Result<(Vec<u8>, BTreeMap<u16, (u16, char)>), String> {
let source = self.source_bytes_for_subset().ok_or_else(|| {
"ParsedFont::subset requires source bytes; construct via \
ParsedFont::from_bytes_shared (production lazy path) or \
attach via ParsedFont::with_source_bytes"
.to_string()
})?;
let scope = ReadScope::new(source.as_slice());
let font_file = scope.read::<FontData<'_>>().map_err(|e| e.to_string())?;
let provider = font_file
.table_provider(self.original_index)
.map_err(|e| e.to_string())?;
// Build glyph mapping: original_id -> (new_id, char)
let glyph_mapping: BTreeMap<u16, (u16, char)> = glyph_ids
.iter()
.enumerate()
.map(|(new_id, &(original_id, ch))| (original_id, (new_id as u16, ch)))
.collect();
// Extract just the glyph IDs for subsetting
let ids: Vec<u16> = glyph_ids.iter().map(|(id, _)| *id).collect();
// Use PDF profile for embedding fonts in PDFs
let font_bytes = allsorts_subset(&provider, &ids, &SubsetProfile::Pdf, cmap_target)
.map_err(|e| format!("Subset error: {e:?}"))?;
Ok((font_bytes, glyph_mapping))
}
/// Get the width of a glyph in font units (internal, unscaled)
pub fn get_glyph_width_internal(&self, glyph_index: u16) -> Option<usize> {
allsorts::glyph_info::advance(
&self.maxp_table,
&self.hhea_table,
self.hmtx_bytes(),
glyph_index,
)
.ok()
.map(|s| s as usize)
}
/// Get the width of the space character (unscaled font units)
#[inline]
pub const fn get_space_width(&self) -> Option<usize> {
self.space_width
}
/// Add glyph-to-text mapping to reverse cache
/// This should be called during text shaping when we know both the source text and
/// resulting glyphs
pub fn cache_glyph_mapping(&mut self, glyph_id: u16, cluster_text: &str) {
self.reverse_glyph_cache
.insert(glyph_id, cluster_text.to_string());
}
/// Get the cluster text that produced a specific glyph ID
/// Returns the original text that was shaped into this glyph (handles ligatures correctly)
pub fn get_glyph_cluster_text(&self, glyph_id: u16) -> Option<&str> {
self.reverse_glyph_cache.get(&glyph_id).map(String::as_str)
}
/// Get the first character from the cluster text for a glyph ID
/// This is useful for PDF `ToUnicode` `CMap` generation which requires single character
/// mappings
pub fn get_glyph_primary_char(&self, glyph_id: u16) -> Option<char> {
self.reverse_glyph_cache
.get(&glyph_id)
.and_then(|text| text.chars().next())
}
/// Clear the reverse glyph cache (useful for memory management)
pub fn clear_glyph_cache(&mut self) {
self.reverse_glyph_cache.clear();
}
/// Get the bounding box size of a glyph (unscaled units) - for PDF
/// Returns (width, height) in font units
pub fn get_glyph_bbox_size(&self, glyph_index: u16) -> Option<(i32, i32)> {
let g = self.get_or_decode_glyph(glyph_index)?;
let glyph_width = i32::from(g.horz_advance);
let glyph_height = i32::from(g.bounding_box.max_y) - i32::from(g.bounding_box.min_y);
Some((glyph_width, glyph_height))
}
}
/// Compute the bounding box from collected glyph outlines.
fn compute_outline_bbox(outlines: &[GlyphOutline]) -> (i16, i16, i16, i16) {
let mut min_x = i16::MAX;
let mut min_y = i16::MAX;
let mut max_x = i16::MIN;
let mut max_y = i16::MIN;
let mut has_points = false;
for outline in outlines {
for op in outline.operations.as_slice() {
let points: &[(i16, i16)] = match op {
GlyphOutlineOperation::MoveTo(m) => &[(m.x, m.y)],
GlyphOutlineOperation::LineTo(l) => &[(l.x, l.y)],
GlyphOutlineOperation::QuadraticCurveTo(q) => {
// Check both control and end point for bbox
min_x = min_x.min(q.ctrl_1_x).min(q.end_x);
min_y = min_y.min(q.ctrl_1_y).min(q.end_y);
max_x = max_x.max(q.ctrl_1_x).max(q.end_x);
max_y = max_y.max(q.ctrl_1_y).max(q.end_y);
has_points = true;
continue;
}
GlyphOutlineOperation::CubicCurveTo(c) => {
min_x = min_x.min(c.ctrl_1_x).min(c.ctrl_2_x).min(c.end_x);
min_y = min_y.min(c.ctrl_1_y).min(c.ctrl_2_y).min(c.end_y);
max_x = max_x.max(c.ctrl_1_x).max(c.ctrl_2_x).max(c.end_x);
max_y = max_y.max(c.ctrl_1_y).max(c.ctrl_2_y).max(c.end_y);
has_points = true;
continue;
}
GlyphOutlineOperation::ClosePath => continue,
};
for &(x, y) in points {
min_x = min_x.min(x);
min_y = min_y.min(y);
max_x = max_x.max(x);
max_y = max_y.max(y);
has_points = true;
}
}
}
if has_points {
(min_x, min_y, max_x, max_y)
} else {
(0, 0, 0, 0)
}
}
#[derive(Debug, Clone)]
pub struct OwnedGlyph {
pub bounding_box: OwnedGlyphBoundingBox,
pub horz_advance: u16,
pub outline: Vec<GlyphOutline>,
pub phantom_points: Option<[Point; 4]>,
/// Raw TrueType points in font units (for hinting). None for composite/CFF glyphs.
pub raw_points: Option<Vec<(i16, i16)>>,
/// On-curve flags for each raw point.
pub raw_on_curve: Option<Vec<bool>>,
/// Contour end-point indices (TrueType).
pub raw_contour_ends: Option<Vec<u16>>,
/// Per-glyph TrueType hinting instructions.
pub instructions: Option<Vec<u8>>,
}
// --- ParsedFontTrait Implementation for ParsedFont ---
impl crate::text3::cache::ShallowClone for ParsedFont {
fn shallow_clone(&self) -> Self {
self.clone() // ParsedFont::clone uses Arc internally, so it's shallow
}
}
impl crate::text3::cache::ParsedFontTrait for ParsedFont {
fn shape_text(
&self,
text: &str,
script: crate::font_traits::Script,
language: crate::font_traits::Language,
direction: crate::font_traits::BidiDirection,
style: &crate::font_traits::StyleProperties,
) -> Result<Vec<crate::font_traits::Glyph>, crate::font_traits::LayoutError> {
// Call the existing shape_text_for_parsed_font method (defined in default.rs)
crate::text3::default::shape_text_for_parsed_font(
self, text, script, language, direction, style,
)
}
fn get_hash(&self) -> u64 {
self.hash
}
fn get_glyph_size(
&self,
glyph_id: u16,
font_size_px: f32,
) -> Option<azul_core::geom::LogicalSize> {
self.get_or_decode_glyph(glyph_id).map(|record| {
let units_per_em = f32::from(self.font_metrics.units_per_em);
let scale_factor = if units_per_em > 0.0 {
font_size_px / units_per_em
} else {
0.01
};
let bbox = &record.bounding_box;
azul_core::geom::LogicalSize {
width: f32::from(bbox.max_x - bbox.min_x) * scale_factor,
height: f32::from(bbox.max_y - bbox.min_y) * scale_factor,
}
})
}
fn get_hyphen_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
let glyph_id = self.lookup_glyph_index('-' as u32)?;
let advance_units = self.get_horizontal_advance(glyph_id);
let scale_factor = if self.font_metrics.units_per_em > 0 {
font_size / f32::from(self.font_metrics.units_per_em)
} else {
return None;
};
let scaled_advance = f32::from(advance_units) * scale_factor;
Some((glyph_id, scaled_advance))
}
fn get_kashida_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
let glyph_id = self.lookup_glyph_index('\u{0640}' as u32)?;
let advance_units = self.get_horizontal_advance(glyph_id);
let scale_factor = if self.font_metrics.units_per_em > 0 {
font_size / f32::from(self.font_metrics.units_per_em)
} else {
return None;
};
let scaled_advance = f32::from(advance_units) * scale_factor;
Some((glyph_id, scaled_advance))
}
fn has_glyph(&self, codepoint: u32) -> bool {
self.lookup_glyph_index(codepoint).is_some()
}
fn get_vertical_metrics(
&self,
glyph_id: u16,
) -> Option<crate::text3::cache::VerticalMetrics> {
self.get_vertical_metrics(glyph_id)
}
fn get_font_metrics(&self) -> LayoutFontMetrics {
self.font_metrics
}
fn num_glyphs(&self) -> u16 {
self.num_glyphs
}
fn get_space_width(&self) -> Option<usize> {
self.space_width
}
}
/// Build an agg-rust `PathStorage` from an `OwnedGlyph` outline (in font units, Y-up → Y-down).
///
/// Returns `None` if the glyph has no outline operations (e.g. space).
/// The caller is responsible for applying scale and translation transforms.
#[cfg(feature = "cpurender")]
#[must_use] pub fn build_glyph_path(glyph: &OwnedGlyph) -> Option<agg_rust::path_storage::PathStorage> {
use agg_rust::{basics::PATH_FLAGS_NONE, path_storage::PathStorage};
let mut path = PathStorage::new();
let mut has_ops = false;
for outline in &glyph.outline {
for op in outline.operations.as_slice() {
has_ops = true;
match op {
GlyphOutlineOperation::MoveTo(OutlineMoveTo { x, y }) => {
path.move_to(f64::from(*x), -f64::from(*y));
}
GlyphOutlineOperation::LineTo(OutlineLineTo { x, y }) => {
path.line_to(f64::from(*x), -f64::from(*y));
}
GlyphOutlineOperation::QuadraticCurveTo(OutlineQuadTo {
ctrl_1_x, ctrl_1_y, end_x, end_y,
}) => {
path.curve3(
f64::from(*ctrl_1_x), -f64::from(*ctrl_1_y),
f64::from(*end_x), -f64::from(*end_y),
);
}
GlyphOutlineOperation::CubicCurveTo(OutlineCubicTo {
ctrl_1_x, ctrl_1_y, ctrl_2_x, ctrl_2_y, end_x, end_y,
}) => {
path.curve4(
f64::from(*ctrl_1_x), -f64::from(*ctrl_1_y),
f64::from(*ctrl_2_x), -f64::from(*ctrl_2_y),
f64::from(*end_x), -f64::from(*end_y),
);
}
GlyphOutlineOperation::ClosePath => {
path.close_polygon(PATH_FLAGS_NONE);
}
}
}
}
if !has_ops {
return None;
}
Some(path)
}
#[cfg(test)]
mod autotest_generated {
//! Adversarial unit tests generated by the autotest fleet.
//!
//! Lives inside `mod parsed` (not at file scope) so it can reach the
//! private sfnt scanner (`manual_be16` / `manual_be32` /
//! `ManualTableProvider`), the outline collector, and the private
//! `ParsedFont` getters.
use allsorts::tables::SfntVersion;
use super::*;
/// Positive control: the built-in `Azul Mock Mono` TrueType font.
/// 13 tables, `glyf` outlines (no CFF), no `vhea`/`vmtx`, upem 1000,
/// 96 glyphs, GSUB + GPOS + GDEF present (empty lists, presence-only).
const MOCK_MONO: &[u8] = crate::text3::mock_fonts::MOCK_MONO_TTF;
fn parse_mock() -> ParsedFont {
let mut warnings = Vec::new();
ParsedFont::from_bytes(MOCK_MONO, 0, &mut warnings)
.expect("Azul Mock Mono must parse (positive control)")
}
fn mock_shared() -> ParsedFont {
let bytes = Arc::new(rust_fontconfig::FontBytes::Owned(Arc::from(MOCK_MONO.to_vec())));
let mut warnings = Vec::new();
ParsedFont::from_bytes_shared(bytes, 0, &mut warnings)
.expect("from_bytes_shared must parse the positive control")
}
fn plain_metrics() -> LayoutFontMetrics {
LayoutFontMetrics {
ascent: 800.0,
descent: -200.0,
line_gap: 0.0,
units_per_em: 1000,
x_height: None,
cap_height: None,
}
}
fn plain_hhea() -> HheaTable {
HheaTable {
ascender: 800,
descender: -200,
line_gap: 0,
advance_width_max: 1000,
min_left_side_bearing: 0,
min_right_side_bearing: 0,
x_max_extent: 0,
caret_slope_rise: 1,
caret_slope_run: 0,
caret_offset: 0,
num_h_metrics: 0,
}
}
/// A hand-built `ParsedFont` with no tables, no cmap and no source
/// bytes — the "default / empty / extreme instance" every getter has
/// to survive.
fn synthetic_font(num_glyphs: u16, mock: Option<Box<MockFont>>) -> ParsedFont {
ParsedFont {
hash: 0,
font_metrics: plain_metrics(),
pdf_font_metrics: PdfFontMetrics::zero(),
num_glyphs,
hhea_table: plain_hhea(),
hmtx_range: (0, 0),
vmtx_range: (0, 0),
vhea_table: None,
maxp_table: MaxpTable {
num_glyphs,
version1_sub_table: None,
},
gsub_bytes: None,
gsub_cache_lazy: std::sync::OnceLock::new(),
gpos_bytes: None,
gpos_cache_lazy: std::sync::OnceLock::new(),
opt_gdef_table: None,
opt_kern_table: None,
last_used: Arc::new(std::sync::atomic::AtomicU64::new(0)),
is_variable_font: false,
glyph_cache: Arc::new(rust_fontconfig::StLock::new(BTreeMap::new())),
loca_glyf: LocaGlyfState::Loaded(None),
space_width: None,
cmap_subtable: None,
mock,
reverse_glyph_cache: BTreeMap::new(),
original_bytes: None,
original_index: 0,
index_to_cid: BTreeMap::new(),
font_type: FontType::TrueType,
font_name: None,
hint_instance: None,
}
}
// ---------------------------------------------------------------
// manual_be16 / manual_be32 (numeric)
// ---------------------------------------------------------------
#[test]
fn manual_be16_zero_max_and_offset() {
assert_eq!(manual_be16(&[0x00, 0x00], 0), 0);
assert_eq!(manual_be16(&[0xFF, 0xFF], 0), 0xFFFF);
assert_eq!(manual_be16(&[0x12, 0x34], 0), 0x1234);
// the widest 16-bit value still fits the u32 return: no truncation
assert_eq!(manual_be16(&[0xAA, 0xBB, 0xFF, 0xFF], 2), u32::from(u16::MAX));
// offsets address the right bytes, not the first ones
assert_eq!(manual_be16(&[0xAA, 0xBB, 0x00, 0x01], 2), 1);
}
#[test]
fn manual_be32_zero_max_and_known_tags() {
assert_eq!(manual_be32(&[0, 0, 0, 0], 0), 0);
// saturating the whole word must not overflow the u32 accumulator
assert_eq!(manual_be32(&[0xFF, 0xFF, 0xFF, 0xFF], 0), u32::MAX);
assert_eq!(manual_be32(b"ttcf", 0), 0x7474_6366);
assert_eq!(manual_be32(&[0x00, 0x01, 0x00, 0x00], 0), 0x0001_0000);
assert_eq!(manual_be32(&[0xEE, 0x00, 0x01, 0x00, 0x00], 1), 0x0001_0000);
// high bit set: the shift must stay unsigned (no sign extension)
assert_eq!(manual_be32(&[0x80, 0x00, 0x00, 0x00], 0), 0x8000_0000);
}
// ---------------------------------------------------------------
// ManualTableProvider (parser)
// ---------------------------------------------------------------
#[test]
fn manual_table_provider_rejects_short_input() {
assert!(ManualTableProvider::new(&[], 0).is_none()); // empty
assert!(ManualTableProvider::new(b" ", 0).is_none()); // whitespace-only
assert!(ManualTableProvider::new(b" \t\n", 0).is_none());
assert!(ManualTableProvider::new(&[0xFF, 0xFE, 0x00], 0).is_none()); // invalid utf8
assert!(ManualTableProvider::new(&[0u8; 11], 0).is_none()); // one byte short
assert!(ManualTableProvider::new(&[0u8; 12], 0).is_some()); // exact minimum
}
#[test]
fn manual_table_provider_garbage_header_terminates() {
// numTables reads back 0xFFFF but every record is past the end of the
// buffer: the scan must break immediately instead of walking off it.
let data = [0xFFu8; 12];
let p = ManualTableProvider::new(&data, 0).expect("12 bytes form an offset table");
assert_eq!(p.num, 0xFFFF);
assert!(p.table_data(tag::HEAD).unwrap().is_none());
assert!(!p.has_table(tag::GLYF));
// table_tags always leads with the 0xFADE sentinel, then stops at the end
assert_eq!(p.table_tags().unwrap(), vec![0x0000_FADE]);
}
#[test]
fn manual_table_provider_ttc_index_out_of_range_is_none() {
let mut data = b"ttcf".to_vec();
data.extend_from_slice(&[0x00, 0x01, 0x00, 0x00]); // version 1.0
data.extend_from_slice(&1u32.to_be_bytes()); // numFonts = 1
data.extend_from_slice(&0u32.to_be_bytes()); // offset[0]
assert!(ManualTableProvider::new(&data, 0).is_some());
// index >= numFonts short-circuits *before* the `12 + font_index * 4`
// arithmetic, so even usize::MAX cannot overflow it
assert!(ManualTableProvider::new(&data, 1).is_none());
assert!(ManualTableProvider::new(&data, 999_999).is_none());
assert!(ManualTableProvider::new(&data, usize::MAX).is_none());
}
#[test]
fn manual_table_provider_ttc_offset_past_end_is_none() {
let mut data = b"ttcf".to_vec();
data.extend_from_slice(&[0x00, 0x01, 0x00, 0x00]);
data.extend_from_slice(&1u32.to_be_bytes());
data.extend_from_slice(&u32::MAX.to_be_bytes()); // offset[0] = 4 GiB
assert!(ManualTableProvider::new(&data, 0).is_none());
}
#[test]
fn manual_table_provider_table_record_past_end_yields_none() {
// One record whose (offset, length) points past the buffer: the
// checked_add + bounds filter must turn it into None, not an OOB slice.
let mut data = vec![0u8; 12 + 16];
data[0..4].copy_from_slice(&0x0001_0000u32.to_be_bytes()); // sfnt version
data[4..6].copy_from_slice(&1u16.to_be_bytes()); // numTables = 1
data[12..16].copy_from_slice(&tag::HEAD.to_be_bytes()); // tag
data[20..24].copy_from_slice(&u32::MAX.to_be_bytes()); // offset = 4 GiB
data[24..28].copy_from_slice(&u32::MAX.to_be_bytes()); // length = 4 GiB
let p = ManualTableProvider::new(&data, 0).unwrap();
assert!(p.table_data(tag::HEAD).unwrap().is_none());
assert!(!p.has_table(tag::HEAD));
}
#[test]
fn manual_table_provider_one_megabyte_of_zeros_terminates() {
let data = vec![0u8; 1_000_000];
let p = ManualTableProvider::new(&data, 0).expect("zeros form a degenerate header");
assert_eq!(p.num, 0); // numTables = 0: nothing to scan
assert!(p.table_data(tag::HEAD).unwrap().is_none());
assert_eq!(p.sfnt_version(), 0);
}
#[test]
fn manual_table_provider_reads_a_real_font() {
let p = ManualTableProvider::new(MOCK_MONO, 0).expect("a real TTF must produce a provider");
assert_eq!(p.sfnt_version(), 0x0001_0000);
assert_eq!(p.num, 13);
assert!(p.has_table(tag::HEAD));
assert!(p.has_table(tag::GLYF) && p.has_table(tag::LOCA));
assert!(!p.has_table(tag::CFF)); // Azul Mock Mono is TrueType, not OpenType-PostScript
let head = p.table_data(tag::HEAD).unwrap().expect("head must be present");
// head.magicNumber sits at offset 12 and is fixed by the spec
assert_eq!(manual_be32(head.as_ref(), 12), 0x5F0F_3CF5);
let tags = p.table_tags().unwrap();
assert_eq!(tags[0], 0x0000_FADE); // diagnostic sentinel
assert_eq!(tags.len(), 14); // sentinel + 13 records
assert!(tags.contains(&tag::GLYF));
}
// ---------------------------------------------------------------
// monotonic_now_nanos
// ---------------------------------------------------------------
#[test]
fn monotonic_now_nanos_never_goes_backwards() {
let a = monotonic_now_nanos();
let b = monotonic_now_nanos();
assert!(b >= a, "clock went backwards: {a} -> {b}");
// the `as u64` truncation cannot wrap in any realistic process lifetime
assert!(b < 60 * 60 * 1_000_000_000);
}
// ---------------------------------------------------------------
// GlyphOutlineCollector
// ---------------------------------------------------------------
#[test]
fn glyph_outline_collector_new_is_empty() {
assert!(GlyphOutlineCollector::new().into_outlines().is_empty());
}
#[test]
fn glyph_outline_collector_flushes_an_unclosed_contour() {
let mut c = GlyphOutlineCollector::new();
c.move_to(Vector2F::new(1.0, 2.0));
c.line_to(Vector2F::new(3.0, 4.0));
// no close(): into_outlines must still flush the pending contour
let outlines = c.into_outlines();
assert_eq!(outlines.len(), 1);
assert_eq!(outlines[0].operations.as_slice().len(), 2);
}
#[test]
fn glyph_outline_collector_splits_contours_on_move_to() {
let mut c = GlyphOutlineCollector::new();
c.move_to(Vector2F::new(0.0, 0.0));
c.line_to(Vector2F::new(10.0, 0.0));
c.close();
// close() already flushed, so this move_to must not emit an empty contour
c.move_to(Vector2F::new(0.0, 0.0));
c.quadratic_curve_to(Vector2F::new(1.0, 1.0), Vector2F::new(2.0, 2.0));
c.cubic_curve_to(
LineSegment2F::new(Vector2F::new(1.0, 1.0), Vector2F::new(2.0, 2.0)),
Vector2F::new(3.0, 3.0),
);
let outlines = c.into_outlines();
assert_eq!(outlines.len(), 2);
assert_eq!(outlines[0].operations.as_slice().len(), 3); // move, line, close
assert_eq!(outlines[1].operations.as_slice().len(), 3); // move, quad, cubic
}
#[test]
fn glyph_outline_collector_saturates_nan_and_infinite_coordinates() {
// allsorts hands us f32s; the `as i16` casts in the sink saturate
// (NaN -> 0, ±inf -> i16::MAX/MIN) rather than wrapping or trapping.
let mut c = GlyphOutlineCollector::new();
c.move_to(Vector2F::new(f32::NAN, f32::INFINITY));
c.line_to(Vector2F::new(f32::NEG_INFINITY, 1e30));
let outlines = c.into_outlines();
let ops = outlines[0].operations.as_slice();
if let GlyphOutlineOperation::MoveTo(m) = &ops[0] {
assert_eq!(m.x, 0); // NaN -> 0
assert_eq!(m.y, i16::MAX); // +inf saturates
} else {
panic!("first op must be a MoveTo");
}
if let GlyphOutlineOperation::LineTo(l) = &ops[1] {
assert_eq!(l.x, i16::MIN); // -inf saturates
assert_eq!(l.y, i16::MAX); // 1e30 saturates
} else {
panic!("second op must be a LineTo");
}
}
// ---------------------------------------------------------------
// compute_outline_bbox
// ---------------------------------------------------------------
#[test]
fn compute_outline_bbox_without_points_is_zero_not_the_sentinel_seed() {
assert_eq!(compute_outline_bbox(&[]), (0, 0, 0, 0));
let only_close = GlyphOutline {
operations: vec![GlyphOutlineOperation::ClosePath].into(),
};
// ClosePath contributes no points: must not leak the
// (i16::MAX, i16::MAX, i16::MIN, i16::MIN) accumulator seed
assert_eq!(
compute_outline_bbox(std::slice::from_ref(&only_close)),
(0, 0, 0, 0)
);
}
#[test]
fn compute_outline_bbox_covers_control_points_and_i16_extremes() {
let outline = GlyphOutline {
operations: vec![
GlyphOutlineOperation::MoveTo(OutlineMoveTo {
x: i16::MIN,
y: i16::MAX,
}),
GlyphOutlineOperation::LineTo(OutlineLineTo { x: 0, y: 0 }),
GlyphOutlineOperation::QuadraticCurveTo(OutlineQuadTo {
ctrl_1_x: 5,
ctrl_1_y: -5,
end_x: 6,
end_y: -6,
}),
GlyphOutlineOperation::CubicCurveTo(OutlineCubicTo {
ctrl_1_x: i16::MAX,
ctrl_1_y: i16::MIN,
ctrl_2_x: 0,
ctrl_2_y: 0,
end_x: 1,
end_y: 1,
}),
GlyphOutlineOperation::ClosePath,
]
.into(),
};
// control points participate in the bbox, and the i16 extremes must not wrap
assert_eq!(
compute_outline_bbox(std::slice::from_ref(&outline)),
(i16::MIN, i16::MIN, i16::MAX, i16::MAX)
);
}
#[test]
fn compute_outline_bbox_spans_every_contour() {
let a = GlyphOutline {
operations: vec![GlyphOutlineOperation::MoveTo(OutlineMoveTo { x: -10, y: -10 })]
.into(),
};
let b = GlyphOutline {
operations: vec![GlyphOutlineOperation::LineTo(OutlineLineTo { x: 20, y: 30 })]
.into(),
};
assert_eq!(compute_outline_bbox(&[a, b]), (-10, -10, 20, 30));
}
// ---------------------------------------------------------------
// PdfFontMetrics
// ---------------------------------------------------------------
#[test]
fn pdf_font_metrics_zero_never_divides_by_zero() {
let z = PdfFontMetrics::zero();
assert_eq!(z.units_per_em, 1000); // callers divide by this: never 0
assert_eq!(z.ascender, 0);
assert_eq!(z.descender, 0);
assert_eq!(z.line_gap, 0);
assert_eq!(z.advance_width_max, 0);
assert_eq!(z.us_weight_class, 0);
assert_eq!(z.y_strikeout_position, 0);
assert_eq!(PdfFontMetrics::default(), z); // Default is the neutral element
let copied = z; // Copy: the zero value is trivially duplicable
assert_eq!(copied, z);
}
// ---------------------------------------------------------------
// SubsetFont::subset_text
// ---------------------------------------------------------------
#[test]
fn subset_text_with_an_empty_mapping_drops_everything() {
let f = SubsetFont {
bytes: Vec::new(),
glyph_mapping: BTreeMap::new(),
};
assert_eq!(f.subset_text(""), "");
assert_eq!(f.subset_text("hello"), "");
// emoji + combining mark: multibyte input must not panic or slice mid-char
assert_eq!(f.subset_text("\u{1F600}e\u{0301}"), "");
}
#[test]
fn subset_text_remaps_chars_to_their_new_gids() {
let mut m = BTreeMap::new();
m.insert(40u16, (65u16, 'A')); // old gid 40 -> new gid 65 -> U+0041
m.insert(41u16, (66u16, 'B'));
let f = SubsetFont {
bytes: Vec::new(),
glyph_mapping: m,
};
assert_eq!(f.subset_text("AB"), "AB");
assert_eq!(f.subset_text("BA"), "BA");
assert_eq!(f.subset_text("A?B"), "AB"); // unmapped chars are dropped
}
#[test]
fn subset_text_gid_boundaries() {
let mut m = BTreeMap::new();
m.insert(1u16, (0u16, 'x')); // new gid 0 -> U+0000
m.insert(2u16, (0xD800u16, 'y')); // surrogate: char::from_u32 -> None
m.insert(3u16, (u16::MAX, 'z')); // U+FFFF is a valid scalar value
let f = SubsetFont {
bytes: Vec::new(),
glyph_mapping: m,
};
assert_eq!(f.subset_text("x"), "\u{0}");
assert_eq!(f.subset_text("y"), ""); // a surrogate gid is silently dropped
assert_eq!(f.subset_text("z"), "\u{FFFF}");
assert_eq!(f.subset_text("xyz"), "\u{0}\u{FFFF}");
}
#[test]
fn subset_text_long_input_terminates() {
let mut m = BTreeMap::new();
m.insert(7u16, (97u16, 'a'));
let f = SubsetFont {
bytes: Vec::new(),
glyph_mapping: m,
};
assert_eq!(f.subset_text(&"a".repeat(100_000)).len(), 100_000);
}
// ---------------------------------------------------------------
// FontParseWarning
// ---------------------------------------------------------------
#[test]
fn font_parse_warning_constructors_preserve_severity_and_message() {
let empty = FontParseWarning::info(String::new());
assert_eq!(empty.severity, FontParseWarningSeverity::Info);
assert!(empty.message.is_empty());
let unicode = FontParseWarning::warning("\u{1F4A5} e\u{0301}\u{202E}".to_string());
assert_eq!(unicode.severity, FontParseWarningSeverity::Warning);
assert_eq!(unicode.message, "\u{1F4A5} e\u{0301}\u{202E}");
let huge = FontParseWarning::error("x".repeat(1_000_000));
assert_eq!(huge.severity, FontParseWarningSeverity::Error);
assert_eq!(huge.message.len(), 1_000_000);
// severity is part of the identity: same message, different level
assert_ne!(
FontParseWarning::error("boom".to_string()),
FontParseWarning::warning("boom".to_string())
);
}
// ---------------------------------------------------------------
// MockFont (constructors)
// ---------------------------------------------------------------
#[test]
fn mock_font_new_defaults_and_extreme_metrics() {
let m = MockFont::new(plain_metrics());
assert_eq!(m.space_width, Some(10)); // documented default
assert!(m.glyph_advances.is_empty());
assert!(m.glyph_sizes.is_empty());
assert!(m.glyph_indices.is_empty());
// metrics are stored verbatim: no normalisation, no panic on NaN/inf/0-upem
let extreme = MockFont::new(LayoutFontMetrics {
ascent: f32::INFINITY,
descent: f32::NAN,
line_gap: f32::MIN,
units_per_em: 0,
x_height: Some(f32::MAX),
cap_height: None,
});
assert!(extreme.font_metrics.ascent.is_infinite());
assert!(extreme.font_metrics.descent.is_nan());
assert_eq!(extreme.font_metrics.units_per_em, 0);
assert_eq!(extreme.space_width, Some(10));
}
#[test]
fn mock_font_builders_store_boundary_values() {
let m = MockFont::new(plain_metrics())
.with_space_width(usize::MAX)
.with_glyph_advance(0, 0)
.with_glyph_advance(u16::MAX, u16::MAX)
.with_glyph_size(u16::MAX, (i32::MIN, i32::MAX))
.with_glyph_index(0, 0)
.with_glyph_index(u32::MAX, u16::MAX); // not a scalar value: stored anyway
assert_eq!(m.space_width, Some(usize::MAX));
assert_eq!(m.glyph_advances.len(), 2);
assert_eq!(m.glyph_advances.get(&u16::MAX), Some(&u16::MAX));
assert_eq!(m.glyph_sizes.get(&u16::MAX), Some(&(i32::MIN, i32::MAX)));
assert_eq!(m.glyph_indices.len(), 2);
assert_eq!(m.glyph_indices.get(&u32::MAX), Some(&u16::MAX));
// last write wins, and an overwrite must not grow the map
let m = m.with_glyph_advance(u16::MAX, 7).with_space_width(0);
assert_eq!(m.glyph_advances.get(&u16::MAX), Some(&7));
assert_eq!(m.glyph_advances.len(), 2);
assert_eq!(m.space_width, Some(0));
}
// ---------------------------------------------------------------
// ParsedFont::from_bytes (parser)
// ---------------------------------------------------------------
#[test]
fn from_bytes_rejects_malformed_input() {
let cases: Vec<(&str, Vec<u8>)> = vec![
("empty", Vec::new()),
("whitespace_only", b" \t\n".to_vec()),
("garbage", (0u8..=255).cycle().take(4096).collect()),
("invalid_utf8", vec![0xFF, 0xFE, 0x00]),
("header_only", MOCK_MONO[..12].to_vec()),
("truncated_font", MOCK_MONO[..64].to_vec()),
("half_a_font", MOCK_MONO[..MOCK_MONO.len() / 2].to_vec()),
("one_megabyte_of_nuls", vec![0u8; 1_000_000]),
("ttcf_junk", {
let mut v = b"ttcf".to_vec();
v.extend_from_slice(&[0xABu8; 1024].repeat(1000));
v
}),
];
for (name, bytes) in cases {
let mut warnings = Vec::new();
assert!(
ParsedFont::from_bytes(&bytes, 0, &mut warnings).is_none(),
"{name} must not parse into a font"
);
}
}
#[test]
fn from_bytes_appends_a_warning_on_failure() {
let mut warnings = Vec::new();
assert!(ParsedFont::from_bytes(&[], 0, &mut warnings).is_none());
assert!(!warnings.is_empty(), "a failed parse must explain itself");
assert!(warnings
.iter()
.any(|w| w.severity == FontParseWarningSeverity::Error));
// the caller's vec is appended to, never cleared
let before = warnings.len();
assert!(ParsedFont::from_bytes(&[0xFF; 3], 0, &mut warnings).is_none());
assert!(warnings.len() > before);
}
#[test]
fn from_bytes_parses_the_positive_control() {
let font = parse_mock();
assert_eq!(font.num_glyphs(), 96);
assert_eq!(font.num_glyphs(), font.maxp_table.num_glyphs);
assert_eq!(font.font_metrics.units_per_em, 1000);
assert!(font.font_metrics.ascent > 0.0);
assert_eq!(font.font_type, FontType::TrueType);
assert_eq!(font.original_index, 0);
assert_eq!(font.pdf_font_metrics.units_per_em, 1000);
assert!(font.pdf_font_metrics.x_max > font.pdf_font_metrics.x_min);
assert!(font.cmap_subtable.is_some());
assert!(font.gsub_bytes.is_some() && font.gpos_bytes.is_some());
assert!(font.hmtx_range.1 > 0, "hmtx must be located in the source");
assert_eq!(font.vmtx_range, (0, 0), "Azul Mock Mono has no vertical metrics");
assert!(!font.is_variable_font);
}
#[test]
fn from_bytes_with_an_out_of_range_font_index_is_deterministic() {
let baseline = parse_mock();
let mut warnings = Vec::new();
// Azul Mock Mono is a single face, not a .ttc: the manual provider ignores the index
// rather than rejecting it. What must NOT happen is a panic or a
// `12 + font_index * 4` overflow.
if let Some(font) = ParsedFont::from_bytes(MOCK_MONO, usize::MAX, &mut warnings) {
assert_eq!(font.num_glyphs(), baseline.num_glyphs());
assert_eq!(font.original_index, usize::MAX);
assert_ne!(font.hash, baseline.hash, "font_index feeds the identity hash");
}
}
#[test]
fn from_bytes_internal_deferred_flag_skips_the_eager_loca_glyf_load() {
let mut warnings = Vec::new();
let eager = ParsedFont::from_bytes_internal(MOCK_MONO, 0, &mut warnings, false)
.expect("eager parse");
assert!(matches!(eager.loca_glyf, LocaGlyfState::Loaded(Some(_))));
let deferred = ParsedFont::from_bytes_internal(MOCK_MONO, 0, &mut warnings, true)
.expect("deferred parse");
// deferring leaves the slot empty for from_bytes_shared to overwrite
assert!(matches!(deferred.loca_glyf, LocaGlyfState::Loaded(None)));
assert_eq!(eager.num_glyphs(), deferred.num_glyphs());
assert_eq!(eager.hash, deferred.hash);
}
// ---------------------------------------------------------------
// cmap lookups (numeric / predicate)
// ---------------------------------------------------------------
#[test]
fn lookup_glyph_index_handles_codepoint_extremes() {
let font = parse_mock();
assert!(font.lookup_glyph_index('A' as u32).is_some());
// 0, the last valid scalar value, and values beyond the Unicode range must
// all resolve deterministically without panicking
for cp in [0u32, 0x0010_FFFF, 0x0011_0000, u32::MAX / 2, u32::MAX] {
let first = font.lookup_glyph_index(cp);
assert_eq!(first, font.lookup_glyph_index(cp), "cp {cp} must be stable");
// has_glyph is defined as lookup_glyph_index().is_some()
assert_eq!(first.is_some(), font.has_glyph(cp));
}
assert!(!font.has_glyph(0x0010_FFFF));
assert!(!font.has_glyph(u32::MAX));
}
// ---------------------------------------------------------------
// advances (numeric)
// ---------------------------------------------------------------
#[test]
fn get_horizontal_advance_saturates_out_of_range_gids() {
let font = parse_mock();
let gid_a = font.lookup_glyph_index('A' as u32).expect("'A' is in Azul Mock Mono");
assert!(font.get_horizontal_advance(gid_a) > 0);
// out-of-range gid: allsorts short-circuits to 0 rather than erroring
assert!(font.num_glyphs() < u16::MAX);
assert_eq!(font.get_horizontal_advance(font.num_glyphs()), 0);
assert_eq!(font.get_horizontal_advance(u16::MAX), 0);
}
#[test]
fn get_glyph_width_internal_matches_hmtx_and_never_panics() {
let font = parse_mock();
let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
assert_eq!(
font.get_glyph_width_internal(gid_a),
Some(usize::from(font.get_horizontal_advance(gid_a)))
);
// an out-of-range gid yields Some(0) (allsorts returns Ok(0)), never None/panic
assert_eq!(font.get_glyph_width_internal(u16::MAX), Some(0));
assert_eq!(font.get_glyph_width_internal(font.num_glyphs()), Some(0));
}
#[test]
fn space_width_is_cached_at_parse_time() {
let font = parse_mock();
let space_gid = font
.lookup_glyph_index(' ' as u32)
.expect("Azul Mock Mono has a space glyph");
let live = usize::from(font.get_horizontal_advance(space_gid));
assert!(live > 0, "the live hmtx advance for space must be non-zero");
let cached = font
.get_space_width()
.expect("space_width is populated at parse time");
// NOTE: `space_width` is computed inside `from_bytes_internal`, *before* the
// source bytes are attached, so hmtx is unreadable at that point and the
// cached value can legitimately read back 0 (see the comment there).
assert!(
cached == 0 || cached == live,
"space_width must be 0 (stale) or the hmtx advance; got {cached} vs {live}"
);
assert_eq!(font.get_space_width(), font.space_width);
}
#[test]
fn get_hinted_advance_px_rejects_degenerate_inputs() {
let font = parse_mock();
let gid = font.lookup_glyph_index('A' as u32).unwrap();
// ppem 0 would divide by zero when computing the scale
assert!(font.get_hinted_advance_px(gid, 0).is_none());
// out-of-range gid is gated by get_or_decode_glyph
assert!(font.get_hinted_advance_px(u16::MAX, 16).is_none());
assert!(font.get_hinted_advance_px(font.num_glyphs(), 16).is_none());
// extreme ppem must not overflow the F26Dot6 fixed-point math; whatever
// comes back is a finite, non-negative, whole-pixel value
for ppem in [1u16, 16, 255, 4096, u16::MAX] {
if let Some(px) = font.get_hinted_advance_px(gid, ppem) {
assert!(px.is_finite(), "ppem {ppem} produced {px}");
assert!(px >= 0.0, "ppem {ppem} produced {px}");
assert!(
(px - px.trunc()).abs() < f32::EPSILON,
"the advance is rounded to the whole-pixel grid, got {px}"
);
}
}
}
// ---------------------------------------------------------------
// glyph decode + lazy cache
// ---------------------------------------------------------------
#[test]
fn get_or_decode_glyph_bounds_and_cache_identity() {
let font = parse_mock();
assert!(font.num_glyphs() > 1);
// gid >= num_glyphs is refused before any decode is attempted
assert!(font.get_or_decode_glyph(font.num_glyphs()).is_none());
assert!(font.get_or_decode_glyph(u16::MAX).is_none());
let a = font.get_or_decode_glyph(0).expect(".notdef must decode");
let b = font.get_or_decode_glyph(0).expect("the cache must hand it back");
assert!(Arc::ptr_eq(&a, &b), "a second call must hit the cache");
let snap = font.glyph_cache_snapshot();
assert!(Arc::ptr_eq(snap.get(&0).expect("gid 0 is cached"), &a));
assert!(!snap.contains_key(&font.num_glyphs()));
}
#[test]
fn get_or_decode_glyph_stamps_the_lru_clock() {
let font = parse_mock();
assert_eq!(font.last_used_nanos(), 0, "an untouched face reports 0");
let _ = font.get_or_decode_glyph(0);
let t = font.last_used_nanos();
assert!(t > 0, "decoding must stamp last_used");
let _ = font.get_or_decode_glyph(1);
assert!(font.last_used_nanos() >= t, "the stamp must not go backwards");
}
#[test]
fn prime_glyph_cache_decodes_every_glyph_and_is_idempotent() {
let mut font = parse_mock();
// the lazy cache starts empty (the space stub is skipped while the source
// bytes are still unattached)
assert!(font.glyph_cache_snapshot().is_empty());
font.prime_glyph_cache();
let snap = font.glyph_cache_snapshot();
assert_eq!(snap.len(), usize::from(font.num_glyphs()));
assert!(snap.contains_key(&0));
assert!(!snap.contains_key(&font.num_glyphs()), "never decodes past the end");
let mut seen = 0usize;
let mut max_gid = 0u16;
font.for_each_decoded_glyph(|gid, _| {
seen += 1;
max_gid = max_gid.max(gid);
});
assert_eq!(seen, snap.len());
assert_eq!(max_gid, font.num_glyphs() - 1);
font.prime_glyph_cache(); // priming twice must not duplicate or grow
assert_eq!(font.glyph_cache_snapshot().len(), snap.len());
}
#[test]
fn decode_glyph_inner_seeds_the_bbox_from_the_advance() {
let font = parse_mock();
let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
let g = font.decode_glyph_inner(gid_a);
assert_eq!(g.horz_advance, font.get_horizontal_advance(gid_a));
assert!(!g.outline.is_empty(), "'A' has a glyf outline");
assert!(g.bounding_box.max_x > g.bounding_box.min_x);
assert!(g.bounding_box.max_y > g.bounding_box.min_y);
assert!(g.raw_points.is_some() && g.raw_on_curve.is_some());
assert_eq!(
g.raw_points.as_ref().map(Vec::len),
g.raw_on_curve.as_ref().map(Vec::len),
"one on-curve flag per raw point"
);
// gid 0 (.notdef) decodes too, and the bbox stays inside i16
let notdef = font.decode_glyph_inner(0);
assert!(notdef.bounding_box.max_x >= notdef.bounding_box.min_x);
}
#[test]
fn get_glyph_bbox_size_bounds() {
let font = parse_mock();
let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
let (w, h) = font.get_glyph_bbox_size(gid_a).expect("'A' has a bbox");
assert!(w > 0 && h > 0);
assert_eq!(w, i32::from(font.get_horizontal_advance(gid_a)));
// out-of-range gid -> None (not a zero-sized box)
assert!(font.get_glyph_bbox_size(u16::MAX).is_none());
assert!(font.get_glyph_bbox_size(font.num_glyphs()).is_none());
}
#[test]
fn get_vertical_metrics_without_vmtx_is_none() {
let font = parse_mock();
// Azul Mock Mono has neither vhea nor vmtx
assert!(font.get_vertical_metrics(0).is_none());
assert!(font.get_vertical_metrics(u16::MAX).is_none());
// vhea present but a zero-length vmtx range must still bail out
let mut synthetic = synthetic_font(4, None);
synthetic.vhea_table = Some(plain_hhea());
assert_eq!(synthetic.vmtx_range.1, 0);
assert!(synthetic.get_vertical_metrics(0).is_none());
}
// ---------------------------------------------------------------
// lazy loca/glyf: from_bytes_shared, eviction
// ---------------------------------------------------------------
#[test]
fn from_bytes_shared_defers_loca_glyf_and_can_evict() {
let font = mock_shared();
assert!(matches!(font.loca_glyf, LocaGlyfState::Deferred { .. }));
assert!(font.source_bytes_for_subset().is_some());
// nothing is loaded until the first decode, so there is nothing to evict yet
assert!(!font.evict_loca_glyf());
let g1 = font.get_or_decode_glyph(1).expect("gid 1 must decode");
assert!(font.evict_loca_glyf(), "a loaded Deferred slot is evictable");
assert!(!font.evict_loca_glyf(), "evicting twice is a no-op");
// after eviction the face still decodes: it re-parses from the retained bytes
let g2 = font.get_or_decode_glyph(2).expect("gid 2 decodes after eviction");
assert_eq!(g2.horz_advance, font.get_horizontal_advance(2));
// and already-decoded glyphs still come from the glyph cache
assert!(Arc::ptr_eq(&g1, &font.get_or_decode_glyph(1).unwrap()));
}
#[test]
fn eager_faces_are_not_evictable() {
let font = parse_mock();
assert!(matches!(font.loca_glyf, LocaGlyfState::Loaded(Some(_))));
let _ = font.get_or_decode_glyph(0);
// Loaded faces have no retained source bytes to re-parse from
assert!(!font.evict_loca_glyf());
assert!(font.resolve_loca_glyf().is_some());
}
#[test]
fn eager_and_deferred_paths_decode_identical_glyphs() {
let eager = parse_mock();
let lazy = mock_shared();
assert_eq!(eager.num_glyphs(), lazy.num_glyphs());
assert_eq!(eager.hash, lazy.hash); // same bytes + index -> same identity
assert_eq!(eager, lazy); // PartialEq is hash-based
let gid = eager.lookup_glyph_index('A' as u32).unwrap();
assert_eq!(lazy.lookup_glyph_index('A' as u32), Some(gid));
let a = eager.get_or_decode_glyph(gid).unwrap();
let b = lazy.get_or_decode_glyph(gid).unwrap();
assert_eq!(a.horz_advance, b.horz_advance);
assert_eq!(a.outline.len(), b.outline.len());
assert_eq!(a.bounding_box.min_x, b.bounding_box.min_x);
assert_eq!(a.bounding_box.min_y, b.bounding_box.min_y);
assert_eq!(a.bounding_box.max_x, b.bounding_box.max_x);
assert_eq!(a.bounding_box.max_y, b.bounding_box.max_y);
}
#[test]
fn with_source_bytes_shares_the_arc() {
let font = parse_mock();
// from_bytes retains an owned copy, so subsetting works without an
// explicit with_source_bytes call
let auto = font
.source_bytes_for_subset()
.expect("from_bytes retains the source bytes");
assert_eq!(auto.as_slice(), MOCK_MONO);
let arc = Arc::new(rust_fontconfig::FontBytes::Owned(Arc::from(MOCK_MONO.to_vec())));
let font = font.with_source_bytes(Arc::clone(&arc));
let got = font.source_bytes_for_subset().unwrap();
assert!(Arc::ptr_eq(&got, &arc), "attached bytes are shared, not copied");
}
#[test]
fn clone_shares_the_glyph_cache_and_drops_hinting() {
let font = parse_mock();
let g = font.get_or_decode_glyph(0).unwrap();
let clone = font.clone();
assert_eq!(clone, font);
// the decode cache is Arc-shared, so the clone sees the decoded glyph...
assert!(Arc::ptr_eq(&clone.get_or_decode_glyph(0).unwrap(), &g));
// ...and decodes through the clone are visible from the original
let _ = clone.get_or_decode_glyph(1);
assert!(font.glyph_cache_snapshot().contains_key(&1));
// HintInstance is not Clone: it is deliberately dropped
assert!(clone.hint_instance.is_none());
}
#[test]
fn gsub_and_gpos_are_memoised() {
let font = parse_mock();
assert!(font.gsub_bytes.is_some(), "Azul Mock Mono ships a GSUB table");
assert!(font.gpos_bytes.is_some(), "Azul Mock Mono ships a GPOS table");
match (font.gsub(), font.gsub()) {
(Some(a), Some(b)) => assert!(Arc::ptr_eq(a, b), "gsub() must be memoised"),
(None, None) => {}
_ => panic!("gsub() must be deterministic across calls"),
}
match (font.gpos(), font.gpos()) {
(Some(a), Some(b)) => assert!(Arc::ptr_eq(a, b), "gpos() must be memoised"),
(None, None) => {}
_ => panic!("gpos() must be deterministic across calls"),
}
}
// ---------------------------------------------------------------
// to_bytes / subset (round-trip)
// ---------------------------------------------------------------
#[test]
fn to_bytes_round_trips_through_from_bytes() {
let font = parse_mock();
let rebuilt = font
.to_bytes(None)
.expect("from_bytes retains source bytes, so to_bytes must succeed");
assert!(rebuilt.len() > 12);
let mut warnings = Vec::new();
let re = ParsedFont::from_bytes(&rebuilt, 0, &mut warnings)
.expect("a font emitted by to_bytes must parse back");
assert_eq!(re.num_glyphs(), font.num_glyphs());
assert_eq!(re.font_metrics.units_per_em, font.font_metrics.units_per_em);
assert_eq!(re.pdf_font_metrics.x_min, font.pdf_font_metrics.x_min);
assert_eq!(re.pdf_font_metrics.y_max, font.pdf_font_metrics.y_max);
let gid = font.lookup_glyph_index('A' as u32).unwrap();
assert_eq!(
re.lookup_glyph_index('A' as u32),
Some(gid),
"the cmap must survive the round-trip"
);
assert_eq!(
re.get_horizontal_advance(gid),
font.get_horizontal_advance(gid),
"hmtx must survive the round-trip"
);
}
#[test]
fn to_bytes_with_an_absent_tag_errors_instead_of_panicking() {
let font = parse_mock();
// Azul Mock Mono has no CFF table: asking for it must surface an Err string
assert!(font.to_bytes(Some(&[tag::CFF])).is_err());
// an empty tag list still reads head+maxp internally: it must return, not panic
drop(font.to_bytes(Some(&[])));
// duplicate tags must not double-insert into the builder and blow up
drop(font.to_bytes(Some(&[tag::HEAD, tag::HEAD, tag::MAXP])));
}
#[test]
fn subset_maps_glyph_ids_and_produces_a_parseable_font() {
let font = parse_mock();
let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
let gid_b = font.lookup_glyph_index('B' as u32).unwrap();
let (bytes, mapping) = font
.subset(&[(0, '\0'), (gid_a, 'A'), (gid_b, 'B')], CmapTarget::Unrestricted)
.expect("subsetting a TrueType font must succeed");
// the mapping is positional: original gid -> (index in the request, char)
assert_eq!(mapping.len(), 3);
assert_eq!(mapping.get(&0), Some(&(0, '\0')));
assert_eq!(mapping.get(&gid_a), Some(&(1, 'A')));
assert_eq!(mapping.get(&gid_b), Some(&(2, 'B')));
let mut warnings = Vec::new();
let sub =
ParsedFont::from_bytes(&bytes, 0, &mut warnings).expect("the subset must re-parse");
assert!(sub.num_glyphs() >= 3);
assert!(sub.num_glyphs() <= font.num_glyphs());
assert_eq!(
sub.get_horizontal_advance(1),
font.get_horizontal_advance(gid_a),
"the remapped 'A' keeps its advance"
);
}
#[test]
fn subset_edge_inputs_do_not_panic() {
let font = parse_mock();
// an empty glyph list may be accepted or rejected; it must not panic
if let Ok((_, mapping)) = font.subset(&[], CmapTarget::Unrestricted) {
assert!(mapping.is_empty());
}
// an out-of-range gid must come back as a Result, never an OOB read
drop(font.subset(&[(0, '\0'), (u16::MAX, 'x')], CmapTarget::Unrestricted));
// duplicate gids collapse in the returned map: the later entry wins
let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
if let Ok((_, mapping)) = font.subset(
&[(0, '\0'), (gid_a, 'a'), (gid_a, 'b')],
CmapTarget::Unrestricted,
) {
assert_eq!(mapping.len(), 2);
assert_eq!(mapping.get(&gid_a), Some(&(2, 'b')));
}
}
// ---------------------------------------------------------------
// empty / extreme instances (getters, predicates)
// ---------------------------------------------------------------
#[test]
fn every_getter_survives_an_empty_font() {
let font = synthetic_font(0, None);
assert_eq!(font.num_glyphs(), 0);
assert!(font.get_or_decode_glyph(0).is_none()); // 0 >= num_glyphs
assert!(font.get_or_decode_glyph(u16::MAX).is_none());
assert!(font.get_glyph_bbox_size(0).is_none());
assert!(font.lookup_glyph_index('A' as u32).is_none()); // no cmap
assert!(!font.has_glyph('A' as u32));
assert!(!font.has_glyph(0));
assert_eq!(font.get_horizontal_advance(0), 0);
assert_eq!(font.get_horizontal_advance(u16::MAX), 0);
assert_eq!(font.get_glyph_width_internal(0), Some(0));
assert!(font.get_vertical_metrics(0).is_none());
assert!(font.get_space_width().is_none());
assert!(font.get_space_width_internal().is_none());
assert!(font.glyph_cache_snapshot().is_empty());
assert!(font.gsub().is_none() && font.gpos().is_none());
assert!(font.resolve_loca_glyf().is_none());
assert!(font.source_bytes_for_subset().is_none());
assert_eq!(font.last_used_nanos(), 0);
assert!(!font.evict_loca_glyf());
assert!(font.hmtx_bytes().is_empty());
assert!(font.vmtx_bytes().is_empty());
assert!(font.get_hinted_advance_px(0, 16).is_none());
font.for_each_decoded_glyph(|_, _| panic!("nothing has been decoded"));
// without source bytes, the PDF paths must report an error, not panic
assert!(font.to_bytes(None).is_err());
assert!(font.subset(&[], CmapTarget::Unrestricted).is_err());
}
#[test]
fn hmtx_bytes_without_source_bytes_is_empty_not_a_panic() {
let mut font = synthetic_font(4, None);
// ranges pointing into bytes we never retained must degrade to an empty
// slice rather than unwrapping a None
font.hmtx_range = (16, 32);
font.vmtx_range = (48, 64);
assert!(font.hmtx_bytes().is_empty());
assert!(font.vmtx_bytes().is_empty());
assert_eq!(font.get_horizontal_advance(0), 0);
}
#[test]
fn hmtx_bytes_slices_the_retained_source() {
let mut font = synthetic_font(2, None);
let raw: Vec<u8> = (0u8..100).collect();
font.original_bytes = Some(Arc::new(rust_fontconfig::FontBytes::Owned(Arc::from(raw))));
font.hmtx_range = (10, 4);
font.vmtx_range = (0, 0);
assert_eq!(font.hmtx_bytes(), [10u8, 11, 12, 13].as_slice());
assert!(font.vmtx_bytes().is_empty()); // a zero-length range short-circuits
}
#[test]
fn mock_backed_font_overrides_advances_and_space_width() {
let mock = MockFont::new(plain_metrics())
.with_space_width(42)
.with_glyph_advance(1, 500);
let font = synthetic_font(4, Some(Box::new(mock)));
assert_eq!(font.get_horizontal_advance(1), 500); // the mock wins over hmtx
assert_eq!(font.get_horizontal_advance(3), 0); // unmapped gid -> 0, no panic
assert_eq!(font.get_horizontal_advance(u16::MAX), 0);
assert_eq!(font.get_space_width_internal(), Some(42));
// the decoded record inherits the mock advance and, with no outline,
// seeds its bbox from it
let g = font.get_or_decode_glyph(1).expect("gid 1 < num_glyphs");
assert_eq!(g.horz_advance, 500);
assert_eq!(g.bounding_box.max_x, 500);
assert!(g.outline.is_empty());
assert_eq!(font.get_glyph_bbox_size(1), Some((500, 0)));
}
#[test]
fn get_font_metrics_normalises_the_descent_sign() {
let mut font = synthetic_font(1, None);
font.font_metrics.descent = -200.0;
assert_eq!(font.get_font_metrics().descent, 200.0);
font.font_metrics.descent = 200.0;
assert_eq!(font.get_font_metrics().descent, 200.0);
// -0.0 is not > 0.0, so it takes the negation branch and comes out +0.0
font.font_metrics.descent = -0.0;
assert!(font.get_font_metrics().descent.is_sign_positive());
font.font_metrics.descent = f32::NEG_INFINITY;
assert_eq!(font.get_font_metrics().descent, f32::INFINITY);
// NaN compares false against 0.0, so it is negated — and stays NaN
font.font_metrics.descent = f32::NAN;
assert!(font.get_font_metrics().descent.is_nan());
// every other field passes through untouched
font.font_metrics.descent = -10.0;
font.font_metrics.ascent = f32::MAX;
font.font_metrics.line_gap = -1.0;
let m = font.get_font_metrics();
assert_eq!(m.ascent, f32::MAX);
assert_eq!(m.line_gap, -1.0);
assert_eq!(m.units_per_em, font.font_metrics.units_per_em);
}
#[test]
fn real_font_metrics_have_a_non_negative_descent() {
let font = parse_mock();
let m = font.get_font_metrics();
assert!(m.descent >= 0.0, "get_font_metrics flips the descent sign");
assert_eq!(m.descent, font.font_metrics.descent.abs());
assert_eq!(m.ascent, font.font_metrics.ascent);
assert_eq!(m.units_per_em, 1000);
}
// ---------------------------------------------------------------
// reverse glyph cache
// ---------------------------------------------------------------
#[test]
fn reverse_glyph_cache_round_trip_and_boundaries() {
let mut font = synthetic_font(2, None);
assert!(font.get_glyph_cluster_text(0).is_none());
assert!(font.get_glyph_primary_char(0).is_none());
font.cache_glyph_mapping(0, ""); // empty cluster
font.cache_glyph_mapping(u16::MAX, "fi"); // ligature at the gid boundary
font.cache_glyph_mapping(7, "\u{1F468}\u{200D}\u{1F469}"); // ZWJ cluster
assert_eq!(font.get_glyph_cluster_text(0), Some(""));
assert_eq!(font.get_glyph_primary_char(0), None); // no first char in ""
assert_eq!(font.get_glyph_cluster_text(u16::MAX), Some("fi"));
assert_eq!(font.get_glyph_primary_char(u16::MAX), Some('f'));
assert_eq!(font.get_glyph_primary_char(7), Some('\u{1F468}'));
assert!(font.get_glyph_cluster_text(1).is_none()); // never written
font.cache_glyph_mapping(u16::MAX, "ffi"); // last write wins
assert_eq!(font.get_glyph_cluster_text(u16::MAX), Some("ffi"));
// clear_glyph_cache drops ONLY the reverse map, not the decoded outlines
let decoded = font.get_or_decode_glyph(0).expect("gid 0 decodes");
font.clear_glyph_cache();
assert!(font.get_glyph_cluster_text(0).is_none());
assert!(font.get_glyph_cluster_text(u16::MAX).is_none());
assert!(font.get_glyph_primary_char(7).is_none());
assert!(Arc::ptr_eq(
font.glyph_cache_snapshot().get(&0).expect("outline cache is untouched"),
&decoded
));
font.clear_glyph_cache(); // idempotent
}
// ---------------------------------------------------------------
// loading / cpurender
// ---------------------------------------------------------------
#[test]
fn build_font_cache_does_not_panic() {
// Smoke: the system font scan must complete. An empty cache is legitimate
// (a headless image may ship no fonts), so only the call itself is asserted.
let _cache = crate::font::loading::build_font_cache();
}
#[cfg(feature = "cpurender")]
#[test]
fn build_glyph_path_needs_at_least_one_operation() {
let empty = OwnedGlyph {
bounding_box: OwnedGlyphBoundingBox {
max_x: 0,
max_y: 0,
min_x: 0,
min_y: 0,
},
horz_advance: 500,
outline: Vec::new(),
phantom_points: None,
raw_points: None,
raw_on_curve: None,
raw_contour_ends: None,
instructions: None,
};
// a space-like glyph has no ops -> None (the caller must skip it)
assert!(build_glyph_path(&empty).is_none());
// an outline whose only contour is empty is still "no ops"
let hollow = OwnedGlyph {
outline: vec![GlyphOutline {
operations: Vec::<GlyphOutlineOperation>::new().into(),
}],
..empty.clone()
};
assert!(build_glyph_path(&hollow).is_none());
// every op kind, at the i16 extremes, must survive the f64 conversion
let full = OwnedGlyph {
outline: vec![GlyphOutline {
operations: vec![
GlyphOutlineOperation::MoveTo(OutlineMoveTo {
x: i16::MIN,
y: i16::MAX,
}),
GlyphOutlineOperation::LineTo(OutlineLineTo {
x: i16::MAX,
y: i16::MIN,
}),
GlyphOutlineOperation::QuadraticCurveTo(OutlineQuadTo {
ctrl_1_x: 0,
ctrl_1_y: 0,
end_x: 1,
end_y: 1,
}),
GlyphOutlineOperation::CubicCurveTo(OutlineCubicTo {
ctrl_1_x: 0,
ctrl_1_y: 0,
ctrl_2_x: 0,
ctrl_2_y: 0,
end_x: 2,
end_y: 2,
}),
GlyphOutlineOperation::ClosePath,
]
.into(),
}],
..empty
};
assert!(build_glyph_path(&full).is_some());
}
}
}