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
//! Pure-Rust TrueType / OpenType font parser.
//!
//! Round-1 scope:
//! - sfnt + table directory walker (`parser`).
//! - Core OpenType tables: `head`, `hhea`, `maxp`, `cmap` (base formats
//! 0/4/6/12 + format 14 Unicode Variation Sequences as a sidecar),
//! `name`, `OS/2`, `hmtx`, `loca`, `glyf` (simple + composite), `post`.
//! - Legacy `kern` table (format 0 subtable).
//! - `GSUB` LookupType 1 (single substitution: positional forms,
//! small-caps, vertical alternates), LookupType 2 (multiple
//! substitution — split one input glyph into N), LookupType 3
//! (alternate substitution — `aalt` / `salt` per-coverage
//! alternates), LookupType 4 (ligature substitution — both walker
//! and lookup-index-specific entry points), LookupType 5
//! (contextual substitution — formats 1 / 2 / 3), LookupType 6
//! (chained contexts substitution — formats 1 / 2 / 3, with
//! recursive sub-lookup dispatch), and LookupType 8 (reverse
//! chained context single substitution), discoverable via the
//! ScriptList / FeatureList / LookupList common-table walk.
//! - `GPOS` LookupType 1 (single adjustment), LookupType 2
//! (pair-adjustment / kerning), LookupType 3 (cursive attachment),
//! LookupType 4 (mark-to-base attachment for diacritics), LookupType 5
//! (mark-to-ligature attachment), LookupType 6 (mark-to-mark
//! attachment for stacked diacritics), LookupType 7 (contextual
//! positioning — `SequenceContext` formats 1/2/3 with recursive
//! nested-lookup dispatch), and LookupType 8 (chained contexts
//! positioning).
//! - `GDEF` (glyph class definitions).
//! - Adobe Glyph List (AGL) glyph-name → Unicode resolution:
//! [`glyph_name_to_codepoints`] / [`glyph_name_to_char`] (direct
//! table lookup against the staged AGL data).
//! - `gasp` (grid-fitting and scan-conversion procedure table, ISO/IEC
//! 14496-22:2019 §5.3.7) — both version 0 and 1, per-record flag
//! accessors, behaviour-for-ppem lookup.
//!
//! The crate is read-only (parsing-only) and dependency-light: only
//! `oxideav-core` for shared types. CFF/Type 2 charstrings live in the
//! sibling `oxideav-otf` crate. TrueType hinting, bidi, and complex
//! shaping are deferred to later rounds.
//!
//! Variable fonts (`fvar`/`avar`/`gvar`) are supported as of round
//! 4: see [`Font::variation_axes`], [`Font::named_instances`],
//! [`Font::set_variation_coords`], and [`Font::glyph_outline`] (which
//! applies gvar deltas via the current axis-coord vector when set).
//!
//! See `README.md` for the public API tour.
#![deny(missing_debug_implementations)]
#![warn(rust_2018_idioms)]
pub mod agl;
pub mod collection;
pub mod outline;
pub mod parser;
pub mod tables;
pub use agl::{glyph_name_to_char, glyph_name_to_codepoints};
pub use collection::{is_collection, CollectionHeader, TTC_MAGIC};
use crate::parser::TableDirectory;
use crate::tables::{
avar::AvarTable, base::BaseTable, cbdt::CbdtTable, cblc::CblcTable, cmap::CmapTable,
colr::ColrTable, cpal::CpalTable, ebdt::EbdtTable, fvar::FvarTable, gasp::GaspTable,
gdef::GdefTable, glyf::GlyfTable, gpos::GposTable, gsub::GsubTable, gvar::GvarTable,
hdmx::HdmxTable, head::HeadTable, hhea::HheaTable, hmtx::HmtxTable, hvar::HvarTable,
kern::KernTable, loca::LocaTable, ltsh::LtshTable, maxp::MaxpTable, meta::MetaTable,
mvar::MvarTable, name::NameTable, os2::Os2Table, pclt::PcltTable, post::PostTable,
sbix::SbixTable, stat::StatTable, vdmx::VdmxTable, vhea::VheaTable, vmtx::VmtxTable,
vorg::VorgTable, vvar::VvarTable,
};
pub use outline::{BBox, Contour, Point, TtOutline};
pub use tables::base::{
AxisTable as BaseAxisTable, BaseCoord, BaseLangSysRecord, BaseScriptRecord, BaseScriptTable,
BaseValuesTable, FeatMinMaxRecord, MinMaxTable as BaseMinMaxTable, BASE_MAJOR_VERSION,
BASE_MINOR_VERSION_0, BASE_MINOR_VERSION_1,
};
pub use tables::cbdt::ColorBitmap;
pub use tables::cblc::{BigGlyphMetrics, SmallGlyphMetrics};
pub use tables::colr::ColorLayer;
pub use tables::ebdt::GrayBitmap;
pub use tables::fvar::{NamedInstance, VariationAxis};
pub use tables::gasp::{
GaspRange, GASP_DOGRAY, GASP_GRIDFIT, GASP_PPEM_SENTINEL, GASP_RESERVED_MASK,
GASP_SYMMETRIC_GRIDFIT, GASP_SYMMETRIC_SMOOTHING, GASP_TABLE_TAG, GASP_VERSION_0,
GASP_VERSION_1,
};
pub use tables::gpos::{CursiveAttachment, PosRecord, PosValue};
pub use tables::gsub::GsubFeature;
pub use tables::hdmx::{
HdmxRecord, HDMX_HEADER_LEN, HDMX_RECORD_HEADER_LEN, HDMX_TABLE_TAG, HDMX_VERSION_0,
};
pub use tables::hvar::DeltaSetIndexMap;
pub use tables::kern::HeaderVariant as KernHeaderVariant;
pub use tables::ltsh::{LTSH_ALWAYS_LINEAR, LTSH_TABLE_TAG, LTSH_VERSION_0};
pub use tables::meta::{
is_valid_meta_tag, script_lang_tags, MetaRecord, ScriptLangTag, META_DATA_MAP_LEN,
META_HEADER_LEN, META_TABLE_TAG, META_TAG_APPL, META_TAG_BILD, META_TAG_DLNG, META_TAG_SLNG,
META_VERSION_1,
};
pub use tables::mvar::ItemVariationStore;
pub use tables::name::{name_id, platform, NameRecord};
pub use tables::pclt::{
PCLT_MAJOR_VERSION, PCLT_STROKE_WEIGHT_RANGE, PCLT_TABLE_LEN, PCLT_TABLE_TAG,
PCLT_WIDTH_TYPE_RANGE,
};
pub use tables::post::{
GlyphNameRef, PostFormat, PostV20, PostV25, POST_HEADER_LEN, POST_TABLE_TAG, POST_VERSION_10,
POST_VERSION_20, POST_VERSION_25, POST_VERSION_30, RECOMMENDED_GLYPH_NAME_MAX_LEN,
STANDARD_MAC_GLYPH_COUNT,
};
pub use tables::sbix::{SbixGlyph, MAX_DUPE_DEPTH as SBIX_MAX_DUPE_DEPTH};
pub use tables::stat::{
AxisRecord as StatAxisRecord, AxisValue as StatAxisValue,
FLAG_ELIDABLE_AXIS_VALUE_NAME as STAT_FLAG_ELIDABLE_AXIS_VALUE_NAME,
FLAG_OLDER_SIBLING_FONT_ATTRIBUTE as STAT_FLAG_OLDER_SIBLING_FONT_ATTRIBUTE,
RANGE_MAX_POS_INFINITY as STAT_RANGE_MAX_POS_INFINITY,
RANGE_MIN_NEG_INFINITY as STAT_RANGE_MIN_NEG_INFINITY,
};
pub use tables::vdmx::{
RatioRange as VdmxRatioRange, VdmxGroup, VdmxVTableRecord, VDMX_GROUP_HEADER_LEN,
VDMX_HEADER_LEN, VDMX_OFFSET_LEN, VDMX_RATIO_RECORD_LEN, VDMX_TABLE_TAG, VDMX_VERSION_0,
VDMX_VERSION_1, VDMX_VTABLE_RECORD_LEN,
};
pub use tables::vhea::{VHEA_VERSION_1_0, VHEA_VERSION_1_1};
pub use tables::vorg::{VertOriginEntry, VORG_MAJOR_VERSION, VORG_MINOR_VERSION};
/// Errors emitted during font parsing or glyph lookup.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
/// The input slice is too short for the requested header / structure.
UnexpectedEof,
/// The sfnt magic version did not match `0x00010000`, `OTTO`, or `true`.
BadMagic,
/// The table count in the sfnt header is implausibly large.
BadHeader,
/// A required table was missing from the table directory.
MissingTable(&'static str),
/// A length / offset field pointed outside the file.
BadOffset,
/// A glyph index was out of range vs. `maxp.numGlyphs`.
GlyphOutOfRange(u16),
/// A cmap subtable used a format we do not implement in round 1.
UnsupportedCmapFormat(u16),
/// A composite-glyph chain exceeded the max recursion depth (16).
CompositeTooDeep,
/// A loca offset pointed past the end of `glyf`.
BadLocaOffset,
/// A varying-length structure was malformed.
BadStructure(&'static str),
/// A `from_collection_bytes` call asked for a subfont index that
/// the TTC header does not contain. Carries the requested index.
SubfontOutOfRange(u32),
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::UnexpectedEof => f.write_str("unexpected end of font data"),
Self::BadMagic => f.write_str("not a TrueType / OpenType font (bad magic)"),
Self::BadHeader => f.write_str("malformed sfnt header"),
Self::MissingTable(t) => write!(f, "required table missing: {t}"),
Self::BadOffset => f.write_str("table offset out of range"),
Self::GlyphOutOfRange(g) => write!(f, "glyph index {g} out of range"),
Self::UnsupportedCmapFormat(fmt) => {
write!(f, "cmap format {fmt} not implemented in round 1")
}
Self::CompositeTooDeep => f.write_str("composite glyph recursion too deep"),
Self::BadLocaOffset => f.write_str("loca offset past end of glyf"),
Self::BadStructure(s) => write!(f, "malformed structure: {s}"),
Self::SubfontOutOfRange(i) => write!(f, "subfont index {i} not in collection"),
}
}
}
impl std::error::Error for Error {}
/// A parsed TrueType / OpenType font, lifetime-bound to the input bytes.
///
/// `Font::from_bytes` walks the sfnt header + table directory once; the
/// individual `*Table` parsers are run on first use and cached as
/// already-validated slices on the struct. Lookup methods (`glyph_index`,
/// `glyph_outline`, etc.) are O(log n) or O(n) over the raw table bytes —
/// no glyphs are pre-decoded or cached.
#[derive(Debug)]
pub struct Font<'a> {
bytes: &'a [u8],
head: HeadTable,
hhea: HheaTable,
maxp: MaxpTable,
cmap: CmapTable<'a>,
name: NameTable<'a>,
os2: Option<Os2Table>,
hmtx: HmtxTable<'a>,
/// Vertical header table (`vhea`, ISO/IEC 14496-22:2019 §5.7.9).
/// Optional — only fonts intended for vertical layout ship one;
/// in particular, CJK fonts and the rare Mongolian / Manchu font.
/// When present, the companion `vmtx` table is also required per
/// §5.7.10 ("OFFvertical fonts require both a vertical header
/// table ('vhea') and the vertical metrics table").
vhea: Option<VheaTable>,
/// Vertical metrics table (`vmtx`, ISO/IEC 14496-22:2019 §5.7.10).
/// Always paired with `vhea`; only present when the font supplies
/// vertical layout data.
vmtx: Option<VmtxTable<'a>>,
/// Vertical origin table (`VORG`, ISO/IEC 14496-22:2019 §5.4.4).
/// Optional table that records, per glyph, the Y coordinate of the
/// glyph's vertical origin in font design units. Per §5.4.4 the
/// table is restricted to CFF-flavoured sfnts ("If present in
/// TrueType OFF fonts it must be ignored by font clients"); when a
/// TrueType-flavoured sfnt nonetheless ships one we still parse it
/// here so the bytes are available, but the
/// [`Font::vert_origin_y_from_vorg`] accessor respects the
/// ignore-on-TrueType policy and returns `None` once `glyf` is
/// present.
vorg: Option<VorgTable>,
/// Glyph-location offsets into `glyf`. Optional because CBDT/CBLC-only
/// colour-emoji fonts (e.g. NotoColorEmoji.ttf) ship without `loca`
/// and `glyf` — every glyph is a colour bitmap and there are no
/// outlines to address.
loca: Option<LocaTable<'a>>,
glyf: Option<GlyfTable<'a>>,
post: Option<PostTable>,
kern: Option<KernTable<'a>>,
gsub: Option<GsubTable<'a>>,
gpos: Option<GposTable<'a>>,
gdef: Option<GdefTable<'a>>,
cblc: Option<CblcTable<'a>>,
cbdt: Option<CbdtTable<'a>>,
/// Embedded bitmap *location* table (`EBLC`, ISO/IEC 14496-22:2019
/// §5.6.3). The monochrome / grayscale analog of `CBLC`; identical
/// on-wire layout (the shared [`CblcTable`] walker accepts both),
/// paired with [`Font::ebdt`](Self::ebdt) rather than `CBDT`.
eblc: Option<CblcTable<'a>>,
/// Embedded monochrome / grayscale bitmap data (`EBDT`, ISO/IEC
/// 14496-22:2019 §5.6.2). Located through the shared `EBLC`/`CBLC`
/// walker (the same `CblcTable` used for colour bitmaps); an `EBLC`
/// (major == 2) strike resolves the same way a `CBLC` colour strike
/// does. Present on legacy
/// pixel / CJK bitmap faces.
ebdt: Option<EbdtTable<'a>>,
colr: Option<ColrTable<'a>>,
cpal: Option<CpalTable<'a>>,
sbix: Option<SbixTable<'a>>,
/// Variable-font axes header (`fvar`). Absent for static fonts.
fvar: Option<FvarTable>,
/// Per-axis non-linear remap (`avar`). Absent unless the font
/// publishes one (most variable fonts do, identity for axes that
/// don't need bending).
avar: Option<AvarTable>,
/// Per-glyph TupleVariationStore (`gvar`). Required when `fvar`
/// is present and the outline kind is TrueType; not populated for
/// CFF2 (which uses `cvar` instead — out of scope here).
gvar: Option<GvarTable<'a>>,
/// Font-wide metrics-variation table (`MVAR`). Present in many
/// variable fonts; carries per-instance adjustments for `OS/2`,
/// `hhea`, `vhea`, `post`, `gasp` metric fields keyed by the
/// §7.3.6.3 value-tag registry.
mvar: Option<MvarTable>,
/// Per-glyph horizontal-metrics variation table (`HVAR`,
/// ISO/IEC 14496-22:2019 §7.3.5). Variable fonts with TrueType
/// outlines are encouraged to ship one; CFF2 variable fonts are
/// required to. Provides interpolated adjustments for `hmtx`
/// advance widths plus optional left- and right-side bearings.
hvar: Option<HvarTable>,
/// Per-glyph vertical-metrics variation table (`VVAR`,
/// ISO/IEC 14496-22:2019 §7.3.8). Optional in TrueType variable
/// fonts (where `gvar` phantom points carry the same data); for
/// CFF2 variable fonts that support vertical layout it is required
/// (§7.3.8.1). Provides interpolated adjustments for `vmtx`
/// advance heights plus optional top-/bottom-side bearings and —
/// for CFF2 fonts that publish a `VORG` table — vertical-origin
/// Y coordinates.
vvar: Option<VvarTable>,
/// Style attributes table (`STAT`, ISO/IEC 14496-22:2019 §7.3.7).
/// Required in all variable fonts; optional otherwise. Carries
/// design-axis records and per-axis-value name mappings used by
/// font pickers to compose family / subfamily strings under the
/// R/B/I/BI, WWS, and unrestricted naming models.
stat: Option<StatTable>,
/// Baseline table (`BASE`, ISO/IEC 14496-22:2019 §6.3.1). Optional
/// table that supplies per-script baseline coordinates and
/// per-script / per-language-system / per-feature minimum and
/// maximum glyph extents. Carries one Axis sub-table per text
/// direction (HorizAxis for Y baselines / horizontal text;
/// VertAxis for X baselines / vertical text).
base: Option<BaseTable>,
/// Grid-fitting and scan-conversion procedure table (`gasp`,
/// ISO/IEC 14496-22:2019 §5.3.7). Optional; carries the
/// per-ppem-range rasterisation hints (grid-fit / grayscale /
/// ClearType-symmetric flags) sorted by `rangeMaxPPEM`. Used by
/// callers that drive a font rasteriser and want to pick the
/// font-author-recommended hinting policy at a given pixel size.
gasp: Option<GaspTable>,
/// Linear threshold table (`LTSH`, ISO/IEC 14496-22:2019 §5.7.4).
/// Optional; carries one byte per glyph recording the lowest ppem
/// at which the grid-fitted advance width has converged on the
/// rounded linear advance, so a rasteriser at or above that ppem
/// can round the linear advance arithmetically without scan-
/// converting the glyph. The §5.7.4 sentinel `1` means "always
/// scales linearly" (the glyph carries no instructions on its
/// sidebearings).
ltsh: Option<LtshTable>,
/// Horizontal device metrics table (`hdmx`, ISO/IEC 14496-22:2019
/// §5.7.2). Optional; carries one device record per selected ppem,
/// each holding the per-glyph grid-fitted advance width in integer
/// pixels. The precomputed-advance counterpart to `LTSH`: instead
/// of recording when the grid-fit advance converges to the linear
/// advance, `hdmx` records the exact grid-fit advance for a fixed
/// set of ppem sizes. §7.3.5 forbids `hdmx` in variable fonts;
/// callers that want to honour that rule can cross-check
/// `is_variable()` before consulting these accessors.
hdmx: Option<HdmxTable>,
/// Vertical device metrics table (`VDMX`, ISO/IEC 14496-22:2019
/// §5.7.8). Optional; carries one or more groups of vTable
/// records (`yPelHeight` → `(yMax, yMin)` pel envelope) indexed
/// via a per-aspect-ratio RatioRange array. The precomputed-extent
/// counterpart to `hdmx`'s per-glyph advance widths: instead of
/// publishing each glyph's grid-fitted advance, `VDMX` publishes
/// the font-wide vertical extent at a curated ppem set so a
/// rasteriser can pick a render bitmap height without
/// grid-fitting every glyph in the font. §7.3.5 forbids `VDMX`
/// in variable fonts; callers can cross-check `is_variable()`
/// before consulting these accessors.
vdmx: Option<VdmxTable>,
/// Metadata table (`meta`, ISO/IEC 14496-22:2019 §5.7.6). Optional;
/// carries a tagged DataMap array whose payloads describe font-wide
/// metadata in either UTF-8 text (`'dlng'`, `'slng'`) or vendor-
/// defined binary form. Records borrow from the on-wire `meta`
/// byte slice — the table itself does not copy the payload data.
meta: Option<MetaTable<'a>>,
/// PCL 5 table (`PCLT`, ISO/IEC 14496-22:2019 §5.7.7). Optional
/// (and "strongly discouraged for OFF fonts with TrueType
/// outlines" per the spec); carries the PCL 5 font-selection
/// attributes — HP font number, pitch / x-height / cap-height,
/// packed style / type-family / symbol-set words, the 16-byte
/// typeface string, the 8-byte character-complement bitfield,
/// the 6-byte PCL file name, and the stroke-weight / width-type
/// / serif-style classification bytes.
pclt: Option<PcltTable>,
/// Current user-space coordinate vector, one per axis (defaults
/// to each axis's `default` value when `fvar` is present, empty
/// vec otherwise). `set_variation_coords` updates this; the
/// outline accessor consults [`Self::normalised_coords`] to
/// derive the per-axis weight applied to gvar deltas.
var_coords: Vec<f32>,
}
impl<'a> Font<'a> {
/// Parse the `index`-th subfont out of a TrueType Collection (`.ttc` /
/// `'ttcf'`) byte slice.
///
/// TTC files start with a `'ttcf'` magic followed by a list of byte
/// offsets pointing at per-subfont sfnt headers. This entry point
/// reads the TTC header, then runs the regular sfnt parse path
/// against the slice rooted at the chosen subfont. The returned
/// `Font<'a>` borrows from the original `bytes` (sub-slicing is
/// done internally; the lifetime stays tied to the input).
///
/// Returns:
/// - `Error::BadMagic` if `bytes` is not a TTC.
/// - `Error::SubfontOutOfRange(index)` if the chosen index exceeds
/// `numFonts`.
/// - Whatever the underlying sfnt path emits otherwise (typically
/// `MissingTable` / `BadOffset` for a malformed subfont).
///
/// Spec: Microsoft OpenType §"Font Collections", Apple TrueType
/// Reference / "TrueType Collections".
pub fn from_collection_bytes(bytes: &'a [u8], index: u32) -> Result<Self, Error> {
let header = CollectionHeader::parse(bytes)?;
let offset = header
.font_offset(index)
.ok_or(Error::SubfontOutOfRange(index))? as usize;
// The TTC spec requires the subfont's table directory offsets to
// be FILE-relative (not subfont-relative), so we hand
// `from_bytes_at` the full file slice and the subfont header
// offset rather than slicing the file from `offset` onwards.
Self::from_bytes_at(bytes, offset)
}
/// Parse a font from a borrowed byte slice.
pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, Error> {
Self::from_bytes_at(bytes, 0)
}
/// Parse a font whose sfnt header sits at `header_offset` inside
/// `bytes`. Used by `from_collection_bytes` for TTC subfonts (whose
/// table records carry file-relative offsets, not subfont-relative
/// ones); equivalent to `from_bytes` when `header_offset == 0`.
fn from_bytes_at(bytes: &'a [u8], header_offset: usize) -> Result<Self, Error> {
let dir = TableDirectory::parse(bytes, header_offset)?;
let head = HeadTable::parse(dir.required(b"head", bytes)?)?;
let hhea = HheaTable::parse(dir.required(b"hhea", bytes)?)?;
let maxp = MaxpTable::parse(dir.required(b"maxp", bytes)?)?;
let cmap = CmapTable::parse(dir.required(b"cmap", bytes)?)?;
let name = NameTable::parse(dir.required(b"name", bytes)?)?;
let hmtx = HmtxTable::parse(
dir.required(b"hmtx", bytes)?,
hhea.num_long_hor_metrics,
maxp.num_glyphs,
)?;
// `vhea` + `vmtx` are jointly optional: a font that lacks
// either is treated as horizontal-only. §5.7.10 mandates that
// a font shipping one ship both ("OFFvertical fonts require
// both"), so a half-pair is rejected as a malformed file
// rather than silently degraded.
let vhea = dir.find(b"vhea", bytes).map(VheaTable::parse).transpose()?;
let vmtx_slice = dir.find(b"vmtx", bytes);
let vmtx = match (vhea.as_ref(), vmtx_slice) {
(Some(vh), Some(slice)) => Some(VmtxTable::parse(
slice,
vh.num_long_ver_metrics,
maxp.num_glyphs,
)?),
(None, None) => None,
(Some(_), None) => {
return Err(Error::BadStructure(
"vhea present but vmtx missing (§5.7.10 requires both)",
));
}
(None, Some(_)) => {
return Err(Error::BadStructure(
"vmtx present but vhea missing (§5.7.10 requires both)",
));
}
};
// `loca` + `glyf` are jointly optional: CBDT/CBLC-only colour-
// emoji fonts (e.g. NotoColorEmoji.ttf) ship without either.
// When loca is present we still require glyf (and vice versa)
// because a half-pair would be malformed.
let loca = match (dir.find(b"loca", bytes), dir.find(b"glyf", bytes)) {
(Some(l), Some(_g)) => Some(LocaTable::parse(
l,
maxp.num_glyphs,
head.index_to_loc_format,
)?),
(None, None) => None,
_ => {
return Err(Error::BadStructure(
"loca/glyf must both be present or both absent",
))
}
};
let glyf = dir.find(b"glyf", bytes).map(GlyfTable::new);
let os2 = dir.find(b"OS/2", bytes).map(Os2Table::parse).transpose()?;
let post = dir.find(b"post", bytes).map(PostTable::parse).transpose()?;
let kern = dir.find(b"kern", bytes).map(KernTable::parse).transpose()?;
let gsub = dir.find(b"GSUB", bytes).map(GsubTable::parse).transpose()?;
let gpos = dir.find(b"GPOS", bytes).map(GposTable::parse).transpose()?;
let gdef = dir.find(b"GDEF", bytes).map(GdefTable::parse).transpose()?;
let cblc = dir.find(b"CBLC", bytes).map(CblcTable::parse).transpose()?;
let cbdt = dir.find(b"CBDT", bytes).map(CbdtTable::parse).transpose()?;
let eblc = dir.find(b"EBLC", bytes).map(CblcTable::parse).transpose()?;
let ebdt = dir.find(b"EBDT", bytes).map(EbdtTable::parse).transpose()?;
let colr = dir.find(b"COLR", bytes).map(ColrTable::parse).transpose()?;
let cpal = dir.find(b"CPAL", bytes).map(CpalTable::parse).transpose()?;
let sbix = dir
.find(b"sbix", bytes)
.map(|s| SbixTable::parse(s, maxp.num_glyphs))
.transpose()?;
// Variable-font tables. `fvar` is the gate: if it's absent the
// font is static and we skip the rest. If it's present we still
// try to load `gvar` (TrueType deltas) and `avar` (axis remap)
// but a missing `gvar` is acceptable for non-outline (CBDT-only)
// variable fonts.
let fvar = dir.find(b"fvar", bytes).map(FvarTable::parse).transpose()?;
let avar = dir.find(b"avar", bytes).map(AvarTable::parse).transpose()?;
let gvar = dir.find(b"gvar", bytes).map(GvarTable::parse).transpose()?;
let mvar = dir.find(b"MVAR", bytes).map(MvarTable::parse).transpose()?;
let hvar = dir.find(b"HVAR", bytes).map(HvarTable::parse).transpose()?;
let vvar = dir.find(b"VVAR", bytes).map(VvarTable::parse).transpose()?;
let stat = dir.find(b"STAT", bytes).map(StatTable::parse).transpose()?;
let base = dir.find(b"BASE", bytes).map(BaseTable::parse).transpose()?;
let gasp = dir.find(b"gasp", bytes).map(GaspTable::parse).transpose()?;
let vorg = dir.find(b"VORG", bytes).map(VorgTable::parse).transpose()?;
// §5.7.4 says `LTSH.numGlyphs` "should be the same as the
// numGlyphs field in the 'maxp' table". A mismatch would either
// truncate or over-read the per-glyph lookups, so cross-check
// at parse time and reject as `BadStructure`.
let ltsh = dir
.find(b"LTSH", bytes)
.map(|s| LtshTable::parse_with_glyph_count(s, maxp.num_glyphs))
.transpose()?;
// §5.7.2 fixes the per-record `widths[]` length at
// `maxp.numGlyphs`. Cross-checking against `maxp.num_glyphs`
// at parse time rejects under-sized records (`UnexpectedEof`)
// and protects per-ppem lookups from over-reading the slice.
let hdmx = dir
.find(b"hdmx", bytes)
.map(|s| HdmxTable::parse(s, maxp.num_glyphs))
.transpose()?;
// §5.7.8 describes a fixed-shape table: 6-byte header, then a
// RatioRange + Offset16 pair of arrays followed by VDMX groups
// referenced from those offsets. No per-glyph cross-check
// against `maxp` is needed — the table publishes font-wide
// extents indexed by ppem only, not per-glyph data. `parse`
// enforces the §5.7.8 sort + sentinel invariants.
let vdmx = dir.find(b"VDMX", bytes).map(VdmxTable::parse).transpose()?;
// §5.7.6 metadata table — header + DataMap array indexed by
// four-character ASCII tags. The data payloads sit later in
// the same byte slice and `MetaRecord::payload` borrows from
// there; the `'a` lifetime of `Font<'a>` therefore covers
// every payload exposed through `meta_*` accessors.
let meta = dir.find(b"meta", bytes).map(MetaTable::parse).transpose()?;
// §5.7.7 PCL 5 table — fixed 54-byte struct of PCL font-
// selection attributes. All fields copy out of the slice at
// parse time so the parsed table carries no lifetime.
let pclt = dir.find(b"PCLT", bytes).map(PcltTable::parse).transpose()?;
let var_coords = match fvar.as_ref() {
Some(f) => f.axes().iter().map(|a| a.default).collect(),
None => Vec::new(),
};
Ok(Self {
bytes,
head,
hhea,
maxp,
cmap,
name,
os2,
hmtx,
vhea,
vmtx,
vorg,
loca,
glyf,
post,
kern,
gsub,
gpos,
gdef,
cblc,
cbdt,
eblc,
ebdt,
colr,
cpal,
sbix,
fvar,
avar,
gvar,
mvar,
hvar,
vvar,
stat,
base,
gasp,
ltsh,
hdmx,
vdmx,
meta,
pclt,
var_coords,
})
}
/// Raw bytes used to build this `Font`. Mostly useful for debugging.
pub fn bytes(&self) -> &'a [u8] {
self.bytes
}
// ---- metadata ----------------------------------------------------------
/// Family name from the `name` table (Windows English first, falls back
/// to Mac Roman if that's all the font has).
pub fn family_name(&self) -> Option<&str> {
// 1 = Family name
self.name.find(1)
}
/// Full name (typically family + style) from the `name` table.
pub fn full_name(&self) -> Option<&str> {
// 4 = Full name
self.name.find(4)
}
/// Subfamily (style) name from the `name` table — e.g. "Bold",
/// "Italic", "Regular". `nameID` 2 (Adobe TN5149 §1.4).
pub fn subfamily_name(&self) -> Option<&str> {
self.name.find(name_id::SUBFAMILY)
}
/// Typographic (preferred) family name — `nameID` 16 — falling back to
/// the standard family name (`nameID` 1) when the font omits it.
/// Adobe TN5149 §1.4: when `nameID` 16 equals `nameID` 1 it may be
/// omitted, so the fallback reconstructs the intended value.
pub fn typographic_family_name(&self) -> Option<&str> {
self.name
.find(name_id::TYPOGRAPHIC_FAMILY)
.or_else(|| self.name.find(name_id::FAMILY))
}
/// Typographic (preferred) subfamily name — `nameID` 17 — falling back
/// to the standard subfamily name (`nameID` 2). Same omission rule as
/// [`Self::typographic_family_name`] (TN5149 §1.4).
pub fn typographic_subfamily_name(&self) -> Option<&str> {
self.name
.find(name_id::TYPOGRAPHIC_SUBFAMILY)
.or_else(|| self.name.find(name_id::SUBFAMILY))
}
/// PostScript name — `nameID` 6 (TN5149 §1.5). The unique name a
/// PostScript interpreter uses to select the font.
pub fn postscript_name(&self) -> Option<&str> {
self.name.find(name_id::POSTSCRIPT)
}
/// Version string — `nameID` 5 (TN5149 §1.9), e.g. "Version 1.000".
pub fn version_string(&self) -> Option<&str> {
self.name.find(name_id::VERSION)
}
/// Copyright notice — `nameID` 0 (TN5149 §1.3).
pub fn copyright(&self) -> Option<&str> {
self.name.find(name_id::COPYRIGHT)
}
/// Trademark — `nameID` 7 (TN5149 §1.10).
pub fn trademark(&self) -> Option<&str> {
self.name.find(name_id::TRADEMARK)
}
/// Manufacturer name — `nameID` 8 (TN5149 §1.10).
pub fn manufacturer(&self) -> Option<&str> {
self.name.find(name_id::MANUFACTURER)
}
/// Designer name — `nameID` 9 (TN5149 §1.10).
pub fn designer(&self) -> Option<&str> {
self.name.find(name_id::DESIGNER)
}
/// Description — `nameID` 10 (TN5149 §1.10).
pub fn description(&self) -> Option<&str> {
self.name.find(name_id::DESCRIPTION)
}
/// Font vendor URL — `nameID` 11 (TN5149 §1.10).
pub fn vendor_url(&self) -> Option<&str> {
self.name.find(name_id::VENDOR_URL)
}
/// Font designer URL — `nameID` 12 (TN5149 §1.10).
pub fn designer_url(&self) -> Option<&str> {
self.name.find(name_id::DESIGNER_URL)
}
/// Licence description — `nameID` 13 (TN5149 §1.10).
pub fn license_description(&self) -> Option<&str> {
self.name.find(name_id::LICENSE)
}
/// Licence URL — `nameID` 14 (TN5149 §1.10).
pub fn license_url(&self) -> Option<&str> {
self.name.find(name_id::LICENSE_URL)
}
/// Arbitrary `name`-table string by `nameID`, picking the best-ranked
/// locale (Windows English first). The well-known IDs are exported as
/// [`name_id`] constants. Use [`Self::name_string_for`] to target a
/// specific platform + language.
pub fn name_string(&self, name_id: u16) -> Option<&str> {
self.name.find(name_id)
}
/// A specific `(nameID, platformID, languageID)` string — no ranking,
/// the exact locale you name (e.g. `(name_id::FAMILY,
/// platform::WINDOWS, 0x0411)` for the Japanese family name). Returns
/// an owned `String` because non-ASCII records are decoded into a new
/// buffer. `None` when no record matches or its encoding is one we
/// cannot decode without an unstaged legacy codepage table (Macintosh
/// non-Roman scripts — TN5149 §1.2).
pub fn name_string_for(
&self,
name_id: u16,
platform_id: u16,
language_id: u16,
) -> Option<String> {
self.name.find_for(name_id, platform_id, language_id)
}
/// Every `name`-table record, decoded where possible (see
/// [`NameRecord`]). The locator tuple `(platformID, encodingID,
/// languageID, nameID)` is always present; `string` is `None` for
/// encodings we cannot decode in-crate.
pub fn name_records(&self) -> Vec<NameRecord> {
self.name.records()
}
/// `head.unitsPerEm`. Almost always 1024 or 2048; never zero in valid
/// fonts.
pub fn units_per_em(&self) -> u16 {
self.head.units_per_em
}
/// Typographic ascent. We prefer `OS/2.sTypoAscender` if present
/// (Windows-clean), falling back to `hhea.ascent`.
pub fn ascent(&self) -> i16 {
self.os2
.as_ref()
.and_then(|o| o.s_typo_ascender)
.unwrap_or(self.hhea.ascent)
}
/// Typographic descent (typically negative).
pub fn descent(&self) -> i16 {
self.os2
.as_ref()
.and_then(|o| o.s_typo_descender)
.unwrap_or(self.hhea.descent)
}
/// Suggested gap between lines.
pub fn line_gap(&self) -> i16 {
self.os2
.as_ref()
.and_then(|o| o.s_typo_line_gap)
.unwrap_or(self.hhea.line_gap)
}
/// `maxp.numGlyphs`.
pub fn glyph_count(&self) -> u16 {
self.maxp.num_glyphs
}
/// `OS/2.usWeightClass` (100..1000), or 400 (Regular) if `OS/2` absent.
pub fn weight_class(&self) -> u16 {
self.os2.as_ref().map(|o| o.us_weight_class).unwrap_or(400)
}
/// `post.italicAngle` in degrees (negative for forward-slanted).
pub fn italic_angle(&self) -> f32 {
self.post.as_ref().map(|p| p.italic_angle).unwrap_or(0.0)
}
/// `true` when the font ships a `post` table (any version).
pub fn has_post(&self) -> bool {
self.post.is_some()
}
/// Borrow the parsed `post` table. `None` when the font does not
/// publish one.
pub fn post_table(&self) -> Option<&PostTable> {
self.post.as_ref()
}
/// Resolve glyph `gid`'s `post`-table name reference, when the
/// table publishes one.
///
/// Returns:
///
/// - `Some(GlyphNameRef::Custom(name))` — the font supplied the
/// glyph's name as a v2.0 Pascal string. The string is already
/// trimmed of its length byte.
/// - `Some(GlyphNameRef::StandardMac { index })` — the glyph
/// resolves to entry `index` of the 258-name standard Macintosh
/// glyph table (referenced through v1.0, v2.0, or v2.5). The
/// 258-name array itself is the subject of a documented gap
/// (#1277 — the standard Macintosh glyph names list, defined
/// exclusively by Apple's TrueType Reference Manual Chapter 6
/// `post` Format 1, is not yet staged in `docs/text/opentype/`).
/// Until the list is staged, [`Font::glyph_name`] returns
/// `None` for these glyphs; this lower-level accessor still
/// surfaces the index so tooling that owns its own copy of the
/// 258-name array can resolve names today.
/// - `None` — the font has no `post` table, the table is v3.0
/// (no glyph names at all), `gid` falls outside the v2.0 /
/// v2.5 index array, or the index references a Pascal string
/// the pool cannot satisfy.
pub fn glyph_name_ref(&self, gid: u16) -> Option<GlyphNameRef<'_>> {
self.post.as_ref()?.glyph_name_ref(gid)
}
/// Convenience accessor: return the glyph's PostScript name when
/// the font supplies a custom one (v2.0 Pascal string).
///
/// Returns `None` for every other case — including the
/// `StandardMac { index }` branch, which would need the 258-name
/// list from #1277 to render. Once the docs gap closes a
/// follow-up commit can route the `StandardMac` index through a
/// `STANDARD_MAC_GLYPH_NAMES[i]` lookup; the current behaviour is
/// the §5.2.10.2 spec's documented "no name available" semantics
/// for callers that need a single `Option<&str>` shape.
pub fn glyph_name(&self, gid: u16) -> Option<&str> {
match self.glyph_name_ref(gid)? {
GlyphNameRef::Custom(s) => Some(s),
GlyphNameRef::StandardMac { .. } => None,
}
}
// ---- glyph lookup ------------------------------------------------------
/// Map a Unicode codepoint to its glyph id.
pub fn glyph_index(&self, codepoint: char) -> Option<u16> {
self.cmap.lookup(codepoint as u32)
}
/// Look up the variant glyph for a `(codepoint, variation_selector)`
/// pair from the cmap format-14 (Unicode Variation Sequences)
/// subtable.
///
/// Returns:
///
/// - `Some(glyph)` from the **non-default** UVS table when the
/// variation selector overrides the base glyph (e.g. emoji
/// presentation `<emoji, U+FE0F>`, text presentation
/// `<emoji, U+FE0E>`, or registered Ideographic Variation
/// Sequence `<CJK, U+E0100..U+E01EF>`).
/// - `Some(base)` when the pair is in the **default** UVS table —
/// semantically "render the base codepoint's default glyph; the
/// variation selector is just a hint". Equivalent to
/// [`Self::glyph_index`] for the base codepoint, returned for
/// API symmetry so callers don't have to special-case the
/// default-presentation branch.
/// - `None` when the font has no format-14 subtable, the variation
/// selector isn't enumerated, or neither UVS table covers the
/// base codepoint.
pub fn lookup_variation(&self, codepoint: char, variation_selector: char) -> Option<u16> {
self.cmap
.lookup_variation(codepoint as u32, variation_selector as u32)
}
/// Decode the TrueType outline for `glyph_id`. Empty / blank glyphs
/// (e.g. the space glyph) return an outline with zero contours.
///
/// Returns an empty outline when the font has no `glyf`/`loca`
/// (CBDT/CBLC-only colour-emoji fonts). Callers that care should
/// check [`Font::has_color_bitmaps`] first.
///
/// **Variable fonts:** if the font ships `fvar`/`gvar` and the
/// caller has set non-default coordinates via
/// [`Font::set_variation_coords`], the static outline returned
/// here has gvar deltas applied (with avar remap on the input
/// coords first). Composite glyphs do not currently propagate
/// per-component variation deltas — only simple glyphs are
/// retargeted; this is sufficient for nearly all Latin/Cyrillic/
/// Greek glyphs, which are simple, and degrades gracefully on the
/// composite-heavy CJK case (the static outline is still returned).
pub fn glyph_outline(&self, glyph_id: u16) -> Result<TtOutline, Error> {
if glyph_id >= self.maxp.num_glyphs {
return Err(Error::GlyphOutOfRange(glyph_id));
}
let (loca, glyf) = match (self.loca.as_ref(), self.glyf.as_ref()) {
(Some(l), Some(g)) => (l, g),
_ => return Ok(TtOutline::default()),
};
let range = loca.glyph_range(glyph_id)?;
if range.is_empty() {
return Ok(TtOutline::default());
}
let mut out = glyf.glyph_outline(range, loca, 0)?;
if let Some(gvar) = self.gvar.as_ref() {
if !self.var_coords.is_empty() && self.coords_differ_from_default() {
let n_pts: usize = out.contours.iter().map(|c| c.points.len()).sum();
if n_pts > 0 && n_pts <= u16::MAX as usize {
let normalised = self.normalised_coords();
if let Ok(deltas) = gvar.glyph_deltas(glyph_id, n_pts as u16, &normalised) {
let mut idx = 0usize;
for c in out.contours.iter_mut() {
for p in c.points.iter_mut() {
let (dx, dy) = deltas[idx];
let nx = p.x as i32 + dx;
let ny = p.y as i32 + dy;
p.x = clamp_i16_for_outline(nx);
p.y = clamp_i16_for_outline(ny);
idx += 1;
}
}
// Re-derive bounds after delta application.
out.bounds = outline::derive_bbox(&out.contours);
}
}
}
}
Ok(out)
}
/// Per-glyph advance width in font units.
pub fn glyph_advance(&self, glyph_id: u16) -> i16 {
self.hmtx.advance(glyph_id) as i16
}
/// Per-glyph left-side bearing in font units.
pub fn glyph_lsb(&self, glyph_id: u16) -> i16 {
self.hmtx.lsb(glyph_id)
}
/// `true` when the font ships both a `vhea` and `vmtx` table —
/// i.e. it supplies vertical-layout metrics for CJK / Mongolian
/// or other top-to-bottom-written scripts.
pub fn has_vertical_metrics(&self) -> bool {
self.vhea.is_some() && self.vmtx.is_some()
}
/// Borrow the parsed `vhea` table, when present.
/// (ISO/IEC 14496-22:2019 §5.7.9.)
pub fn vhea_table(&self) -> Option<&VheaTable> {
self.vhea.as_ref()
}
/// Vertical typographic ascender from `vhea`. For v1.1 this is
/// `vertTypoAscender` (distance in font design units from the
/// ideographic em-box centre baseline to the right side of the
/// em-box, per §5.7.9 v1.1 row 2); for v1.0 the same bytes are
/// the centre-line-relative `ascent` field. Returns `None` if the
/// font lacks a `vhea` table.
pub fn vertical_ascent(&self) -> Option<i16> {
self.vhea.map(|v| v.vert_typo_ascender)
}
/// Vertical typographic descender from `vhea` (v1.1
/// `vertTypoDescender`; v1.0 `descent`).
pub fn vertical_descent(&self) -> Option<i16> {
self.vhea.map(|v| v.vert_typo_descender)
}
/// Vertical typographic line gap from `vhea` (v1.1
/// `vertTypoLineGap`; v1.0 row "Reserved; set to 0", so static
/// v1.0 fonts will return `Some(0)` here).
pub fn vertical_line_gap(&self) -> Option<i16> {
self.vhea.map(|v| v.vert_typo_line_gap)
}
/// `vhea.advanceHeightMax` — the maximum advance height in the
/// font, in design units. Per §5.7.9 the field is `int16`.
pub fn advance_height_max(&self) -> Option<i16> {
self.vhea.map(|v| v.advance_height_max)
}
/// Borrow the parsed `vmtx` table, when present.
/// (ISO/IEC 14496-22:2019 §5.7.10.)
pub fn vmtx_table(&self) -> Option<&VmtxTable<'a>> {
self.vmtx.as_ref()
}
/// Per-glyph advance height in font design units. Returns `None`
/// when the font lacks `vhea`/`vmtx`; otherwise returns the
/// `vMetrics` advance for `glyph_id`, with the §5.7.10 "monospaced
/// tail" rule (glyphs beyond `numOfLongVerMetrics` inherit the
/// last pair's advance height) applied transparently.
pub fn glyph_advance_height(&self, glyph_id: u16) -> Option<u16> {
Some(self.vmtx.as_ref()?.advance_height(glyph_id))
}
/// Per-glyph top side bearing in font design units. Returns
/// `None` when the font lacks `vmtx`.
pub fn glyph_top_side_bearing(&self, glyph_id: u16) -> Option<i16> {
Some(self.vmtx.as_ref()?.top_side_bearing(glyph_id))
}
/// Per-glyph vertical origin Y coordinate in font design units.
/// Per §5.7.10 ("Vertical Origin and Advance Height"), this is
/// `topSideBearing + glyph_bounding_box.y_max`. Returns `None`
/// when the font lacks `vmtx` or when the glyph has no outline
/// bounding box (empty glyph, blank glyph, or a CBDT-only colour-
/// emoji font with no `glyf`/`loca`). For CFF fonts the spec
/// recommends the optional `VORG` table instead; that path is not
/// implemented here (TrueType outlines only).
pub fn glyph_vertical_origin_y(&self, glyph_id: u16) -> Option<i16> {
let tsb = self.vmtx.as_ref()?.top_side_bearing(glyph_id);
let bbox = self.glyph_bounding_box(glyph_id)?;
// Saturating add keeps a pathological bbox from panicking;
// real-world fonts are nowhere near i16::MAX in this dim.
Some(tsb.saturating_add(bbox.y_max))
}
/// `true` when the font ships a `VORG` table per §5.4.4. The table
/// is optional and, per spec, restricted to CFF-flavoured sfnts;
/// it appears occasionally in TrueType sfnts as well, in which case
/// the parser surfaces the bytes but [`Self::vert_origin_y_from_vorg`]
/// declines to consult it (the spec mandates "If present in
/// TrueType OFF fonts it must be ignored by font clients").
pub fn has_vorg(&self) -> bool {
self.vorg.is_some()
}
/// Borrow the parsed `VORG` table, when present. Surfaced verbatim
/// so callers that want to introspect the metrics array directly
/// (e.g. font tooling) can do so without re-parsing the bytes.
pub fn vorg_table(&self) -> Option<&VorgTable> {
self.vorg.as_ref()
}
/// Default vertical-origin Y per §5.4.4, in font design units.
/// Returns `None` when no `VORG` table is present.
pub fn vorg_default_vert_origin_y(&self) -> Option<i16> {
self.vorg.as_ref().map(|v| v.default_vert_origin_y)
}
/// Y coordinate of the vertical origin for `glyph_id` per `VORG`
/// §5.4.4, in font design units.
///
/// Returns:
/// - `None` when the font has no `VORG`.
/// - `None` when the font is TrueType-flavoured (a `glyf` table is
/// present). §5.4.4 mandates "If present in TrueType OFF fonts
/// it must be ignored by font clients, just as any other
/// unrecognized table would be"; we honour that rule here.
/// Callers that want the TrueType-derived origin should use
/// [`Self::glyph_vertical_origin_y`] (which derives the value
/// from `vmtx.topSideBearing` + `glyf` bbox per §5.7.10).
/// - `Some(default_vert_origin_y)` when the glyph has no per-glyph
/// override entry — §5.4.4 size-optimised form ("glyphs whose
/// vertical origin's y coordinate equals defaultVertOriginY will
/// not have an entry").
/// - `Some(vert_origin_y)` from the metrics-array override when
/// one is present.
pub fn vert_origin_y_from_vorg(&self, glyph_id: u16) -> Option<i16> {
let vorg = self.vorg.as_ref()?;
// §5.4.4: TrueType clients must ignore the table. The presence
// of `glyf` is the canonical sfnt signal that the outlines are
// TrueType (a CFF font carries `CFF ` or `CFF2` instead and has
// no `glyf`/`loca`).
if self.glyf.is_some() {
return None;
}
Some(vorg.vert_origin_y(glyph_id))
}
/// `true` when the font ships a `BASE` table (ISO/IEC 14496-22:2019
/// §6.3.1). The table is optional for both TrueType and CFF sfnts
/// and is consulted by text-layout clients when aligning glyphs
/// from different scripts on a common baseline.
pub fn has_base(&self) -> bool {
self.base.is_some()
}
/// Borrow the parsed `BASE` table when present. Exposes the
/// HorizAxis / VertAxis trees plus (in v1.1 tables) the
/// ItemVariationStore offset for variable-font baseline deltas.
pub fn base_table(&self) -> Option<&BaseTable> {
self.base.as_ref()
}
/// Per-script default Y baseline (HorizAxis, §6.3.1.3) for the
/// given script tag and baseline tag. Returns the design-unit
/// coordinate from the BaseValues entry whose index matches
/// `baseline_tag` inside the Axis's BaseTagList.
///
/// Returns `None` when:
/// - the font has no `BASE` table;
/// - the HorizAxis is missing (typical for CJK vertical-only
/// fonts);
/// - the script tag is not listed in the Axis's BaseScriptList
/// (§6.3.1.3 "If a script is not listed here, then the
/// text-processing client will render the script using the
/// layout information specified for the entire font");
/// - the BaseTagList is NULL or `baseline_tag` is not in it;
/// - the BaseValues array is shorter than the BaseTagList index.
pub fn base_horiz_y_for_script_baseline(
&self,
script_tag: [u8; 4],
baseline_tag: [u8; 4],
) -> Option<i16> {
let base = self.base.as_ref()?;
let h = base.horiz_axis.as_ref()?;
let idx = h.baseline_index_for_tag(baseline_tag)?;
let bs = h.base_script_for_tag(script_tag)?;
let bv = bs.base_values.as_ref()?;
bv.base_coords.get(idx).map(|c| c.coordinate())
}
/// Per-script default X baseline (VertAxis, §6.3.1.3) for the given
/// script tag and baseline tag. Mirror of
/// [`Self::base_horiz_y_for_script_baseline`] for vertical layout.
pub fn base_vert_x_for_script_baseline(
&self,
script_tag: [u8; 4],
baseline_tag: [u8; 4],
) -> Option<i16> {
let base = self.base.as_ref()?;
let v = base.vert_axis.as_ref()?;
let idx = v.baseline_index_for_tag(baseline_tag)?;
let bs = v.base_script_for_tag(script_tag)?;
let bv = bs.base_values.as_ref()?;
bv.base_coords.get(idx).map(|c| c.coordinate())
}
/// `true` when the font carries a `gasp` table
/// (ISO/IEC 14496-22:2019 §5.3.7). Absent in many fonts; the
/// rasteriser applies its default policy when missing.
pub fn has_gasp(&self) -> bool {
self.gasp.is_some()
}
/// Borrow the parsed `gasp` table when present. Carries the
/// per-ppem rasterisation hints (`GASP_GRIDFIT`, `GASP_DOGRAY`,
/// `GASP_SYMMETRIC_GRIDFIT`, `GASP_SYMMETRIC_SMOOTHING`) sorted
/// by `rangeMaxPPEM`.
pub fn gasp_table(&self) -> Option<&GaspTable> {
self.gasp.as_ref()
}
/// Pick the `gasp` record that governs rasterisation at the given
/// pixel-per-em size — the first record whose `rangeMaxPPEM` is at
/// least `ppem` (§5.3.7). Returns `None` when the font ships no
/// `gasp` table or every record's upper limit is below `ppem`; in
/// either case the caller should fall back to the rasteriser's
/// default policy.
pub fn gasp_behavior_for_ppem(&self, ppem: u16) -> Option<&GaspRange> {
self.gasp.as_ref()?.behavior_for_ppem(ppem)
}
/// `true` when the font ships an `LTSH` table (ISO/IEC 14496-22:2019
/// §5.7.4). Absent in most fonts; rasterisers without one always
/// grid-fit (or consult `hdmx` / `vdmx` if those are present
/// instead) to find each glyph's true advance width.
pub fn has_ltsh(&self) -> bool {
self.ltsh.is_some()
}
/// Borrow the parsed `LTSH` table when present. Carries the
/// per-glyph `yPels` array recording each glyph's linear-threshold
/// ppem per §5.7.4.
pub fn ltsh_table(&self) -> Option<&LtshTable> {
self.ltsh.as_ref()
}
/// Lowest ppem at which the grid-fitted advance for `glyph_id` has
/// converged on the rounded linear advance per §5.7.4 — i.e. the
/// rasteriser may round the design-unit advance to integer pixels
/// at every ppem at least the returned value. Returns `None` when
/// the font ships no `LTSH` table or `glyph_id` is out of range.
pub fn ltsh_threshold(&self, glyph_id: u16) -> Option<u8> {
self.ltsh.as_ref()?.linear_threshold(glyph_id)
}
/// `true` when `glyph_id` is safe to advance-scale linearly at
/// `ppem` per §5.7.4 — i.e. `ppem >= LTSH.yPels[glyph_id]`. When
/// the font ships no `LTSH` table, returns `false` so the caller
/// falls back to grid-fitting (which is what §5.7.4 also prescribes
/// for fonts without an `LTSH`). Returns `false` for out-of-range
/// `glyph_id`.
pub fn ltsh_linearly_scales_at_ppem(&self, glyph_id: u16, ppem: u16) -> bool {
match self.ltsh.as_ref() {
Some(t) => t.linearly_scales_at_ppem(glyph_id, ppem),
None => false,
}
}
/// `true` when the font ships an `hdmx` table (ISO/IEC 14496-22:2019
/// §5.7.2). Optional table; absent in most fonts. §7.3.5 forbids
/// `hdmx` in variable fonts — a caller that wants to validate the
/// font shape may pair this with [`Self::is_variable`].
pub fn has_hdmx(&self) -> bool {
self.hdmx.is_some()
}
/// Borrow the parsed `hdmx` table when present. Carries the
/// per-ppem device records mapping each glyph to its grid-fitted
/// integer-pixel advance width at that ppem.
pub fn hdmx_table(&self) -> Option<&HdmxTable> {
self.hdmx.as_ref()
}
/// Grid-fitted advance width of `glyph_id` at the requested
/// `ppem`, in integer pixels, per §5.7.2. Returns `None` when the
/// font ships no `hdmx`, when the requested `ppem` is not in the
/// table's record array (§5.7.2 has no "round down" rule — the
/// caller falls back to scan-converting), or when `glyph_id`
/// exceeds the recorded per-glyph array. `ppem` is `u8` because
/// the on-wire field that drives the lookup is `uint8`; values
/// above 255 ppem are not representable in the table.
pub fn hdmx_advance_pixels(&self, glyph_id: u16, ppem: u8) -> Option<u8> {
self.hdmx.as_ref()?.advance_pixels(glyph_id, ppem)
}
/// The set of ppem sizes the font's `hdmx` table covers, in
/// ascending order. Returns an empty `Vec` when no `hdmx` is
/// present.
pub fn hdmx_recorded_ppem_sizes(&self) -> Vec<u8> {
match self.hdmx.as_ref() {
Some(t) => t.recorded_ppem_sizes(),
None => Vec::new(),
}
}
/// `true` when the font ships a `VDMX` table (ISO/IEC 14496-22:2019
/// §5.7.8). Optional table; absent in most fonts. §7.3.5 forbids
/// `VDMX` in variable fonts — pair with [`Self::is_variable`] when
/// validating a font's shape.
pub fn has_vdmx(&self) -> bool {
self.vdmx.is_some()
}
/// Borrow the parsed `VDMX` table when present. Carries one or
/// more VDMX groups indexed via a per-aspect-ratio RatioRange
/// array; each group publishes per-ppem `(yMax, yMin)` envelopes
/// for the font as a whole.
pub fn vdmx_table(&self) -> Option<&VdmxTable> {
self.vdmx.as_ref()
}
/// `(yMax, yMin)` pel envelope for `(ppem, deviceXRatio,
/// deviceYRatio)`, per §5.7.8's first-match RatioRange search.
/// Returns `None` when the font ships no `VDMX`, when no
/// RatioRange matches the device pair (and there is no `(0,0,0)`
/// sentinel), or when the matched group does not record the
/// exact `ppem` requested (§5.7.8 "need not be continuous" — no
/// fallback to neighbouring records).
///
/// For square-pixel screens the canonical call is
/// `vdmx_y_extent_for_device(ppem, 1, 1)`.
pub fn vdmx_y_extent_for_device(
&self,
ppem: u16,
device_x_ratio: u8,
device_y_ratio: u8,
) -> Option<(i16, i16)> {
self.vdmx
.as_ref()?
.y_extent_for_device(ppem, device_x_ratio, device_y_ratio)
}
/// Convenience for the common square-pixel case: equivalent to
/// `vdmx_y_extent_for_device(ppem, 1, 1)`. Returns the `(yMax,
/// yMin)` pel envelope at `ppem` under the 1:1 RatioRange
/// (matching either the explicit `(xRatio=1, yStartRatio=1,
/// yEndRatio=1)` entry, or the `(0,0,0)` catch-all sentinel
/// when present), or `None` otherwise.
pub fn vdmx_y_extent_square(&self, ppem: u16) -> Option<(i16, i16)> {
self.vdmx_y_extent_for_device(ppem, 1, 1)
}
/// `true` when the font ships a `meta` (Metadata) table per
/// ISO/IEC 14496-22:2019 §5.7.6.
pub fn has_meta(&self) -> bool {
self.meta.is_some()
}
/// Borrow the parsed `meta` table when present.
///
/// The returned [`MetaTable`] carries the §5.7.6 DataMap array;
/// per-record payloads borrow from the on-wire `meta` byte slice
/// for the lifetime of the [`Font`].
pub fn meta_table(&self) -> Option<&MetaTable<'a>> {
self.meta.as_ref()
}
/// First `meta` DataMap record whose tag equals `tag`, or
/// `None`. §5.7.6.1's closing paragraph permits multiple records
/// for the same tag but specifies that "any instances after the
/// first may be ignored" for single-record tags; this accessor
/// honours that rule by returning the first match. Callers that
/// want every record for a duplicated tag should iterate
/// [`MetaTable::records`] directly.
pub fn meta_record(&self, tag: &[u8; 4]) -> Option<MetaRecord<'_>> {
self.meta.as_ref()?.record(tag)
}
/// Design-language declaration from the `meta` table's `'dlng'`
/// record (ISO/IEC 14496-22:2019 §5.7.6.2), if present and
/// well-formed UTF-8. The value is a comma-separated list of
/// ScriptLangTags identifying the languages or scripts the font
/// was primarily designed for.
pub fn meta_design_languages(&self) -> Option<&'a str> {
self.meta.as_ref()?.design_languages()
}
/// Supported-language declaration from the `meta` table's
/// `'slng'` record (ISO/IEC 14496-22:2019 §5.7.6.2), if present
/// and well-formed UTF-8. Used to declare languages or scripts
/// the font is capable of supporting (a superset of
/// [`Self::meta_design_languages`] in typical use).
pub fn meta_supported_languages(&self) -> Option<&'a str> {
self.meta.as_ref()?.supported_languages()
}
/// `true` when the font ships a `PCLT` (PCL 5) table per ISO/IEC
/// 14496-22:2019 §5.7.7. The spec deems the table "strongly
/// discouraged for OFF fonts with TrueType outlines", so a `true`
/// here typically marks a legacy font.
pub fn has_pclt(&self) -> bool {
self.pclt.is_some()
}
/// Borrow the parsed `PCLT` table when present.
///
/// The returned [`PcltTable`] carries the §5.7.7 PCL 5
/// font-selection attributes: HP font number, pitch / x-height /
/// cap-height design-unit metrics, the packed style / type-family
/// / symbol-set words, the typeface "font print" string, the
/// character-complement bitfield, the PCL file name, and the
/// stroke-weight / width-type / serif-style classification bytes.
pub fn pclt_table(&self) -> Option<&PcltTable> {
self.pclt.as_ref()
}
/// Glyph bounding box from the `glyf` header (xMin/yMin/xMax/yMax).
/// Returns `None` for empty / blank glyphs and for fonts that lack
/// a `glyf`/`loca` pair (CBDT-only colour-emoji fonts).
pub fn glyph_bounding_box(&self, glyph_id: u16) -> Option<BBox> {
if glyph_id >= self.maxp.num_glyphs {
return None;
}
let (loca, glyf) = (self.loca.as_ref()?, self.glyf.as_ref()?);
let range = loca.glyph_range(glyph_id).ok()?;
if range.is_empty() {
return None;
}
glyf.bbox(range)
}
// ---- shaping support ---------------------------------------------------
/// Look up a ligature substitution for the input glyph run.
///
/// Returns `Some((replacement, consumed))` if a GSUB LookupType 4 rule
/// matches a prefix of `glyphs` of length `consumed >= 2`. Returns
/// `None` otherwise (no ligature, or no GSUB table).
pub fn lookup_ligature(&self, glyphs: &[u16]) -> Option<(u16, usize)> {
self.gsub.as_ref().and_then(|g| g.lookup_ligature(glyphs))
}
/// Resolve every GSUB feature active for `script_tag` under
/// `lang_tag` to a list of `GsubFeature { tag, lookup_indices }`.
///
/// `lang_tag = None` selects the script's `DefaultLangSys`. If
/// `lang_tag` is supplied but isn't enumerated for the script, the
/// lookup falls back to `DefaultLangSys` (matching the spec's
/// "language system not present in script → use default" rule).
///
/// The resulting `Vec` is empty when the font has no GSUB table or
/// the script tag isn't in the ScriptList. Order matches the
/// LangSys's `featureIndices` field, so a shaper can apply features
/// in declaration order. The required feature (when present) is
/// emitted first.
///
/// Used by the consumer crate's Arabic shaper to discover which
/// lookup indices implement `init` / `medi` / `fina` / `isol` for
/// the current script — modern Arabic fonts (Noto Sans Arabic UI,
/// most Indic fonts) ship positional forms via GSUB rather than
/// the legacy Presentation Forms-B Unicode block.
pub fn gsub_features_for_script(
&self,
script_tag: [u8; 4],
lang_tag: Option<[u8; 4]>,
) -> Vec<GsubFeature> {
match self.gsub.as_ref() {
Some(g) => g.features_for_script(script_tag, lang_tag),
None => Vec::new(),
}
}
/// Like [`Self::gsub_features_for_script`], but honours the GSUB
/// **FeatureVariations** table (ISO/IEC 14496-22:2019 §6.2.9) at the
/// font's current variation instance.
///
/// A variable font may publish a version-1.1 GSUB header that swaps
/// the lookups behind a feature for an alternate set when the
/// current instance falls inside a normalised range on one or more
/// `fvar` axes (the canonical use is optical-size- or
/// weight-conditional substitution). This accessor evaluates the
/// active condition set against [`Self::normalised_coords`] and, for
/// every feature whose index is overridden by the matching
/// FeatureTableSubstitution, returns the alternate lookup-index list
/// while keeping the feature tag unchanged.
///
/// For static fonts, v1.0 GSUB headers, or instances that match no
/// condition set, the result is identical to
/// [`Self::gsub_features_for_script`]. Set the instance with
/// [`Self::set_variation_coords`] first.
pub fn gsub_features_for_script_at_instance(
&self,
script_tag: [u8; 4],
lang_tag: Option<[u8; 4]>,
) -> Vec<GsubFeature> {
match self.gsub.as_ref() {
Some(g) => {
let coords = self.normalised_coords();
g.features_for_script_at_coords(script_tag, lang_tag, &coords)
}
None => Vec::new(),
}
}
/// `true` when the GSUB table carries a §6.2.9 FeatureVariations
/// table (a version-1.1 header with a non-zero offset). When this is
/// `false`, [`Self::gsub_features_for_script_at_instance`] is
/// identical to [`Self::gsub_features_for_script`].
pub fn gsub_has_feature_variations(&self) -> bool {
self.gsub
.as_ref()
.map(|g| g.has_feature_variations())
.unwrap_or(false)
}
/// Apply GSUB LookupType 1 (Single Substitution) lookup
/// `lookup_index` to a single input glyph `gid`.
///
/// Returns `Some(replacement_gid)` when the lookup's coverage
/// covers `gid`, or `None` when no substitution applies (caller
/// keeps the input glyph unchanged). `None` is also returned when
/// the font has no GSUB, the lookup index is out of range, or the
/// referenced lookup isn't a single-substitution lookup (e.g. a
/// ligature lookup is silently skipped here — call
/// [`Self::lookup_ligature`] for those).
///
/// Format 1 (delta) and Format 2 (substitute-array) sub-tables are
/// both supported; ExtensionSubst (LookupType 7) wrappers are
/// unwrapped transparently.
pub fn gsub_apply_lookup_type_1(&self, lookup_index: u16, gid: u16) -> Option<u16> {
self.gsub.as_ref()?.apply_lookup_type_1(lookup_index, gid)
}
/// Apply GSUB LookupType 4 (Ligature Substitution) lookup
/// `lookup_index` to a prefix of `gids`.
///
/// Returns `Some((replacement_gid, consumed))` when a sub-table in
/// the named lookup matches a prefix of `gids` of length `consumed`
/// (typically `>= 2` for real ligatures). Returns `None` when no
/// rule applies, the lookup index is out of range, the referenced
/// lookup is not a ligature lookup, or the font has no GSUB table.
/// ExtensionSubst (LookupType 7) wrappers are unwrapped
/// transparently.
///
/// This is the lookup-index-specific counterpart of
/// [`Self::lookup_ligature`] (which walks every lookup) and is the
/// API a feature-driven shaper uses after resolving the `liga` /
/// `rlig` / `dlig` feature for the active script via
/// [`Self::gsub_features_for_script`].
pub fn gsub_apply_lookup_type_4(
&self,
lookup_index: u16,
gids: &[u16],
) -> Option<(u16, usize)> {
self.gsub.as_ref()?.apply_lookup_type_4(lookup_index, gids)
}
/// Apply GSUB LookupType 6 (Chained Contexts Substitution) lookup
/// `lookup_index` to the glyph run starting at `pos`.
///
/// Returns `Some(rewritten_run)` — a fresh `Vec<u16>` of the full
/// run with any sub-lookups dispatched at the matched
/// `(backtrack, input, lookahead)` window — when one of the
/// lookup's sub-tables (Format 1 / 2 / 3) matches around `pos`.
/// Returns `None` when no chained-context rule applies, the lookup
/// index is out of range, the referenced lookup is not a
/// chain-context lookup, or the font has no GSUB table.
///
/// Each `SubstLookupRecord { sequenceIndex, lookupListIndex }`
/// inside the matched rule is recursively dispatched: LookupType 1
/// substitutes the single glyph at the relative `sequenceIndex`,
/// LookupType 4 substitutes `componentCount` glyphs starting there.
/// Nested LookupType 6 references are also handled (bounded depth).
/// ExtensionSubst (LookupType 7) is unwrapped transparently.
///
/// This is the biggest GSUB unlock for complex scripts: Arabic
/// shaping cascades, Indic reordering, and most ligature-with-
/// context rules (e.g. Latin `ct` only between word boundaries)
/// all run through chained-context lookups.
pub fn gsub_apply_lookup_type_6(
&self,
lookup_index: u16,
gids: &[u16],
pos: usize,
) -> Option<Vec<u16>> {
self.gsub
.as_ref()?
.apply_lookup_type_6(lookup_index, gids, pos)
}
/// Apply GSUB LookupType 2 (Multiple Substitution) lookup
/// `lookup_index` to a single input glyph `gid`.
///
/// Returns `Some(substitute_sequence)` — a `Vec<u16>` of the
/// expanded glyph sequence — when the lookup's coverage covers
/// `gid`. Returns `None` when no rule applies, the lookup index is
/// out of range, the referenced lookup is not a multiple
/// substitution, or the font has no GSUB table. ExtensionSubst
/// (LookupType 7) wrappers are unwrapped transparently. The spec
/// permits `glyphCount = 0` (deletion); such hits surface as
/// `Some(Vec::new())`.
pub fn gsub_apply_lookup_type_2(&self, lookup_index: u16, gid: u16) -> Option<Vec<u16>> {
self.gsub.as_ref()?.apply_lookup_type_2(lookup_index, gid)
}
/// Apply GSUB LookupType 3 (Alternate Substitution) lookup
/// `lookup_index` to `gid`, picking `alternate_index` from the
/// resolved `AlternateSet`.
///
/// Returns `Some(replacement_gid)` when the lookup covers `gid`
/// AND `alternate_index` is in range for that coverage's
/// `AlternateSet`. Returns `None` on coverage miss, out-of-range
/// alternate index, non-alternate-substitution referenced lookup,
/// or a font without GSUB. Default callers should pass
/// `alternate_index = 0` — the spec doesn't register a
/// per-feature variant index. ExtensionSubst (LookupType 7) is
/// unwrapped transparently.
pub fn gsub_apply_lookup_type_3(
&self,
lookup_index: u16,
gid: u16,
alternate_index: u16,
) -> Option<u16> {
self.gsub
.as_ref()?
.apply_lookup_type_3(lookup_index, gid, alternate_index)
}
/// Apply GSUB LookupType 5 (Contextual Substitution) lookup
/// `lookup_index` to the glyph run starting at `pos`.
///
/// LookupType 5 mirrors LookupType 6 minus backtrack and
/// lookahead — the input window is the only context. Returns
/// `Some(rewritten_run)` — a fresh `Vec<u16>` with any sub-lookups
/// dispatched at the matched input window — when one of the
/// lookup's sub-tables (Format 1 / 2 / 3) matches around `pos`.
/// Returns `None` when no contextual rule applies, the lookup
/// index is out of range, the referenced lookup is not a
/// contextual lookup, or the font has no GSUB.
/// ExtensionSubst (LookupType 7) is unwrapped transparently.
/// Recursive sub-lookup expansion is bounded.
pub fn gsub_apply_lookup_type_5(
&self,
lookup_index: u16,
gids: &[u16],
pos: usize,
) -> Option<Vec<u16>> {
self.gsub
.as_ref()?
.apply_lookup_type_5(lookup_index, gids, pos)
}
/// Apply GSUB LookupType 8 (Reverse Chained Context Substitution)
/// lookup `lookup_index` to the glyph at `gids[pos]`.
///
/// Returns `Some(replacement_gid)` when the input coverage covers
/// `gids[pos]` AND every backtrack / lookahead coverage matches
/// the surrounding glyphs. Returns `None` otherwise (no rule, out
/// of range, wrong lookup type, no GSUB). ExtensionSubst
/// (LookupType 7) is unwrapped transparently.
///
/// The spec mandates reverse-text processing of the input run
/// (essential for Arabic isolated forms in some fonts) — a higher-
/// level shaper is what walks `pos` from right to left; this
/// per-position entry point answers "does the rule fire here?".
pub fn gsub_apply_lookup_type_8(
&self,
lookup_index: u16,
gids: &[u16],
pos: usize,
) -> Option<u16> {
self.gsub
.as_ref()?
.apply_lookup_type_8(lookup_index, gids, pos)
}
/// On-disk header variant of the legacy `kern` table, if present.
///
/// Two header layouts coexist: Microsoft-format `kern` (every
/// Windows-authored / most Adobe / Google TTF — `u16 version,
/// u16 nTables`) and Apple-format `kern` (macOS-bundled TTFs —
/// `u32 version = 0x00010000, u32 nTables`, with different
/// per-subtable header bytes). This crate decodes Microsoft-format
/// Format-0 horizontal kerning subtables; Apple-format tables
/// parse cleanly but their subtable bodies surface as zero pairs
/// (see [`KernHeaderVariant::Apple`]).
///
/// Returns `None` for fonts that don't ship a `kern` table at all
/// (modern OpenType fonts use GPOS LookupType 2 instead).
pub fn kern_header_variant(&self) -> Option<KernHeaderVariant> {
self.kern.as_ref().map(|k| k.header_variant())
}
/// Look up the kerning between an ordered glyph pair, in font units.
///
/// Tries GPOS LookupType 2 first; falls back to the legacy `kern`
/// table (format 0). Returns 0 if neither is present or the pair has
/// no defined kerning.
pub fn lookup_kerning(&self, left: u16, right: u16) -> i16 {
if let Some(gpos) = &self.gpos {
let v = gpos.lookup_kerning(left, right, self.gdef.as_ref());
if v != 0 {
return v;
}
}
if let Some(kern) = &self.kern {
return kern.lookup(left, right);
}
0
}
/// Look up a mark-to-base attachment offset for a `(base, mark)`
/// glyph pair. Returns `(dx, dy)` in font units (TT Y-up convention)
/// to add to the mark's pen origin so its anchor lands on the
/// base's anchor for the mark's class.
///
/// Walks GPOS LookupType 4 sub-tables; returns `None` if no
/// matching MarkBasePos rule covers both glyphs (or if the font has
/// no GPOS table). Used by the consumer crate's shaper to position
/// diacritics above / below their base glyph (essential for
/// European Latin extended, Vietnamese, polytonic Greek).
///
/// Whether `mark` is actually a mark glyph (per `GDEF`) is the
/// caller's responsibility — typically the shaper checks
/// [`Font::is_mark_glyph`] before calling this. The lookup itself
/// works for any pair the font's MarkBasePos coverage tables
/// list, regardless of GDEF.
pub fn lookup_mark_to_base(&self, base: u16, mark: u16) -> Option<(i16, i16)> {
self.gpos.as_ref()?.lookup_mark_to_base(base, mark)
}
/// Look up a mark-to-mark attachment offset for a `(mark1, mark2)`
/// glyph pair, where `mark1` is the previously-positioned mark
/// (already attached to a base via a prior mark-to-base lookup) and
/// `mark2` is the mark we want to stack on top of (or below) it.
/// Returns `(dx, dy)` in font units (TT Y-up convention) to add to
/// `mark2`'s pen origin so its anchor lands on `mark1`'s anchor for
/// `mark2`'s class.
///
/// Walks GPOS LookupType 6 sub-tables; returns `None` if no
/// matching MarkMarkPos rule covers both glyphs (or if the font
/// has no GPOS table). Used by the consumer crate's shaper to
/// build multi-mark stacks (e.g. polytonic Greek `α + tonos +
/// dialytika`, Vietnamese `a + circumflex + acute`).
pub fn lookup_mark_to_mark(&self, mark1: u16, mark2: u16) -> Option<(i16, i16)> {
self.gpos.as_ref()?.lookup_mark_to_mark(mark1, mark2)
}
/// Is this glyph classified as a mark by the font's `GDEF` table?
/// Returns `false` if the font has no GDEF or the glyph isn't
/// enumerated. Used by the consumer crate's shaper to decide
/// whether to attempt mark-to-base attachment for an adjacent
/// glyph pair.
pub fn is_mark_glyph(&self, glyph_id: u16) -> bool {
self.gdef
.as_ref()
.map(|g| g.is_mark(glyph_id))
.unwrap_or(false)
}
/// Apply GPOS LookupType 1 (Single Adjustment Positioning) to
/// `gid` via the lookup at `lookup_index`.
///
/// Returns `Some(PosValue)` with the four geometric adjustments
/// (`xPlacement`, `yPlacement`, `xAdvance`, `yAdvance`) when the
/// lookup's coverage covers `gid`, or `None` when no rule applies
/// (or the font has no GPOS). Both SinglePosFormat 1 (one shared
/// ValueRecord) and Format 2 (per-glyph ValueRecord) are
/// supported; ExtensionPos (LookupType 9) wrappers are unwrapped
/// transparently.
///
/// Use this for features that don't need pair context — e.g. the
/// `cpsp` (capital spacing) feature applies a SinglePos to every
/// uppercase glyph to add side bearing.
pub fn gpos_apply_lookup_type_1(&self, lookup_index: u16, gid: u16) -> Option<PosValue> {
self.gpos.as_ref()?.apply_lookup_type_1(lookup_index, gid)
}
/// Apply GPOS LookupType 3 (Cursive Attachment) to `gid` via the
/// lookup at `lookup_index`.
///
/// Returns `Some(CursiveAttachment { entry, exit })` when the
/// lookup's coverage covers `gid`. Either anchor may be `None`
/// (the spec allows one-sided cursive glyphs at cluster
/// boundaries). Returns `None` when no rule applies, the lookup
/// index is out of range, the referenced lookup is not a cursive
/// lookup, or the font has no GPOS. ExtensionPos (LookupType 9)
/// wrappers are unwrapped transparently.
///
/// Cursive attachment chains glyph N+1 onto glyph N: the shaper
/// translates glyph N+1's pen origin so its `entry` anchor lands
/// on glyph N's `exit` anchor — i.e. the per-glyph delta is
/// `prev.exit - this.entry` in (x, y) font units.
pub fn gpos_apply_lookup_type_3(
&self,
lookup_index: u16,
gid: u16,
) -> Option<CursiveAttachment> {
self.gpos.as_ref()?.apply_lookup_type_3(lookup_index, gid)
}
/// Walk every GPOS LookupType-3 (Cursive Attachment) lookup
/// looking for `gid`'s entry/exit anchor pair. Convenience wrapper
/// around [`Self::gpos_apply_lookup_type_3`] for fonts that ship a
/// single `curs` lookup (the common Arabic Nastaliq case). Returns
/// the first hit in lookup order.
pub fn lookup_cursive_attachment(&self, gid: u16) -> Option<CursiveAttachment> {
self.gpos.as_ref()?.lookup_cursive_attachment(gid)
}
/// Apply GPOS LookupType 5 (Mark-to-Ligature Attachment) to the
/// `(ligature, ligature_component, mark)` triple via the lookup
/// at `lookup_index`.
///
/// Returns `Some((dx, dy))` (font units, TT Y-up) — the offset to
/// add to the mark's pen origin so its class anchor lands on the
/// selected component's anchor. `ligature_component` is 0-indexed
/// (component 0 = first component, e.g. `f` in `fi`). Returns
/// `None` when no rule covers both glyphs, when the component
/// index is out of range, or when no anchor exists for the mark's
/// class on the requested component. ExtensionPos (LookupType 9)
/// wrappers are unwrapped transparently.
///
/// Closes the "fi + dot-above" gap: a mark following the second
/// codepoint of a 2-component ligature attaches to component 1.
pub fn gpos_apply_lookup_type_5(
&self,
lookup_index: u16,
ligature: u16,
ligature_component: u16,
mark: u16,
) -> Option<(i16, i16)> {
self.gpos
.as_ref()?
.apply_lookup_type_5(lookup_index, ligature, ligature_component, mark)
}
/// Walk every GPOS LookupType-5 (Mark-to-Ligature) lookup looking
/// for the `(ligature, ligature_component, mark)` triple.
/// Convenience wrapper around [`Self::gpos_apply_lookup_type_5`]
/// that scans the LookupList rather than a specific index.
pub fn lookup_mark_to_ligature(
&self,
ligature: u16,
ligature_component: u16,
mark: u16,
) -> Option<(i16, i16)> {
self.gpos
.as_ref()?
.lookup_mark_to_ligature(ligature, ligature_component, mark)
}
/// Apply GPOS LookupType 7 (Contextual Positioning) to the glyph
/// run starting at `pos` via the lookup at `lookup_index`.
///
/// LookupType 7 is the non-chained sibling of LookupType 8: it
/// matches an input glyph sequence (no backtrack / lookahead) and,
/// on a hit, dispatches the rule's `SequenceLookupRecord[]` into
/// nested per-glyph positioning lookups. Returns `Some(records)` —
/// a `Vec<PosRecord>` of the per-glyph adjustments emitted — when a
/// sub-table matches the input window at `pos`. Each
/// `PosRecord.glyph_index` is an absolute offset into `gids`.
///
/// All three sub-table formats (1 glyph-sequence, 2 class-based,
/// 3 coverage-based) are supported. ExtensionPos (LookupType 9)
/// wrappers are unwrapped transparently; nested records into
/// LookupType 1 / 2 / 3 / 4 / 6 / 7 / 8 dispatch through the same
/// bounded-recursion machinery as the chained path.
pub fn gpos_apply_lookup_type_7(
&self,
lookup_index: u16,
gids: &[u16],
pos: usize,
) -> Option<Vec<PosRecord>> {
self.gpos
.as_ref()?
.apply_lookup_type_7(lookup_index, gids, pos)
}
/// Apply GPOS LookupType 8 (Chained Contexts Positioning) to the
/// glyph run starting at `pos` via the lookup at `lookup_index`.
///
/// Returns `Some(records)` — a `Vec<PosRecord>` listing every
/// per-glyph adjustment the matched chain rule emits — when one
/// of the lookup's sub-tables matches the
/// `(backtrack, input, lookahead)` window around `pos`. Each
/// `PosRecord.glyph_index` is an absolute offset into `gids`.
///
/// All three sub-table formats (1 glyph-sequence, 2 class-based,
/// 3 coverage-based) are supported. ExtensionPos (LookupType 9)
/// wrappers are unwrapped transparently. Nested
/// `PosLookupRecord` references into LookupType 1 / 2 / 4 / 6 / 8
/// dispatch through the same machinery; recursion is bounded.
pub fn gpos_apply_lookup_type_8(
&self,
lookup_index: u16,
gids: &[u16],
pos: usize,
) -> Option<Vec<PosRecord>> {
self.gpos
.as_ref()?
.apply_lookup_type_8(lookup_index, gids, pos)
}
/// Enumerate every GPOS lookup as `(lookup_index, lookup_type,
/// subtable_count)`.
///
/// The reported `lookup_type` is the **effective** type after
/// unwrapping any LookupType-9 ExtensionPos wrapper. Returns an
/// empty iterator when the font has no GPOS table.
///
/// Use this to find every chained-context positioning lookup, or
/// every mark-to-ligature lookup, etc., without probing each
/// index in turn — for example,
/// `font.gpos_lookup_list().filter(|(_, t, _)| *t == 8)` enumerates
/// the chained-context-positioning lookups.
pub fn gpos_lookup_list(&self) -> Vec<(u16, u16, u16)> {
match self.gpos.as_ref() {
Some(g) => g.lookup_list().collect(),
None => Vec::new(),
}
}
/// Enumerate every GSUB lookup as `(lookup_index, lookup_type,
/// subtable_count)`. Same shape as [`Self::gpos_lookup_list`] —
/// the reported `lookup_type` is post-unwrap of any
/// LookupType-7 ExtensionSubst wrapper.
pub fn gsub_lookup_list(&self) -> Vec<(u16, u16, u16)> {
match self.gsub.as_ref() {
Some(g) => g.lookup_list().collect(),
None => Vec::new(),
}
}
// ---- color bitmap glyphs (CBDT/CBLC) ---------------------------------
/// `true` if this font ships a CBDT/CBLC pair — i.e. carries
/// embedded colour bitmap glyphs (Noto Color Emoji, Apple Color
/// Emoji's Google-format counterparts, and most Android emoji
/// fonts). Returns `false` for plain outline-only fonts.
pub fn has_color_bitmaps(&self) -> bool {
self.cblc.is_some() && self.cbdt.is_some()
}
/// All `(ppem_x, ppem_y)` strikes the colour-bitmap tables ship.
/// Returns an empty iterator when the font lacks CBDT/CBLC.
/// Useful for picking a strike before calling
/// [`Font::glyph_color_bitmap`].
pub fn color_strike_sizes(&self) -> Vec<(u8, u8)> {
self.cblc
.as_ref()
.map(|c| c.ppem_sizes().collect())
.unwrap_or_default()
}
/// Resolve `glyph_id`'s colour bitmap at the strike whose `ppem_y`
/// is closest to `target_ppem`. Returns `None` if the font has no
/// CBDT/CBLC tables OR no strike contains `glyph_id` OR the strike's
/// per-glyph entry is in a CBDT format we don't decode (anything
/// other than 17/18/19 — the three PNG-payload formats).
///
/// On success returns a [`ColorBitmap`] with raw `png_bytes` ready
/// to feed into `oxideav-png` in the consumer crate. We deliberately
/// don't decode the PNG here so this crate stays dependency-light.
pub fn glyph_color_bitmap(&self, glyph_id: u16, target_ppem: u8) -> Option<ColorBitmap<'a>> {
let cblc = self.cblc.as_ref()?;
let cbdt = self.cbdt.as_ref()?;
let entry = cblc.lookup_glyph(glyph_id, target_ppem)?;
cbdt.lookup(&entry).ok().flatten()
}
// ---- monochrome / grayscale bitmap glyphs (EBDT/EBLC) ----------------
/// `true` if this font ships an EBDT/EBLC pair — i.e. carries
/// embedded monochrome or grayscale bitmap glyphs (legacy pixel /
/// CJK bitmap faces, hand-hinted small-size strikes). Returns `false`
/// for outline-only and colour-bitmap-only fonts.
pub fn has_gray_bitmaps(&self) -> bool {
self.eblc.is_some() && self.ebdt.is_some()
}
/// All `(ppem_x, ppem_y)` strikes the monochrome / grayscale bitmap
/// tables ship, in declaration order. Empty when the font lacks
/// EBDT/EBLC. Useful for picking a strike before calling
/// [`Font::glyph_gray_bitmap`].
pub fn gray_strike_sizes(&self) -> Vec<(u8, u8)> {
self.eblc
.as_ref()
.map(|c| c.ppem_sizes().collect())
.unwrap_or_default()
}
/// Resolve `glyph_id`'s monochrome / grayscale bitmap at the strike
/// whose `ppem_y` is closest to `target_ppem`. Returns `None` if the
/// font has no EBDT/EBLC tables OR no strike contains `glyph_id` OR
/// the strike's per-glyph entry is in an EBDT format we don't decode
/// (format 4 compressed, or formats 8 / 9 composite).
///
/// On success returns a [`GrayBitmap`] whose `pixels` field is an
/// unpacked `width * height` row-major grid of alpha coverage
/// (`0x00` = transparent, `0xFF` = opaque), ready to blit as a glyph
/// mask at `(bearing_x, bearing_y)`. Bit depths 1 / 2 / 4 / 8 are all
/// expanded to the full 0..=255 range (§5.6.2.2 / §5.6.3.1).
pub fn glyph_gray_bitmap(&self, glyph_id: u16, target_ppem: u8) -> Option<GrayBitmap> {
let eblc = self.eblc.as_ref()?;
let ebdt = self.ebdt.as_ref()?;
let entry = eblc.lookup_glyph(glyph_id, target_ppem)?;
ebdt.lookup(&entry).ok().flatten()
}
// ---- color layer glyphs (COLR / CPAL) --------------------------------
/// `true` if this font ships a `COLR` + `CPAL` pair — i.e. carries
/// vector colour-emoji glyphs as a per-glyph layer stack
/// (Microsoft's Segoe UI Emoji, Twemoji's Mozilla cut, FiraCode's
/// "color" variant, and so on). Returns `false` for plain
/// outline-only fonts and for CBDT-only colour-emoji fonts.
///
/// Only **COLR version 0** (flat palette-indexed layer stack) is
/// supported; v1 (paint graph with gradients/transforms) and v2/v3
/// (variable-COLR) are accepted at parse time but the v0
/// `BaseGlyphRecord` array is the only thing
/// [`Font::color_layers`] returns. v1 paint graphs are out of
/// scope for this crate.
pub fn has_color_layers(&self) -> bool {
self.colr.is_some() && self.cpal.is_some()
}
/// All colour layers for `glyph_id`, in back-to-front paint order.
/// Each layer carries an outline-glyph id (whose outline you fetch
/// via [`Font::glyph_outline`]) and a CPAL palette-entry index.
/// The reserved palette index `0xFFFF` means "use the renderer's
/// foreground colour" — substitute your own.
///
/// Returns an empty `Vec` when the font has no `COLR` table or
/// `glyph_id` isn't a base glyph (i.e. it's a single-colour
/// outline glyph or a layer-only glyph used by other bases).
pub fn color_layers(&self, glyph_id: u16) -> Vec<ColorLayer> {
match self.colr.as_ref() {
Some(colr) => colr.layers(glyph_id),
None => Vec::new(),
}
}
/// Resolve a single CPAL colour by `(palette_index, color_index)`.
/// Returns `[r, g, b, a]` (the byte order swizzled out of CPAL's
/// on-disk BGRA) or `None` when either index is out of range or the
/// font has no `CPAL` table.
///
/// Palette 0 is the spec's "default" palette. CPAL v1's palette
/// flags (`USABLE_WITH_LIGHT_BACKGROUND`,
/// `USABLE_WITH_DARK_BACKGROUND`) are exposed via
/// [`Font::cpal_palette_type`] for renderers that want to pick a
/// theme-appropriate palette.
pub fn cpal_color(&self, palette_index: u16, color_index: u16) -> Option<[u8; 4]> {
self.cpal.as_ref()?.color(palette_index, color_index)
}
/// All colours for palette `palette_index` as an `Vec<[u8; 4]>`
/// (RGBA byte order). `None` if the font has no CPAL table or
/// `palette_index` is out of range.
pub fn cpal_palette(&self, palette_index: u16) -> Option<Vec<[u8; 4]>> {
self.cpal.as_ref()?.palette(palette_index)
}
/// Number of CPAL palettes the font ships, or `0` if there's no
/// `CPAL` table. Mostly useful for renderers that pick a palette
/// based on `cpal_palette_type` flags.
pub fn cpal_num_palettes(&self) -> u16 {
self.cpal.as_ref().map(|c| c.num_palettes()).unwrap_or(0)
}
/// CPAL v1 palette-type flags for `palette_index`. Returns 0 when
/// the font has no CPAL table, the table is v0, or the palette
/// index is out of range.
///
/// Bit 0 (`0x0001`) = USABLE_WITH_LIGHT_BACKGROUND
/// Bit 1 (`0x0002`) = USABLE_WITH_DARK_BACKGROUND
pub fn cpal_palette_type(&self, palette_index: u16) -> u32 {
self.cpal
.as_ref()
.map(|c| c.palette_type(palette_index))
.unwrap_or(0)
}
// ---- sbix bitmap glyphs (Apple Color Emoji format) -------------------
/// `true` if this font ships an `sbix` table — Apple's PNG/JPEG/
/// TIFF bitmap-strike container, used by Apple Color Emoji and
/// every macOS/iOS-native colour-emoji font. Returns `false` for
/// outline-only fonts and for CBDT/CBLC- or COLR/CPAL-flavoured
/// colour fonts.
pub fn has_sbix(&self) -> bool {
self.sbix.is_some()
}
/// All strike ppem sizes the `sbix` table ships, sorted ascending
/// and de-duplicated. Apple Color Emoji typically lists eight
/// strikes in the 20-160 ppem range. Returns an empty `Vec` when
/// the font has no `sbix` table.
pub fn sbix_strikes(&self) -> Vec<u16> {
self.sbix
.as_ref()
.map(|s| s.all_ppems_unique_sorted())
.unwrap_or_default()
}
/// Resolve `glyph_id`'s sbix bitmap from the strike whose `ppem`
/// is closest to the requested `ppem` (ties favour the larger
/// strike, per the spec recommendation). Returns `None` if the
/// font has no `sbix` table OR no strike contains a bitmap for
/// `glyph_id`.
///
/// `SbixGlyph::graphic_type` is one of `*b"png "`, `*b"jpg "`,
/// `*b"tiff"`, or `*b"dupe"` — the consumer crate is expected to
/// route the payload to the right decoder. The special `'dupe'`
/// value indicates a 2-byte big-endian glyph id whose bitmap
/// should be substituted; this method surfaces the indirection
/// sentinel as-is for byte-level introspection. Use
/// [`Self::sbix_glyph_resolved`] when the caller wants the
/// indirection chased for them.
pub fn sbix_glyph(&self, glyph_id: u16, ppem: u16) -> Option<SbixGlyph<'a>> {
self.sbix.as_ref()?.lookup_best_fit(glyph_id, ppem)
}
/// Like [`Self::sbix_glyph`], but chases `'dupe'` indirections
/// within the chosen strike — up to [`SBIX_MAX_DUPE_DEPTH`] hops
/// — with explicit cycle detection. Returns the first reachable
/// non-`'dupe'` entry, or `None` if the chain cycles, exceeds the
/// hop cap, or hits a malformed / out-of-range target. Callers
/// that need to introspect the raw `'dupe'` sentinel keep using
/// [`Self::sbix_glyph`].
pub fn sbix_glyph_resolved(&self, glyph_id: u16, ppem: u16) -> Option<SbixGlyph<'a>> {
self.sbix.as_ref()?.lookup_best_fit_resolved(glyph_id, ppem)
}
// ---- variable fonts (fvar / avar / gvar) -----------------------------
/// `true` if the font ships an `fvar` table — i.e. it exposes one
/// or more variation axes. Returns `false` for static fonts.
pub fn is_variable(&self) -> bool {
self.fvar.is_some()
}
/// All variation axes the font publishes (`fvar`), in declaration
/// order. Returns an empty slice for static fonts.
pub fn variation_axes(&self) -> &[VariationAxis] {
self.fvar.as_ref().map(|f| f.axes()).unwrap_or(&[])
}
/// All named instances the font ships (`fvar`), in declaration
/// order. Each carries a coordinate vector matching
/// [`Self::variation_axes`] (one f32 per axis) plus a `name`
/// table id for the human-readable subfamily label.
pub fn named_instances(&self) -> &[NamedInstance] {
self.fvar.as_ref().map(|f| f.instances()).unwrap_or(&[])
}
/// Current user-space variation coordinates (one entry per axis,
/// in `fvar` declaration order). Empty slice for static fonts.
/// Defaults to each axis's `default` value at parse time;
/// updated by [`Self::set_variation_coords`].
pub fn variation_coords(&self) -> &[f32] {
&self.var_coords
}
/// Replace the current variation coordinates. Each entry is in
/// **user-space** units (e.g. `wght` is 100..900). The vector
/// must be the same length as [`Self::variation_axes`]; shorter
/// vectors leave the trailing axes at their previous value, longer
/// vectors are truncated. Out-of-range values are clamped to each
/// axis's `[min, max]`.
///
/// No-op when the font is static (`is_variable() == false`).
pub fn set_variation_coords(&mut self, coords: &[f32]) {
let axes = match self.fvar.as_ref() {
Some(f) => f.axes(),
None => return,
};
for (i, &v) in coords.iter().enumerate() {
if i >= self.var_coords.len() {
break;
}
let a = &axes[i];
self.var_coords[i] = v.clamp(a.min, a.max);
}
}
/// Compute the normalised coordinate vector (each entry in
/// `[-1, +1]`) by mapping each user-space value through the
/// `fvar` axis triple, then through the `avar` per-axis remap.
/// Returns an empty vec for static fonts.
pub fn normalised_coords(&self) -> Vec<f32> {
let axes = match self.fvar.as_ref() {
Some(f) => f.axes(),
None => return Vec::new(),
};
let mut out = Vec::with_capacity(axes.len());
for (i, axis) in axes.iter().enumerate() {
let v = self.var_coords.get(i).copied().unwrap_or(axis.default);
let n = if (v - axis.default).abs() < f32::EPSILON {
0.0
} else if v < axis.default {
if (axis.default - axis.min).abs() < f32::EPSILON {
0.0
} else {
((v - axis.default) / (axis.default - axis.min)).clamp(-1.0, 0.0)
}
} else if (axis.max - axis.default).abs() < f32::EPSILON {
0.0
} else {
((v - axis.default) / (axis.max - axis.default)).clamp(0.0, 1.0)
};
let n = match self.avar.as_ref() {
Some(a) => a.remap_normalised(i, n),
None => n,
};
out.push(n);
}
out
}
/// Borrow the parsed `MVAR` table, when present. Static fonts and
/// variable fonts that omit MVAR return `None`.
pub fn mvar_table(&self) -> Option<&MvarTable> {
self.mvar.as_ref()
}
/// Interpolated `MVAR` adjustment for a four-byte metric tag (e.g.
/// `*b"xhgt"`, `*b"cpht"`, `*b"hasc"`) at the current variation
/// coordinates.
///
/// Per ISO/IEC 14496-22:2019 §7.3.6.2, the adjustment is computed
/// against the current **normalised** coordinate vector (i.e.
/// after the `avar` remap, see [`Self::normalised_coords`]). The
/// returned value is a delta to be **added** to the corresponding
/// field in `OS/2` / `hhea` / `vhea` / `post` / `gasp`.
///
/// Returns `None` when:
/// * the font lacks an `MVAR` table, or
/// * the requested `tag` is not present in MVAR's value-record
/// array (the spec's "if the tag does not occur, the item is
/// constant across the variation space" rule).
///
/// Returns `Some(0.0)` when the variation evaluates to zero at the
/// current instance (e.g. at the axis defaults).
pub fn metric_variation_delta(&self, tag: &[u8; 4]) -> Option<f32> {
let m = self.mvar.as_ref()?;
let coords = self.normalised_coords();
m.delta_for_tag(tag, &coords)
}
/// Borrow the parsed `HVAR` table, when present.
pub fn hvar_table(&self) -> Option<&HvarTable> {
self.hvar.as_ref()
}
/// Interpolated `HVAR` adjustment to the advance width of
/// `glyph_id` at the current variation coordinates.
///
/// Per ISO/IEC 14496-22:2019 §7.3.5.3, the application reads the
/// default advance width from `hmtx` and adds this delta to derive
/// the per-instance advance. When an `advanceWidthMapping` table
/// is published, that map provides the `(outer, inner)` index
/// pair; otherwise the glyph ID itself acts as the inner index
/// and the outer index is zero (the implicit form).
///
/// Returns `None` when the font lacks `HVAR` or when the resolved
/// index pair is out of range for the embedded item variation
/// store. Returns `Some(0.0)` when the variation evaluates to
/// zero at the current instance (e.g. at the axis defaults).
pub fn advance_width_variation_delta(&self, glyph_id: u16) -> Option<f32> {
let h = self.hvar.as_ref()?;
let coords = self.normalised_coords();
h.advance_width_delta(glyph_id, &coords)
}
/// Interpolated `HVAR` adjustment to the left side bearing of
/// `glyph_id`. Requires that the font ship a left-side-bearing
/// mapping table (§7.3.5.2 says LSB / RSB lookups always need
/// one); returns `None` otherwise.
pub fn lsb_variation_delta(&self, glyph_id: u16) -> Option<f32> {
let h = self.hvar.as_ref()?;
let coords = self.normalised_coords();
h.lsb_delta(glyph_id, &coords)
}
/// Interpolated `HVAR` adjustment to the right side bearing of
/// `glyph_id`. Requires a right-side-bearing mapping table per
/// §7.3.5.2; returns `None` otherwise.
pub fn rsb_variation_delta(&self, glyph_id: u16) -> Option<f32> {
let h = self.hvar.as_ref()?;
let coords = self.normalised_coords();
h.rsb_delta(glyph_id, &coords)
}
/// Borrow the parsed `VVAR` table, when present.
pub fn vvar_table(&self) -> Option<&VvarTable> {
self.vvar.as_ref()
}
/// Interpolated `VVAR` adjustment to the advance height of
/// `glyph_id` at the current variation coordinates.
///
/// Per ISO/IEC 14496-22:2019 §7.3.8.2 (cross-referenced back to
/// §7.3.5.3), the application reads the default advance height
/// from `vmtx` and adds this delta to derive the per-instance
/// advance. When an `advanceHeightMapping` table is published,
/// that map provides the `(outer, inner)` index pair; otherwise
/// the glyph ID itself acts as the inner index and the outer index
/// is zero (the implicit form).
///
/// Returns `None` when the font lacks `VVAR` or when the resolved
/// index pair is out of range for the embedded item variation
/// store. Returns `Some(0.0)` when the variation evaluates to zero
/// at the current instance (e.g. at the axis defaults).
pub fn advance_height_variation_delta(&self, glyph_id: u16) -> Option<f32> {
let v = self.vvar.as_ref()?;
let coords = self.normalised_coords();
v.advance_height_delta(glyph_id, &coords)
}
/// Interpolated `VVAR` adjustment to the top side bearing of
/// `glyph_id`. Requires that the font ship a top-side-bearing
/// mapping table (§7.3.8.2 inherits the §7.3.5.2 rule that side-
/// bearing lookups always need a map); returns `None` otherwise.
pub fn tsb_variation_delta(&self, glyph_id: u16) -> Option<f32> {
let v = self.vvar.as_ref()?;
let coords = self.normalised_coords();
v.tsb_delta(glyph_id, &coords)
}
/// Interpolated `VVAR` adjustment to the bottom side bearing of
/// `glyph_id`. Requires a bottom-side-bearing mapping table per
/// §7.3.8.2; returns `None` otherwise.
pub fn bsb_variation_delta(&self, glyph_id: u16) -> Option<f32> {
let v = self.vvar.as_ref()?;
let coords = self.normalised_coords();
v.bsb_delta(glyph_id, &coords)
}
/// Interpolated `VVAR` adjustment to the vertical-origin Y of
/// `glyph_id`. §7.3.8.2 final paragraph: a mapping table is
/// required for vertical-origin variation data, and the data is
/// "not used in fonts with TrueType outlines" — populated only by
/// CFF2 variable fonts that publish a `VORG` table. Returns
/// `None` otherwise.
pub fn vorg_variation_delta(&self, glyph_id: u16) -> Option<f32> {
let v = self.vvar.as_ref()?;
let coords = self.normalised_coords();
v.vorg_delta(glyph_id, &coords)
}
/// Borrow the parsed `STAT` table, when present. Static fonts may
/// omit it; variable fonts are required by ISO/IEC 14496-22:2019
/// §7.3.7 to ship one.
pub fn stat_table(&self) -> Option<&StatTable> {
self.stat.as_ref()
}
/// `STAT.designAxes` — one record per design axis. For a variable
/// font, every `fvar` axis must appear here; the order is arbitrary
/// (sort by `axis_ordering` if a stable UI order is needed).
/// Returns an empty slice when no STAT table is present.
pub fn stat_axes(&self) -> &[StatAxisRecord] {
match self.stat.as_ref() {
Some(s) => s.axes(),
None => &[],
}
}
/// `STAT.axisValueTables` — every axis value record in document
/// order. Filter by axis tag with [`Self::stat_axis_values_for_tag`]
/// or walk by format to compose subfamily strings under the
/// R/B/I/BI, WWS, or unrestricted naming models (§7.3.7.3).
/// Returns an empty slice when no STAT table is present.
pub fn stat_axis_values(&self) -> &[StatAxisValue] {
match self.stat.as_ref() {
Some(s) => s.axis_values(),
None => &[],
}
}
/// `STAT.elidedFallbackNameID` — the `name` table nameID applied
/// when every component of a composed subfamily string would be
/// elided (§7.3.7.1). Returns `None` when the font ships no STAT
/// table; returns name ID 2 ("Regular") for the deprecated v1.0
/// header that lacked the field.
pub fn stat_elided_fallback_name_id(&self) -> Option<u16> {
Some(self.stat.as_ref()?.elided_fallback_name_id())
}
/// Every STAT axis-value record whose axis is `axis_tag` (e.g.
/// `*b"wght"`, `*b"wdth"`). Format-4 records are matched when one
/// of their contributing axes references this tag. Returns an
/// empty iterator when the font has no STAT table or the tag is
/// not in the design-axes array.
pub fn stat_axis_values_for_tag(
&self,
axis_tag: [u8; 4],
) -> Box<dyn Iterator<Item = &StatAxisValue> + '_> {
match self.stat.as_ref() {
Some(s) => Box::new(s.axis_values_for_tag(axis_tag)),
None => Box::new(core::iter::empty()),
}
}
/// `true` if any current coordinate diverges from its axis default.
fn coords_differ_from_default(&self) -> bool {
let axes = match self.fvar.as_ref() {
Some(f) => f.axes(),
None => return false,
};
for (i, axis) in axes.iter().enumerate() {
if let Some(v) = self.var_coords.get(i) {
if (v - axis.default).abs() > f32::EPSILON {
return true;
}
}
}
false
}
}
#[inline]
fn clamp_i16_for_outline(v: i32) -> i16 {
if v < i16::MIN as i32 {
i16::MIN
} else if v > i16::MAX as i32 {
i16::MAX
} else {
v as i16
}
}