glyphs-reader 1.0.0

Parsing .glyphs source files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
//! The general strategy is just to use a plist for storage. Also, lots of
//! unwrapping.
//!
//! There are lots of other ways this could go, including something serde-like
//! where it gets serialized to more Rust-native structures, proc macros, etc.

use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::ffi::OsStr;
use std::hash::Hash;
use std::num::ParseIntError;
use std::ops::RangeInclusive;
use std::str::FromStr;
use std::sync::{LazyLock, Mutex};
use std::{fs, path};

use crate::glyphdata::{Category, GlyphData, Subcategory};
use ascii_plist_derive::FromPlist;
use fontdrasil::types::WidthClass;
use indexmap::{IndexMap, IndexSet};
use kurbo::{Affine, CubicBez, Line, PathSeg, Point, QuadBez};
use log::{debug, warn};
use ordered_float::OrderedFloat;
use regex::Regex;
use smol_str::SmolStr;

use crate::error::Error;
use crate::plist::{FromPlist, Plist, Token, Tokenizer, VecDelimiters};

// Static set to track warnings we've already logged, to avoid repetition
static LOGGED_WARNINGS: LazyLock<Mutex<HashSet<String>>> =
    LazyLock::new(|| Mutex::new(HashSet::new()));

/// Log a warning message only once per process lifetime
macro_rules! log_once_warn {
    ($($arg:tt)*) => {{
        if log::log_enabled!(log::Level::Warn) {
            let msg = format!($($arg)*);
            let mut logged = LOGGED_WARNINGS.lock().unwrap();
            if !logged.contains(&msg) {
                log::warn!("{}", msg);
                logged.insert(msg);
            }
        }
    }};
}

const V3_METRIC_NAMES: [&str; 6] = [
    "ascender",
    "baseline",
    "descender",
    "cap height",
    "x-height",
    "italic angle",
];

#[derive(Clone, Debug, Default, PartialEq, Hash)]
pub struct UserToDesignMapping(BTreeMap<String, AxisUserToDesignMap>);

#[derive(Clone, Debug, Default, PartialEq, Hash)]
pub struct AxisUserToDesignMap(Vec<(OrderedFloat<f64>, OrderedFloat<f64>)>);

/// A tidied up font from a plist.
///
/// Normalized representation of Glyphs 2/3 content
#[derive(Clone, Debug, Default, PartialEq, Hash)]
pub struct Font {
    pub units_per_em: u16,
    pub axes: Vec<Axis>,
    pub masters: Vec<FontMaster>,
    pub default_master_idx: usize,
    pub glyphs: BTreeMap<SmolStr, Glyph>,
    pub glyph_order: Vec<SmolStr>,
    // tag => (user:design) tuples
    pub axis_mappings: UserToDesignMapping,
    pub virtual_masters: Vec<BTreeMap<String, OrderedFloat<f64>>>,
    pub features: Vec<FeatureSnippet>,
    // Incliudes both default (English) and localized property names.
    // Maps property key (e.g., "familyNames") to list of (language code, value)
    pub all_names: BTreeMap<String, Vec<(String, String)>>,
    pub instances: Vec<Instance>,
    pub version_major: i32,
    pub version_minor: u32,
    pub date: Option<String>,

    // master id => { (name or class, name or class) => adjustment }
    pub kerning_ltr: Kerning,
    pub kerning_rtl: Kerning,

    pub custom_parameters: CustomParameters,
    pub user_data: BTreeMap<SmolStr, Plist>,
}

/// Custom parameter options that can be set on a glyphs font
#[derive(Clone, Debug, PartialEq, Hash, Default)]
pub struct CustomParameters {
    pub propagate_anchors: Option<bool>,
    pub use_typo_metrics: Option<bool>,
    pub is_fixed_pitch: Option<bool>,
    pub fs_type: Option<u16>,
    pub has_wws_names: Option<bool>,
    pub typo_ascender: Option<i64>,
    pub typo_descender: Option<i64>,
    pub typo_line_gap: Option<i64>,
    pub win_ascent: Option<i64>,
    pub win_descent: Option<i64>,
    pub hhea_ascender: Option<i64>,
    pub hhea_descender: Option<i64>,
    pub hhea_line_gap: Option<i64>,
    pub vhea_ascender: Option<i64>,
    pub vhea_descender: Option<i64>,
    pub vhea_line_gap: Option<i64>,
    pub underline_thickness: Option<OrderedFloat<f64>>,
    pub underline_position: Option<OrderedFloat<f64>>,
    pub strikeout_position: Option<i64>,
    pub strikeout_size: Option<i64>,
    pub subscript_x_offset: Option<i64>,
    pub subscript_x_size: Option<i64>,
    pub subscript_y_offset: Option<i64>,
    pub subscript_y_size: Option<i64>,
    pub superscript_x_offset: Option<i64>,
    pub superscript_x_size: Option<i64>,
    pub superscript_y_offset: Option<i64>,
    pub superscript_y_size: Option<i64>,
    pub unicode_range_bits: Option<BTreeSet<u32>>,
    pub codepage_range_bits: Option<BTreeSet<u32>>,
    pub panose: Option<Vec<i64>>,

    pub head_flags: Option<Vec<i64>>,
    pub lowest_rec_ppem: Option<i64>,
    pub hhea_caret_slope_run: Option<i64>,
    pub hhea_caret_slope_rise: Option<i64>,
    pub hhea_caret_offset: Option<i64>,
    pub vhea_caret_slope_run: Option<i64>,
    pub vhea_caret_slope_rise: Option<i64>,
    pub vhea_caret_offset: Option<i64>,
    pub meta_table: Option<MetaTableValues>,
    pub dont_use_production_names: Option<bool>,
    // Master-level parameters for linking metrics to another master
    pub link_metrics_with_first_master: Option<bool>,
    pub link_metrics_with_master: Option<SmolStr>,
    // these fields are parsed via the config, but are stored
    // in the top-level `Font` struct
    pub virtual_masters: Option<Vec<BTreeMap<String, OrderedFloat<f64>>>>,
    pub glyph_order: Option<Vec<SmolStr>>,
    pub gasp_table: Option<BTreeMap<i64, i64>>,
    pub feature_for_feature_variations: Option<SmolStr>,
    pub color_palettes: Option<Vec<Vec<Color>>>,
    pub name_table_entries: Vec<NameTableEntry>,
}

/// Values for the 'meta Table' custom parameter
#[derive(Clone, Debug, PartialEq, Hash, Default)]
pub struct MetaTableValues {
    pub dlng: Vec<SmolStr>,
    pub slng: Vec<SmolStr>,
}

impl MetaTableValues {
    fn from_plist(plist: &Plist) -> Option<Self> {
        let mut ret = MetaTableValues::default();
        let as_array = plist.as_array()?;
        for item in as_array {
            let tag = item.get("tag").and_then(Plist::as_str)?;
            let data = item.get("data").and_then(Plist::as_str)?;
            let data = data.split(',').map(SmolStr::new).collect();

            match tag {
                "dlng" => ret.dlng = data,
                "slng" => ret.slng = data,
                _ => log_once_warn!("Unknown meta table tag '{tag}'"),
            }
        }

        if ret.dlng.len() + ret.slng.len() > 0 {
            Some(ret)
        } else {
            None
        }
    }
}

/// master id => { (name or class, name or class) => adjustment }
#[derive(Clone, Debug, Default, PartialEq, Hash)]
pub struct Kerning(BTreeMap<String, BTreeMap<(SmolStr, SmolStr), OrderedFloat<f64>>>);

impl Kerning {
    pub fn get(&self, master_id: &str) -> Option<&BTreeMap<(SmolStr, SmolStr), OrderedFloat<f64>>> {
        self.0.get(master_id)
    }

    pub fn keys(&self) -> impl Iterator<Item = &String> {
        self.0.keys()
    }

    pub fn iter(
        &self,
    ) -> impl Iterator<Item = (&String, &BTreeMap<(SmolStr, SmolStr), OrderedFloat<f64>>)> {
        self.0.iter()
    }

    fn insert(
        &mut self,
        master_id: String,
        lhs_class_or_group: SmolStr,
        rhs_class_or_group: SmolStr,
        kern: f64,
    ) {
        *self
            .0
            .entry(master_id)
            .or_default()
            .entry((lhs_class_or_group, rhs_class_or_group))
            .or_default() = kern.into();
    }
}

/// Hand-parse because it's a bit weird
impl FromPlist for Kerning {
    fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
        let mut kerning = Kerning::default();

        tokenizer.eat(b'{')?;

        loop {
            if tokenizer.eat(b'}').is_ok() {
                break;
            }

            // parse string-that-is-master-id = {
            let master_id: String = tokenizer.parse()?;
            tokenizer.eat(b'=')?;

            // The map for the master
            tokenizer.eat(b'{')?;
            loop {
                if tokenizer.eat(b'}').is_ok() {
                    break;
                }
                let lhs_name_or_class: SmolStr = tokenizer.parse()?;
                tokenizer.eat(b'=')?;
                tokenizer.eat(b'{')?;

                // rhs name = value pairs
                loop {
                    if tokenizer.eat(b'}').is_ok() {
                        break;
                    }

                    let rhs_name_or_class: SmolStr = tokenizer.parse()?;
                    tokenizer.eat(b'=')?;
                    let value: f64 = tokenizer.parse()?;
                    tokenizer.eat(b';')?;

                    kerning.insert(
                        master_id.clone(),
                        lhs_name_or_class.clone(),
                        rhs_name_or_class,
                        value,
                    );
                }
                tokenizer.eat(b';')?;
            }

            tokenizer.eat(b';')?;
        }

        Ok(kerning)
    }
}

/// A chunk of FEA code
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FeatureSnippet {
    pub content: String,
    /// If `true` the content should be ignored.
    pub disabled: bool,
}

impl FeatureSnippet {
    pub fn new(content: String, disabled: bool) -> Self {
        FeatureSnippet { content, disabled }
    }

    pub fn str_if_enabled(&self) -> Option<&str> {
        (!self.disabled).then_some(&self.content)
    }
}

#[derive(Clone, Default, Debug, PartialEq, Hash)]
pub struct Glyph {
    pub name: SmolStr,
    pub export: bool,
    pub layers: Vec<Layer>,
    pub bracket_layers: Vec<Layer>,
    pub unicode: BTreeSet<u32>,
    /// The left kerning group
    pub left_kern: Option<SmolStr>,
    /// The right kerning group
    pub right_kern: Option<SmolStr>,
    pub category: Option<Category>,
    pub sub_category: Option<Subcategory>,
    pub production_name: Option<SmolStr>,
    /// If this is a smart component, these are the axe names -> user coords
    pub smart_component_axes: BTreeMap<SmolStr, RangeInclusive<i64>>,
}

impl Glyph {
    pub fn is_nonspacing_mark(&self) -> bool {
        matches!(
            (self.category, self.sub_category),
            (Some(Category::Mark), Some(Subcategory::Nonspacing))
        )
    }

    pub fn has_components(&self) -> bool {
        self.layers
            .iter()
            .chain(self.bracket_layers.iter())
            .flat_map(Layer::components)
            .next()
            .is_some()
    }
}

impl fontdrasil::util::CompositeLike for Glyph {
    fn name(&self) -> SmolStr {
        self.name.clone()
    }

    fn has_components(&self) -> bool {
        Glyph::has_components(self)
    }

    fn component_names(&self) -> impl Iterator<Item = SmolStr> {
        self.layers
            .iter()
            .chain(self.bracket_layers.iter())
            .flat_map(|layer| layer.shapes.iter())
            .filter_map(|shape| match shape {
                Shape::Path(..) => None,
                Shape::Component(c) => Some(c.name.clone()),
            })
    }
}

/// Whether a given layer of a smart component is at the min or max of a given axis.
#[derive(Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AxisPole {
    /// this layer is at the minimum value for this property
    Min,
    /// this layer is at the maximum value for this property
    Max,
}

/// A hint in a Glyphs layer (e.g., corner component, stem hint, etc.)
#[derive(Clone, Debug, Default, PartialEq, FromPlist)]
pub struct RawHint {
    #[fromplist(alt_name = "type")]
    hint_type: SmolStr,
    name: SmolStr,
    origin: RawHint2Tuple, // (shape_index, node_index)
    scale: Option<RawHint2Tuple>,
    options: i64, // Alignment option for corner components
}

// we use a custom type because the data has a different shape between
// glyphs formats
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RawHint2Tuple {
    x: f64,
    y: f64,
}

impl FromPlist for RawHint2Tuple {
    fn parse(tokenizer: &mut Tokenizer) -> Result<Self, crate::plist::Error> {
        if matches!(tokenizer.peek(), Ok(Token::String(_))) {
            let s = tokenizer.parse::<SmolStr>().unwrap();
            // format2 is a string, like "{0, 3}"
            let s = s.trim_matches(['{', '}']);
            let Some((x, y)) = s.split_once(',') else {
                return Err(crate::plist::Error::ExpectedComma);
            };
            let x = x
                .trim()
                .parse()
                .map_err(|_| crate::plist::Error::ExpectedNumber)?;
            let y = y
                .trim()
                .parse()
                .map_err(|_| crate::plist::Error::ExpectedNumber)?;
            return Ok(RawHint2Tuple { x, y });
        }

        let origin: Vec<f64> = tokenizer.parse()?;
        Ok(RawHint2Tuple {
            x: origin.first().copied().unwrap_or_default(),
            y: origin.get(1).copied().unwrap_or_default(),
        })
    }
}

impl RawHint {
    fn to_hint(&self) -> Result<Hint, Error> {
        let type_ = match self.hint_type.as_str() {
            "Corner" => HintType::Corner,
            "Cap" => HintType::Cap,
            "Stem" => HintType::Stem,
            "TTStem" => HintType::TTStem,
            _other => {
                log::info!("unhandled hint type '{_other}'");
                HintType::Unknown
            }
        };

        let shape_index = self.origin.x as usize;
        let node_index = self.origin.y as usize;

        let scale = self
            .scale
            .map(|RawHint2Tuple { x, y }| Scale::new(x, y))
            .unwrap_or_default();

        let alignment = match self.options {
            0 => Alignment::OutStroke,
            1 => Alignment::InStroke,
            2 => Alignment::Middle,
            3 => Alignment::Unused,
            4 => Alignment::Unaligned,
            _other => {
                // doesn't seem worth it to fail for this, easy to imagine
                // new variants added in the future
                log::info!("unexpected hint option '{_other}'");
                Default::default()
            }
        };

        Ok(Hint {
            type_,
            name: self.name.clone(),
            shape_index,
            node_index,
            scale,
            alignment,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Hash)]
pub struct Hint {
    pub type_: HintType,
    pub name: SmolStr,
    pub shape_index: usize,
    pub node_index: usize,
    pub scale: Scale,
    pub alignment: Alignment,
}

#[derive(Debug, Clone, PartialEq, Hash)]
pub struct Scale {
    pub x: OrderedFloat<f64>,
    pub y: OrderedFloat<f64>,
}

impl Default for Scale {
    fn default() -> Self {
        Self {
            x: 1.0.into(),
            y: 1.0.into(),
        }
    }
}

impl Scale {
    fn new(x: f64, y: f64) -> Self {
        Self {
            x: x.into(),
            y: y.into(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Hash)]
#[non_exhaustive]
pub enum HintType {
    Corner,
    // other hint types are currently unused
    Stem,
    Cap,
    TTStem,
    // catch all, we don't want to fail parsing unknwon variants,
    Unknown,
}

/// How to align a corner component to the attaching node
#[derive(Debug, Clone, Copy, Default, PartialEq, Hash)]
#[non_exhaustive]
pub enum Alignment {
    // glyphs calls this 'left'
    #[default]
    OutStroke,
    // glyphs calls this 'right'
    InStroke,
    Middle,
    Unused,
    Unaligned,
}

#[derive(Debug, Default, Clone, PartialEq, Hash)]
pub struct Layer {
    pub layer_id: String,
    pub associated_master_id: Option<String>,
    pub width: OrderedFloat<f64>,
    pub vert_width: Option<OrderedFloat<f64>>,
    pub vert_origin: Option<OrderedFloat<f64>>,
    pub shapes: Vec<Shape>,
    pub anchors: Vec<Anchor>,
    pub attributes: LayerAttributes,
    /// If this layer is part of a smart component, this defines its location.
    ///
    /// Smart component layers can only be defined at the min or max of a given
    /// axis.
    pub smart_component_positions: BTreeMap<SmolStr, AxisPole>,
    /// Hints for this layer (e.g., corner components, stem hints, etc.)
    pub hints: Vec<Hint>,
}

impl Layer {
    pub fn is_master(&self) -> bool {
        self.associated_master_id.is_none()
    }

    /// associated master id if set, else layer id
    pub fn master_id(&self) -> &str {
        self.associated_master_id
            .as_deref()
            .unwrap_or(&self.layer_id)
    }

    pub fn is_intermediate(&self) -> bool {
        self.associated_master_id.is_some() && !self.attributes.coordinates.is_empty()
    }

    pub fn is_color(&self) -> bool {
        self.attributes.color || self.attributes.color_palette.is_some()
    }

    pub(crate) fn components(&self) -> impl Iterator<Item = &Component> + '_ {
        self.shapes.iter().filter_map(|shape| match shape {
            Shape::Path(_) => None,
            Shape::Component(comp) => Some(comp),
        })
    }

    /// NOTE: panics if called on a non-bracket layer
    fn bracket_info(&self, axes: &[Axis]) -> BTreeMap<String, (Option<i64>, Option<i64>)> {
        assert!(
            !self.attributes.axis_rules.is_empty(),
            "all bracket layers have axis rules"
        );
        axes.iter()
            .zip(&self.attributes.axis_rules)
            .map(|(axis, rule)| (axis.tag.clone(), (rule.min, rule.max)))
            .collect()
    }

    fn axis_rules_sort_key(&self) -> Vec<(i64, i64)> {
        self.attributes
            .axis_rules
            .iter()
            .map(|ax| (ax.min.unwrap_or(i64::MIN), ax.max.unwrap_or(i64::MAX)))
            .collect()
    }

    pub(crate) fn get_anchor_pt(&self, anchor_name: &str) -> Option<Point> {
        self.anchors
            .iter()
            .find(|a| a.name == anchor_name)
            .map(|a| a.pos)
    }
    // TODO add is_alternate, is_color, etc.
}

#[derive(Clone, Default, Debug, PartialEq, Hash)]
pub struct LayerAttributes {
    pub coordinates: Vec<OrderedFloat<f64>>,
    pub color: bool,
    // in the same order that axes are declared for the font
    pub axis_rules: Vec<AxisRule>,
    pub color_palette: Option<i64>,
}

#[derive(Clone, Default, FromPlist, Debug, PartialEq, Hash)]
pub struct AxisRule {
    // if missing, assume default min/max for font
    pub min: Option<i64>,
    pub max: Option<i64>,
}

impl AxisRule {
    /// Parse an AxisRule from a glyphs v2 layer name.
    ///
    /// See <https://glyphsapp.com/learn/alternating-glyph-shapes> for an
    /// overview of the naming conventions.
    fn from_layer_name(name: &str) -> Option<Self> {
        // the pattern can either be "$name [100]" or "$name ]100]"
        // (python uses a regex for this:)
        // https://github.com/googlefonts/glyphsLib/blob/c4db6b981d/Lib/glyphsLib/classes.py#L3938
        let idx = name.find([']', '['])?;
        let reversed = name.as_bytes()[idx] == b']';
        let tail = name.get(idx + 1..)?;
        let (value, _) = tail.split_once(']')?;
        let value = str::parse::<u32>(value.trim()).ok()?;
        let (min, max) = if reversed {
            (None, Some(value as _))
        } else {
            (Some(value as _), None)
        };
        Some(AxisRule { min, max })
    }
}

// hand-parse because they can take multiple shapes
impl FromPlist for LayerAttributes {
    fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
        let mut coordinates = Vec::new();
        let mut color = false;
        let mut axis_rules = Vec::new();
        let mut color_palette = None;

        tokenizer.eat(b'{')?;

        loop {
            if tokenizer.eat(b'}').is_ok() {
                break;
            }

            let key: String = tokenizer.parse()?;
            tokenizer.eat(b'=')?;
            match key.as_str() {
                "coordinates" => coordinates = tokenizer.parse()?,
                "color" => color = tokenizer.parse()?,
                "axisRules" => axis_rules = tokenizer.parse()?,
                "colorPalette" => {
                    // colorPalette can be a palette index or the string "*"
                    // which should be parsed as the special palette index
                    // 0xFFFF (foreground color)
                    let value = match tokenizer.peek()?.as_str() {
                        Some("*") => {
                            tokenizer.lex()?;
                            0xFFFF
                        }
                        _ => tokenizer.parse()?,
                    };
                    color_palette = Some(value);
                }
                // skip unsupported attributes for now
                // TODO: match the others
                _ => tokenizer.skip_rec()?,
            }
            tokenizer.eat(b';')?;
        }

        Ok(LayerAttributes {
            coordinates,
            color,
            axis_rules,
            color_palette,
        })
    }
}

#[derive(Clone, Default, Debug, PartialEq, Eq, Hash, FromPlist)]
pub struct ShapeAttributes {
    pub gradient: Option<Gradient>,
    pub fill_color: Option<Color>,
}

impl ShapeAttributes {
    pub fn colors(&self) -> impl Iterator<Item = &Color> {
        self.gradient
            .iter()
            .flat_map(|g| g.colors())
            .chain(self.fill_color.iter())
    }
}

#[derive(Clone, Default, Debug, PartialEq, Eq, Hash, FromPlist)]
pub struct Gradient {
    pub start: Vec<OrderedFloat<f64>>,
    pub end: Vec<OrderedFloat<f64>>,
    pub colors: Vec<ColorStop>,
    #[fromplist(key = "type")]
    pub style: String,
}

impl Gradient {
    fn colors(&self) -> impl Iterator<Item = &Color> {
        self.colors.iter().map(|c| &c.color)
    }
}

#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
pub struct Color {
    pub r: i64,
    pub g: i64,
    pub b: i64,
    pub a: i64,
}

#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
pub struct ColorStop {
    pub color: Color,
    // The position on the color line, see <https://learn.microsoft.com/en-us/typography/opentype/spec/colr#color-lines>
    pub stop_offset: OrderedFloat<f64>,
}

impl Color {
    pub fn rgba(r: i64, g: i64, b: i64, a: i64) -> Self {
        Self { r, g, b, a }
    }

    pub(crate) fn from_glyphs_color(colors: &[i64]) -> Result<Self, crate::plist::Error> {
        // See <https://github.com/googlefonts/glyphsLib/blob/c4db6b981d577f456d64ebe9993818770e170454/Lib/glyphsLib/builder/common.py#L41-L50>
        match *colors {
            // Grayscale
            [black, alpha] => Ok(Color::rgba(black, black, black, alpha)),
            // RGBA
            [r, g, b, a] => Ok(Color::rgba(r, g, b, a)),
            // 5 is CMYK, match python by not supporting that
            _ => Err(crate::plist::Error::UnexpectedNumberOfValues {
                value_type: "grayscale (2) or rgba (4)",
                actual: colors.len(),
            }),
        }
    }
}

// hand-parse because it's a list of inconsistent types
impl FromPlist for Color {
    fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
        let colors = tokenizer.parse::<Vec<i64>>()?;
        Color::from_glyphs_color(&colors)
    }
}

// hand-parse because it's a list of inconsistent types
impl FromPlist for ColorStop {
    fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
        tokenizer.eat(b'(')?;

        let color = Color::parse(tokenizer)?;
        tokenizer.eat(b',')?;
        let stop_offset = tokenizer.parse::<f64>()?;
        tokenizer.eat(b')')?;

        Ok(ColorStop {
            color,
            stop_offset: stop_offset.into(),
        })
    }
}

#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Shape {
    Path(Path),
    Component(Component),
}

impl Shape {
    pub fn attributes(&self) -> &ShapeAttributes {
        match self {
            Shape::Path(p) => &p.attributes,
            Shape::Component(c) => &c.attributes,
        }
    }

    pub(crate) fn as_path(&self) -> Option<&Path> {
        match self {
            Shape::Path(path) => Some(path),
            _ => None,
        }
    }

    pub(crate) fn as_component(&self) -> Option<&Component> {
        match self {
            Shape::Component(component) => Some(component),
            _ => None,
        }
    }

    /// If the shape is a path, reverse it
    ///
    /// In Glyphs, the last node in the node list is the "start" node of a
    /// closed contour (see `to_ir_path`). A naive `reverse()` would move the
    /// start node to position 0, so `to_ir_path` would pick the wrong start.
    ///
    /// Python's `GSPath.reverse()` (which works via segments) is equivalent to
    /// `reverse() + rotate_left(1)`, which keeps the start node at the last
    /// position. We match that here.
    ///
    /// Note: this logic is only correct for closed paths. For open paths the
    /// start node is `nodes[0]` (see `to_ir_path`), so a plain `reverse()`
    /// without rotation would be correct. Python's segment-based `reverse()`
    /// also appears to mishandle open paths (it silently drops the new start
    /// node via `setSegments`). In practice this method is only called when
    /// handling smart components, which are always closed?
    ///
    /// <https://github.com/googlefonts/glyphsLib/blob/d42d3b15/Lib/glyphsLib/classes.py#L2369>
    pub(crate) fn reverse(&mut self) {
        if let Shape::Path(path) = self {
            path.reverse();
            if path.closed && !path.nodes.is_empty() {
                path.nodes.rotate_left(1);
            }
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
enum FormatVersion {
    #[default]
    V2,
    V3,
}

// The font you get directly from a plist, minimally modified
// Types chosen specifically to accomodate plist translation.
#[derive(Default, Debug, PartialEq, FromPlist)]
#[allow(non_snake_case)]
struct RawFont {
    #[fromplist(key = ".formatVersion")]
    format_version: FormatVersion,
    units_per_em: Option<i64>,
    metrics: Vec<RawMetric>,
    family_name: String,
    date: Option<String>,
    copyright: Option<String>,
    designer: Option<String>,
    designerURL: Option<String>,
    manufacturer: Option<String>,
    manufacturerURL: Option<String>,
    versionMajor: Option<i64>,
    versionMinor: Option<i64>,
    axes: Vec<Axis>,
    glyphs: Vec<RawGlyph>,
    font_master: Vec<RawFontMaster>,
    instances: Vec<RawInstance>,
    feature_prefixes: Vec<RawFeature>,
    features: Vec<RawFeature>,
    classes: Vec<RawFeature>,
    properties: Vec<RawName>,
    #[fromplist(alt_name = "kerning")]
    kerning_LTR: Kerning,
    kerning_RTL: Kerning,
    custom_parameters: RawCustomParameters,
    numbers: Vec<NumberName>,
    user_data: BTreeMap<SmolStr, Plist>,
}

#[derive(Default, Debug, PartialEq, FromPlist)]
struct NumberName {
    name: SmolStr,
}

// we use a vec of tuples instead of a map because there can be multiple
// values for the same name (e.g. 'Virtual Master')
#[derive(Clone, Default, Debug, PartialEq, Eq, Hash)]
pub(crate) struct RawCustomParameters(Vec<RawCustomParameterValue>);

#[derive(Clone, Default, Debug, PartialEq, Eq, Hash, FromPlist)]
struct RawCustomParameterValue {
    name: SmolStr,
    value: Plist,
    disabled: Option<bool>,
}

impl RawCustomParameterValue {
    /// Returns true if this parameter has been taken
    ///
    /// We use a special sentinel value to indicate that a parameter has been handled
    /// specially and shouldn't be parsed as/stored in CustomParameters.
    fn taken(&self) -> bool {
        self == &Self::default()
    }
}

impl FromPlist for FormatVersion {
    fn parse(tokenizer: &mut Tokenizer) -> Result<Self, crate::plist::Error> {
        let raw: i64 = FromPlist::parse(tokenizer)?;
        if raw == 3 {
            Ok(FormatVersion::V3)
        } else {
            // format version 2 is the default value, if no explicit version is set
            Err(crate::plist::Error::Parse(
                "'3' is the only known format version".into(),
            ))
        }
    }
}

impl FormatVersion {
    fn is_v2(self) -> bool {
        self == FormatVersion::V2
    }

    fn codepoint_radix(self) -> u32 {
        match self {
            FormatVersion::V2 => 16,
            FormatVersion::V3 => 10,
        }
    }
}

impl FromPlist for RawCustomParameters {
    fn parse(tokenizer: &mut Tokenizer) -> Result<Self, crate::plist::Error> {
        Vec::parse(tokenizer).map(RawCustomParameters)
    }
}

/// Convenience methods for converting `Plist` structs to concrete custom param types
trait PlistParamsExt {
    fn as_codepage_bits(&self) -> Option<BTreeSet<u32>>;
    fn as_unicode_code_ranges(&self) -> Option<BTreeSet<u32>>;
    fn as_fs_type(&self) -> Option<u16>;
    fn as_mapping_values(&self) -> Option<Vec<(OrderedFloat<f64>, OrderedFloat<f64>)>>;
    fn as_axis_location(&self) -> Option<AxisLocation>;
    fn as_axis(&self) -> Option<Axis>;
    fn as_bool(&self) -> Option<bool>;
    fn as_ordered_f64(&self) -> Option<OrderedFloat<f64>>;
    fn as_vec_of_ints(&self) -> Option<Vec<i64>>;
    fn as_axis_locations(&self) -> Option<Vec<AxisLocation>>;
    fn as_vec_of_string(&self) -> Option<Vec<SmolStr>>;
    fn as_axes(&self) -> Option<Vec<Axis>>;
    fn as_axis_mappings(&self) -> Option<Vec<AxisMapping>>;
    fn as_virtual_master(&self) -> Option<BTreeMap<String, OrderedFloat<f64>>>;
    fn as_gasp_table(&self) -> Option<BTreeMap<i64, i64>>;
    fn as_color_palettes(&self) -> Option<Vec<Vec<Color>>>;
}

impl PlistParamsExt for Plist {
    fn as_bool(&self) -> Option<bool> {
        self.as_i64().map(|val| val == 1)
    }

    fn as_ordered_f64(&self) -> Option<OrderedFloat<f64>> {
        self.as_f64().map(OrderedFloat)
    }

    fn as_vec_of_ints(&self) -> Option<Vec<i64>> {
        // exciting! apparently glyphs (at least sometimes?) serializes
        // this as a vec of strings? (this is true in WghtVar_OS2.glyphs)
        if let Some(thing_that_makes_sense) = self.as_array()?.iter().map(Plist::as_i64).collect() {
            return Some(thing_that_makes_sense);
        }

        self.as_array()?
            .iter()
            .map(|val| val.as_str().and_then(|s| s.parse::<i64>().ok()))
            .collect()
    }

    fn as_axis_location(&self) -> Option<AxisLocation> {
        let plist = self.as_dict()?;
        let name = plist.get("Axis").and_then(Plist::as_str)?;
        let location = plist.get("Location").and_then(Plist::as_f64)?;
        Some(AxisLocation {
            axis_name: name.into(),
            location: location.into(),
        })
    }

    fn as_axis_locations(&self) -> Option<Vec<AxisLocation>> {
        let array = self.as_array()?;
        array.iter().map(Plist::as_axis_location).collect()
    }

    fn as_vec_of_string(&self) -> Option<Vec<SmolStr>> {
        self.as_array()?
            .iter()
            .map(|plist| plist.as_str().map(SmolStr::from))
            .collect()
    }

    fn as_axis(&self) -> Option<Axis> {
        let plist = self.as_dict()?;
        let name = plist.get("Name").and_then(Plist::as_str)?;
        let tag = plist.get("Tag").and_then(Plist::as_str)?;
        let hidden = plist.get("hidden").and_then(Plist::as_bool);
        Some(Axis {
            name: name.into(),
            tag: tag.into(),
            hidden,
        })
    }

    fn as_axes(&self) -> Option<Vec<Axis>> {
        self.as_array()?.iter().map(Plist::as_axis).collect()
    }

    fn as_mapping_values(&self) -> Option<Vec<(OrderedFloat<f64>, OrderedFloat<f64>)>> {
        let plist = self.as_dict()?;
        plist
            .iter()
            .map(|(key, value)| {
                // our keys are strings, but we want to interpret them as floats:
                let key = key
                    .parse::<f64>()
                    .or_else(|_| key.parse::<i64>().map(|i| i as f64))
                    .ok()?;
                let val = value.as_f64()?;
                Some((key.into(), val.into()))
            })
            .collect()
    }

    fn as_axis_mappings(&self) -> Option<Vec<AxisMapping>> {
        self.as_dict()?
            .iter()
            .map(|(tag, mappings)| {
                let user_to_design = mappings.as_mapping_values()?;
                Some(AxisMapping {
                    tag: tag.to_string(),
                    user_to_design,
                })
            })
            .collect()
    }

    fn as_virtual_master(&self) -> Option<BTreeMap<String, OrderedFloat<f64>>> {
        self.as_array()?
            .iter()
            .map(Plist::as_axis_location)
            .map(|loc| loc.map(|loc| (loc.axis_name, loc.location)))
            .collect()
    }

    fn as_fs_type(&self) -> Option<u16> {
        Some(self.as_vec_of_ints()?.iter().map(|bit| 1 << bit).sum())
    }

    fn as_unicode_code_ranges(&self) -> Option<BTreeSet<u32>> {
        let bits = self.as_vec_of_ints()?;
        Some(bits.iter().map(|bit| *bit as u32).collect())
    }

    fn as_codepage_bits(&self) -> Option<BTreeSet<u32>> {
        // Values can be integers (e.g. 1252), string-encoded integers ("1252"),
        // or "bit N" strings for raw bit positions — matching glyphsLib behaviour.
        // https://github.com/googlefonts/glyphsLib/blob/d42d3b15/Lib/glyphsLib/builder/custom_params.py#L505
        self.as_array()?
            .iter()
            .map(|val| {
                if let Some(n) = val.as_i64() {
                    return codepage_range_bit(n as u32);
                }
                if let Some(s) = val.as_str() {
                    if let Ok(n) = s.parse::<u32>() {
                        return codepage_range_bit(n);
                    }
                    if let Some(rest) = s.strip_prefix("bit ")
                        && let Ok(bit) = rest.parse::<u32>()
                    {
                        return codepage_range_bit(bit);
                    }
                }
                Err(Error::InvalidCodePage(0))
            })
            .collect::<Result<_, _>>()
            .ok()
    }

    fn as_gasp_table(&self) -> Option<BTreeMap<i64, i64>> {
        Some(
            self.as_dict()?
                .iter()
                .filter_map(|(k, v)| k.parse::<i64>().ok().zip(v.as_i64()))
                .collect(),
        )
    }

    fn as_color_palettes(&self) -> Option<Vec<Vec<Color>>> {
        let raw_palettes = self.as_array()?;
        let mut palettes = Vec::with_capacity(raw_palettes.len());
        for raw_palette in raw_palettes {
            let Some(raw_palette) = raw_palette.as_array() else {
                warn!("Non-array color palette, ignored");
                continue;
            };

            let mut palette = Vec::with_capacity(raw_palette.len());
            for raw_color in raw_palette {
                let Some(raw_color) = raw_color.as_vec_of_ints() else {
                    warn!("Non-int-array color palette entry, ignored");
                    continue;
                };
                let Ok(color) = Color::from_glyphs_color(&raw_color) else {
                    warn!("Invalid color palette entry, ignored");
                    continue;
                };
                palette.push(color);
            }

            palettes.push(palette);
        }
        Some(palettes)
    }
}

impl RawCustomParameters {
    ////convert into the parsed params for a top-level font
    fn to_custom_params(&self) -> Result<CustomParameters, Error> {
        let mut params = CustomParameters::default();
        let mut virtual_masters = Vec::<BTreeMap<String, OrderedFloat<f64>>>::new();
        // PANOSE custom parameter is accessible under a short name and a long name:
        //     https://github.com/googlefonts/glyphsLib/blob/050ef62c/Lib/glyphsLib/builder/custom_params.py#L322-L323
        // ...with the value under the short name taking precendence:
        //     https://github.com/googlefonts/glyphsLib/blob/050ef62c/Lib/glyphsLib/builder/custom_params.py#L258-L269
        let mut panose = None;
        let mut panose_old = None;

        for param in &self.0 {
            // Silently skip special parameters that were handled elsewhere
            if param.taken() {
                continue;
            }

            let name = &param.name;
            let value = &param.value;
            let disabled = &param.disabled;

            // we need to use a macro here because you can't pass the name of a field to a
            // function.
            macro_rules! add_and_report_issues {
                ($field:ident, $converter:path) => {{ add_and_report_issues!($field, $converter(value)) }};

                ($field:ident, $converter:path, into) => {{ add_and_report_issues!($field, $converter(value).map(Into::into)) }};

                ($field:ident, $value_expr:expr_2021) => {{
                    let value = $value_expr;

                    if value.is_none() {
                        log::warn!("failed to parse param for '{}'", stringify!($field));
                    }
                    // Only set if not already set - glyphsLib uses the first occurrence
                    // for duplicate params, not the last:
                    // <https://github.com/googlefonts/glyphsLib/blob/a5b99adc/Lib/glyphsLib/classes.py#L517-L520>
                    if params.$field.is_none() {
                        params.$field = value;
                    } else {
                        log::warn!(
                            "ignoring duplicate param value for field '{}'",
                            stringify!($field)
                        );
                    }
                }};
            }

            if *disabled == Some(true) {
                log::debug!("skipping disabled custom param '{name}'");
                continue;
            }
            match name.as_str() {
                "Propagate Anchors" => add_and_report_issues!(propagate_anchors, Plist::as_bool),
                "Use Typo Metrics" => add_and_report_issues!(use_typo_metrics, Plist::as_bool),
                // <https://github.com/googlefonts/glyphsLib/blob/52c982399ba20dc96a2c2195df6fc6cea1f9a906/Lib/glyphsLib/builder/custom_params.py#L356>
                "postscriptIsFixedPitch" | "isFixedPitch" => {
                    add_and_report_issues!(is_fixed_pitch, Plist::as_bool)
                }
                "Has WWS Names" => add_and_report_issues!(has_wws_names, Plist::as_bool),
                "typoAscender" => add_and_report_issues!(typo_ascender, Plist::as_i64),
                "typoDescender" => add_and_report_issues!(typo_descender, Plist::as_i64),
                "typoLineGap" => add_and_report_issues!(typo_line_gap, Plist::as_i64),
                "winAscent" => add_and_report_issues!(win_ascent, Plist::as_i64),
                "winDescent" => add_and_report_issues!(win_descent, Plist::as_i64),
                "hheaAscender" => add_and_report_issues!(hhea_ascender, Plist::as_i64),
                "hheaDescender" => add_and_report_issues!(hhea_descender, Plist::as_i64),
                "hheaLineGap" => add_and_report_issues!(hhea_line_gap, Plist::as_i64),
                "vheaVertAscender" => add_and_report_issues!(vhea_ascender, Plist::as_i64),
                "vheaVertDescender" => add_and_report_issues!(vhea_descender, Plist::as_i64),
                "vheaVertLineGap" => add_and_report_issues!(vhea_line_gap, Plist::as_i64),
                "underlineThickness" => {
                    add_and_report_issues!(underline_thickness, Plist::as_ordered_f64)
                }
                "underlinePosition" => {
                    add_and_report_issues!(underline_position, Plist::as_ordered_f64)
                }
                // Glyphs uses short names (e.g. "subscriptXSize") but some fonts use the
                // long UFO names (e.g. "openTypeOS2SubscriptXSize"). Both are accepted.
                // https://github.com/googlefonts/glyphsLib/blob/d42d3b15/Lib/glyphsLib/builder/custom_params.py#L329-L340
                "strikeoutPosition" | "openTypeOS2StrikeoutPosition" => {
                    add_and_report_issues!(strikeout_position, Plist::as_i64)
                }
                "strikeoutSize" | "openTypeOS2StrikeoutSize" => {
                    add_and_report_issues!(strikeout_size, Plist::as_i64)
                }
                "subscriptXOffset" | "openTypeOS2SubscriptXOffset" => {
                    add_and_report_issues!(subscript_x_offset, Plist::as_i64)
                }
                "subscriptXSize" | "openTypeOS2SubscriptXSize" => {
                    add_and_report_issues!(subscript_x_size, Plist::as_i64)
                }
                "subscriptYOffset" | "openTypeOS2SubscriptYOffset" => {
                    add_and_report_issues!(subscript_y_offset, Plist::as_i64)
                }
                "subscriptYSize" | "openTypeOS2SubscriptYSize" => {
                    add_and_report_issues!(subscript_y_size, Plist::as_i64)
                }
                "superscriptXOffset" | "openTypeOS2SuperscriptXOffset" => {
                    add_and_report_issues!(superscript_x_offset, Plist::as_i64)
                }
                "superscriptXSize" | "openTypeOS2SuperscriptXSize" => {
                    add_and_report_issues!(superscript_x_size, Plist::as_i64)
                }
                "superscriptYOffset" | "openTypeOS2SuperscriptYOffset" => {
                    add_and_report_issues!(superscript_y_offset, Plist::as_i64)
                }
                "superscriptYSize" | "openTypeOS2SuperscriptYSize" => {
                    add_and_report_issues!(superscript_y_size, Plist::as_i64)
                }
                "fsType" | "openTypeOS2Type" => add_and_report_issues!(fs_type, Plist::as_fs_type),
                "unicodeRanges" | "openTypeOS2UnicodeRanges" => {
                    add_and_report_issues!(unicode_range_bits, Plist::as_unicode_code_ranges)
                }
                "codePageRanges" => {
                    add_and_report_issues!(codepage_range_bits, Plist::as_codepage_bits)
                }
                // these values are not listed in the glyphs.app UI, but exist
                // in some fonts:
                // https://github.com/googlefonts/fontc/pull/1144#issuecomment-2503134008
                "openTypeHeadLowestRecPPEM" => {
                    add_and_report_issues!(lowest_rec_ppem, Plist::as_i64)
                }
                "openTypeHheaCaretSlopeRun" => {
                    add_and_report_issues!(hhea_caret_slope_run, Plist::as_i64)
                }
                "openTypeHheaCaretSlopeRise" => {
                    add_and_report_issues!(hhea_caret_slope_rise, Plist::as_i64)
                }
                "openTypeHheaCaretOffset" => {
                    add_and_report_issues!(hhea_caret_offset, Plist::as_i64)
                }
                "openTypeVheaCaretSlopeRun" => {
                    add_and_report_issues!(vhea_caret_slope_run, Plist::as_i64)
                }
                "openTypeVheaCaretSlopeRise" => {
                    add_and_report_issues!(vhea_caret_slope_rise, Plist::as_i64)
                }
                "openTypeVheaCaretOffset" => {
                    add_and_report_issues!(vhea_caret_offset, Plist::as_i64)
                }
                "meta Table" => {
                    add_and_report_issues!(meta_table, MetaTableValues::from_plist)
                }
                "Don't use Production Names" => {
                    add_and_report_issues!(dont_use_production_names, Plist::as_bool)
                }
                "Link Metrics With First Master" => {
                    add_and_report_issues!(link_metrics_with_first_master, Plist::as_bool)
                }
                "Link Metrics With Master" => {
                    add_and_report_issues!(link_metrics_with_master, Plist::as_str, into)
                }
                "openTypeHeadFlags" => {
                    add_and_report_issues!(head_flags, Plist::as_vec_of_ints)
                }
                // these might need to be handled? they're in the same list as
                // the items above:
                // https://github.com/googlefonts/glyphsLib/blob/74c63244fdb/Lib/glyphsLib/builder/custom_params.py#L429
                "openTypeOS2FamilyClass" => {
                    log_once_warn!("unhandled custom param '{name}'")
                }

                "Virtual Master" => match value.as_virtual_master() {
                    Some(val) => virtual_masters.push(val),
                    None => log::warn!("failed to parse virtual master '{value:?}'"),
                },
                "panose" => panose = value.as_vec_of_ints(),
                "openTypeOS2Panose" => panose_old = value.as_vec_of_ints(),
                "glyphOrder" => add_and_report_issues!(glyph_order, Plist::as_vec_of_string),
                "gasp Table" => add_and_report_issues!(gasp_table, Plist::as_gasp_table),
                "Feature for Feature Variations" => {
                    add_and_report_issues!(feature_for_feature_variations, Plist::as_str, into)
                }
                "Color Palettes" => {
                    add_and_report_issues!(color_palettes, Plist::as_color_palettes)
                }
                "Name Table Entry" => match value
                    .as_str()
                    .ok_or_else(|| "should be a string".into())
                    .and_then(NameTableEntry::from_str)
                {
                    Ok(s) => params.name_table_entries.push(s),
                    Err(e) => log::warn!("bad 'Name Table Entry': {e}"),
                },
                _ => log_once_warn!("unknown custom parameter '{name}'"),
            }
        }
        params.panose = panose.or(panose_old);
        params.virtual_masters = Some(virtual_masters).filter(|x| !x.is_empty());
        Ok(params)
    }

    fn contains(&self, name: &str) -> bool {
        self.0.iter().any(|val| val.name == name)
    }

    /// Consume and return the first (non-disabled) parameter with the given name, if any.
    ///
    /// This is for parameters that are handled elsewhere before `to_custom_params` and
    /// shouldn't be stored in CustomParameters.
    fn take(&mut self, name: &str) -> Option<Plist> {
        let pos = self
            .0
            .iter()
            .position(|val| val.name == name && val.disabled != Some(true))?;

        // Replace with a sentinel value rather than removing it from the Vec to avoid
        // the overhead of shifting elements. This is skipped during `to_custom_params`
        let taken = std::mem::take(&mut self.0[pos]);

        Some(taken.value)
    }

    fn take_string(&mut self, name: &str) -> Option<String> {
        self.take(name)
            .and_then(|p| p.as_str().map(|s| s.to_owned()))
    }

    fn take_axes(&mut self) -> Option<Vec<Axis>> {
        self.take("Axes").and_then(|p| p.as_axes())
    }

    fn take_axis_mappings(&mut self) -> Option<Vec<AxisMapping>> {
        self.take("Axis Mappings")
            .and_then(|p| p.as_axis_mappings())
    }

    fn take_axis_locations(&mut self) -> Option<Vec<AxisLocation>> {
        self.take("Axis Location")
            .and_then(|p| p.as_axis_locations())
    }
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
pub struct AxisLocation {
    axis_name: String,
    location: OrderedFloat<f64>,
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
pub struct AxisMapping {
    //TODO this should really be a `Tag`?
    tag: String,
    user_to_design: Vec<(OrderedFloat<f64>, OrderedFloat<f64>)>,
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, FromPlist)]
struct RawMetric {
    // So named to let FromPlist populate it from a field called "type"
    type_: String,
}

#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
struct RawName {
    key: String,
    value: Option<String>,
    values: Vec<RawNameValue>,
}

#[derive(Clone, Debug, PartialEq, Hash, Default)]
pub struct NameTableEntry {
    pub name_id: u16,
    pub platform_id: u16,
    pub encoding_id: u16,
    pub lang_id: u16,
    pub value: String,
}

fn parse_maybe_hex_int(s: &str) -> Result<u16, ParseIntError> {
    match s.strip_prefix("0x") {
        Some(hex) => u16::from_str_radix(hex, 16),
        None => s.parse(),
    }
}

impl FromStr for NameTableEntry {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // format like: "4 3 1 1028; 粉圓 Regular";

        let Some((head, tail)) = s.split_once(';') else {
            return Err(format!("expected ';', found '{s}'"));
        };
        let mut iter = head.split(" ").flat_map(parse_maybe_hex_int);
        let value = tail.trim().into();
        match (iter.next(), iter.next(), iter.next(), iter.next()) {
            (Some(name_id), None | Some(3), None, None) => Ok(NameTableEntry {
                name_id,
                platform_id: 3,
                encoding_id: 1,
                lang_id: 0x409,
                value,
            }),
            // "If only platformID is specified as 1, then both encID and langID
            // will be assumed as 0 (Mac Roman, and Mac English)."
            // (https://glyphsapp.com/media/pages/learn/3ec528a11c-1634835554/glyphs-3-handbook.pdf)
            (Some(name_id), Some(1), None, None) => Ok(NameTableEntry {
                name_id,
                platform_id: 1,
                encoding_id: 0,
                lang_id: 0,
                value,
            }),
            (Some(name_id), Some(platform_id), Some(encoding_id), None) => Ok(NameTableEntry {
                name_id,
                platform_id,
                encoding_id,
                lang_id: 0,
                value,
            }),

            (Some(a), Some(b), Some(c), Some(d)) => Ok(NameTableEntry {
                name_id: a,
                platform_id: b,
                encoding_id: c,
                lang_id: d,
                value,
            }),
            _ => Err(format!("expected four numerical ids, found '{s}'")),
        }
    }
}

/// Compute a priority score for a language code when selecting default names.
///
/// Lower scores have higher priority.
/// Priority order: dflt > default > ENG > others (by insertion order)
fn default_language_score(lang: &str, index: usize, scale: i32) -> i32 {
    match lang {
        "dflt" => -scale * 3 - index as i32,
        "default" => -scale * 2 - index as i32,
        "ENG" => -scale - index as i32,
        _ => index as i32,
    }
}

impl RawName {
    fn is_empty(&self) -> bool {
        self.value.is_none() && self.values.is_empty()
    }

    fn get_value(&self) -> Option<&str> {
        if let Some(value) = &self.value {
            return Some(value.as_str());
        }

        // This is a localized (multivalued) name. Pick a winner.
        // See <https://github.com/googlefonts/fontc/issues/1011>
        // In order of preference: dflt, default, ENG, whatever is first
        // <https://github.com/googlefonts/glyphsLib/blob/1cb4fc5ae2cf385df95d2b7768e7ab4eb60a5ac3/Lib/glyphsLib/classes.py#L3155-L3161>
        // If the same name is defined repeatedly, e.g. dflt has 2 values, pick the last occurrence.

        let scale = self.values.len() as i32;
        self.values
            .iter()
            .enumerate()
            .map(|(i, raw)| {
                (
                    default_language_score(raw.language.as_str(), i, scale),
                    raw.value.as_str(),
                )
            })
            .min()
            .map(|(_, raw)| raw)
    }

    fn localized_values(&self) -> impl Iterator<Item = (&str, &str)> {
        self.values
            .iter()
            .map(|raw| (raw.language.as_str(), raw.value.as_str()))
    }
}

#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
struct RawNameValue {
    language: String,
    value: String,
}

#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
struct RawFeature {
    automatic: Option<i64>,
    disabled: Option<i64>,
    name: Option<String>,
    tag: Option<String>,
    notes: Option<String>,
    code: String,
    labels: Vec<RawNameValue>,

    #[fromplist(ignore)]
    other_stuff: BTreeMap<String, Plist>,
}

#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
pub struct Axis {
    #[fromplist(alt_name = "Name")]
    pub name: String,
    #[fromplist(alt_name = "Tag")]
    pub tag: String,
    pub hidden: Option<bool>,
}

#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
struct RawGlyph {
    layers: Vec<RawLayer>,
    glyphname: SmolStr,
    export: Option<bool>,
    #[fromplist(alt_name = "leftKerningGroup")]
    kern_left: Option<SmolStr>,
    #[fromplist(alt_name = "rightKerningGroup")]
    kern_right: Option<SmolStr>,
    unicode: Option<String>,
    category: Option<SmolStr>,
    sub_category: Option<SmolStr>,
    #[fromplist(alt_name = "production")]
    production_name: Option<SmolStr>,
    parts_settings: Vec<RawPartSetting>,
    #[fromplist(ignore)]
    other_stuff: BTreeMap<String, Plist>,
}

#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
struct RawPartSetting {
    name: SmolStr,
    bottom_name: Option<SmolStr>,
    bottom_value: i64,
    top_name: Option<SmolStr>,
    top_value: i64,
}

#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
struct RawLayer {
    name: String,
    layer_id: String,
    associated_master_id: Option<String>,
    width: Option<OrderedFloat<f64>>,
    vert_width: Option<OrderedFloat<f64>>,
    vert_origin: Option<OrderedFloat<f64>>,
    shapes: Vec<RawShape>,
    paths: Vec<Path>,
    components: Vec<Component>,
    anchors: Vec<RawAnchor>,
    hints: Vec<RawHint>,
    #[fromplist(alt_name = "attr")]
    attributes: LayerAttributes,
    // if this layer is part of a smart component; values should be 1 or 2
    // (this is validated when we convert to Layer)
    part_selection: BTreeMap<SmolStr, i64>,
    // glyphs2 only?
    user_data: LayerUserData,
    #[fromplist(ignore)]
    other_stuff: BTreeMap<String, Plist>,
}

#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
struct LayerUserData {
    #[fromplist(alt_name = "PartSelection")]
    part_selection: BTreeMap<SmolStr, i64>,
}

impl RawLayer {
    /// Return true if the layer is a draft that is not meant to be compiled.
    ///
    /// The presence of an associated master indicates this is not a simple 'master' instance.
    /// Without 'attributes' that specify whether it's a special intermediate, alternate or
    /// color layer, we can assume the non-master layer is a draft.
    fn is_draft(&self) -> bool {
        self.associated_master_id.is_some()
            && self.attributes == Default::default()
            && self.part_selection.is_empty() // v3
            && self.user_data.part_selection.is_empty() // v2
    }

    /// Glyphs uses the concept of 'bracket layers' to represent GSUB feature variations.
    ///
    /// See <https://glyphsapp.com/learn/switching-shapes#g-1-alternate-layers-bracket-layers>
    /// for more information.
    fn is_bracket_layer(&self, format_version: FormatVersion) -> bool {
        // can't be a bracket without an associated_master_id
        //https://github.com/googlefonts/glyphsLib/blob/c4db6b981d57/Lib/glyphsLib/builder/builders.py#L270
        self.associated_master_id.is_some()
            && self.associated_master_id.as_ref() != Some(&self.layer_id)
            //https://github.com/googlefonts/glyphsLib/blob/c4db6b981d5/Lib/glyphsLib/classes.py#L3942
            && match format_version {
                FormatVersion::V2 => AxisRule::from_layer_name(&self.name).is_some(),
                FormatVersion::V3 => !self.attributes.axis_rules.is_empty(),
            }
    }

    fn v2_to_v3_attributes(&mut self) {
        // In Glyphs v2, 'brace' or intermediate layer coordinates are stored in the
        // layer name as comma-separated values inside braces
        let mut brace_coordinates = Vec::new();
        if let (Some(start), Some(end)) = (self.name.find('{'), self.name.find('}')) {
            let mut tokenizer = Tokenizer::new(&self.name[start..=end]);
            // we don't want this to fail, technically '{foobar}' is valid inside a
            // layer name which is not meant to specify intermediate coordinates.
            // Typos are also possible. Perhaps we should warn?
            brace_coordinates = tokenizer
                .parse_delimited_vec(VecDelimiters::CSV_IN_BRACES)
                .unwrap_or_default();
        }
        if !brace_coordinates.is_empty() {
            self.attributes.coordinates = brace_coordinates;
        }
        // TODO: handle 'bracket' layers and other attributes
    }
}

/// Represents a path OR a component
///
/// <https://github.com/schriftgestalt/GlyphsSDK/blob/Glyphs3/GlyphsFileFormat/GlyphsFileFormatv3.md#differences-between-version-2>
#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
struct RawShape {
    // TODO: add numerous unsupported attributes

    // When I'm a path
    closed: Option<bool>,
    nodes: Vec<Node>,

    // When I'm a component I specifically want all my attributes to end up in other_stuff
    // My Component'ness can be detected by presence of a ref (Glyphs3) or name(Glyphs2) attribute
    // ref is reserved so take advantage of alt names
    #[fromplist(alt_name = "ref", alt_name = "name")]
    glyph_name: Option<SmolStr>,
    // if this is a reference to a smart component, this is the location in the
    // mini designspace of the component instance (user coords).
    piece: BTreeMap<SmolStr, f64>,

    // for components, an optional name to rename an anchor
    // on the target glyph during anchor propagation
    anchor: Option<SmolStr>,
    transform: Option<String>, // v2
    pos: Vec<f64>,             // v3
    angle: Option<f64>,        // v3
    scale: Vec<f64>,           // v3
    /// Horizontal and vertical slant, in degrees (v3)
    slant: Vec<f64>,

    #[fromplist(alt_name = "attr")]
    attributes: ShapeAttributes,
}

/// <https://github.com/schriftgestalt/GlyphsSDK/blob/Glyphs3/GlyphsFileFormat/GlyphsFileFormatv3.md#spec-glyphs-3-path>
#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
pub struct Path {
    pub closed: bool,
    pub nodes: Vec<Node>,
    pub attributes: ShapeAttributes,
}

/// <https://github.com/schriftgestalt/GlyphsSDK/blob/Glyphs3/GlyphsFileFormat/GlyphsFileFormatv3.md#spec-glyphs-3-component>
#[derive(Default, Clone, Debug, FromPlist)]
pub struct Component {
    /// The glyph this component references
    pub name: SmolStr,
    /// meh
    pub transform: Affine,
    /// An alternative anchor name used during anchor propagation
    ///
    /// For instance, if an acute accent is a component of a ligature glyph,
    /// we might rename its 'top' anchor to 'top_2'
    pub anchor: Option<SmolStr>,
    /// For smart components, the location in the mini designspace of the instance.
    ///
    /// Keys should reference the axes in the component, with the value being
    /// a position in user coords.
    #[fromplist(alt_name = "piece")]
    pub smart_component_values: BTreeMap<SmolStr, f64>,
    pub attributes: ShapeAttributes,
}

impl PartialEq for Component {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && Into::<AffineForEqAndHash>::into(self.transform) == other.transform.into()
    }
}

impl Eq for Component {}

impl Hash for Component {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        Into::<AffineForEqAndHash>::into(self.transform).hash(state);
    }
}

#[derive(Clone, Copy, Debug)]
pub struct Node {
    pub pt: Point,
    pub node_type: NodeType,
}

impl Node {
    pub fn is_on_curve(&self) -> bool {
        !matches!(self.node_type, NodeType::OffCurve)
    }
}

impl PartialEq for Node {
    fn eq(&self, other: &Self) -> bool {
        Into::<PointForEqAndHash>::into(self.pt) == other.pt.into()
            && self.node_type == other.node_type
    }
}

impl Eq for Node {}

impl Hash for Node {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        PointForEqAndHash::new(self.pt).hash(state);
        self.node_type.hash(state);
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NodeType {
    Line,
    LineSmooth,
    OffCurve,
    Curve,
    CurveSmooth,
    QCurve,
    QCurveSmooth,
}

#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
struct RawAnchor {
    name: SmolStr,
    pos: Option<Point>,       // v3
    position: Option<String>, // v2
}

#[derive(Clone, Debug, PartialEq)]
pub struct Anchor {
    pub name: SmolStr,
    pub pos: Point,
}

impl Hash for Anchor {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        PointForEqAndHash::new(self.pos).hash(state);
    }
}

#[derive(Clone, Debug, PartialEq, Hash)]
pub struct FontMaster {
    pub id: String,
    pub name: String,
    pub axes_values: Vec<OrderedFloat<f64>>,
    metric_values: BTreeMap<String, MetricValue>,
    pub number_values: BTreeMap<SmolStr, OrderedFloat<f64>>,
    pub custom_parameters: CustomParameters,
    pub user_data: BTreeMap<SmolStr, Plist>,
    pub metrics_source_id: Option<String>,
}

impl FontMaster {
    fn read_metric(&self, metric_name: &str) -> Option<f64> {
        self.metric_values
            .get(metric_name)
            .map(|metric| metric.pos.into_inner())
    }

    pub fn ascender(&self) -> Option<f64> {
        self.read_metric("ascender")
    }

    pub fn descender(&self) -> Option<f64> {
        self.read_metric("descender")
    }

    pub fn x_height(&self) -> Option<f64> {
        self.read_metric("x-height")
    }

    pub fn cap_height(&self) -> Option<f64> {
        self.read_metric("cap height")
    }

    pub fn italic_angle(&self) -> Option<f64> {
        self.read_metric("italic angle")
    }
}

/// Resolves the linked metrics master ID from "Link Metrics..." custom parameters.
///
/// See <https://github.com/googlefonts/glyphsLib/blob/a045b48/Lib/glyphsLib/classes.py#L1641-L1665>
fn resolve_metrics_source_id(
    custom_params: &CustomParameters,
    master_ids_to_names: &IndexMap<String, Option<String>>,
) -> Option<String> {
    // "Link Metrics With First Master" takes precedence over "Link Metrics With Master"
    if custom_params.link_metrics_with_first_master == Some(true) {
        return master_ids_to_names.first().map(|(id, _)| id.clone());
    }

    if let Some(ref source_ref) = custom_params.link_metrics_with_master {
        // Try by master ID first
        if master_ids_to_names.contains_key(source_ref.as_str()) {
            return Some(source_ref.to_string());
        }
        // Try by master name
        if let Some((id, _)) = master_ids_to_names
            .iter()
            .find(|(_, name)| name.as_deref() == Some(source_ref.as_str()))
        {
            return Some(id.clone());
        }
        log::warn!("Source master for metrics not found: '{source_ref}'");
    }

    None
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, FromPlist)]
struct RawFontMaster {
    id: String,
    name: Option<String>,

    weight: Option<String>,
    width: Option<String>,
    custom: Option<String>,

    weight_value: Option<OrderedFloat<f64>>,
    interpolation_weight: Option<OrderedFloat<f64>>,

    width_value: Option<OrderedFloat<f64>>,
    interpolation_width: Option<OrderedFloat<f64>>,

    custom_value: Option<OrderedFloat<f64>>,

    typo_ascender: Option<i64>,
    typo_descender: Option<OrderedFloat<f64>>,
    typo_line_gap: Option<OrderedFloat<f64>>,
    win_ascender: Option<OrderedFloat<f64>>,
    win_descender: Option<OrderedFloat<f64>>,

    axes_values: Vec<OrderedFloat<f64>>,
    metric_values: Vec<RawMetricValue>, // v3

    ascender: Option<OrderedFloat<f64>>,   // v2
    baseline: Option<OrderedFloat<f64>>,   // v2
    descender: Option<OrderedFloat<f64>>,  // v2
    cap_height: Option<OrderedFloat<f64>>, // v2
    x_height: Option<OrderedFloat<f64>>,   // v2
    #[fromplist(alt_name = "italic angle")]
    italic_angle: Option<OrderedFloat<f64>>, // v2

    alignment_zones: Vec<String>, // v2

    custom_parameters: RawCustomParameters,
    number_values: Vec<OrderedFloat<f64>>,
    user_data: BTreeMap<SmolStr, Plist>,

    #[fromplist(ignore)]
    other_stuff: BTreeMap<String, Plist>,
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, FromPlist)]
struct RawMetricValue {
    pos: Option<OrderedFloat<f64>>,
    over: Option<OrderedFloat<f64>>,
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
pub struct MetricValue {
    pos: OrderedFloat<f64>,
    over: OrderedFloat<f64>,
}

impl From<RawMetricValue> for MetricValue {
    fn from(src: RawMetricValue) -> MetricValue {
        MetricValue {
            pos: src.pos.unwrap_or_default(),
            over: src.over.unwrap_or_default(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Hash)]
pub struct Instance {
    pub name: String,
    pub active: bool,
    // So named to let FromPlist populate it from a field called "type"
    pub type_: InstanceType,
    pub axis_mappings: BTreeMap<String, AxisUserToDesignMap>,
    pub axes_values: Vec<OrderedFloat<f64>>,
    pub custom_parameters: CustomParameters,
    properties: Vec<RawName>, // used for name resolution
}

/// <https://github.com/googlefonts/glyphsLib/blob/6f243c1f732ea1092717918d0328f3b5303ffe56/Lib/glyphsLib/classes.py#L150>
#[derive(Clone, Debug, PartialEq, Hash)]
pub enum InstanceType {
    Single,
    Variable,
}

impl From<&str> for InstanceType {
    fn from(value: &str) -> Self {
        if value.eq_ignore_ascii_case("variable") {
            InstanceType::Variable
        } else {
            InstanceType::Single
        }
    }
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, FromPlist)]
struct RawInstance {
    name: String,
    exports: Option<i64>,
    active: Option<i64>,
    type_: Option<String>,
    axes_values: Vec<OrderedFloat<f64>>,

    weight_value: Option<OrderedFloat<f64>>,
    interpolation_weight: Option<OrderedFloat<f64>>,

    width_value: Option<OrderedFloat<f64>>,
    interpolation_width: Option<OrderedFloat<f64>>,

    custom_value: Option<OrderedFloat<f64>>,
    interpolation_custom: Option<OrderedFloat<f64>>,

    weight_class: Option<String>,
    width_class: Option<String>,
    properties: Vec<RawName>,
    custom_parameters: RawCustomParameters,
}

impl RawInstance {
    /// Per glyphsLib both "exports=0" and "active=0" mean inactive
    /// <https://github.com/googlefonts/glyphsLib/blob/6f243c1f732ea1092717918d0328f3b5303ffe56/Lib/glyphsLib/builder/axes.py#L637>
    fn is_active(&self) -> bool {
        self.exports.unwrap_or(1) != 0 && self.active.unwrap_or(1) != 0
    }
}

trait GlyphsV2OrderedAxes {
    fn weight_value(&self) -> Option<OrderedFloat<f64>>;
    fn interpolation_weight(&self) -> Option<OrderedFloat<f64>>;
    fn width_value(&self) -> Option<OrderedFloat<f64>>;
    fn interpolation_width(&self) -> Option<OrderedFloat<f64>>;
    fn custom_value(&self) -> Option<OrderedFloat<f64>>;
    fn interpolation_custom(&self) -> Option<OrderedFloat<f64>>;

    fn value_for_nth_axis(&self, nth_axis: usize) -> Result<OrderedFloat<f64>, Error> {
        // Per https://github.com/googlefonts/fontmake-rs/pull/42#pullrequestreview-1211619812
        // the field to use is based on the order in axes NOT the tag.
        // That is, whatever the first axis is, it's value is in the weightValue field. Long sigh.
        // Defaults per https://github.com/googlefonts/fontmake-rs/pull/42#discussion_r1044415236.
        // v2 instances use novel field names so send back several for linear probing.
        Ok(match nth_axis {
            0 => self
                .weight_value()
                .or(self.interpolation_weight())
                .unwrap_or(100.0.into()),
            1 => self
                .width_value()
                .or(self.interpolation_width())
                .unwrap_or(100.0.into()),
            2 => self
                .custom_value()
                .or(self.interpolation_custom())
                .unwrap_or(0.0.into()),
            _ => {
                return Err(Error::StructuralError(format!(
                    "We don't know what field to use for axis {nth_axis}"
                )));
            }
        })
    }

    fn axis_values(&self, axes: &[Axis]) -> Result<Vec<OrderedFloat<f64>>, Error> {
        (0..axes.len())
            .map(|nth_axis| self.value_for_nth_axis(nth_axis))
            .collect::<Result<Vec<OrderedFloat<f64>>, Error>>()
    }
}

impl GlyphsV2OrderedAxes for RawFontMaster {
    fn weight_value(&self) -> Option<OrderedFloat<f64>> {
        self.weight_value
    }

    fn interpolation_weight(&self) -> Option<OrderedFloat<f64>> {
        self.interpolation_weight
    }

    fn width_value(&self) -> Option<OrderedFloat<f64>> {
        self.width_value
    }

    fn interpolation_width(&self) -> Option<OrderedFloat<f64>> {
        self.interpolation_width
    }

    fn custom_value(&self) -> Option<OrderedFloat<f64>> {
        self.custom_value
    }

    fn interpolation_custom(&self) -> Option<OrderedFloat<f64>> {
        // Masters use customValue, not interpolationCustom
        None
    }
}

impl GlyphsV2OrderedAxes for RawInstance {
    fn weight_value(&self) -> Option<OrderedFloat<f64>> {
        self.weight_value
    }

    fn interpolation_weight(&self) -> Option<OrderedFloat<f64>> {
        self.interpolation_weight
    }

    fn width_value(&self) -> Option<OrderedFloat<f64>> {
        self.width_value
    }

    fn interpolation_width(&self) -> Option<OrderedFloat<f64>> {
        self.interpolation_width
    }

    fn custom_value(&self) -> Option<OrderedFloat<f64>> {
        self.custom_value
    }

    fn interpolation_custom(&self) -> Option<OrderedFloat<f64>> {
        self.interpolation_custom
    }
}

fn parse_node_from_string(value: &str) -> Node {
    let mut spl = value.splitn(3, ' ');
    let x = spl.next().unwrap().parse().unwrap();
    let y = spl.next().unwrap().parse().unwrap();
    let pt = Point::new(x, y);
    let mut raw_node_type = spl.next().unwrap();
    // drop the userData dict, we don't use it for compilation
    if raw_node_type.contains('{') {
        raw_node_type = raw_node_type.split('{').next().unwrap().trim_end();
    }
    let node_type = raw_node_type.parse().unwrap();
    Node { pt, node_type }
}

fn parse_node_from_tokenizer(tokenizer: &mut Tokenizer<'_>) -> Result<Node, crate::plist::Error> {
    // (x,y,type)
    let x: f64 = tokenizer.parse()?;
    tokenizer.eat(b',')?;
    let y: f64 = tokenizer.parse()?;
    tokenizer.eat(b',')?;
    let node_type: String = tokenizer.parse()?;
    let node_type = NodeType::from_str(&node_type)
        .map_err(|_| crate::plist::Error::Parse(format!("unknown node type '{node_type}'")))?;

    // Sometimes there is userData; ignore it
    if tokenizer.eat(b',').is_ok() {
        tokenizer.skip_rec()?;
    }

    Ok(Node {
        pt: Point { x, y },
        node_type,
    })
}

impl std::str::FromStr for NodeType {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            // Glyphs 2 style
            "LINE" => Ok(NodeType::Line),
            "LINE SMOOTH" => Ok(NodeType::LineSmooth),
            "OFFCURVE" => Ok(NodeType::OffCurve),
            "CURVE" => Ok(NodeType::Curve),
            "CURVE SMOOTH" => Ok(NodeType::CurveSmooth),
            "QCURVE" => Ok(NodeType::QCurve),
            "QCURVE SMOOTH" => Ok(NodeType::QCurveSmooth),
            // Glyphs 3 style
            "l" => Ok(NodeType::Line),
            "ls" => Ok(NodeType::LineSmooth),
            "o" => Ok(NodeType::OffCurve),
            "c" => Ok(NodeType::Curve),
            "cs" => Ok(NodeType::CurveSmooth),
            "q" => Ok(NodeType::QCurve),
            "qs" => Ok(NodeType::QCurveSmooth),
            _ => Err(format!("unknown node type {s}")),
        }
    }
}

// Hand-parse Node because it doesn't follow the normal structure
impl FromPlist for Node {
    fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
        use crate::plist::Error;
        let tok = tokenizer.lex()?;
        let node = match &tok {
            Token::Atom(value) => parse_node_from_string(value),
            Token::String(value) => parse_node_from_string(value),
            Token::OpenParen => {
                let node = parse_node_from_tokenizer(tokenizer)?;
                tokenizer.eat(b')')?;
                node
            }
            _ => return Err(Error::ExpectedString),
        };
        Ok(node)
    }
}

impl Path {
    pub fn new(closed: bool) -> Path {
        Path {
            nodes: Vec::new(),
            closed,
            ..Default::default()
        }
    }

    pub fn add(&mut self, pt: impl Into<Point>, node_type: NodeType) {
        let pt = pt.into();
        self.nodes.push(Node { pt, node_type });
    }

    /// Rotate left by one, placing the first point at the end. This is because
    /// it's what glyphs seems to expect.
    pub fn rotate_left(&mut self, delta: usize) {
        self.nodes.rotate_left(delta);
    }

    pub fn reverse(&mut self) {
        self.nodes.reverse();
    }

    /// get the segment ending at `idx`
    pub(crate) fn get_previous_segment(&self, idx: usize) -> Option<PathSeg> {
        if self.nodes.len() < 2 {
            return None;
        }
        let end = self.nodes.get(idx)?.pt;
        let mut idx = self.prev_idx(idx);
        let prev = self.nodes.get(idx)?;
        if prev.node_type == NodeType::OffCurve {
            idx = self.prev_idx(idx);
            let control1 = self.nodes.get(idx)?;
            if control1.node_type != NodeType::OffCurve {
                // seems extremely unlikely but not exactly impossible, let's at least log?
                log::info!("path for corner component contains unexpected quadratic");
                return Some(QuadBez::new(control1.pt, prev.pt, end).into());
            }
            let start = self.nodes.get(self.prev_idx(idx))?;
            Some(CubicBez::new(start.pt, control1.pt, prev.pt, end).into())
        } else {
            Some(Line::new(prev.pt, end).into())
        }
    }

    /// get the segment beginning at `idx`
    pub(crate) fn get_next_segment(&self, idx: usize) -> Option<PathSeg> {
        if self.nodes.len() < 2 {
            return None;
        }
        let start = self.nodes.get(idx)?.pt;
        let mut idx = self.next_idx(idx);
        let next = self.nodes.get(idx)?;
        if next.node_type == NodeType::OffCurve {
            idx = self.next_idx(idx);
            let control2 = self.nodes.get(idx)?;
            if control2.node_type != NodeType::OffCurve {
                // seems extremely unlikely but not exactly impossible, let's at least log?
                log::info!("path for corner component contains unexpected quadratic");
                return Some(QuadBez::new(start, next.pt, control2.pt).into());
            }
            let end = self.nodes.get(self.next_idx(idx))?;
            Some(CubicBez::new(start, next.pt, control2.pt, end.pt).into())
        } else {
            Some(Line::new(start, next.pt).into())
        }
    }

    pub(crate) fn prev_idx(&self, idx: usize) -> usize {
        if idx == 0 {
            self.nodes.len().saturating_sub(1)
        } else {
            idx - 1
        }
    }

    pub(crate) fn next_idx(&self, idx: usize) -> usize {
        (idx + 1) % self.nodes.len()
    }

    #[cfg(test)]
    pub(crate) fn to_points(&self) -> Vec<Point> {
        self.nodes.iter().map(|n| n.pt).collect()
    }
}

fn v2_to_v3_name(v2_prop: Option<&str>, v3_name: &str) -> Option<RawName> {
    // https://github.com/schriftgestalt/GlyphsSDK/blob/Glyphs3/GlyphsFileFormat/GlyphsFileFormatv3.md#properties
    // Keys ending with "s" are localizable that means the second key is values
    v2_prop.map(|value| {
        if v3_name.ends_with('s') {
            RawName {
                key: v3_name.into(),
                value: None,
                values: vec![RawNameValue {
                    language: "dflt".into(),
                    value: value.to_string(),
                }],
            }
        } else {
            RawName {
                key: v3_name.into(),
                value: Some(value.to_string()),
                values: vec![],
            }
        }
    })
}

impl RawFont {
    pub fn load_from_string(raw_content: &str) -> Result<Self, crate::plist::Error> {
        let raw_content = preprocess_unparsed_plist(raw_content);
        Self::parse_plist(&raw_content)
    }

    pub fn load(glyphs_file: &path::Path) -> Result<Self, Error> {
        if glyphs_file.extension() == Some(OsStr::new("glyphspackage")) {
            return Self::load_package(glyphs_file);
        }

        debug!("Read glyphs {glyphs_file:?}");
        let raw_content = fs::read_to_string(glyphs_file).map_err(Error::IoError)?;
        Self::load_from_string(&raw_content)
            .map_err(|e| Error::ParseError(glyphs_file.to_path_buf(), e.to_string()))
    }

    /// load from a .glyphspackage
    fn load_package(glyphs_package: &path::Path) -> Result<RawFont, Error> {
        if !glyphs_package.is_dir() {
            return Err(Error::NotAGlyphsPackage(glyphs_package.to_path_buf()));
        }
        debug!("Read glyphs package {glyphs_package:?}");

        let fontinfo_file = glyphs_package.join("fontinfo.plist");
        let fontinfo_data = fs::read_to_string(&fontinfo_file).map_err(Error::IoError)?;
        let mut raw_font = RawFont::parse_plist(&fontinfo_data)
            .map_err(|e| Error::ParseError(fontinfo_file.to_path_buf(), format!("{e}")))?;

        let mut glyphs: HashMap<SmolStr, RawGlyph> = HashMap::new();
        let glyphs_dir = glyphs_package.join("glyphs");
        if glyphs_dir.is_dir() {
            for entry in fs::read_dir(glyphs_dir).map_err(Error::IoError)? {
                let entry = entry.map_err(Error::IoError)?;
                let path = entry.path();
                if path.extension() == Some(OsStr::new("glyph")) {
                    let glyph_data = fs::read_to_string(&path).map_err(Error::IoError)?;
                    let glyph_data = preprocess_unparsed_plist(&glyph_data);
                    let glyph = RawGlyph::parse_plist(&glyph_data)
                        .map_err(|e| Error::ParseError(path.clone(), e.to_string()))?;
                    if glyph.glyphname.is_empty() {
                        return Err(Error::ParseError(
                            path.clone(),
                            "Glyph dict must have a 'glyphname' key".to_string(),
                        ));
                    }
                    glyphs.insert(glyph.glyphname.clone(), glyph);
                }
            }
        }

        // if order.plist file exists, read it and sort glyphs in it accordingly
        let order_file = glyphs_package.join("order.plist");
        let mut ordered_glyphs = Vec::new();
        if order_file.exists() {
            let order_data = fs::read_to_string(&order_file).map_err(Error::IoError)?;
            let order_plist = Plist::parse(&order_data)
                .map_err(|e| Error::ParseError(order_file.to_path_buf(), e.to_string()))?;
            let order = order_plist
                .expect_array()
                .map_err(|e| Error::ParseError(order_file.to_path_buf(), e.to_string()))?;
            for glyph_name in order {
                let glyph_name = glyph_name
                    .expect_string()
                    .map_err(|e| Error::ParseError(order_file.to_path_buf(), e.to_string()))?;
                if let Some(glyph) = glyphs.remove(glyph_name.as_str()) {
                    ordered_glyphs.push(glyph);
                }
            }
        }
        // sort the glyphs not in order.plist by their name
        let mut glyph_names: Vec<_> = glyphs.keys().cloned().collect();
        glyph_names.sort();
        ordered_glyphs.extend(
            glyph_names
                .into_iter()
                .map(|glyph_name| glyphs.remove(&glyph_name).unwrap()),
        );
        assert!(glyphs.is_empty());
        raw_font.glyphs = ordered_glyphs;

        // ignore UIState.plist which stuff like displayStrings that are not used by us

        Ok(raw_font)
    }

    fn v2_to_v3_axes(&mut self) -> Result<Vec<String>, Error> {
        let mut tags = Vec::new();
        if let Some(v2_axes) = self.custom_parameters.take_axes() {
            for v2_axis in v2_axes {
                tags.push(v2_axis.tag.clone());
                self.axes.push(v2_axis.clone());
            }
        }

        // Match the defaults from https://github.com/googlefonts/glyphsLib/blob/f6e9c4a29ce764d34c309caef5118c48c156be36/Lib/glyphsLib/builder/axes.py#L526
        // if we have nothing
        if self.axes.is_empty() {
            self.axes.push(Axis {
                name: "Weight".into(),
                tag: "wght".into(),
                hidden: None,
            });
            self.axes.push(Axis {
                name: "Width".into(),
                tag: "wdth".into(),
                hidden: None,
            });
            self.axes.push(Axis {
                name: "Custom".into(),
                tag: "XXXX".into(),
                hidden: None,
            });
        }

        if self.axes.len() > 3 {
            return Err(Error::StructuralError(
                "We only understand 0..3 axes for Glyphs v2".into(),
            ));
        }

        // v2 stores values for axes in specific fields, find them and put them into place
        // "Axis position related properties (e.g. weightValue, widthValue, customValue) have been replaced by the axesValues list which is indexed in parallel with the toplevel axes list."
        for master in self.font_master.iter_mut() {
            master.axes_values = master.axis_values(&self.axes)?;
        }
        for instance in self.instances.iter_mut() {
            instance.axes_values = instance.axis_values(&self.axes)?;
        }

        Ok(tags)
    }

    fn v2_to_v3_metrics(&mut self) -> Result<(), Error> {
        // setup storage for the basic metrics
        self.metrics = V3_METRIC_NAMES
            .iter()
            .map(|n| RawMetric {
                type_: n.to_string(),
            })
            .collect();

        let mut used_metrics = [false; 6];
        // first which metric occurs in any master:
        for m in &self.font_master {
            for (i, val) in [
                m.ascender,
                m.baseline,
                m.descender,
                m.cap_height,
                m.x_height,
                m.italic_angle,
            ]
            .iter()
            .enumerate()
            {
                used_metrics[i] |= val.is_some();
            }
        }

        // add only used metrics to the metric list
        self.metrics = V3_METRIC_NAMES
            .into_iter()
            .zip(used_metrics)
            .filter(|(_, used)| *used)
            .map(|(name, _)| RawMetric {
                type_: name.to_string(),
            })
            .collect();

        let mut non_metric_alignment_zones = vec![vec![]; self.font_master.len()];

        // in each font master setup the parallel array
        for (i, master) in self.font_master.iter_mut().enumerate() {
            // each master has to have an entry for each defined metric,
            // even if it is 'None', and they need to be in the same order
            // as in the self.metrics list.
            let mut metric_values = vec![RawMetricValue::default(); self.metrics.len()];
            for (metric_idx, name) in self.metrics.iter().enumerate() {
                let value = match name.type_.as_ref() {
                    "ascender" => master.ascender,
                    "baseline" => master.baseline,
                    "descender" => master.descender,
                    "cap height" => master.cap_height,
                    "x-height" => master.x_height,
                    "italic angle" => master.italic_angle,
                    _ => unreachable!("only these values exist in V3_METRIC_NAMES"),
                };
                metric_values[metric_idx].pos = value;
            }

            // "alignmentZones is now a set of over (overshoot) properties attached to metrics"
            for alignment_zone in &master.alignment_zones {
                let Some((pos, over)) = parse_alignment_zone(alignment_zone) else {
                    warn!("Confusing alignment zone '{alignment_zone}', skipping");
                    continue;
                };

                // skip zero-height zones
                if over == 0. {
                    continue;
                }

                // special handling for this; we assume it's the baseline, and
                // we know where that is in our vec (and it has pos: None, set
                // above)
                if pos == 0. {
                    if let Some((idx, _)) = self
                        .metrics
                        .iter()
                        .enumerate()
                        .find(|(_, name)| name.type_ == "baseline")
                    {
                        metric_values[idx].over = Some(over);
                    }
                    continue;
                }

                // now look for a metric that has the same position as this zone
                // this is quadratic but N is small
                if let Some(metric) = metric_values.iter_mut().find(|x| x.pos == Some(pos)) {
                    metric.over = Some(over);
                } else {
                    non_metric_alignment_zones[i].push((pos, over))
                }
            }
            master.metric_values = metric_values;
        }

        // now handle any non-metric alignment zones, converting them to metrics.
        // first we assign a name to each unique position:
        let mut new_metrics = HashMap::new();
        for pos in non_metric_alignment_zones
            .iter()
            .flat_map(|master| master.iter().map(|(pos, _)| *pos))
        {
            if !new_metrics.contains_key(&pos) {
                let next_zone = new_metrics.len() + 1;
                let idx = self.metrics.len();
                self.metrics.push(RawMetric {
                    type_: format!("zone {next_zone}"),
                });
                new_metrics.insert(pos, idx);
            }
        }

        // flip our map, so it's ordered on index:
        let new_metrics: BTreeMap<_, _> = new_metrics.into_iter().map(|(k, v)| (v, k)).collect();

        // then for each master, add a metric value for each newly named metric
        for (idx, metrics) in non_metric_alignment_zones.into_iter().enumerate() {
            for pos_to_add in new_metrics.values().copied() {
                let to_add = metrics.iter().copied().find_map(|(pos, over)| {
                    (pos == pos_to_add).then_some(RawMetricValue {
                        pos: Some(pos),
                        over: Some(over),
                    })
                });

                self.font_master[idx]
                    .metric_values
                    .push(to_add.unwrap_or_default());
            }
        }
        Ok(())
    }

    fn v2_to_v3_master_names(&mut self) -> Result<(), Error> {
        // in Glyphs 2, masters don't have a single 'name' attribute, but rather
        // a concatenation of three other optional attributes weirdly called
        // 'width', 'weight' and 'custom' (in exactly this order).
        // The first two can only contain few predefined values, the last one is
        // residual and free-form. They default to 'Regular' when omitted in
        // the source. See:
        // https://github.com/schriftgestalt/GlyphsSDK/blob/Glyphs3/GlyphsFileFormat/GlyphsFileFormatv2.md
        // https://github.com/googlefonts/glyphsLib/blob/9d5828d/Lib/glyphsLib/classes.py#L1700-L1711
        for master in self.font_master.iter_mut() {
            // Even though glyphs2 masters don't officially have a 'name' attribute,
            // some glyphs2 sources produced by more recent versions of Glyphs
            // sometimes have it (unclear exactly when or from which version on).
            // We keep the 'name' attribute as is, instead of generating a one.
            if master.name.is_some() {
                continue;
            }

            // Remove Nones, empty strings and redundant occurrences of 'Regular'
            let mut names = [
                master.width.as_deref(),
                master.weight.as_deref(),
                master.custom.as_deref(),
            ]
            .iter()
            .flatten()
            .flat_map(|n| n.split_ascii_whitespace())
            .filter(|x| *x != "Regular")
            .collect::<Vec<_>>();

            // append "Italic" if italic angle != 0
            if let Some(italic_angle) = master.italic_angle
                && italic_angle != 0.0
                && (names.is_empty()
                    || !names
                        .iter()
                        // https://github.com/googlefonts/glyphsLib/blob/d42d3b15/Lib/glyphsLib/classes.py#L1710
                        .any(|name| name.contains("Italic") || name.contains("Oblique")))
            {
                names.push("Italic");
            }
            // if all are empty, default to "Regular"
            master.name = if names.is_empty() {
                Some("Regular".into())
            } else {
                Some(names.join(" "))
            };
        }
        Ok(())
    }

    fn v2_to_v3_names(&mut self) -> Result<(), Error> {
        // The copyright, designer, designerURL, manufacturer, manufacturerURL top-level entries
        // have been moved into new top-level properties dictionary and made localizable.
        // Take properties to avoid incompatible borrowing against self
        let mut properties = std::mem::take(&mut self.properties);

        properties.extend(v2_to_v3_name(self.copyright.as_deref(), "copyrights"));
        properties.extend(v2_to_v3_name(self.designer.as_deref(), "designers"));
        properties.extend(v2_to_v3_name(self.designerURL.as_deref(), "designerURL"));
        properties.extend(v2_to_v3_name(self.manufacturer.as_deref(), "manufacturers"));
        properties.extend(v2_to_v3_name(
            self.manufacturerURL.as_deref(),
            "manufacturerURL",
        ));

        // glyphsLib tries both long and short names, with short names taking precedence
        //https://github.com/googlefonts/glyphsLib/blob/c4db6b981d577f456d64ebe9993818770e170454/Lib/glyphsLib/builder/custom_params.py#L258
        let mut v2_to_v3_param = |v2_names: &[&str], v3_name: &str| {
            if properties.iter().any(|n| n.key == v3_name && !n.is_empty()) {
                return;
            }
            for v2_name in v2_names {
                if let Some(value) = v2_to_v3_name(
                    self.custom_parameters.take_string(v2_name).as_deref(),
                    v3_name,
                ) {
                    properties.push(value);
                    return;
                }
            }
        };

        v2_to_v3_param(&["description", "openTypeNameDescription"], "descriptions");
        v2_to_v3_param(&["licenseURL", "openTypeNameLicenseURL"], "licenseURL");
        v2_to_v3_param(&["versionString", "openTypeNameVersion"], "versionString");
        v2_to_v3_param(&["compatibleFullName"], "compatibleFullNames");
        v2_to_v3_param(&["license", "openTypeNameLicense"], "licenses");
        v2_to_v3_param(&["uniqueID", "openTypeNameUniqueID"], "uniqueID");
        v2_to_v3_param(&["trademark"], "trademarks");
        v2_to_v3_param(&["sampleText", "openTypeNameSampleText"], "sampleTexts");
        v2_to_v3_param(&["postscriptFullName"], "postscriptFullName");
        v2_to_v3_param(&["postscriptFontName"], "postscriptFontName");
        v2_to_v3_param(
            &["WWSFamilyName", "openTypeNameWWSFamilyName"],
            "WWSFamilyName",
        );
        v2_to_v3_param(&["vendorID", "openTypeOS2VendorID"], "vendorID");

        self.properties = properties;

        Ok(())
    }

    fn v2_to_v3_instances(&mut self) -> Result<(), Error> {
        for instance in self.instances.iter_mut() {
            if let Some(custom_weight_class) = instance.custom_parameters.take("weightClass") {
                instance.weight_class = custom_weight_class.to_string().into();
            }
            // named clases become #s in v3
            for (tag, opt) in [
                ("wght", &mut instance.weight_class),
                ("wdth", &mut instance.width_class),
            ] {
                let Some(value) = opt.as_ref() else {
                    continue;
                };
                if f64::from_str(value).is_ok() {
                    continue;
                };
                let Some(value) = lookup_class_value(tag, value) else {
                    return Err(Error::UnknownValueName(value.clone()));
                };
                let _ = opt.insert(value.to_string());
            }

            instance.properties.extend(v2_to_v3_name(
                instance
                    .custom_parameters
                    .take_string("postscriptFontName")
                    .as_deref(),
                "postscriptFontName",
            ));
        }

        Ok(())
    }

    fn v2_to_v3_layer_attributes(&mut self) {
        for raw_glyph in self.glyphs.iter_mut() {
            for layer in raw_glyph.layers.iter_mut() {
                layer.v2_to_v3_attributes();
            }
        }
    }

    /// `<See https://github.com/schriftgestalt/GlyphsSDK/blob/Glyphs3/GlyphsFileFormat/GlyphsFileFormatv3.md#differences-between-version-2>`
    fn v2_to_v3(&mut self) -> Result<(), Error> {
        self.v2_to_v3_master_names()?;
        self.v2_to_v3_axes()?;
        self.v2_to_v3_metrics()?;
        self.v2_to_v3_instances()?;
        self.v2_to_v3_names()?; // uses instances
        self.v2_to_v3_layer_attributes();
        Ok(())
    }
}

// in the form '{INT, INT}'
fn parse_alignment_zone(zone: &str) -> Option<(OrderedFloat<f64>, OrderedFloat<f64>)> {
    let (one, two) = zone.split_once(',')?;
    let one = one.trim_start_matches(['{', ' ']).parse::<i32>().ok()?;
    let two = two.trim_start().trim_end_matches('}').parse::<i32>().ok()?;
    Some((OrderedFloat(one as f64), OrderedFloat(two as f64)))
}

fn make_glyph_order(glyphs: &[RawGlyph], custom_order: Option<Vec<SmolStr>>) -> Vec<SmolStr> {
    let mut valid_names: HashSet<_> = glyphs.iter().map(|g| &g.glyphname).collect();
    let mut glyph_order = Vec::new();

    // Add all valid glyphOrder entries in order
    // See https://github.com/googlefonts/fontmake-rs/pull/43/files#r1044627972
    for name in custom_order.into_iter().flatten() {
        if valid_names.remove(&name) {
            glyph_order.push(name.clone());
        }
    }

    // Add anything left over in file order
    glyph_order.extend(
        glyphs
            .iter()
            .filter(|g| valid_names.contains(&g.glyphname))
            .map(|g| g.glyphname.clone()),
    );

    glyph_order
}

// glyphs2 uses hex, glyphs3 uses base10
fn parse_codepoint_str(s: &str, radix: u32) -> BTreeSet<u32> {
    s.split(',')
        .map(|cp| u32::from_str_radix(cp, radix).unwrap())
        .collect()
}

/// <https://github.com/googlefonts/glyphsLib/blob/6f243c1f732ea1092717918d0328f3b5303ffe56/Lib/glyphsLib/builder/axes.py#L578>
fn default_master_idx(raw_font: &mut RawFont) -> usize {
    // Prefer an explicit origin
    // https://github.com/googlefonts/fontmake-rs/issues/44
    if let Some(master_idx) = raw_font
        .custom_parameters
        .take_string("Variable Font Origin")
        .and_then(|origin| {
            raw_font
                .font_master
                .iter()
                .position(|master| master.id == origin)
        })
    {
        return master_idx;
    }

    // No explicit origin, try to pick a winner

    // Contenders: (ordinal, words in name) for all masters that have names
    let contenders = raw_font
        .font_master
        .iter()
        .enumerate()
        .filter_map(|(i, m)| {
            m.name
                .as_deref()
                .map(|name| (i, whitespace_separated_tokens(name)))
        })
        .collect::<Vec<_>>();

    // EARLY EXIT: no contenders, just pick 0
    if contenders.is_empty() {
        return 0;
    }

    // In Python find_base_style <https://github.com/googlefonts/glyphsLib/blob/9d5828d874110c42dfc5f542db8eb84f88641eb5/Lib/glyphsLib/builder/axes.py#L652-L663>
    let mut common_words = contenders[0].1.clone();
    for (_, words) in contenders.iter().skip(1) {
        common_words.retain(|w| words.contains(w));
    }

    // Find the best match:
    //   Find the common words in the master names
    //   If any master is named exactly that, it wins
    //      "Foo Bar" is the best match for {Foo Bar Donkey, Foo Bar Cat, Foo Bar}
    //   Otherwise, a master whose name matches the common words if we delete "Regular" wins
    //      "Foo Bar Regular" is the best match for {Foo Bar Italic, Foo Bar Majestic, Foo Bar Regular}
    let mut best_idx = 0;
    for (idx, mut words) in contenders {
        // if name exactly matches common words you just win
        if *common_words == words {
            best_idx = idx;
            break;
        }

        // if our words excluding "Regular" match we're the best
        // a subsequent contender could match exactly so we don't win yet
        words.retain(|w| *w != "Regular");
        if *common_words == words {
            best_idx = idx;
        }
    }
    best_idx
}

fn whitespace_separated_tokens(s: &str) -> Vec<&str> {
    s.split_whitespace().collect()
}

fn axis_index(axes: &[Axis], pred: impl Fn(&Axis) -> bool) -> Option<usize> {
    axes.iter()
        .enumerate()
        .find_map(|(i, a)| if pred(a) { Some(i) } else { None })
}

fn user_to_design_from_axis_mapping(
    from: &mut RawFont,
) -> Option<BTreeMap<String, AxisUserToDesignMap>> {
    let mappings = from.custom_parameters.take_axis_mappings()?;
    let mut axis_mappings: BTreeMap<String, AxisUserToDesignMap> = BTreeMap::new();
    for mapping in mappings {
        let Some(axis_index) = axis_index(&from.axes, |a| a.tag == mapping.tag) else {
            log::warn!(
                "axis mapping includes tag {:?} not included in font",
                mapping.tag
            );
            continue;
        };
        let axis_name = &from.axes.get(axis_index).unwrap().name;
        for (user, design) in mapping.user_to_design.iter() {
            axis_mappings
                .entry(axis_name.clone())
                .or_default()
                .add_if_new(*user, *design);
        }
    }
    if axis_mappings.is_empty() {
        return None;
    }
    Some(axis_mappings)
}

fn user_to_design_from_axis_location(
    from: &mut RawFont,
) -> Option<BTreeMap<String, AxisUserToDesignMap>> {
    // glyphsLib only trusts Axis Location when all masters have it, match that
    // https://github.com/googlefonts/fontmake-rs/pull/83#discussion_r1065814670
    let master_locations: Vec<_> = from
        .font_master
        .iter_mut()
        .filter_map(|m| m.custom_parameters.take_axis_locations())
        .collect();
    if master_locations.len() != from.font_master.len() {
        if !master_locations.is_empty() {
            warn!(
                "{}/{} masters have Axis Location; ignoring",
                master_locations.len(),
                from.font_master.len()
            );
        }
        return None;
    }

    let mut axis_mappings: BTreeMap<String, AxisUserToDesignMap> = BTreeMap::new();
    for (master, axis_locations) in from.font_master.iter().zip(master_locations) {
        // masters' Axis Locations custom parameters can reference axes that aren't defined in the font,
        // so take font axes as the source of truth.
        for (idx, axis) in from.axes.iter().enumerate() {
            let Some(axis_location) = axis_locations.iter().find(|loc| loc.axis_name == axis.name)
            else {
                continue;
            };
            let user = axis_location.location;
            let design = master.axes_values[idx];
            // Last master wins, matching glyphsLib overwrite semantics:
            // https://github.com/googlefonts/glyphsLib/blob/71f487f9d24e/Lib/glyphsLib/builder/axes.py#L221
            let old = axis_mappings
                .entry(axis_location.axis_name.clone())
                .or_default()
                .add_or_replace(user, design);
            if let Some(old) = old {
                let name = master.name.as_deref().unwrap_or(&master.id);
                warn!(
                    "Axis {}: master '{}' redefines mapping for user \
                     location {user} from {old} to {design}",
                    axis.name, name
                );
            }
        }
    }
    Some(axis_mappings)
}

impl AxisUserToDesignMap {
    fn add_if_new(&mut self, user: OrderedFloat<f64>, design: OrderedFloat<f64>) {
        // only keys (input/user-space) should be unique, values (output/design-space) can be duplicated
        if self.0.iter().any(|(u, _)| *u == user) {
            return;
        }
        self.0.push((user, design));
    }

    /// Insert or overwrite mapping for `user`.
    /// Returns the previous design value if an existing entry was overwritten.
    fn add_or_replace(
        &mut self,
        user: OrderedFloat<f64>,
        design: OrderedFloat<f64>,
    ) -> Option<OrderedFloat<f64>> {
        if let Some(entry) = self.0.iter_mut().find(|(u, _)| *u == user) {
            if entry.1 != design {
                let old = entry.1;
                entry.1 = design;
                return Some(old);
            }
        } else {
            self.0.push((user, design));
        }
        None
    }

    fn add_identity_map(&mut self, value: OrderedFloat<f64>) {
        // no duplicate keys nor values allowed
        if self.0.iter().any(|(u, d)| *u == value || *d == value) {
            return;
        }
        self.0.push((value, value));
    }

    pub fn iter(&self) -> impl Iterator<Item = &(OrderedFloat<f64>, OrderedFloat<f64>)> {
        self.0.iter()
    }

    pub fn is_identity(&self) -> bool {
        self.0.iter().all(|(u, d)| u == d)
    }
}

impl UserToDesignMapping {
    /// From most to least preferred: Axis Mappings, Axis Location, mappings from instances, assume user == design
    ///
    /// <https://github.com/googlefonts/glyphsLib/blob/6f243c1f732ea1092717918d0328f3b5303ffe56/Lib/glyphsLib/builder/axes.py#L155>
    fn new(from: &mut RawFont, instances: &[Instance]) -> Self {
        let from_axis_mapping = user_to_design_from_axis_mapping(from);
        let from_axis_location = user_to_design_from_axis_location(from);
        let (result, incomplete_mapping) = match (from_axis_mapping, from_axis_location) {
            (Some(from_mapping), Some(..)) => {
                warn!("Axis Mapping *and* Axis Location are defined; using Axis Mapping");
                (from_mapping, false)
            }
            (Some(from_mapping), None) => (from_mapping, false),
            (None, Some(from_location)) => (from_location, true),
            (None, None) => (BTreeMap::new(), true),
        };
        let mut result = Self(result);
        if incomplete_mapping {
            //https://github.com/googlefonts/glyphsLib/blob/682ff4b17/Lib/glyphsLib/builder/axes.py#L251
            result.add_instance_mappings(instances);
            if result.0.is_empty() || result.0.values().all(|v| v.is_identity()) {
                result.add_master_mappings_if_new(from);
            }
        }
        result
    }

    pub fn contains(&self, axis_name: &str) -> bool {
        self.0.contains_key(axis_name)
    }

    pub fn get(&self, axis_name: &str) -> Option<&AxisUserToDesignMap> {
        self.0.get(axis_name)
    }

    /// Last instance wins, matching glyphsLib overwrite semantics:
    /// * <https://github.com/googlefonts/glyphsLib/blob/71f487f9d24e/Lib/glyphsLib/builder/axes.py#L153>
    fn add_instance_mappings(&mut self, instances: &[Instance]) {
        for instance in instances
            .iter()
            .filter(|i| i.active && i.type_ == InstanceType::Single)
        {
            for (axis_name, inst_mapping) in instance.axis_mappings.iter() {
                let entry = self.0.entry(axis_name.clone()).or_default();
                for (user, design) in inst_mapping.iter() {
                    if let Some(old) = entry.add_or_replace(*user, *design) {
                        warn!(
                            "Axis {axis_name}: instance '{}' redefines mapping for user \
                             location {user} from {old} to {design}",
                            instance.name
                        );
                    }
                }
            }
        }
    }

    fn add_master_mappings_if_new(&mut self, from: &RawFont) {
        for master in from.font_master.iter() {
            for (axis, value) in from.axes.iter().zip(&master.axes_values) {
                self.0
                    .entry(axis.name.clone())
                    .or_default()
                    .add_identity_map(*value);
            }
        }
    }
}

impl TryFrom<RawShape> for Shape {
    type Error = Error;

    fn try_from(from: RawShape) -> Result<Self, Self::Error> {
        // TODO: handle numerous unsupported attributes
        // See <https://github.com/schriftgestalt/GlyphsSDK/blob/Glyphs3/GlyphsFileFormat/GlyphsFileFormatv3.md#differences-between-version-2>

        let shape = if let Some(glyph_name) = from.glyph_name {
            assert!(!glyph_name.is_empty(), "A pointless component");

            // V3 vs v2: The transform entry has been replaced by angle, pos, scale and slant.
            let mut transform = if let Some(transform) = from.transform {
                Affine::parse_plist(&transform)?
            } else {
                Affine::IDENTITY
            };

            // Glyphs 3 gives us {angle, pos, scale, slant}. Glyphs 2 gives us the standard 2x3 matrix.
            // The matrix is more general and less ambiguous (what order do you apply the angle, pos, scale, slant?)
            // so convert Glyphs 3 to that. Order based on saving the same transformed component as
            // Glyphs 2 and Glyphs 3 then trying to convert one to the other.
            if !from.pos.is_empty() {
                if from.pos.len() != 2 {
                    return Err(Error::StructuralError(format!("Bad pos: {:?}", from.pos)));
                }
                transform *= Affine::translate((from.pos[0], from.pos[1]));
            }
            if !from.slant.is_empty() {
                if from.slant.len() != 2 {
                    return Err(Error::StructuralError(format!(
                        "Bad slant: {:?}",
                        from.slant
                    )));
                }
                // Glyphs stores slant as angles in degrees; Affine::skew wants the
                // shear factors, i.e. the tangent of those angles.
                transform *= Affine::skew(
                    from.slant[0].to_radians().tan(),
                    from.slant[1].to_radians().tan(),
                );
            }
            if let Some(angle) = from.angle {
                transform *= normalized_rotation(angle);
            }
            if !from.scale.is_empty() {
                if from.scale.len() != 2 {
                    return Err(Error::StructuralError(format!(
                        "Bad scale: {:?}",
                        from.scale
                    )));
                }
                transform *= Affine::scale_non_uniform(from.scale[0], from.scale[1]);
            }

            Shape::Component(Component {
                name: glyph_name,
                transform,
                anchor: from.anchor,
                attributes: from.attributes,
                smart_component_values: from.piece,
            })
        } else {
            // no ref; presume it's a path
            Shape::Path(Path {
                closed: from.closed.unwrap_or_default(),
                nodes: from.nodes.clone(),
                attributes: from.attributes,
            })
        };
        Ok(shape)
    }
}

/// Return [kurbo::Affine] rotation around angle (in degrees) with normalized sin/cos.
///
/// This ensures that for the four "cardinal" rotations (0, 90, 180, 270), the values
/// of sin(angle) and cos(angle) are rounded to *exactly* 0.0, +1.0 or -1.0, thus avoiding
/// very small values (e.g. 1.2246467991473532e-16) whose effect may be amplified as some
/// transformed point coordinates end up close to the 0.5 threshold before being rounded
/// to integer later in the build.
/// It matches the output of the fontTools' Transform.rotate() used by glyphsLib.
/// <https://github.com/fonttools/fonttools/blob/b7509b2/Lib/fontTools/misc/transform.py#L246-L258>
fn normalized_rotation(angle_deg: f64) -> Affine {
    const ROT_90: Affine = Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]);
    const ROT_180: Affine = Affine::new([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0]);
    const ROT_270: Affine = Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]);
    // Normalize angle to [0, 360)
    let normalized_angle = angle_deg.rem_euclid(360.0);

    match normalized_angle {
        0.0 => Affine::IDENTITY,
        90.0 => ROT_90,
        180.0 => ROT_180,
        270.0 => ROT_270,
        _ => Affine::rotate(angle_deg.to_radians()),
    }
}

fn map_and_push_if_present<T, U>(dest: &mut Vec<T>, src: Vec<U>, map: fn(U) -> T) {
    src.into_iter().map(map).for_each(|v| dest.push(v));
}

impl RawLayer {
    fn build(self, format_version: FormatVersion) -> Result<Layer, Error> {
        // we do what glyphsLib does:
        // https://github.com/googlefonts/glyphsLib/blob/c4db6b981d577f4/Lib/glyphsLib/classes.py#L3662
        // which is apparently standard, in that if a field is missing it has
        // some implied default value? Although I don't know where these are
        // all documented, outside of glyphsLib.
        const DEFAULT_LAYER_WIDTH: f64 = 600.;
        let mut shapes = Vec::new();

        // Glyphs v2 uses paths and components
        map_and_push_if_present(&mut shapes, self.paths, Shape::Path);
        map_and_push_if_present(&mut shapes, self.components, Shape::Component);

        // Glyphs v3 uses shapes for both
        for raw_shape in self.shapes {
            shapes.push(raw_shape.try_into()?);
        }

        let anchors = self
            .anchors
            .into_iter()
            .map(|ra| {
                let pos = if let Some(pos) = ra.pos {
                    pos
                } else if let Some(raw) = ra.position {
                    Point::parse_plist(&raw).unwrap()
                } else {
                    Point::ZERO
                };
                Anchor { name: ra.name, pos }
            })
            .collect();

        let mut attributes = self.attributes;
        // convert v2 bracket layers (based on name) into AxisRule attrs
        if let Some(axis_rule) =
            AxisRule::from_layer_name(&self.name).filter(|_| format_version.is_v2())
        {
            assert!(
                attributes.axis_rules.is_empty(),
                "glyphs v2 does not use axisRules attr"
            );
            attributes.axis_rules.push(axis_rule);
        }
        let smart_component_positions = if format_version.is_v2() {
            self.user_data.part_selection
        } else {
            self.part_selection
        }
        .into_iter()
        .map(|(k, v)| match v {
            1 => Ok((k, AxisPole::Min)),
            2 => Ok((k, AxisPole::Max)),
            other => Err(Error::BadValue(format!(
                "expected only 1 or 2 in partSelection, found '{other}'"
            ))),
        })
        .collect::<Result<_, _>>()?;
        let hints = self
            .hints
            .iter()
            .map(RawHint::to_hint)
            .collect::<Result<_, _>>()?;
        Ok(Layer {
            layer_id: self.layer_id,
            associated_master_id: self.associated_master_id,
            width: self.width.unwrap_or(DEFAULT_LAYER_WIDTH.into()),
            vert_width: self.vert_width,
            vert_origin: self.vert_origin,
            shapes,
            anchors,
            attributes,
            smart_component_positions,
            hints,
        })
    }
}

impl RawGlyph {
    // we pass in the radix because it depends on the version, stored in the font struct
    fn build(self, format_version: FormatVersion, glyph_data: &GlyphData) -> Result<Glyph, Error> {
        let mut instances = Vec::new();
        let mut bracket_layers = Vec::new();
        for mut layer in self.layers {
            if layer.is_bracket_layer(format_version) {
                bracket_layers.push(layer.build(format_version)?);
            } else if !layer.is_draft() {
                // it's possible for these to exist even if there's no
                // associated master id, in which case we don't care
                layer.attributes.axis_rules.clear();
                instances.push(layer.build(format_version)?);
            }
        }
        // if category/subcategory were set in the source, we keep them;
        // otherwise we look them up based on the bundled GlyphData.
        // (we use this info later to determine GDEF categories, zero the width
        // on non-spacing marks, etc)
        fn parse_category<T>(s: Option<&str>, glyph: &SmolStr) -> Option<T>
        where
            T: FromStr<Err = SmolStr>,
        {
            match s.filter(|s| !s.is_empty()).map(T::from_str).transpose() {
                Ok(x) => x,
                // if we don't know a category ignore it and we'll compute it later
                Err(err) => {
                    log::warn!("Unknown category '{err}' for glyph '{glyph}'");
                    None
                }
            }
        }

        let mut category = parse_category(self.category.as_deref(), &self.glyphname);
        let mut sub_category = parse_category(self.sub_category.as_deref(), &self.glyphname);
        let mut production_name = self.production_name;

        // Whether the source explicitly set a non-empty category/subCategory. A value that
        // was set but not recognized parses to None (parse_category logs and drops it), so
        // we track "was set" separately to distinguish it from "absent". When the author
        // set a value, we don't let the name-based GlyphData lookup override it -- even if
        // we failed to parse it -- otherwise an underscore-named glyph explicitly marked as
        // e.g. `subCategory = <something fontc doesn't recognize>` silently reverts to being
        // guessed as a Ligature (breaking mark attachment).
        // https://github.com/googlefonts/fontc/issues/2055
        let category_was_set = self.category.as_deref().is_some_and(|s| !s.is_empty());
        let sub_category_was_set = self.sub_category.as_deref().is_some_and(|s| !s.is_empty());

        let codepoints = self
            .unicode
            .map(|s| parse_codepoint_str(&s, format_version.codepoint_radix()))
            .unwrap_or_default();

        if (category.is_none() || sub_category.is_none() || production_name.is_none())
            && let Some(result) = glyph_data.query(&self.glyphname, Some(&codepoints))
        {
            // Only fall back to the looked-up value for fields the source left unset;
            // an explicitly-set value (even one we couldn't parse) is the author's intent.
            if !category_was_set {
                category = category.or(Some(result.category));
            }
            if !sub_category_was_set {
                sub_category = sub_category.or(result.subcategory);
            }
            production_name = production_name.or(result.production_name.map(Into::into));
        }

        let part_settings = self
            .parts_settings
            .iter()
            .map(|raw| (raw.name.clone(), raw.bottom_value..=raw.top_value))
            .collect();

        Ok(Glyph {
            name: self.glyphname,
            export: self.export.unwrap_or(true),
            layers: instances,
            bracket_layers,
            left_kern: self.kern_left,
            right_kern: self.kern_right,
            unicode: codepoints,
            category,
            sub_category,
            production_name,
            smart_component_axes: part_settings,
        })
    }
}

// https://github.com/googlefonts/glyphsLib/blob/044f19e4/Lib/glyphsLib/builder/constants.py#L231
#[rustfmt::skip]
static GLYPHS_TO_OPENTYPE_LANGUAGE_ID: &[(&str, i32)] = &[
    ("AFK", 0x0436), ("ARA", 0x0C01), ("ASM", 0x044D), ("AZE", 0x042C), ("BEL", 0x0423),
    ("BEN", 0x0845), ("BGR", 0x0402), ("BRE", 0x047E), ("CAT", 0x0403), ("CSY", 0x0405),
    ("DAN", 0x0406), ("DEU", 0x0407), ("ELL", 0x0408), ("ENG", 0x0409), ("ESP", 0x0C0A),
    ("ETI", 0x0425), ("EUQ", 0x042D), ("FIN", 0x040B), ("FLE", 0x0813), ("FOS", 0x0438),
    ("FRA", 0x040C), ("FRI", 0x0462), ("GRN", 0x046F), ("GUJ", 0x0447), ("HAU", 0x0468),
    ("HIN", 0x0439), ("HRV", 0x041A), ("HUN", 0x040E), ("HVE", 0x042B), ("IRI", 0x083C),
    ("ISL", 0x040F), ("ITA", 0x0410), ("IWR", 0x040D), ("JPN", 0x0411), ("KAN", 0x044B),
    ("KAT", 0x0437), ("KAZ", 0x043F), ("KHM", 0x0453), ("KOK", 0x0457), ("KOR", 0x0412), ("LAO", 0x0454),
    ("LSB", 0x082E), ("LTH", 0x0427), ("LVI", 0x0426), ("MAR", 0x044E), ("MKD", 0x042F),
    ("MLR", 0x044C), ("MLY", 0x043E), ("MNG", 0x0352), ("MOL", 0x0818), ("MTS", 0x043A), ("NEP", 0x0461),
    ("NLD", 0x0413), ("NOB", 0x0414), ("ORI", 0x0448), ("PAN", 0x0446), ("PAS", 0x0463),
    ("PLK", 0x0415), ("PTG", 0x0816), ("PTG-BR", 0x0416), ("RMS", 0x0417), ("ROM", 0x0418),
    ("RUS", 0x0419), ("SAN", 0x044F), ("SKY", 0x041B), ("SLV", 0x0424), ("SQI", 0x041C),
    ("SRB", 0x081A), ("SVE", 0x041D), ("TAM", 0x0449), ("TAT", 0x0444), ("TEL", 0x044A),
    ("THA", 0x041E), ("TIB", 0x0451), ("TRK", 0x041F), ("UKR", 0x0422), ("URD", 0x0420),
    ("USB", 0x042E), ("UYG", 0x0480), ("UZB", 0x0443), ("VIT", 0x042A), ("WEL", 0x0452),
    ("ZHH", 0x0C04), ("ZHS", 0x0804), ("ZHT", 0x0404),
    ("dflt", 0x0409),
];

/// Maps Glyphs language codes to OpenType language IDs
pub fn glyphs_to_opentype_lang_id(lang: &str) -> Option<u16> {
    GLYPHS_TO_OPENTYPE_LANGUAGE_ID
        .binary_search_by_key(&lang, |entry| entry.0)
        .ok()
        .map(|idx| GLYPHS_TO_OPENTYPE_LANGUAGE_ID[idx].1 as u16)
}

impl RawFeature {
    // https://github.com/googlefonts/glyphsLib/blob/24b4d340e4c82948ba121dcfe563c1450a8e69c9/Lib/glyphsLib/builder/features.py#L43
    fn autostr(&self) -> &str {
        match self.automatic {
            Some(1) => "# automatic\n",
            _ => "",
        }
    }

    fn name(&self) -> Result<&str, Error> {
        self.name
            .as_deref()
            .or(self.tag.as_deref())
            .ok_or_else(|| Error::StructuralError(format!("{self:?} missing name and tag")))
    }

    fn disabled(&self) -> bool {
        self.disabled == Some(1)
    }

    /// Some glyphs sources store stylistic set names in the 'note' field
    ///
    /// See the little sidebar item here:
    /// <https://glyphsapp.com/learn/stylistic-sets#g-names-for-stylistic-sets>
    fn legacy_name_record_maybe(&self) -> Option<String> {
        let name = self.notes.as_deref()?.strip_prefix("Name:")?.trim();
        if name.is_empty() {
            None
        } else {
            Some(format!("name 3 1 0x409 \"{name}\";"))
        }
    }

    // https://github.com/googlefonts/glyphsLib/blob/24b4d340e4c82948ba121dcfe563c1450a8e69c9/Lib/glyphsLib/builder/features.py#L134
    fn feature_names(&self) -> String {
        let labels = self
            .labels
            .iter()
            .filter_map(|label| label.to_fea())
            .chain(self.legacy_name_record_maybe())
            .collect::<Vec<_>>()
            .join("\n");
        if labels.is_empty() {
            Default::default()
        } else {
            format!("featureNames {{\n{labels}\n}};\n")
        }
    }

    // https://github.com/googlefonts/glyphsLib/blob/24b4d340e4c82948ba121dcfe563c1450a8e69c9/Lib/glyphsLib/builder/features.py#L90
    fn prefix_to_feature(&self) -> Result<FeatureSnippet, Error> {
        let name = self.name.as_deref().unwrap_or_default();
        let code = format!("# Prefix: {}\n{}{}", name, self.autostr(), self.code);
        Ok(FeatureSnippet::new(code, self.disabled()))
    }

    // https://github.com/googlefonts/glyphsLib/blob/24b4d340e4c82948ba121dcfe563c1450a8e69c9/Lib/glyphsLib/builder/features.py#L101
    fn class_to_feature(&self) -> Result<FeatureSnippet, Error> {
        let name = self.name()?;
        let code = format!(
            "{}{}{name} = [ {}\n];",
            self.autostr(),
            if name.starts_with('@') { "" } else { "@" },
            self.code
        );
        Ok(FeatureSnippet::new(code, self.disabled()))
    }

    // https://github.com/googlefonts/glyphsLib/blob/24b4d340e4c82948ba121dcfe563c1450a8e69c9/Lib/glyphsLib/builder/features.py#L113
    fn raw_feature_to_feature(&self) -> Result<FeatureSnippet, Error> {
        let name = self.name()?;
        let insert_mark = self.insert_mark_if_manual_kern_feature();
        let code = format!(
            "feature {name} {{\n{}{}{}{insert_mark}\n}} {name};",
            self.autostr(),
            self.feature_names(),
            self.code
        );
        Ok(FeatureSnippet::new(code, self.disabled()))
    }

    //https://github.com/googlefonts/glyphsLib/blob/c4db6b981d577f4/Lib/glyphsLib/builder/features.py#L180
    fn insert_mark_if_manual_kern_feature(&self) -> &str {
        if self.name().unwrap_or_default() == "kern"
            && self.automatic != Some(1)
            && !self.code.contains("# Automatic Code")
        {
            "# Automatic Code\n"
        } else {
            ""
        }
    }
}

impl RawNameValue {
    fn to_fea(&self) -> Option<String> {
        if self.value.is_empty() {
            // skip empty names:
            // https://github.com/googlefonts/glyphsLib/blob/c4db6b981d577f/Lib/glyphsLib/builder/features.py#L155
            return None;
        }

        let Some(language_id) = glyphs_to_opentype_lang_id(&self.language) else {
            warn!("Unknown feature label language: {}", self.language);
            return None;
        };
        let name = self.value.replace("\\", "\\005c").replace("\"", "\\0022");
        Some(format!("  name 3 1 0x{language_id:04X} \"{name}\";"))
    }
}

/// <https://github.com/googlefonts/glyphsLib/blob/6f243c1f732ea1092717918d0328f3b5303ffe56/Lib/glyphsLib/classes.py#L220-L249>
fn lookup_class_value(axis_tag: &str, user_class: &str) -> Option<u16> {
    let user_class = match user_class {
        value if !value.is_empty() => {
            let mut value = value.to_ascii_lowercase();
            value.retain(|c| c != ' ');
            value
        }
        _ => String::from(""),
    };
    match (axis_tag, user_class.as_str()) {
        ("wght", "thin") => Some(100),
        ("wght", "extralight" | "ultralight") => Some(200),
        ("wght", "light") => Some(300),
        ("wght", "" | "normal" | "regular") => Some(400),
        ("wght", "medium") => Some(500),
        ("wght", "demibold" | "semibold") => Some(600),
        ("wght", "bold") => Some(700),
        ("wght", "ultrabold" | "extrabold") => Some(800),
        ("wght", "black" | "heavy") => Some(900),
        ("wdth", "ultracondensed") => Some(1),
        ("wdth", "extracondensed") => Some(2),
        ("wdth", "condensed") => Some(3),
        ("wdth", "semicondensed") => Some(4),
        ("wdth", "" | "Medium (normal)") => Some(5),
        ("wdth", "semiexpanded") => Some(6),
        ("wdth", "expanded") => Some(7),
        ("wdth", "extraexpanded") => Some(8),
        ("wdth", "ultraexpanded") => Some(9),
        _ => {
            warn!("Unrecognized ('{axis_tag}', '{user_class}')");
            None
        }
    }
}

fn add_mapping_if_new(
    axis_mappings: &mut BTreeMap<String, AxisUserToDesignMap>,
    axes: &[Axis],
    axis_tag: &str,
    axes_values: &[OrderedFloat<f64>],
    value: f64,
) {
    let Some(idx) = axes.iter().position(|a| a.tag == axis_tag) else {
        return;
    };
    let axis = &axes[idx];
    let Some(design) = axes_values.get(idx) else {
        return;
    };

    axis_mappings
        .entry(axis.name.clone())
        .or_default()
        .add_if_new(value.into(), *design);
}

impl Instance {
    /// Glyphs 2 instances have fun fields.
    ///
    /// Mappings based on
    /// <https://github.com/googlefonts/glyphsLib/blob/6f243c1f732ea1092717918d0328f3b5303ffe56/Lib/glyphsLib/classes.py#L3451>
    fn new(
        axes: &[Axis],
        value: &mut RawInstance,
        masters_have_axis_locations: bool,
    ) -> Result<Self, Error> {
        let active = value.is_active();
        let mut axis_mappings: BTreeMap<String, AxisUserToDesignMap> = BTreeMap::new();

        // Instances can also have "Axis Location" custom parameters, complementing the ones
        // from the masters: https://github.com/googlefonts/fontc/issues/918
        let mut tags_done = BTreeSet::new();
        for axis_location in value
            .custom_parameters
            .take_axis_locations()
            .unwrap_or_default()
        {
            let Some(axis_index) = axis_index(axes, |a| a.name == axis_location.axis_name) else {
                log_once_warn!(
                    "{} instance's 'Axis Location' includes axis {:?} not included in font",
                    value.name,
                    axis_location.axis_name
                );
                continue;
            };
            let user = axis_location.location;
            let design = value.axes_values[axis_index];

            axis_mappings
                .entry(axis_location.axis_name.clone())
                .or_default()
                .add_if_new(user, design);

            tags_done.insert(axes[axis_index].tag.as_str());
        }

        // For non-wght without an "Axis Location" CP, the user
        // location defaults to the design location (identity mapping), matching
        // glyphsLib's AxisDefinition.get_user_loc() behavior:
        // https://github.com/googlefonts/glyphsLib/blob/75c07d42/Lib/glyphsLib/builder/axes.py#L403-L405
        for (i, axis) in axes.iter().enumerate() {
            if tags_done.contains(axis.tag.as_str()) {
                continue;
            }
            if axis.tag == "wght" || axis.tag == "wdth" {
                continue;
            }
            if let Some(&design) = value.axes_values.get(i) {
                axis_mappings
                    .entry(axis.name.clone())
                    .or_default()
                    .add_if_new(design, design);
            }
        }

        // only infer legacy mappings when Axis Locations aren't defined
        if !masters_have_axis_locations && !tags_done.contains("wght") {
            // OS/2 weight_class corresponds to 'wght' axis user-space value
            add_mapping_if_new(
                &mut axis_mappings,
                axes,
                "wght",
                &value.axes_values,
                value
                    .weight_class
                    .as_ref()
                    .map(|v| f64::from_str(v).unwrap())
                    .unwrap_or(400.0),
            );
        }

        if !masters_have_axis_locations && !tags_done.contains("wdth") {
            // OS/2 width_class gets mapped to 'wdth' percent scale, see:
            // https://github.com/googlefonts/glyphsLib/blob/7041311e/Lib/glyphsLib/builder/constants.py#L222
            add_mapping_if_new(
                &mut axis_mappings,
                axes,
                "wdth",
                value.axes_values.as_ref(),
                value
                    .width_class
                    .as_ref()
                    .map(|v| match WidthClass::try_from(u16::from_str(v).unwrap()) {
                        Ok(width_class) => width_class.to_percent(),
                        Err(err) => {
                            warn!("{err}");
                            100.0
                        }
                    })
                    .unwrap_or(100.0),
            );
        }

        Ok(Instance {
            name: value.name.clone(),
            active,
            type_: value
                .type_
                .as_ref()
                .map(|v| v.as_str().into())
                .unwrap_or(InstanceType::Single),
            axis_mappings,
            axes_values: value.axes_values.clone(),
            properties: value.properties.clone(),
            custom_parameters: value.custom_parameters.to_custom_params()?,
        })
    }

    fn family_name(&self) -> Option<&str> {
        self.properties
            .iter()
            .find(|raw| raw.key == "familyNames")
            .and_then(RawName::get_value)
        // glyphsLib here also checks for 'familyName' in customParams, but we
        // don't have that key? Possible that we're ignoring it in the raw params
        // conversion..
        // https://github.com/googlefonts/glyphsLib/blob/c4db6b981d577/Lib/glyphsLib/classes.py#L3271
    }

    /// Get the optional postscript name to use for the `fvar` named instance.
    pub fn postscript_name(&self) -> Option<&str> {
        // https://handbook.glyphsapp.com/custom-parameter-descriptions/
        // https://github.com/googlefonts/glyphsLib/blob/7a8f643a711ffb9d351d037425a7eb60759e6219/Lib/glyphsLib/builder/instances.py#L118-L121
        ["variablePostscriptFontName", "postscriptFontName"]
            .iter()
            .find_map(|key| {
                self.properties
                    .iter()
                    .find(|raw| raw.key == *key)
                    .and_then(RawName::get_value)
            })
    }
}

/// Glyphs appears to use code page identifiers rather than bits
///
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/os2#ulcodepagerange>
fn codepage_range_bit(codepage: u32) -> Result<u32, Error> {
    Ok(match codepage {
        1252 => 0,  // Latin 1
        1250 => 1,  // Latin 2: Eastern Europe
        1251 => 2,  // Cyrillic
        1253 => 3,  // Greek
        1254 => 4,  // Turkish
        1255 => 5,  // Hebrew
        1256 => 6,  // Arabic
        1257 => 7,  // Windows Baltic
        1258 => 8,  // Vietnamese
        874 => 16,  // Thai
        932 => 17,  // JIS/Japan
        936 => 18,  // Chinese: Simplified PRC and Singapore
        949 => 19,  // Korean Wansung
        950 => 20,  // Chinese: Traditional Taiwan and Hong Kong SAR
        1361 => 21, // Korean Johab
        869 => 48,  // IBM Greek
        866 => 49,  // MS-DOS Russian
        865 => 50,  // MS-DOS Nordic
        864 => 51,  // Arabic
        863 => 52,  //	MS-DOS Canadian French
        862 => 53,  //		Hebrew
        861 => 54,  //		MS-DOS Icelandic
        860 => 55,  //		MS-DOS Portuguese
        857 => 56,  //		IBM Turkish
        855 => 57,  //	IBM Cyrillic; primarily Russian
        852 => 58,  //		Latin 2
        775 => 59,  //		MS-DOS Baltic
        737 => 60,  //	Greek; former 437 G
        708 => 61,  //	Arabic; ASMO 708
        850 => 62,  //	WE/Latin 1
        437 => 63,  //	US

        v if v < 64 => v, // an actual bit
        _ => return Err(Error::InvalidCodePage(codepage)),
    })
}

fn update_names(all_names: &mut BTreeMap<String, Vec<(String, String)>>, raw_names: &[RawName]) {
    for name in raw_names {
        // Collect ALL language values into IndexMap to deduplicate (last occurrence wins)
        // while preserving insertion order. This is critical for the fallback behavior:
        // when there's no dflt/default/ENG, the FIRST entry becomes the English fallback,
        // see `return list(self._localized_values.values())[0]` in glyphsLib:
        // https://github.com/googlefonts/glyphsLib/blob/f90e406/Lib/glyphsLib/classes.py#L3162
        let mut lang_map: IndexMap<String, String> = IndexMap::new();

        // Handle old-style single value (v2 format); we treat as dflt
        if let Some(value) = &name.value {
            lang_map.insert("dflt".to_string(), value.clone());
        }

        // Handle new-style localized values (v3 format)
        for (lang, val) in name.localized_values() {
            lang_map.insert(lang.to_string(), val.to_string());
        }

        if !lang_map.is_empty() {
            let values: Vec<_> = lang_map.into_iter().collect();
            all_names.insert(name.key.clone(), values);
        }
    }
}

impl TryFrom<RawFont> for Font {
    type Error = Error;

    fn try_from(mut from: RawFont) -> Result<Self, Self::Error> {
        if from.format_version.is_v2() {
            from.v2_to_v3()?;
        } else {
            // <https://github.com/googlefonts/fontc/issues/1029>
            from.v2_to_v3_names()?;
        }

        // TODO: this should be provided in a manner that allows for overrides
        let glyph_data = GlyphData::default();

        // originally glyphsLib would infer wght/wdth mappings from the instance weight/width classes;
        // then, a new "Axis Location" custom parameter was defined for both masters and instances;
        // when (all) masters use the latter, only explicit "Axis Location" parameters get used from
        // instances, and the legacy heuristic for wght/wdth is disabled, so we need to keep track
        // of this when building instance axis mappings:
        // https://github.com/googlefonts/glyphsLib/blob/7a8f643a/Lib/glyphsLib/builder/axes.py#L225-L227
        let masters_have_axis_locations = from
            .font_master
            .iter()
            .all(|master| master.custom_parameters.contains("Axis Location"));

        let instances: Vec<_> = from
            .instances
            .iter_mut()
            .map(|ri| Instance::new(&from.axes, ri, masters_have_axis_locations))
            .collect::<Result<Vec<_>, Error>>()?;

        // parameters like "Axis Location", "Axis Mappings" and "Variable Font Origin" are
        // handled separately from to_custom_params() and need to be taken before the latter
        // is called, to avoid spurious "unknown custom parameter" warnings
        // https://github.com/googlefonts/fontc/issues/1682
        let axis_mappings = UserToDesignMapping::new(&mut from, &instances);
        let default_master_idx = default_master_idx(&mut from);

        let mut custom_parameters = from.custom_parameters.to_custom_params()?;

        let glyph_order = make_glyph_order(&from.glyphs, custom_parameters.glyph_order.take());

        let mut glyphs = BTreeMap::new();
        for raw_glyph in from.glyphs.into_iter() {
            let mut glyph = raw_glyph.build(from.format_version, &glyph_data)?;
            // v2 bracket layers can only reference a single axis position (on the
            // first axis in the font) so we add empty axis rules for any other
            // axes.
            for layer in glyph.bracket_layers.iter_mut() {
                layer
                    .attributes
                    .axis_rules
                    .resize(from.axes.len(), Default::default());
            }
            glyphs.insert(glyph.name.clone(), glyph);
        }

        let mut features = Vec::new();
        for class in from.classes {
            features.push(class.class_to_feature()?);
        }
        for prefix in from.feature_prefixes {
            features.push(prefix.prefix_to_feature()?);
        }
        for feature in from.features {
            features.push(feature.raw_feature_to_feature()?);
        }

        let units_per_em = from.units_per_em.ok_or(Error::NoUnitsPerEm)?;
        let units_per_em = units_per_em.try_into().map_err(Error::InvalidUpem)?;

        let mut all_names = BTreeMap::new();
        update_names(&mut all_names, &from.properties);
        for instance in &instances {
            if instance.active
                && instance.type_ == InstanceType::Variable
                    // glyphsLib has instance.familyName return the root familyName
                    // if it has no other value; we just unwrap_or_true here
                    // https://github.com/googlefonts/glyphsLib/blob/c4db6b981d577/Lib/glyphsLib/classes.py#L3272
                && instance.family_name().map(|name| name == from.family_name.as_str()).unwrap_or(true)
            {
                update_names(&mut all_names, &instance.properties);
            }
        }
        // Insert RawFont.family_name as the default familyNames where downstream code
        // expects to find it
        let family_names = all_names
            .entry("familyNames".into())
            .or_insert_with(Vec::new);
        family_names.retain(|(lang, _)| lang != "dflt");
        family_names.insert(0, ("dflt".to_string(), from.family_name.clone()));
        // Rename versionString to version
        if let Some(version_values) = all_names.remove("versionString") {
            all_names.insert("version".into(), version_values);
        }

        let metric_names: BTreeMap<usize, String> = from
            .metrics
            .into_iter()
            .enumerate()
            .map(|(idx, metric)| (idx, metric.type_))
            .collect();

        let master_ids_to_names: IndexMap<_, _> = from
            .font_master
            .iter()
            .map(|m| (m.id.clone(), m.name.clone()))
            .collect();

        let masters = from
            .font_master
            .into_iter()
            .map(|m| {
                let custom_parameters = m.custom_parameters.to_custom_params()?;
                let metrics_source_id =
                    resolve_metrics_source_id(&custom_parameters, &master_ids_to_names);
                Ok(FontMaster {
                    id: m.id,
                    name: m.name.unwrap_or_default(),
                    axes_values: m.axes_values,
                    metric_values: m
                        .metric_values
                        .into_iter()
                        .enumerate()
                        .filter_map(|(idx, value)| {
                            metric_names.get(&idx).map(|name| (name.clone(), value))
                        })
                        .fold(BTreeMap::new(), |mut acc, (name, value)| {
                            // only insert a metric if one with the same name hasn't been added
                            // yet; matches glyphsLib's behavior where the first duplicate wins
                            // https://github.com/googlefonts/fontc/issues/1269
                            acc.entry(name).or_insert(value.into());
                            acc
                        }),
                    number_values: from
                        .numbers
                        .iter()
                        .zip(m.number_values.iter())
                        .map(|(k, v)| (k.name.clone(), *v))
                        .collect(),
                    custom_parameters,
                    user_data: m.user_data,
                    metrics_source_id,
                })
            })
            .collect::<Result<Vec<_>, Error>>()?;

        let virtual_masters = custom_parameters.virtual_masters.take().unwrap_or_default();
        Ok(Font {
            units_per_em,
            axes: from.axes,
            masters,
            default_master_idx,
            glyphs,
            glyph_order,
            axis_mappings,
            virtual_masters,
            features,
            all_names,
            instances,
            version_major: from.versionMajor.unwrap_or_default() as i32,
            version_minor: from.versionMinor.unwrap_or_default() as u32,
            date: from.date,
            kerning_ltr: from.kerning_LTR,
            kerning_rtl: from.kerning_RTL,
            custom_parameters,
            user_data: from.user_data,
        })
    }
}

fn preprocess_unparsed_plist(s: &str) -> Cow<'_, str> {
    // Glyphs has a wide variety of unicode definitions, not all of them parser friendly
    // Make unicode always a string, without any wrapping () so we can parse as csv, radix based on format version
    let unicode_re =
        Regex::new(r"(?m)^(?P<prefix>\s*unicode\s*=\s*)[(]?(?P<value>[0-9a-zA-Z,]+)[)]?;\s*$")
            .unwrap();
    unicode_re.replace_all(s, r#"$prefix"$value";"#)
}

fn variable_instance_for<'a>(instances: &'a [Instance], name: &str) -> Option<&'a Instance> {
    instances
        .iter()
        .find(|i| i.active && i.type_ == InstanceType::Variable && i.name == name)
}

impl Font {
    pub fn load_from_string(data: &str) -> Result<Font, Error> {
        let raw_font = RawFont::load_from_string(data)?;
        let mut font = Font::try_from(raw_font)?;
        font.preprocess()?;
        Ok(font)
    }

    pub fn load(glyphs_file: &path::Path) -> Result<Font, Error> {
        let mut font = Self::load_raw(glyphs_file)?;
        font.preprocess()?;
        Ok(font)
    }

    pub fn color_palettes(&self) -> Option<&Vec<Vec<Color>>> {
        self.default_master()
            .custom_parameters
            .color_palettes
            .as_ref()
            .or(self.custom_parameters.color_palettes.as_ref())
    }

    pub fn default_palette(&self) -> Option<&[Color]> {
        self.color_palettes().map(|p| p[0].as_slice())
    }

    fn preprocess(&mut self) -> Result<(), Error> {
        // ensure that glyphs with components that have bracket layers
        // also have bracket layers.
        self.align_bracket_layers();

        // Anchor propagation now happens in fontir as a compilation flag.
        // Preprocessing disabled - anchor propagation now happens in IR.
        // The PROPAGATE_ANCHORS flag controls this behavior.
        // See fontir/src/propagate_anchors.rs and fontir/src/glyph.rs
        //
        // The two-phase GDEF categories approach breaks the circular dependency:
        // - Preliminary categories (computed WITHOUT anchor inspection) are used for propagation
        // - Final categories (computed AFTER propagation WITH anchor inspection) are used for GDEF table
        // if any glyphs reference smart components, convert them to outlines.
        // (see https://glyphsapp.com/learn/smart-components)
        self.instantiate_all_smart_components()?;

        // if any glyphs have corner component hints, insert them into the paths
        self.insert_all_corner_components()
    }

    /// Returns a list of all glyphs, sorted by component depth.
    ///
    /// This is also used for bracket layers.
    pub(crate) fn depth_sorted_composite_glyphs(&self) -> Vec<SmolStr> {
        fontdrasil::util::depth_sorted_composite_glyphs(&self.glyphs)
    }

    /// if a glyph has components that have alternate layers, copy the layer
    /// locations into the glyph.
    ///
    /// This is required to correctly handle bracket glyphs.
    // https://github.com/googlefonts/glyphsLib/blob/c4db6b981d/Lib/glyphsLib/builder/bracket_layers.py#L176
    fn align_bracket_layers(&mut self) {
        // python does this recursively but we'll presort instead
        let todo = self.depth_sorted_composite_glyphs();

        for name in &todo {
            let mut needed = IndexMap::new();
            let glyph = self.glyphs.get(name).unwrap();
            let my_bracket_layers = glyph
                .bracket_layers
                .iter()
                .map(|l| l.bracket_info(&self.axes))
                .collect::<IndexSet<_>>();
            for layer in &glyph.layers {
                for comp in layer.components() {
                    let comp_glyph = self.glyphs.get(&comp.name).unwrap();

                    let comp_bracket_layers = comp_glyph
                        .bracket_layers
                        .iter()
                        .map(|l| l.bracket_info(&self.axes))
                        .collect::<IndexSet<_>>();
                    if comp_bracket_layers != my_bracket_layers {
                        let missing = comp_bracket_layers.difference(&my_bracket_layers);
                        needed
                            .entry(layer.layer_id.clone())
                            .or_insert(IndexSet::new())
                            .extend(missing.cloned());
                    }
                }
            }

            if needed.is_empty() {
                // all good, next glyph
                continue;
            }

            let mut new_layers = Vec::new();
            for (master, needed_brackets) in needed {
                let master_name = self
                    .masters
                    .iter()
                    .find_map(|m| (m.id == master).then_some(m.name.as_str()))
                    .unwrap_or(master.as_str());
                if !my_bracket_layers.is_empty() {
                    log::warn!(
                        "Glyph {name} in master {master_name} has different bracket layers \
                        than its components. This is not supported, so some bracket layers \
                        will not be applied. Consider fixing the source instead."
                    );
                }

                let base_layer = glyph.layers.iter().find(|l| l.layer_id == master).unwrap();
                for box_ in needed_brackets {
                    log::debug!("synthesized layer {box_:?} in master {master_name} for '{name}'",);
                    let new_layer = synthesize_bracket_layer(base_layer, box_, &self.axes);
                    new_layers.push(new_layer);
                }
            }

            // match glyphsLib sorting: https://github.com/googlefonts/glyphsLib/blob/d42d3b15/Lib/glyphsLib/builder/transformations/align_alternate_layers.py#L79
            new_layers.sort_by_cached_key(|l| l.axis_rules_sort_key());

            self.glyphs
                .get_mut(name)
                .unwrap()
                .bracket_layers
                .extend_from_slice(&new_layers);
        }
    }

    // smart components get converted into normal paths before IR.
    // see https://glyphsapp.com/learn/smart-components
    fn instantiate_all_smart_components(&mut self) -> Result<(), Error> {
        // find all the glyphs that include smart components
        let mut glyphs_with_smart_components = self
            .glyphs
            .values()
            .filter(|glyph| {
                glyph
                    .layers
                    .iter()
                    .flat_map(|layer| layer.components())
                    .any(|comp| {
                        // Check the referenced glyph's axes, not the component's
                        // values. Glyphs.app omits 'piece' when a smart component
                        // is newly placed without adjusting any slider (glyphsLib#1134).
                        self.glyphs
                            .get(&comp.name)
                            .map(|ref_glyph| !ref_glyph.smart_component_axes.is_empty())
                            .unwrap_or(false)
                    })
            })
            .cloned()
            .collect::<Vec<_>>();

        if glyphs_with_smart_components.is_empty() {
            return Ok(());
        }
        // then make sure we do everything depth-first, so that if any smart components
        // contain _other_ smart components, those are instantiated first.
        let depth_ranked = self
            .depth_sorted_composite_glyphs()
            .into_iter()
            .enumerate()
            .map(|(rank, name)| (name, rank))
            .collect::<HashMap<_, _>>();

        glyphs_with_smart_components.sort_by_key(|g| depth_ranked.get(&g.name).unwrap());

        // convert the smart components to normal outlines, per-glyph
        for mut glyph in glyphs_with_smart_components {
            for layer in glyph.layers.iter_mut() {
                // Snapshot the glyph's own explicit anchors which represent the designer's
                // intent and must not be overridden by interpolated smart component anchors.
                let explicit_anchor_names: HashSet<SmolStr> =
                    layer.anchors.iter().map(|a| a.name.clone()).collect();
                let old_shapes = std::mem::take(&mut layer.shapes);
                let mut new_shapes = Vec::new();
                for shape in old_shapes {
                    if let Some(comp) = shape.as_component()
                        && let Some(ref_glyph) = self
                            .glyphs
                            .get(&comp.name)
                            .filter(|g| !g.smart_component_axes.is_empty())
                    {
                        log::debug!(
                            "instantiating smart component '{}' for '{}'",
                            comp.name,
                            glyph.name
                        );
                        let instance = crate::smart_components::instantiate_for_layer(
                            layer.master_id(),
                            comp,
                            ref_glyph,
                        )
                        .map_err(|issue| Error::BadSmartComponent {
                            glyph: glyph.name.clone(),
                            component: comp.name.clone(),
                            issue,
                        })?;
                        new_shapes.extend(instance.shapes);
                        // Add anchors from smart component, skipping any that
                        // would override the glyph's explicit anchors.
                        let new_anchors: Vec<_> = instance
                            .anchors
                            .into_iter()
                            .filter(|a| !explicit_anchor_names.contains(&a.name))
                            .collect();
                        // When duplicates exist among smart component anchors,
                        // keep the last one (matching Glyphs.app).
                        let new_names: HashSet<&SmolStr> =
                            new_anchors.iter().map(|a| &a.name).collect();
                        layer.anchors.retain(|a| !new_names.contains(&a.name));
                        layer.anchors.extend(new_anchors);
                    } else {
                        layer.shapes.push(shape);
                    }
                }
                layer.shapes.extend(new_shapes);
            }
            // replace the old glyph with the new, component-free glyph
            self.glyphs.insert(glyph.name.clone(), glyph);
        }
        Ok(())
    }

    // insert corner components into glyphs that have them
    fn insert_all_corner_components(&mut self) -> Result<(), Error> {
        // Find all glyphs that have corner component hints
        let glyphs_with_corners: Vec<_> = self
            .glyphs
            .values()
            .filter(|glyph| {
                glyph
                    .layers
                    .iter()
                    .chain(glyph.bracket_layers.iter())
                    .any(|layer| {
                        layer
                            .hints
                            .iter()
                            .any(|hint| hint.type_ == HintType::Corner)
                    })
            })
            .cloned()
            .collect();

        if glyphs_with_corners.is_empty() {
            return Ok(());
        }

        for mut glyph in glyphs_with_corners {
            for layer in glyph
                .layers
                .iter_mut()
                .chain(glyph.bracket_layers.iter_mut())
            {
                crate::corner_components::insert_corner_components_for_layer(layer, &self.glyphs)
                    .map_err(|issue| Error::BadCornerComponent {
                    glyph: glyph.name.clone(),
                    issue,
                })?;
            }

            self.glyphs.insert(glyph.name.clone(), glyph);
        }

        Ok(())
    }

    // load without propagating anchors or components
    pub(crate) fn load_raw(glyphs_file: impl AsRef<path::Path>) -> Result<Font, Error> {
        RawFont::load(glyphs_file.as_ref()).and_then(Font::try_from)
    }

    pub fn default_master(&self) -> &FontMaster {
        &self.masters[self.default_master_idx]
    }

    /// Whether the given master declares any kerning, LTR or RTL.
    pub fn has_kerns_for_master(&self, master_id: &str) -> bool {
        self.kerning_ltr
            .get(master_id)
            .is_some_and(|k| !k.is_empty())
            || self
                .kerning_rtl
                .get(master_id)
                .is_some_and(|k| !k.is_empty())
    }

    /// <https://handbook.glyphsapp.com/exports/>
    pub fn variable_export_settings(&self, master: &FontMaster) -> Option<&Instance> {
        variable_instance_for(&self.instances, &master.name)
    }

    /// Get the default (English) value for a name property.
    ///
    /// Searches for a value with language "dflt", "default", or "ENG" in the all_names field,
    /// in order of preference: dflt > default > ENG > first value.
    /// Returns None if the property key doesn't exist or has no values.
    pub fn get_default_name(&self, key: &str) -> Option<&str> {
        let values = self.all_names.get(key)?;
        let scale = values.len() as i32;
        values
            .iter()
            .enumerate()
            .map(|(i, (lang, val))| {
                (
                    default_language_score(lang.as_str(), i, scale),
                    val.as_str(),
                )
            })
            .min()
            .map(|(_, val)| val)
    }

    /// Get all localized values for a name property.
    ///
    /// Returns an iterator of (language code, value) tuples. Default languages
    /// ("dflt", "default", "ENG") are excluded.
    pub fn get_localized_names(&self, key: &str) -> impl Iterator<Item = (&str, &str)> + '_ {
        self.all_names
            .get(key)
            .into_iter()
            .flat_map(|v| v.iter())
            .filter(|(lang, _)| !matches!(lang.as_str(), "dflt" | "default" | "ENG"))
            .map(|(lang, val)| (lang.as_str(), val.as_str()))
    }

    /// Iterate over all default name entries.
    ///
    /// Returns an iterator of (property key, default value) tuples.
    /// Uses priority order: dflt > default > ENG > first value.
    pub fn default_names(&self) -> impl Iterator<Item = (&str, &str)> + '_ {
        self.all_names
            .keys()
            .filter_map(|key| self.get_default_name(key).map(|val| (key.as_str(), val)))
    }

    /// Iterate over all localized name entries.
    ///
    /// Returns an iterator of (property key, language code, value) tuples.
    /// Default languages ("dflt", "default", "ENG") are excluded.
    pub fn localized_names(&self) -> impl Iterator<Item = (&str, &str, &str)> + '_ {
        self.all_names.iter().flat_map(|(key, values)| {
            values
                .iter()
                .filter(|(lang, _)| !matches!(lang.as_str(), "dflt" | "default" | "ENG"))
                .map(move |(lang, val)| (key.as_str(), lang.as_str(), val.as_str()))
        })
    }

    pub fn vendor_id(&self) -> Option<&str> {
        self.get_default_name("vendorID")
    }
}

//https://github.com/googlefonts/glyphsLib/blob/c4db6b981d/Lib/glyphsLib/builder/bracket_layers.py#L258
fn synthesize_bracket_layer(
    old_layer: &Layer,
    box_: BTreeMap<String, (Option<i64>, Option<i64>)>,
    axes: &[Axis],
) -> Layer {
    let mut new_layer = old_layer.clone();
    new_layer.associated_master_id = Some(std::mem::take(&mut new_layer.layer_id));
    new_layer.attributes.axis_rules = axes
        .iter()
        .map(|axis| {
            if let Some((min, max)) = box_.get(&axis.tag) {
                AxisRule {
                    min: min.map(|x| x as _),
                    max: max.map(|x| x as _),
                }
            } else {
                Default::default()
            }
        })
        .collect();

    new_layer
}

/// Convert [kurbo::Point] to this for eq and hash/
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct PointForEqAndHash {
    x: OrderedFloat<f64>,
    y: OrderedFloat<f64>,
}

impl PointForEqAndHash {
    fn new(point: Point) -> PointForEqAndHash {
        point.into()
    }
}

impl From<Point> for PointForEqAndHash {
    fn from(value: Point) -> Self {
        PointForEqAndHash {
            x: value.x.into(),
            y: value.y.into(),
        }
    }
}

/// Convert [kurbo::Affine] to this for eq and hash/
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct AffineForEqAndHash([OrderedFloat<f64>; 6]);

impl From<Affine> for AffineForEqAndHash {
    fn from(value: Affine) -> Self {
        Self(value.as_coeffs().map(|coeff| coeff.into()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Font, FontMaster, Node, Shape, plist::FromPlist, smart_components};
    use std::{
        collections::{BTreeMap, BTreeSet, HashSet},
        path::{Path, PathBuf},
    };

    use ordered_float::OrderedFloat;

    use pretty_assertions::assert_eq;

    use kurbo::{Affine, Point, Rect, Vec2};

    use rstest::rstest;
    use smol_str::ToSmolStr;

    fn testdata_dir() -> PathBuf {
        // working dir varies CLI vs VSCode
        let mut dir = Path::new("../resources/testdata");
        if !dir.is_dir() {
            dir = Path::new("./resources/testdata");
        }
        assert!(dir.is_dir());
        dir.to_path_buf()
    }

    fn glyphs2_dir() -> PathBuf {
        testdata_dir().join("glyphs2")
    }

    fn glyphs3_dir() -> PathBuf {
        testdata_dir().join("glyphs3")
    }

    fn round(transform: Affine, digits: u8) -> Affine {
        let m = 10f64.powi(digits as i32);
        let mut coeffs = transform.as_coeffs();
        for c in coeffs.iter_mut() {
            *c = (*c * m).round() / m;
        }
        Affine::new(coeffs)
    }

    #[test]
    fn v2_format_version() {
        let v2_font = glyphs2_dir().join("Mono.glyphs");
        let as_str = std::fs::read_to_string(&v2_font).unwrap();
        assert!(!as_str.contains(".formatVersion"), "only exists in v3");
        let font = RawFont::load(&v2_font).unwrap();
        // falls back to default
        assert_eq!(font.format_version, FormatVersion::V2);
    }

    #[test]
    fn v3_format_version() {
        let v3_font = glyphs3_dir().join("MasterNames.glyphs");
        let as_str = std::fs::read_to_string(&v3_font).unwrap();
        assert!(as_str.contains(".formatVersion"), "exists in v3");
        let font = RawFont::load(&v3_font).unwrap();
        // falls back to default
        assert_eq!(font.format_version, FormatVersion::V3);
    }

    #[test]
    fn test_glyphs3_node() {
        let node: Node = Node::parse_plist("(354, 183, l)").unwrap();
        assert_eq!(
            Node {
                node_type: crate::NodeType::Line,
                pt: super::Point { x: 354.0, y: 183.0 }
            },
            node
        );
    }

    #[test]
    fn test_glyphs2_node() {
        let node: Node = Node::parse_plist("\"354 183 LINE\"").unwrap();
        assert_eq!(
            Node {
                node_type: crate::NodeType::Line,
                pt: super::Point { x: 354.0, y: 183.0 }
            },
            node
        );
    }

    #[test]
    fn test_glyphs3_node_userdata() {
        let node = Node::parse_plist("(354, 183, l,{name = hr00;})").unwrap();
        assert_eq!(
            Node {
                node_type: crate::NodeType::Line,
                pt: super::Point { x: 354.0, y: 183.0 }
            },
            node
        );
    }

    #[test]
    fn test_glyphs2_node_userdata() {
        let node = Node::parse_plist("\"354 183 LINE {name=duck}\"").unwrap();
        assert_eq!(
            Node {
                node_type: crate::NodeType::Line,
                pt: super::Point { x: 354.0, y: 183.0 }
            },
            node
        );
    }

    // unquoted infinity likes to parse as a float which is suboptimal for glyph names. Survive.
    // Observed on Work Sans and Lexend.
    #[test]
    fn survive_unquoted_infinity() {
        // Read a minimal glyphs file that reproduces the error
        Font::load(&glyphs3_dir().join("infinity.glyphs")).unwrap();
    }

    fn assert_wght_var_metrics(font: &Font) {
        let default_master = font.default_master();
        assert_eq!(737.0, default_master.ascender().unwrap());
        assert_eq!(-42.0, default_master.descender().unwrap());
    }

    #[test]
    fn read_wght_var_2_metrics() {
        assert_wght_var_metrics(&Font::load(&glyphs2_dir().join("WghtVar.glyphs")).unwrap());
    }

    #[test]
    fn read_wght_var_3_metrics() {
        assert_wght_var_metrics(&Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap());
    }

    /// So far we don't have any package-only examples
    enum LoadCompare {
        Glyphs,
        GlyphsAndPackage,
    }

    /// Asserts that two Font structs are equal, excluding localized name entries.
    /// This is useful for comparing v2 and v3 Glyphs files where localized names
    /// may differ due to format changes. Only default (dflt/default/ENG) names are compared.
    fn assert_fonts_equal_sans_localized_names(f1: &Font, f2: &Font, context: &str) {
        let mut f1_clone = f1.clone();
        let mut f2_clone = f2.clone();
        // Filter all_names to keep only default entries (dflt/default/ENG)
        for all_names in [&mut f1_clone.all_names, &mut f2_clone.all_names] {
            for values in all_names.values_mut() {
                values.retain(|(lang, _)| matches!(lang.as_str(), "dflt" | "default" | "ENG"));
            }
        }
        assert_eq!(f1_clone, f2_clone, "{context}");
    }

    /// Asserts that two Font structs are equal, including localized name entries.
    /// This is useful for comparing two v3 Glyphs files where all fields should match.
    fn assert_fonts_equal(f1: &Font, f2: &Font, context: &str) {
        assert_eq!(f1, f2, "{context}");
    }

    fn assert_load_v2_matches_load_v3(name: &str, compare: LoadCompare) {
        let has_package = matches!(compare, LoadCompare::GlyphsAndPackage);
        let _ = tracing_subscriber::fmt().with_test_writer().try_init();
        let filename = format!("{name}.glyphs");
        let pkgname = format!("{name}.glyphspackage");
        let g2_file = glyphs2_dir().join(filename.clone());
        let g3_file = glyphs3_dir().join(filename.clone());
        let g2 = Font::load(&g2_file).unwrap();
        let g3 = Font::load(&g3_file).unwrap();

        // Handy if troubleshooting
        std::fs::write("/tmp/g2.glyphs.txt", format!("{g2:#?}")).unwrap();
        std::fs::write("/tmp/g3.glyphs.txt", format!("{g3:#?}")).unwrap();

        assert_fonts_equal_sans_localized_names(
            &g2,
            &g3,
            &format!("g2 vs g3: {g2_file:?} vs {g3_file:?}"),
        );

        if has_package {
            let g2_pkg = Font::load(&glyphs2_dir().join(pkgname.clone())).unwrap();
            let g3_pkg = Font::load(&glyphs3_dir().join(pkgname.clone())).unwrap();

            std::fs::write("/tmp/g2.glyphspackage.txt", format!("{g2_pkg:#?}")).unwrap();
            std::fs::write("/tmp/g3.glyphspackage.txt", format!("{g3_pkg:#?}")).unwrap();

            assert_fonts_equal_sans_localized_names(&g2_pkg, &g3_pkg, "g2_pkg vs g3_pkg");
            assert_fonts_equal(&g3_pkg, &g3, "g3_pkg vs g3");
        }
    }

    #[test]
    fn read_wght_var_2_and_3() {
        assert_load_v2_matches_load_v3("WghtVar", LoadCompare::GlyphsAndPackage);
    }

    #[test]
    fn read_wght_var_avar_2_and_3() {
        assert_load_v2_matches_load_v3("WghtVar_Avar", LoadCompare::GlyphsAndPackage);
    }

    #[test]
    fn read_wght_var_instances_2_and_3() {
        assert_load_v2_matches_load_v3("WghtVar_Instances", LoadCompare::GlyphsAndPackage);
    }

    #[test]
    fn read_wght_var_os2_2_and_3() {
        assert_load_v2_matches_load_v3("WghtVar_OS2", LoadCompare::GlyphsAndPackage);
    }

    #[test]
    fn read_wght_var_anchors_2_and_3() {
        assert_load_v2_matches_load_v3("WghtVar_Anchors", LoadCompare::GlyphsAndPackage);
    }

    #[test]
    fn read_infinity_2_and_3() {
        assert_load_v2_matches_load_v3("infinity", LoadCompare::GlyphsAndPackage);
    }

    #[test]
    fn read_wght_var_noexport_2_and_3() {
        assert_load_v2_matches_load_v3("WghtVar_NoExport", LoadCompare::Glyphs);
    }

    #[test]
    fn read_master_names_2_and_3() {
        assert_load_v2_matches_load_v3("MasterNames", LoadCompare::Glyphs);
    }

    #[test]
    fn read_master_names_with_italic_2_and_3() {
        assert_load_v2_matches_load_v3("MasterNames-Italic", LoadCompare::Glyphs);
    }

    fn only_shape_in_only_layer<'a>(font: &'a Font, glyph_name: &str) -> &'a Shape {
        let glyph = font.glyphs.get(glyph_name).unwrap();
        assert_eq!(1, glyph.layers.len());
        assert_eq!(1, glyph.layers[0].shapes.len());
        &glyph.layers[0].shapes[0]
    }

    fn check_v2_to_v3_transform(glyphs_file: &str, glyph_name: &str, expected: Affine) {
        let g2 = Font::load(&glyphs2_dir().join(glyphs_file)).unwrap();
        let g3 = Font::load(&glyphs3_dir().join(glyphs_file)).unwrap();

        // We're exclusively interested in the transform
        let g2_shape = only_shape_in_only_layer(&g2, glyph_name);
        let g3_shape = only_shape_in_only_layer(&g3, glyph_name);

        let Shape::Component(g2_shape) = g2_shape else {
            panic!("{g2_shape:?} should be a component");
        };
        let Shape::Component(g3_shape) = g3_shape else {
            panic!("{g3_shape:?} should be a component");
        };

        assert_eq!(expected, round(g2_shape.transform, 4));
        assert_eq!(expected, round(g3_shape.transform, 4));
    }

    #[test]
    fn read_transformed_component_2_and_3_uniform_scale() {
        let expected = Affine::new([1.6655, 1.1611, -1.1611, 1.6655, -233.0, -129.0]);
        check_v2_to_v3_transform("Component.glyphs", "comma", expected);
    }

    #[test]
    fn read_transformed_component_2_and_3_nonuniform_scale() {
        let expected = Affine::new([0.8452, 0.5892, -1.1611, 1.6655, -233.0, -129.0]);
        check_v2_to_v3_transform("Component.glyphs", "non_uniform_scale", expected);
    }

    /// A slanted component must load the same from a Glyphs 2 matrix and Glyphs 3 fields.
    ///
    /// Both fixture files were written by Glyphs 3.4.1 (3436) from the same in-memory
    /// font: v3 stores angle=20, scale=(0.8,0.8), slant=(10,0), while v2 stores the
    /// equivalent raw `transform` matrix.
    ///
    /// The rotation makes the case discriminate slant-then-rotate from rotate-then-slant.
    #[test]
    fn read_component_slant_2_and_3() {
        let expected = Affine::new([0.8, 0.2736, -0.1411, 0.7518, 0.0, 0.0]);
        check_v2_to_v3_transform("ComponentSlant.glyphs", "slanted_square", expected);
    }

    /// Parse a Glyphs 3 component plist fragment and return its transform.
    fn component_transform(shape_plist: &str) -> Affine {
        let shape: Shape = RawShape::parse_plist(shape_plist)
            .unwrap()
            .try_into()
            .unwrap();
        let Shape::Component(component) = shape else {
            panic!("{shape:?} should be a component");
        };
        component.transform
    }

    #[test]
    fn parse_component_slant_key() {
        let raw = RawShape::parse_plist(
            r#"
{
ref = A;
pos = (5,21);
scale = (1,0.94);
slant = (-0.7,0);
}
        "#,
        )
        .unwrap();
        assert_eq!(raw.slant, vec![-0.7, 0.0]);
    }

    // Slant is in degrees; the shear factor is its tangent. The component transform is
    // translate * slant * rotate * scale, i.e. a point is scaled, then rotated, then
    // slanted, then translated.
    //
    // Provenance of the expected coefficients: the first tuple comes from the linked
    // glyphsLib#1047 issue thread; the rotated tuple is backed by a Glyphs 3.4.1 round-trip
    // (see the ComponentSlant fixture pair exercised by read_component_slant_2_and_3).
    #[test]
    fn read_component_slant_x_with_scale() {
        let transform = component_transform(
            r#"
{
ref = A;
pos = (5,21);
scale = (1,0.94);
slant = (-0.7,0);
}
        "#,
        );
        assert_eq!(
            round(transform, 9),
            round(
                Affine::new([1.0, 0.0, -0.011484837902484654, 0.94, 5.0, 21.0]),
                9
            )
        );
    }

    #[test]
    fn read_component_slant_with_rotation_and_scale() {
        let transform = component_transform(
            r#"
{
ref = A;
angle = 20;
scale = (0.8,0.8);
slant = (10,0);
}
        "#,
        );
        assert_eq!(
            round(transform, 9),
            round(
                Affine::new([
                    0.8,
                    0.273616114660535,
                    -0.14106158456677195,
                    0.7517540966287268,
                    0.0,
                    0.0
                ]),
                9
            )
        );
    }

    /// Vertical slant lands in the 'b' coefficient as tan(degrees).
    ///
    /// Unlike the two cases above this expectation is derived from the documented
    /// conversion rather than from a Glyphs.app-produced reference file.
    #[test]
    fn read_component_slant_y() {
        let transform = component_transform(
            r#"
{
ref = A;
slant = (0,5);
}
        "#,
        );
        assert_eq!(
            round(transform, 9),
            round(
                Affine::new([1.0, 5f64.to_radians().tan(), 0.0, 1.0, 0.0, 0.0]),
                9
            )
        );
    }

    #[test]
    fn reject_malformed_component_slant() {
        let raw = RawShape::parse_plist(
            r#"
{
ref = A;
slant = (10);
}
        "#,
        )
        .unwrap();
        let result = Shape::try_from(raw);
        assert!(
            matches!(&result, Err(Error::StructuralError(msg)) if msg.starts_with("Bad slant")),
            "{result:?}"
        );
    }

    #[test]
    fn upgrade_2_to_3_with_implicit_axes() {
        let font = Font::load(&glyphs2_dir().join("WghtVar_ImplicitAxes.glyphs")).unwrap();
        assert_eq!(
            font.axes
                .iter()
                .map(|a| a.tag.as_str())
                .collect::<Vec<&str>>(),
            vec!["wght", "wdth", "XXXX"]
        );
    }

    #[test]
    fn understand_v2_style_unquoted_hex_unicode() {
        let font = Font::load(&glyphs2_dir().join("Unicode-UnquotedHex.glyphs")).unwrap();
        assert_eq!(
            BTreeSet::from([0x1234]),
            font.glyphs.get("name").unwrap().unicode,
        );
        assert_eq!(1, font.glyphs.len());
    }

    #[test]
    fn understand_v2_style_quoted_hex_unicode_sequence() {
        let font = Font::load(&glyphs2_dir().join("Unicode-QuotedHexSequence.glyphs")).unwrap();
        assert_eq!(
            BTreeSet::from([0x2044, 0x200D, 0x2215]),
            font.glyphs.get("name").unwrap().unicode,
        );
        assert_eq!(1, font.glyphs.len());
    }

    #[test]
    fn understand_v3_style_unquoted_decimal_unicode() {
        let font = Font::load(&glyphs3_dir().join("Unicode-UnquotedDec.glyphs")).unwrap();
        assert_eq!(
            BTreeSet::from([182]),
            font.glyphs.get("name").unwrap().unicode
        );
        assert_eq!(1, font.glyphs.len());
    }

    #[test]
    fn understand_v3_style_unquoted_decimal_unicode_sequence() {
        let font = Font::load(&glyphs3_dir().join("Unicode-UnquotedDecSequence.glyphs")).unwrap();
        assert_eq!(
            BTreeSet::from([1619, 1764]),
            font.glyphs.get("name").unwrap().unicode,
        );
        assert_eq!(1, font.glyphs.len());
    }

    #[test]
    fn axes_not_hidden() {
        let font = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
        assert_eq!(
            font.axes.iter().map(|a| a.hidden).collect::<Vec<_>>(),
            vec![None]
        );
    }

    #[test]
    fn axis_hidden() {
        let font = Font::load(&glyphs3_dir().join("WghtVar_3master_CustomOrigin.glyphs")).unwrap();
        assert_eq!(
            font.axes.iter().map(|a| a.hidden).collect::<Vec<_>>(),
            vec![Some(true)]
        );
    }

    #[test]
    fn vf_origin_single_axis_default() {
        let font = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
        assert_eq!(0, font.default_master_idx);
    }

    #[test]
    fn vf_origin_multi_axis_default() {
        let font = Font::load(&glyphs2_dir().join("WghtVar_ImplicitAxes.glyphs")).unwrap();
        assert_eq!(0, font.default_master_idx);
    }

    #[test]
    fn vf_origin_multi_axis_custom() {
        let font = Font::load(&glyphs3_dir().join("WghtVar_3master_CustomOrigin.glyphs")).unwrap();
        assert_eq!(2, font.default_master_idx);
    }

    #[test]
    fn vf_origin_unquoted_string() {
        // the 'Variable Font Origin' custom parameter has the value `m01`,
        // un un-quoted plist string, which happens to be the default master.id
        // that Glyphs.app assigns to the predefined 'Regular' master that any
        // "New Font" comes with when it is first crated.
        // We just test that we do not crash attempting to parse the unquoted
        // string as an integer.
        let font = Font::load(&glyphs3_dir().join("CustomOrigin.glyphs")).unwrap();
        assert_eq!(1, font.default_master_idx);
    }

    #[rstest]
    #[case::base_style_without_regular(
        &[
            "Expanded Thin Italic",
            "Expanded Italic",
            "Expanded Bold Italic",
        ],
        "Expanded Italic"  // is common and exactly matches [1]
    )]
    #[case::base_style_contains_regular(
        &[
            "Regular Foo Bar",
            "Regular Foo Baz",
            "Regular Foo",
        ],
        "Regular Foo" // is common and exactly matches [2]
    )]
    #[case::base_style_with_regular_omitted(
        &[
            "Condensed Thin",
            "Condensed Light",
            "Condensed Regular",
        ],
        // "Condensed" is common and matches "Condensed Regular" when "Regular" is ignored
        "Condensed Regular"
    )]
    // "" is common and matches "Regular when "Regular" is ignored
    #[case::default_to_regular(
        &["Thin", "Light", "Regular", "Medium", "Bold"],
        "Regular"
    )]
    // "" is common, nothing matches, just take the first
    #[case::default_to_first(&["Foo", "Bar", "Baz"], "Foo")]
    fn find_default_master(#[case] master_names: &[&str], #[case] expected: &str) {
        let mut font = RawFont::default();
        for name in master_names {
            let master = RawFontMaster {
                name: Some(name.to_string()),
                ..Default::default()
            };
            font.font_master.push(master);
        }

        let idx = default_master_idx(&mut font);

        assert_eq!(expected, font.font_master[idx].name.as_deref().unwrap());
    }

    #[test]
    fn glyph_order_default_is_file_order() {
        let font = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
        assert_eq!(
            vec![
                "space",
                "exclam",
                "hyphen",
                "bracketleft",
                "bracketright",
                "manual-component"
            ],
            font.glyph_order
        );
    }

    #[test]
    fn glyph_order_override_obeyed() {
        let _ = tracing_subscriber::fmt().with_test_writer().try_init();
        let font = Font::load(&glyphs3_dir().join("WghtVar_GlyphOrder.glyphs")).unwrap();
        assert_eq!(vec!["hyphen", "space", "exclam"], font.glyph_order);
    }

    #[test]
    fn loads_global_axis_mappings_from_glyphs2() {
        let font = Font::load(&glyphs2_dir().join("OpszWghtVar_AxisMappings.glyphs")).unwrap();

        // Did you load the mappings? DID YOU?!
        assert_eq!(
            UserToDesignMapping(BTreeMap::from([
                (
                    "Optical Size".into(),
                    AxisUserToDesignMap(vec![
                        (OrderedFloat(12.0), OrderedFloat(12.0)),
                        (OrderedFloat(72.0), OrderedFloat(72.0))
                    ])
                ),
                (
                    "Weight".into(),
                    AxisUserToDesignMap(vec![
                        (OrderedFloat(100.0), OrderedFloat(40.0)),
                        (OrderedFloat(200.0), OrderedFloat(46.0)),
                        (OrderedFloat(300.0), OrderedFloat(51.0)),
                        (OrderedFloat(400.0), OrderedFloat(57.0)),
                        (OrderedFloat(450.0), OrderedFloat(57.0)), // duplicate value is valid
                        (OrderedFloat(500.0), OrderedFloat(62.0)),
                        (OrderedFloat(600.0), OrderedFloat(68.0)),
                        (OrderedFloat(700.0), OrderedFloat(73.0)),
                    ])
                ),
            ])),
            font.axis_mappings
        );
    }

    #[test]
    fn loads_global_axis_locations_from_glyphs3() {
        let font = Font::load(&glyphs3_dir().join("WghtVar_AxisLocation.glyphs")).unwrap();

        // Did you load the mappings? DID YOU?!
        assert_eq!(
            UserToDesignMapping(BTreeMap::from([(
                "Weight".into(),
                AxisUserToDesignMap(vec![
                    (OrderedFloat(400.0), OrderedFloat(0.0)),
                    (OrderedFloat(500.0), OrderedFloat(8.0)),
                    (OrderedFloat(700.0), OrderedFloat(10.0)),
                    // this comes from the 'SemiBold' instance's 'Axis Location'
                    (OrderedFloat(600.0), OrderedFloat(8.5)),
                    // the 'SemiMedium' instance contains no explict 'Axis Location' so
                    // it doesn't show up (implicit mappings are ignored in this case)
                    // (OrderedFloat(450.0), OrderedFloat(4.0)),
                ])
            ),])),
            font.axis_mappings
        );
    }

    #[test]
    fn loads_global_axis_mappings_from_instances_wght_glyphs3() {
        let font = Font::load(&glyphs3_dir().join("WghtVar_Avar_From_Instances.glyphs")).unwrap();

        let wght_idx = font.axes.iter().position(|a| a.tag == "wght").unwrap();
        assert_eq!(
            vec![60.0, 80.0, 132.0],
            font.masters
                .iter()
                .map(|m| m.axes_values[wght_idx].into_inner())
                .collect::<Vec<_>>()
        );
        // the default master is the 'Bold' in this test font
        assert_eq!(
            (132.0, 2),
            (
                font.default_master().axes_values[wght_idx].into_inner(),
                font.default_master_idx
            )
        );

        // Did you load the mappings? DID YOU?!
        assert_eq!(
            UserToDesignMapping(BTreeMap::from([(
                "Weight".into(),
                AxisUserToDesignMap(vec![
                    (OrderedFloat(300.0), OrderedFloat(60.0)),
                    // we expect a map 400:80 here, even though the 'Regular' instance's
                    // Weight Class property is omitted in the .glyphs source because it
                    // is equal to its default value (400):
                    // https://github.com/googlefonts/fontc/issues/905
                    (OrderedFloat(400.0), OrderedFloat(80.0)),
                    (OrderedFloat(500.0), OrderedFloat(100.0)),
                    (OrderedFloat(700.0), OrderedFloat(132.0)),
                ])
            ),])),
            font.axis_mappings
        );
    }

    #[test]
    fn empty_axis_mappings_falls_back_to_instances() {
        // An empty "Axis Mappings" custom parameter ({}) should be treated as absent,
        // falling back to instance-based mappings. Regression test for
        // https://github.com/googlefonts/fontc/issues/1830
        let base_path = glyphs3_dir().join("WghtVar_Avar_From_Instances.glyphs");
        let raw = std::fs::read_to_string(&base_path).unwrap();
        // Inject an empty Axis Mappings param into the existing customParameters
        let raw = raw.replace(
            "customParameters = (\n{",
            "customParameters = (\n{\nname = \"Axis Mappings\";\nvalue = {};\n},\n{",
        );
        let font = Font::load_from_string(&raw).unwrap();

        // Should produce the same instance-based mappings as the unmodified font
        let font_without = Font::load(&base_path).unwrap();
        assert_eq!(font_without.axis_mappings, font.axis_mappings);
    }

    #[test]
    fn custom_axis_instance_without_axis_location_gets_identity_mapping() {
        // A font with a custom axis (YEAR) where instances lack "Axis Location" CPs
        // should get identity mappings (user = design) for that axis.
        // Regression test for dancoull/ClimateCrisis crash.
        let font = Font::load(&glyphs3_dir().join("CustomAxisNoAxisLocation.glyphs")).unwrap();

        assert_eq!(
            UserToDesignMapping(BTreeMap::from([(
                "Year".into(),
                AxisUserToDesignMap(vec![
                    (OrderedFloat(1979.0), OrderedFloat(1979.0)),
                    (OrderedFloat(2020.0), OrderedFloat(2020.0)),
                    (OrderedFloat(2050.0), OrderedFloat(2050.0)),
                ])
            )])),
            font.axis_mappings
        );
    }

    #[test]
    fn loads_global_axis_mappings_from_instances_wdth_glyphs3() {
        let font = Font::load(&glyphs3_dir().join("WdthVar.glyphs")).unwrap();

        assert_eq!(font.axes.len(), 1);
        assert_eq!(font.axes[0].tag, "wdth");
        assert_eq!(
            vec![22.0, 62.0],
            font.masters
                .iter()
                .map(|m| m.axes_values[0].into_inner())
                .collect::<Vec<_>>()
        );
        // the default master is the 'Condensed' in this test font
        assert_eq!(
            (22.0, 0),
            (
                font.default_master().axes_values[0].into_inner(),
                font.default_master_idx
            )
        );
        // Did you load the mappings? DID YOU?!
        assert_eq!(
            UserToDesignMapping(BTreeMap::from([(
                "Width".into(),
                AxisUserToDesignMap(vec![
                    // The "1: Ultra-condensed" instance width class corresponds to a
                    // `wdth` of 50 (user-space), in turn mapped to 22 (design-space).
                    (OrderedFloat(50.0), OrderedFloat(22.0)),
                    // We expect a map 100:41 here, even though the 'Regular' instance's
                    // Width Class property is omitted in the .glyphs source because it
                    // is equal to its default value "5: Medium (normal)" (or wdth=100):
                    // https://github.com/googlefonts/fontc/issues/905
                    (OrderedFloat(100.0), OrderedFloat(41.0)),
                    // The "9: Ultra-expanded" instance width class corresponds to a
                    // `wdth` of 200 (user-space), in turn mapped to 62 (design-space).
                    (OrderedFloat(200.0), OrderedFloat(62.0)),
                ])
            ),])),
            font.axis_mappings
        );
    }

    #[test]
    fn fea_for_class() {
        let font = Font::load(&glyphs2_dir().join("Fea_Class.glyphs")).unwrap();
        assert_eq!(
            vec![
                concat!("# automatic\n", "@Uppercase = [ A B C\n", "];",),
                concat!("@Lowercase = [ a b c\n", "];",),
            ],
            font.features
                .iter()
                .filter_map(|f| f.str_if_enabled())
                .collect::<Vec<_>>()
        )
    }

    #[test]
    fn fea_for_prefix() {
        let font = Font::load(&glyphs2_dir().join("Fea_Prefix.glyphs")).unwrap();
        assert_eq!(
            vec![
                "\
# Prefix: Languagesystems
# automatic
languagesystem DFLT dflt;

languagesystem latn dflt;
and more;
",
                "# Prefix: \n# automatic\nthanks for all the fish;",
            ],
            font.features
                .iter()
                .filter_map(|f| f.str_if_enabled())
                .collect::<Vec<_>>()
        )
    }

    #[test]
    fn fea_for_feature() {
        let font = Font::load(&glyphs2_dir().join("Fea_Feature.glyphs")).unwrap();
        assert_eq!(
            vec![
                "\
feature aalt {
feature locl;
feature tnum;
} aalt;",
                "\
feature ccmp {
# automatic
lookup ccmp_Other_2 {
  sub @Markscomb' @MarkscombCase by @MarkscombCase;
  sub @MarkscombCase @Markscomb' by @MarkscombCase;
} ccmp_Other_2;

etc;
} ccmp;",
            ],
            font.features
                .iter()
                .filter_map(|f| f.str_if_enabled())
                .collect::<Vec<_>>()
        )
    }

    #[test]
    fn fea_order() {
        let font = Font::load(&glyphs2_dir().join("Fea_Order.glyphs")).unwrap();
        assert_eq!(
            vec![
                "@class_first = [ meh\n];",
                "# Prefix: second\nmeh",
                "feature third {\nmeh\n} third;",
            ],
            font.features
                .iter()
                .filter_map(|f| f.str_if_enabled())
                .collect::<Vec<_>>()
        )
    }

    #[test]
    fn fea_labels() {
        let font = Font::load(&glyphs3_dir().join("Fea_Labels.glyphs")).unwrap();
        assert_eq!(
            vec![
                concat!(
                    "feature ss01 {\n",
                    "# automatic\n",
                    "featureNames {\n",
                    "  name 3 1 0x0409 \"Test 1\";\n",
                    "  name 3 1 0x0C01 \"اختبار ١\";\n",
                    "};\n",
                    "sub a by a.ss01;\n",
                    "sub b by b.ss01;\n\n",
                    "} ss01;",
                ),
                concat!(
                    "feature ss02 {\n",
                    "featureNames {\n",
                    "  name 3 1 0x0409 \"Test 2\";\n",
                    "};\n",
                    "sub c by c.alt;\n",
                    "} ss02;",
                ),
            ],
            font.features
                .iter()
                .filter_map(|f| f.str_if_enabled())
                .collect::<Vec<_>>()
        )
    }

    #[test]
    fn tags_make_excellent_names() {
        let raw = RawFeature {
            tag: Some("aalt".to_string()),
            code: "blah".to_string(),
            ..Default::default()
        };
        assert_eq!("aalt", raw.name().unwrap());
    }

    #[test]
    fn manual_kern_always_gets_insert_mark() {
        let feature = RawFeature {
            tag: Some("kern".into()),
            ..Default::default()
        };

        assert!(
            feature
                .raw_feature_to_feature()
                .unwrap()
                .content
                .contains("# Automatic Code")
        )
    }

    #[test]
    fn but_automatic_does_not() {
        let feature = RawFeature {
            tag: Some("kern".into()),
            automatic: Some(1),
            ..Default::default()
        };

        assert!(
            !feature
                .raw_feature_to_feature()
                .unwrap()
                .content
                .contains("# Automatic Code")
        )
    }

    #[test]
    fn v2_to_v3_simple_names() {
        let v2 = Font::load(&glyphs2_dir().join("WghtVar.glyphs")).unwrap();
        let v3 = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
        // Compare only default names - v2 and v3 may have different localized entries
        let v2_defaults: BTreeMap<_, _> = v2.default_names().collect();
        let v3_defaults: BTreeMap<_, _> = v3.default_names().collect();
        assert_eq!(v3_defaults, v2_defaults);
    }

    #[test]
    fn v2_to_v3_more_names() {
        let v2 = Font::load(&glyphs2_dir().join("TheBestNames.glyphs")).unwrap();
        let v3 = Font::load(&glyphs3_dir().join("TheBestNames.glyphs")).unwrap();

        // V2 root-level fields (designer, manufacturer, copyright, etc.) are converted
        // to properties format by v2_to_v3_names(), so v2 and v3 should have identical defaults
        let v2_defaults: BTreeMap<_, _> = v2.default_names().collect();
        let v3_defaults: BTreeMap<_, _> = v3.default_names().collect();

        assert_eq!(v2_defaults, v3_defaults);
    }

    #[test]
    fn v2_long_param_names() {
        let v2 = Font::load(&glyphs2_dir().join("LongParamNames.glyphs")).unwrap();
        assert_eq!(v2.get_default_name("vendorID"), Some("DERP"));
        assert_eq!(
            v2.get_default_name("descriptions"),
            Some("legacy description")
        );
        assert_eq!(
            v2.get_default_name("licenseURL"),
            Some("www.example.com/legacy")
        );
        assert_eq!(v2.get_default_name("version"), Some("legacy version"));
        assert_eq!(v2.get_default_name("licenses"), Some("legacy license"));
        assert_eq!(v2.get_default_name("uniqueID"), Some("legacy unique id"));
        assert_eq!(
            v2.get_default_name("sampleTexts"),
            Some("legacy sample text")
        );
    }

    #[test]
    fn v2_style_names_in_a_v3_file() {
        let v3_mixed_with_v2 =
            Font::load(&glyphs3_dir().join("TheBestV2NamesInAV3File.glyphs")).unwrap();
        let v3 = Font::load(&glyphs3_dir().join("TheBestNames.glyphs")).unwrap();

        // V3 file with v2-style root-level fields (copyright, designer, etc.) gets those
        // converted to properties format by v2_to_v3_names(), so should match the pure v3 file
        let v3_mixed_defaults: BTreeMap<_, _> = v3_mixed_with_v2.default_names().collect();
        let v3_defaults: BTreeMap<_, _> = v3.default_names().collect();

        assert_eq!(v3_mixed_defaults, v3_defaults);
    }

    #[test]
    fn no_english_names_fallback() {
        // Test file with NO dflt/default/ENG entries, only FRA, DEU, ITA, ESP, JPN
        // This validates that the fallback uses insertion-order first, and not
        // alphabetical first, and that the overlap between default_names() and
        // localized_names() is as intended.
        let font = Font::load(&glyphs3_dir().join("NoEnglishNames.glyphs")).unwrap();

        // copyrights: FRA (1st), DEU (2nd), JPN (3rd) => should use FRA
        assert_eq!(
            font.get_default_name("copyrights"),
            Some("Droit d'auteur français")
        );

        // designers: FRA (1st), DEU (2nd) => should use FRA
        assert_eq!(
            font.get_default_name("designers"),
            Some("Concepteur français")
        );

        // manufacturers: ITA (1st), ESP (2nd) => should use ITA
        assert_eq!(
            font.get_default_name("manufacturers"),
            Some("Produttore italiano")
        );

        let localized: Vec<_> = font.localized_names().collect();

        // The FRA copyright should appear in both default and localized
        assert!(localized.contains(&("copyrights", "FRA", "Droit d'auteur français")));
        // The DEU and JPN copyright should only appear in localized
        assert!(localized.contains(&("copyrights", "DEU", "Deutsches Urheberrecht")));
        assert!(localized.contains(&("copyrights", "JPN", "日本の著作権")));
    }

    fn assert_wghtvar_avar_master_and_axes(glyphs_file: &Path) {
        let font = Font::load(glyphs_file).unwrap();
        let wght_idx = font.axes.iter().position(|a| a.tag == "wght").unwrap();
        assert_eq!(
            vec![300.0, 400.0, 700.0],
            font.masters
                .iter()
                .map(|m| m.axes_values[wght_idx].into_inner())
                .collect::<Vec<_>>()
        );
        assert_eq!(
            (400.0, 1),
            (
                font.default_master().axes_values[wght_idx].into_inner(),
                font.default_master_idx
            )
        );
    }

    #[test]
    fn favor_regular_as_origin_glyphs2() {
        assert_wghtvar_avar_master_and_axes(&glyphs2_dir().join("WghtVar_Avar.glyphs"));
    }

    #[test]
    fn favor_regular_as_origin_glyphs3() {
        assert_wghtvar_avar_master_and_axes(&glyphs3_dir().join("WghtVar_Avar.glyphs"));
    }

    #[test]
    fn have_all_the_best_instances() {
        let font = Font::load(&glyphs3_dir().join("WghtVar_Instances.glyphs")).unwrap();
        assert_eq!(
            vec![
                ("Regular", vec![("Weight", 400.0)]),
                ("Bold", vec![("Weight", 700.0)])
            ],
            font.instances
                .iter()
                .map(|inst| (
                    inst.name.as_str(),
                    font.axes
                        .iter()
                        .zip(&inst.axes_values)
                        .map(|(a, v)| (a.name.as_str(), v.0))
                        .collect::<Vec<_>>()
                ))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn read_typo_whatsits() {
        let font = Font::load(&glyphs2_dir().join("WghtVar_OS2.glyphs")).unwrap();
        let master = font.default_master();
        assert_eq!(Some(1193), master.custom_parameters.typo_ascender);
        assert_eq!(Some(-289), master.custom_parameters.typo_descender);
    }

    #[test]
    fn read_os2_flags_default_set() {
        let font = Font::load(&glyphs2_dir().join("WghtVar.glyphs")).unwrap();
        assert_eq!(font.custom_parameters.use_typo_metrics, Some(true));
        assert_eq!(font.custom_parameters.has_wws_names, Some(true));
    }

    #[test]
    fn read_os2_flags_default_unset() {
        let font = Font::load(&glyphs2_dir().join("WghtVar_OS2.glyphs")).unwrap();
        assert_eq!(font.custom_parameters.use_typo_metrics, None);
        assert_eq!(font.custom_parameters.has_wws_names, None);
    }

    #[test]
    fn read_os2_longform_param_names() {
        // Older Glyphs files may use either the short form ("subscriptXSize")
        // or the long UFO form ("openTypeOS2SubscriptXSize").
        let font = Font::load(&glyphs2_dir().join("os2_longform_params.glyphs")).unwrap();
        assert_eq!(font.custom_parameters.strikeout_position, Some(300));
        assert_eq!(font.custom_parameters.strikeout_size, Some(50));
        assert_eq!(font.custom_parameters.subscript_x_offset, Some(-80));
        assert_eq!(font.custom_parameters.subscript_x_size, Some(700));
        assert_eq!(font.custom_parameters.subscript_y_offset, Some(-75));
        assert_eq!(font.custom_parameters.subscript_y_size, Some(650));
        assert_eq!(font.custom_parameters.superscript_x_offset, Some(50));
        assert_eq!(font.custom_parameters.superscript_x_size, Some(600));
        assert_eq!(font.custom_parameters.superscript_y_offset, Some(350));
        assert_eq!(font.custom_parameters.superscript_y_size, Some(600));
    }

    #[test]
    fn read_simple_kerning() {
        let font = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
        assert_eq!(
            HashSet::from(["m01", "E09E0C54-128D-4FEA-B209-1B70BEFE300B",]),
            font.kerning_ltr
                .keys()
                .map(|k| k.as_str())
                .collect::<HashSet<_>>()
        );

        let actual_groups: Vec<_> = font
            .glyphs
            .iter()
            .filter_map(|(name, glyph)| {
                if glyph.left_kern.is_some() || glyph.right_kern.is_some() {
                    Some((
                        name.as_str(),
                        glyph.left_kern.as_deref(),
                        glyph.right_kern.as_deref(),
                    ))
                } else {
                    None
                }
            })
            .collect();

        let actual_kerning = font
            .kerning_ltr
            .get("m01")
            .unwrap()
            .iter()
            .map(|((n1, n2), value)| (n1.as_str(), n2.as_str(), value.0))
            .collect::<Vec<_>>();

        assert_eq!(
            (
                vec![
                    ("bracketleft", Some("bracketleft_L"), Some("bracketleft_R")),
                    (
                        "bracketright",
                        Some("bracketright_L"),
                        Some("bracketright_R")
                    ),
                ],
                vec![
                    ("@MMK_L_bracketleft_R", "exclam", -165.),
                    ("bracketleft", "bracketright", -300.),
                    ("exclam", "@MMK_R_bracketright_L", -160.),
                    ("exclam", "exclam", -360.),
                    ("exclam", "hyphen", 20.),
                    ("hyphen", "hyphen", -150.),
                ],
            ),
            (actual_groups, actual_kerning),
            "{:?}",
            font.kerning_ltr
        );
    }

    #[test]
    fn kern_floats() {
        let font = Font::load(&glyphs3_dir().join("KernFloats.glyphs")).unwrap();

        let kerns = font.kerning_ltr.get("m01").unwrap();
        let key = ("space".to_smolstr(), "space".to_smolstr());
        assert_eq!(kerns.get(&key), Some(&OrderedFloat(4.2001)));
    }

    #[test]
    fn read_simple_anchor() {
        let font = Font::load(&glyphs3_dir().join("WghtVar_Anchors.glyphs")).unwrap();
        assert_eq!(
            vec![
                ("m01", "top", Point::new(300.0, 700.0)),
                ("l2", "top", Point::new(325.0, 725.0))
            ],
            font.glyphs
                .get("A")
                .unwrap()
                .layers
                .iter()
                .flat_map(|l| l.anchors.iter().map(|a| (
                    l.layer_id.as_str(),
                    a.name.as_str(),
                    a.pos
                )))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn read_export_glyph() {
        let font = Font::load(&glyphs3_dir().join("WghtVar_NoExport.glyphs")).unwrap();
        assert_eq!(
            vec![
                ("bracketleft", true),
                ("bracketright", true),
                ("exclam", true),
                ("hyphen", false),
                ("manual-component", true),
                ("space", true),
            ],
            font.glyphs
                .iter()
                .map(|(name, glyph)| (name.as_str(), glyph.export))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn read_fstype_none() {
        let font = Font::load(&glyphs3_dir().join("infinity.glyphs")).unwrap();
        assert!(font.custom_parameters.fs_type.is_none());
    }

    #[test]
    fn read_fstype_zero() {
        let font = Font::load(&glyphs3_dir().join("fstype_0x0000.glyphs")).unwrap();
        assert_eq!(Some(0), font.custom_parameters.fs_type);
    }

    #[test]
    fn read_fstype_bits() {
        let font = Font::load(&glyphs3_dir().join("fstype_0x0104.glyphs")).unwrap();
        assert_eq!(Some(0x104), font.custom_parameters.fs_type);
    }

    #[test]
    fn anchor_components() {
        let font = Font::load(&glyphs3_dir().join("ComponentAnchor.glyphs")).unwrap();
        let glyph = font.glyphs.get("A_Aacute").unwrap();
        let acute_comb = glyph.layers[0]
            .shapes
            .iter()
            .find_map(|shape| match shape {
                Shape::Component(c) if c.name == "acutecomb" => Some(c),
                _ => None,
            })
            .unwrap();
        assert_eq!(acute_comb.anchor.as_deref(), Some("top_2"));
    }

    #[test]
    fn parse_alignment_zone_smoke_test() {
        assert_eq!(
            super::parse_alignment_zone("{1, -12}").map(|x| (x.0.0, x.1.0)),
            Some((1., -12.))
        );
        assert_eq!(
            super::parse_alignment_zone("{-5001, 12}").map(|x| (x.0.0, x.1.0)),
            Some((-5001., 12.))
        );
    }

    // a little helper used in tests below
    impl FontMaster {
        fn get_metric(&self, name: &str) -> Option<(f64, f64)> {
            self.metric_values
                .get(name)
                .map(|raw| (raw.pos.0, raw.over.0))
        }
    }

    #[test]
    fn v2_alignment_zones_to_metrics() {
        let font = Font::load(&glyphs2_dir().join("alignment_zones_v2.glyphs")).unwrap();
        let master = font.default_master();

        assert_eq!(master.get_metric("ascender"), Some((800., 17.)));
        assert_eq!(master.get_metric("cap height"), Some((700., 16.)));
        assert_eq!(master.get_metric("baseline"), Some((0., -16.)));
        assert_eq!(master.get_metric("descender"), Some((-200., -17.)));
        assert_eq!(master.get_metric("x-height"), Some((500., 15.)));
        assert_eq!(master.get_metric("italic angle"), None);
    }

    #[test]
    fn v3_duplicate_metrics_first_wins() {
        // In this test font, the default master contains two 'x-height' metric values,
        // the first (501) that applies globally, and a second one (450) that applies
        // only to small-caps, using GSMetric's `filter` attribute which we ignore as
        // it is not relevant to build OS/2 and MVAR tables.
        // We match glyphsLib and only consider the first metric with a given name.
        let font = Font::load(&glyphs3_dir().join("WghtVar_OS2.glyphs")).unwrap();
        let master = font.default_master();

        assert_eq!(master.get_metric("x-height"), Some((501., 0.)));
    }

    #[test]
    fn v2_preserve_custom_alignment_zones() {
        let font = Font::load(&glyphs2_dir().join("alignment_zones_v2.glyphs")).unwrap();
        let master = font.default_master();
        assert_eq!(master.get_metric("zone 1"), Some((1000., 20.)));
        assert_eq!(master.get_metric("zone 2"), Some((-100., -15.)));
    }

    // If the source explicitly sets a category we don't recognize, we keep it unset
    // rather than letting the name-based GlyphData guess override the author's intent.
    // https://github.com/googlefonts/fontc/issues/2055
    #[test]
    fn unknown_glyph_category() {
        let raw = super::RawGlyph {
            glyphname: "A".into(),
            category: Some("Fake".into()),
            ..Default::default()
        };

        let cooked = raw.build(FormatVersion::V2, &GlyphData::default()).unwrap();
        assert_eq!((cooked.category, cooked.sub_category), (None, None));
    }

    // An unrecognized *explicit* subCategory on an underscore-named glyph must not fall
    // through to the name-based Ligature guess: the author set something, so we leave the
    // slot None (which later resolves to Base from anchors) instead of guessing Ligature.
    // https://github.com/googlefonts/fontc/issues/2055
    #[test]
    fn explicit_unknown_subcategory_does_not_revert_to_ligature_guess() {
        let raw = super::RawGlyph {
            glyphname: "a_a".into(),
            category: Some("Letter".into()),
            sub_category: Some("Conjunct-but-fontc-doesnt-know-it".into()),
            ..Default::default()
        };

        let cooked = raw.build(FormatVersion::V2, &GlyphData::default()).unwrap();
        assert_eq!(cooked.category, Some(Category::Letter));
        assert_eq!(cooked.sub_category, None); // NOT Some(Ligature)
    }

    #[test]
    fn custom_params_disable() {
        let font = Font::load(&glyphs3_dir().join("custom_param_disable.glyphs")).unwrap();

        assert!(font.custom_parameters.fs_type.is_none())
    }

    #[test]
    fn parse_numbers() {
        let font = Font::load(&glyphs3_dir().join("number_value.glyphs")).unwrap();
        assert_eq!(
            font.masters[0].number_values.get("foo"),
            Some(&OrderedFloat(12.4f64))
        );
        assert_eq!(
            font.masters[1].number_values.get("foo"),
            Some(&OrderedFloat(0f64))
        );
    }

    #[test]
    fn read_font_metrics() {
        let font =
            Font::load(&glyphs3_dir().join("GlobalMetrics_font_customParameters.glyphs")).unwrap();
        assert_eq!(Some(950), font.custom_parameters.typo_ascender);
        assert_eq!(Some(-350), font.custom_parameters.typo_descender);
        assert_eq!(Some(0), font.custom_parameters.typo_line_gap);
        assert_eq!(Some(950), font.custom_parameters.hhea_ascender);
        assert_eq!(Some(-350), font.custom_parameters.hhea_descender);
        assert_eq!(Some(0), font.custom_parameters.hhea_line_gap);
        assert_eq!(Some(1185), font.custom_parameters.win_ascent);
        assert_eq!(Some(420), font.custom_parameters.win_descent);
        assert_eq!(
            Some(OrderedFloat(42_f64)),
            font.custom_parameters.underline_thickness
        );
        assert_eq!(
            Some(OrderedFloat(-300_f64)),
            font.custom_parameters.underline_position
        );
    }

    #[test]
    fn parse_legacy_stylistic_set_name() {
        let font = Font::load(&glyphs2_dir().join("FeaLegacyName.glyphs")).unwrap();
        assert_eq!(font.features.len(), 2);
        let [ss01, ss02] = font.features.as_slice() else {
            panic!("wrong number of features");
        };

        assert!(
            ss01.content
                .contains("name 3 1 0x409 \"Alternate placeholder\"")
        );
        assert!(!ss02.content.contains("name 3 1"))
    }

    // <https://github.com/googlefonts/fontc/issues/1175>
    #[test]
    fn one_italic_is_enough() {
        let font = Font::load(&glyphs2_dir().join("ItalicItalic.glyphs")).unwrap();
        for master in font.masters {
            let mut fragments = master.name.split_ascii_whitespace().collect::<Vec<_>>();
            fragments.sort();
            for words in fragments.windows(2) {
                assert!(
                    words[0] != words[1],
                    "Multiple instances of {} in {}",
                    words[0],
                    master.name
                );
            }
        }
    }

    #[test]
    fn master_name_contains_italic() {
        // ensure that we don't add 'Italic' to a name like 'ThinItalic' (that contains
        // the word italic, but not as a standalone word)

        let font = Font::load(&glyphs2_dir().join("MasterNameNotExactlyItalic.glyphs")).unwrap();

        assert_eq!(font.default_master().name, "ThinItalic");
    }

    // We had a bug where if a master wasn't at a mapping point the Axis Mapping was modified
    #[test]
    fn ignore_masters_if_axis_mapping() {
        let font = Font::load(&glyphs2_dir().join("MasterNotMapped.glyphs")).unwrap();
        let mapping = &font.axis_mappings.0.get("Weight").unwrap().0;
        assert_eq!(
            vec![
                (OrderedFloat(400_f64), OrderedFloat(40.0)),
                (OrderedFloat(700_f64), OrderedFloat(70.0))
            ],
            *mapping
        );
    }

    #[rstest]
    #[case::rotate_0(0.0, Affine::new([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]))]
    #[case::rotate_360(360.0, Affine::new([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]))]
    #[case::rotate_90(90.0, Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]))]
    #[case::rotate_minus_90(-90.0, Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]))]
    #[case::rotate_180(180.0, Affine::new([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0]))]
    #[case::rotate_minus_180(-180.0, Affine::new([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0]))]
    #[case::rotate_270(270.0, Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]))]
    #[case::rotate_minus_270(-270.0, Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]))]
    #[case::rotate_450(450.0, Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]))]
    #[case::rotate_540(540.0, Affine::new([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0]))]
    fn cardinal_rotation_contain_exact_zeros_and_ones(
        #[case] angle: f64,
        #[case] expected: Affine,
    ) {
        // When Glyphs 3 components are rotated by a 90, 180 or 270 degree angle,
        // we want to match fontTools Transform.rotate() and have the sine and
        // cosine terms rounded exactly to 0.0 or ±1.0 to avoid unnecessary diffs
        // upon rounding transformed coordinates to integer:
        // https://github.com/googlefonts/fontc/issues/1218
        assert_eq!(expected, normalized_rotation(angle));
    }

    #[rstest]
    #[case::rotate_30(30.0, 4, Affine::new([0.866, 0.5, -0.5, 0.866, 0.0, 0.0]))]
    #[case::rotate_minus_30(-30.0, 4, Affine::new([0.866, -0.5, 0.5, 0.866, 0.0, 0.0]))]
    #[case::rotate_almost_90(
        90.01, 8, Affine::new([-0.00017453, 0.99999998, -0.99999998, -0.00017453, 0.0, 0.0])
    )]
    fn non_cardinal_rotation_left_untouched(
        #[case] angle: f64,
        #[case] precision: u8,
        #[case] expected: Affine,
    ) {
        // any other angles' sin and cos != (0, ±1) are passed through unchanged
        assert_eq!(expected, round(normalized_rotation(angle), precision));
    }

    #[test]
    fn parse_colrv1_identify_colr_glyphs() {
        let font = Font::load(&glyphs3_dir().join("COLRv1-gradient.glyphs")).unwrap();
        let expected_colr = HashSet::from(["A", "B", "C", "D", "K", "L", "M", "N"]);
        assert_eq!(
            expected_colr,
            font.glyphs
                .values()
                .filter(|g| g.layers.iter().all(|l| l.attributes.color))
                .map(|g| g.name.as_str())
                .collect::<HashSet<_>>()
        );
    }

    #[test]
    fn parse_colrv1_gradients() {
        let font = Font::load(&glyphs3_dir().join("COLRv1-gradient.glyphs")).unwrap();
        let expected_colr = HashSet::from([
            (
                "A",
                Gradient {
                    start: vec![OrderedFloat(0.1), OrderedFloat(0.1)],
                    end: vec![OrderedFloat(0.9), OrderedFloat(0.9)],
                    colors: vec![
                        ColorStop {
                            color: Color::rgba(255, 0, 0, 255),
                            stop_offset: 0.into(),
                        },
                        ColorStop {
                            color: Color::rgba(0, 0, 255, 255),
                            stop_offset: 1.into(),
                        },
                    ],
                    ..Default::default()
                },
            ),
            (
                "N",
                Gradient {
                    start: vec![OrderedFloat(1.0), OrderedFloat(1.0)],
                    end: vec![OrderedFloat(0.0), OrderedFloat(0.0)],
                    colors: vec![
                        ColorStop {
                            color: Color::rgba(255, 0, 0, 255),
                            stop_offset: 0.into(),
                        },
                        ColorStop {
                            color: Color::rgba(0, 0, 255, 255),
                            stop_offset: 1.into(),
                        },
                    ],
                    style: "circle".to_string(),
                },
            ),
        ]);
        assert_eq!(
            expected_colr,
            font.glyphs
                .values()
                .filter(|g| expected_colr.iter().any(|(name, _)| *name == g.name))
                .flat_map(|g| g.layers.iter().flat_map(|l| l.shapes.iter()).map(|s| (
                    g.name.as_str(),
                    s.attributes().gradient.as_ref().unwrap().clone()
                )))
                .collect::<HashSet<_>>()
        );
    }

    #[test]
    fn parse_grayscale_colors() {
        let font = Font::load(&glyphs3_dir().join("COLRv1-grayscale.glyphs")).unwrap();
        assert_eq!(
            vec![
                ColorStop {
                    color: Color::rgba(64, 64, 64, 255),
                    stop_offset: 0.into(),
                },
                ColorStop {
                    color: Color::rgba(0, 0, 0, 255),
                    stop_offset: 1.into(),
                },
            ],
            font.glyphs
                .values()
                .flat_map(
                    |g| g.layers.iter().flat_map(|l| l.shapes.iter()).flat_map(|s| s
                        .attributes()
                        .gradient
                        .iter()
                        .flat_map(|g| g.colors.iter())
                        .cloned())
                )
                .collect::<Vec<_>>()
        );
    }

    // we want to match glyphsLib and use a value of 600 if the width is missing.
    #[test]
    fn missing_width_no_problem() {
        let font = Font::load(&glyphs3_dir().join("MissingWidth.glyphs")).unwrap();
        let glyph = font.glyphs.get("widthless").unwrap();
        assert_eq!(glyph.layers[0].width, 600.);
    }

    #[test]
    fn read_preferred_names_from_properties() {
        let font = Font::load(&glyphs3_dir().join("PreferableNames.glyphs")).unwrap();
        assert_eq!(
            vec![
                Some("Pref Family Name"),
                Some("Pref Regular"),
                Some("Name 25?!")
            ],
            vec![
                font.get_default_name("preferredFamilyNames"),
                font.get_default_name("preferredSubfamilyNames"),
                font.get_default_name("variationsPostScriptNamePrefix"),
            ]
        );
    }

    #[test]
    fn zero_value_metrics() {
        let font = Font::load(&glyphs3_dir().join("ZeroMetrics.glyphs")).unwrap();
        let master = font.default_master();
        assert_eq!(master.ascender(), Some(789.));
        // this has no value set, but has overshoot set, so this should be a 0
        assert_eq!(master.cap_height(), Some(0.));
        // this has neither value nor overshoot, but since the metric is defined,
        // it's still here and still zero
        assert_eq!(master.x_height(), Some(0.));
        // but this metric is not defined in the font, so it it's `None`
        assert_eq!(master.italic_angle(), None);
    }

    /// If there is a variable instance and it does not have a set familyName,
    /// we should still use names stored in that instance.
    #[test]
    fn names_from_instances() {
        let font = Font::load(&glyphs3_dir().join("InstanceNames.glyphs")).unwrap();
        assert_eq!(
            font.get_default_name("preferredSubfamilyNames").unwrap(),
            "Italic"
        )
    }

    #[rstest]
    #[case::v2(glyphs2_dir())]
    #[case::v3(glyphs3_dir())]
    fn glyph_production_names(#[case] glyphs_dir: PathBuf) {
        let font = Font::load(&glyphs_dir.join("ProductionNames.glyphs")).unwrap();
        let glyphs = font.glyphs;

        // this glyph has no production name in GlyphData.xml nor in the .glyphs file
        assert_eq!(glyphs.get("A").unwrap().production_name, None);

        // this one would have 'dotlessi' in GlyphData.xml, but the .glyphs file overrides it
        assert_eq!(
            glyphs.get("idotless").unwrap().production_name,
            Some("uni0131".into())
        );

        // this has no custom production_name in the .glyphs file, and the one from
        // GlyphData.xml is used
        assert_eq!(
            glyphs.get("nbspace").unwrap().production_name,
            Some("uni00A0".into())
        );
    }

    #[test]
    fn parse_axis_rules() {
        let raw = RawFont::load(&glyphs3_dir().join("AxisRules.glyphs")).unwrap();
        let space = &raw.glyphs[0];
        let axes = &space.layers[0].attributes.axis_rules;
        assert_eq!(
            axes,
            &[
                AxisRule {
                    min: None,
                    max: Some(400)
                },
                AxisRule {
                    min: Some(100),
                    max: None,
                },
                AxisRule {
                    min: None,
                    max: None,
                },
            ]
        )
    }

    #[test]
    fn drop_axis_rules_if_no_assoc_master() {
        // as in, if it's a bracket layer it doesn't need axis rules
        let font = Font::load(&glyphs3_dir().join("AxisRules.glyphs")).unwrap();
        let space = font.glyphs.get("space").unwrap();
        assert!(space.layers[0].attributes.axis_rules.is_empty());
    }

    #[test]
    fn parse_v2_bracket_layers() {
        let font = Font::load(&glyphs2_dir().join("AxisRules.glyphs")).unwrap();
        let glyph = font.glyphs.get("space").unwrap();
        assert_eq!(
            glyph.bracket_layers[0].attributes.axis_rules,
            [
                AxisRule {
                    min: None,
                    max: Some(141)
                },
                AxisRule::default()
            ]
        );
    }

    #[test]
    fn parse_layer_normal() {
        for name in &["[60]", "Light Extended [ 60 ]"] {
            let rule = AxisRule::from_layer_name(name);
            assert_eq!(
                rule,
                Some(AxisRule {
                    min: Some(60),
                    max: None
                }),
                "{name}"
            )
        }
    }

    #[test]
    fn parse_layer_reversed() {
        for name in &["]60]", "Light Extended ] 60 ]"] {
            let rule = AxisRule::from_layer_name(name);
            assert_eq!(
                rule,
                Some(AxisRule {
                    min: None,
                    max: Some(60)
                })
            )
        }
    }

    #[test]
    fn parse_layer_fails() {
        for name in &["[hi]", "[45opsz]", "Medium [499‹wg]"] {
            assert!(AxisRule::from_layer_name(name).is_none(), "{name}")
        }
    }

    #[test]
    fn v2_bracket_layers() {
        let font = Font::load(&glyphs2_dir().join("WorkSans-minimal-bracketlayer.glyphs")).unwrap();
        let glyph = font.glyphs.get("colonsign").unwrap();
        assert_eq!(glyph.layers.len(), 3);
        assert_eq!(glyph.bracket_layers.len(), 3);

        assert!(
            glyph
                .layers
                .iter()
                .all(|l| l.attributes.axis_rules.is_empty())
        );
        assert!(
            glyph
                .bracket_layers
                .iter()
                .all(|l| !l.attributes.axis_rules.is_empty())
        );
    }

    #[test]
    fn v3_bracket_layers() {
        let font = Font::load(&glyphs3_dir().join("LibreFranklin-bracketlayer.glyphs")).unwrap();
        let glyph = font.glyphs.get("peso").unwrap();
        assert_eq!(glyph.layers.len(), 2);
        assert_eq!(glyph.bracket_layers.len(), 2);

        assert!(
            glyph
                .layers
                .iter()
                .all(|l| l.attributes.axis_rules.is_empty())
        );
        assert!(
            glyph
                .bracket_layers
                .iter()
                .all(|l| !l.attributes.axis_rules.is_empty())
        );
    }

    #[test]
    fn glyphs2_weight_class_custom_instance_parameter() {
        // older glyphs sources can use a custom param in the instance
        // in order to pass a custom value for the weight class.
        let font = Font::load(&glyphs2_dir().join("WeightClassCustomParam.glyphs")).unwrap();
        let mapping = &font.axis_mappings.0.get("Weight").unwrap().0;
        assert_eq!(
            mapping.as_slice(),
            &[
                (OrderedFloat(200f64), OrderedFloat(42f64)),
                (OrderedFloat(700.), OrderedFloat(125.)),
                (OrderedFloat(1000.), OrderedFloat(208.))
            ]
        )
    }

    #[test]
    fn glyphs2_avoid_adding_mapping_from_master() {
        // this source has a master which does not correspond to an instance,
        // but the instances provide a valid non-identity mapping; we should
        // avoid adding the mapping from the master.

        let font = Font::load(&glyphs2_dir().join("master_missing_from_instances.glyphs")).unwrap();

        let mapping = &font.axis_mappings.0.get("Weight").unwrap().0;
        assert_eq!(
            mapping.as_slice(),
            &[
                (OrderedFloat(100f64), OrderedFloat(20f64)),
                (OrderedFloat(300.), OrderedFloat(50.)),
                (OrderedFloat(400.), OrderedFloat(71.)),
                (OrderedFloat(700.), OrderedFloat(156.)),
                (OrderedFloat(900.), OrderedFloat(226.)),
            ]
        )
    }

    #[test]
    fn does_not_truncate_axis_location() {
        let font = Font::load(&glyphs3_dir().join("WghtVar_AxisLocationFloat.glyphs")).unwrap();
        let mapping = &font.axis_mappings.0.get("Weight").unwrap().0;

        // The user location 400.75 must *NOT* be truncated
        assert_eq!(
            mapping.as_slice(),
            &[(OrderedFloat(400.75), OrderedFloat(0f64)),]
        )
    }

    fn make_axis_location_params(values: &[(&str, i64)]) -> RawCustomParameterValue {
        RawCustomParameterValue {
            name: "Axis Location".into(),
            value: Plist::Array(
                values
                    .iter()
                    .map(|(name, loc)| {
                        Plist::Dictionary(BTreeMap::from([
                            ("Axis".into(), Plist::String(name.to_string())),
                            ("Location".into(), Plist::Integer(*loc)),
                        ]))
                    })
                    .collect(),
            ),
            disabled: None,
        }
    }

    #[test]
    fn user_to_design_with_no_axes() {
        let _ = tracing_subscriber::fmt().with_test_writer().try_init();
        let mut myfont = RawFont {
            font_master: vec![RawFontMaster {
                custom_parameters: RawCustomParameters(vec![make_axis_location_params(&[(
                    "Weight", 400,
                )])]),
                ..Default::default()
            }],
            ..Default::default()
        };

        let _just_dont_crash_plz = user_to_design_from_axis_location(&mut myfont);
    }

    #[test]
    fn user_to_design_with_unknown_axis_location() {
        let _ = tracing_subscriber::fmt().with_test_writer().try_init();
        let mut myfont = RawFont {
            axes: vec![Axis {
                name: "Weight".into(),
                tag: "wght".into(),
                hidden: None,
            }],
            font_master: vec![RawFontMaster {
                custom_parameters: RawCustomParameters(vec![make_axis_location_params(&[
                    ("Weight", 400),
                    ("Italic", 0),
                ])]),
                axes_values: vec![60.0.into()],
                ..Default::default()
            }],
            ..Default::default()
        };

        let _just_dont_crash_plz = user_to_design_from_axis_location(&mut myfont);
    }

    #[test]
    fn axis_location_string_value() {
        let raw = Plist::Dictionary(BTreeMap::from([
            ("Axis".into(), Plist::String("Weight".into())),
            ("Location".into(), Plist::String("42".into())),
        ]));
        assert_eq!(
            Some(AxisLocation {
                axis_name: "Weight".into(),
                location: 42.0.into(),
            }),
            raw.as_axis_location()
        );
    }

    #[test]
    fn glyphs2_unicode_ranges() {
        let font = Font::load(&glyphs2_dir().join("UnicodeRanges.glyphs")).unwrap();
        assert_eq!(
            Some(BTreeSet::from([8])),
            font.custom_parameters.unicode_range_bits
        );
    }

    #[test]
    fn parse_smart_components_v3() {
        // we load from raw directly so that we can skip preprocessing, which would
        // replace the components with the actual outlines
        let font = RawFont::load(&glyphs3_dir().join("SmartComponents.glyphs")).unwrap();
        let font = Font::try_from(font).unwrap();
        let shoulder = font.glyphs.get("_part.shoulder").unwrap();
        assert_eq!(
            shoulder.smart_component_axes,
            BTreeMap::from([
                ("shoulderWidth".into(), 0..=100),
                ("crotchDepth".into(), -100..=0)
            ])
        );

        let m = font.glyphs.get("m").unwrap();
        let expected = [
            Component {
                name: "_part.stem".into(),
                ..Default::default()
            },
            Component {
                name: "_part.shoulder".into(),
                transform: Affine::translate((17., 0.)),
                smart_component_values: BTreeMap::from([
                    ("crotchDepth".into(), -44.28304),
                    ("shoulderWidth".into(), 28.78011),
                ]),
                ..Default::default()
            },
            Component {
                name: "_part.shoulder".into(),
                transform: Affine::translate((180., 1.)),
                smart_component_values: BTreeMap::from([
                    ("crotchDepth".into(), -81.24796),
                    ("shoulderWidth".into(), 0.0),
                ]),
                ..Default::default()
            },
        ];
        assert_eq!(
            m.layers[0].components().cloned().collect::<Vec<_>>(),
            expected
        );
    }

    fn instantiate_shoulder_at(location: &[(&str, f64)]) -> Shape {
        fn make_component_values(inp: &[(&str, f64)]) -> BTreeMap<SmolStr, f64> {
            inp.iter().map(|(k, v)| (k.to_smolstr(), *v)).collect()
        }
        let font = RawFont::load(&glyphs3_dir().join("SmartComponents.glyphs")).unwrap();
        let font = Font::try_from(font).unwrap();

        let smart_comp = font.glyphs.get("_part.shoulder").unwrap();
        let default_pos = Component {
            name: "_part.shoulder".into(),
            smart_component_values: make_component_values(location),
            ..Default::default()
        };

        let instance =
            smart_components::instantiate_for_layer("m01", &default_pos, smart_comp).unwrap();
        assert_eq!(instance.shapes.len(), 1);
        instance.shapes[0].clone()
    }

    #[test]
    fn instantiate_smart_component_at_default() {
        let font = Font::load(&glyphs3_dir().join("SmartComponents.glyphs")).unwrap();
        let smart_comp = font.glyphs.get("_part.shoulder").unwrap();
        let shape = instantiate_shoulder_at(&[("shoulderWidth", 100.), ("crotchDepth", 0.)]);

        assert_eq!(smart_comp.layers[1].layer_id, "m01");
        assert_eq!(shape, smart_comp.layers[1].shapes[0]);
    }

    // https://github.com/googlefonts/glyphsLib/issues/1134
    #[test]
    fn instantiate_smart_component_at_default_empty_values() {
        let font = Font::load(&glyphs3_dir().join("SmartComponents.glyphs")).unwrap();
        let smart_comp = font.glyphs.get("_part.shoulder").unwrap();

        // When a smart component is newly placed without adjusting any slider,
        // Glyphs.app omits the 'piece' attribute, so smart_component_values is empty.
        let component = Component {
            name: "_part.shoulder".into(),
            smart_component_values: BTreeMap::new(),
            ..Default::default()
        };

        let instance =
            smart_components::instantiate_for_layer("m01", &component, smart_comp).unwrap();
        assert_eq!(instance.shapes.len(), 1);

        // Should produce the same result as explicit default values
        let shape_with_explicit_defaults =
            instantiate_shoulder_at(&[("shoulderWidth", 100.), ("crotchDepth", 0.)]);
        assert_eq!(instance.shapes[0], shape_with_explicit_defaults);
    }

    #[test]
    fn instantiate_smart_component_at_not_default() {
        let Shape::Path(path) =
            instantiate_shoulder_at(&[("shoulderWidth", 0.), ("crotchDepth", -100.)])
        else {
            panic!("wat")
        };
        // the first point is at its lowest value (crotch -100) (first point is at end!)
        assert_eq!(path.nodes.last().unwrap().pt.round().y, 267.0);
        // the shoulder width means the max x is also at its lowest value
        assert_eq!(
            path.nodes.iter().map(|nd| nd.pt.x.round() as i64).max(),
            Some(335)
        );
    }

    impl crate::Path {
        fn bbox(&self) -> Option<Rect> {
            let points = self.to_points();
            let (head, rest) = points.as_slice().split_first()?;
            Some(
                rest.iter()
                    .fold(Rect::ZERO.with_origin(*head), |bbox, pt| bbox.union_pt(*pt)),
            )
        }
    }

    #[test]
    fn smart_component_v2() {
        let font = Font::load(&glyphs2_dir().join("SmartComponent.glyphs")).unwrap();

        let glyph = font.glyphs.get("composite").unwrap();
        let shapes = &glyph.layers[0].shapes;
        let paths = shapes
            .iter()
            .map(|s| s.as_path().unwrap().to_points())
            .collect::<Vec<_>>();
        let expected1 = [(9., 405.), (9., 300.), (276., 300.), (276.0, 405.0)]
            .into_iter()
            .map(Point::from)
            .collect::<Vec<_>>();

        let expected2 = [(9., 405.), (9., 383.), (276., 383.), (276.0, 405.0)]
            .into_iter()
            .map(|pt| Point::from(pt) + Vec2::new(100., 100.))
            .collect::<Vec<_>>();

        assert_eq!(paths, [expected1, expected2]);
    }

    #[test]
    fn nested_smart_components() {
        // ensure that if a smart component has its own smart components, those
        // get instantiated first.
        let font = Font::load(&glyphs2_dir().join("NestedSmartComponent.glyphs")).unwrap();
        let glyph = font.glyphs.get("w").unwrap();
        let shapes = &glyph.layers[0].shapes;
        let rects = shapes
            .iter()
            .map(|s| s.as_path().unwrap().bbox().unwrap())
            .collect::<Vec<_>>();
        assert_eq!(
            rects,
            [
                Rect::new(0., 200., 400., 400.),
                Rect::new(0., 0., 400., 100.),
                Rect::new(500., 200., 550., 400.),
                Rect::new(500., 0., 550., 100.),
            ]
        );
    }

    /// Explicit anchors on a composite glyph must not be overridden by
    /// interpolated smart component anchors.
    /// Regression test for <https://github.com/googlefonts/fontc/pull/1892>
    #[test]
    fn smart_component_preserves_explicit_anchors() {
        let font = Font::load(&glyphs3_dir().join("SmartComponentExplicitAnchors.glyphs")).unwrap();
        let glyph = font.glyphs.get("composite").unwrap();
        let layer = &glyph.layers[0];

        // The glyph's explicit anchors should survive smart component instantiation
        let anchor_map: std::collections::HashMap<&str, (f64, f64)> = layer
            .anchors
            .iter()
            .map(|a| (a.name.as_str(), (a.pos.x, a.pos.y)))
            .collect();

        // These are the glyph's own explicit anchor positions, NOT the smart
        // component's interpolated values (which would be (250,600) / (250,0)).
        assert_eq!(
            anchor_map.get("top"),
            Some(&(300.0, 700.0)),
            "explicit 'top' anchor was overridden by smart component"
        );
        assert_eq!(
            anchor_map.get("bottom"),
            Some(&(300.0, 0.0)),
            "explicit 'bottom' anchor was overridden by smart component"
        );
    }

    /// `_`-prefixed anchors on smart components must survive instantiation.
    /// Regression test for <https://github.com/googlefonts/fontc/issues/2010>
    #[test]
    fn smart_component_preserves_underscore_anchors() {
        let font =
            Font::load(&glyphs3_dir().join("SmartComponentUnderscoreAnchors.glyphs")).unwrap();
        let glyph = font.glyphs.get("knmAU").unwrap();
        let layer = &glyph.layers[0];
        let anchor_map: std::collections::HashMap<&str, (f64, f64)> = layer
            .anchors
            .iter()
            .map(|a| (a.name.as_str(), (a.pos.x, a.pos.y)))
            .collect();

        assert_eq!(
            anchor_map.get("_headline"),
            Some(&(135.0, 383.0)),
            "_headline anchor was dropped during smart component instantiation"
        );
        assert_eq!(
            anchor_map.get("top"),
            Some(&(250.0, 600.0)),
            "top anchor was dropped during smart component instantiation"
        );
    }

    #[test]
    fn parse_basic_corner_component_hint() {
        let font = Font::load_raw(glyphs3_dir().join("CornerComponents.glyphs")).unwrap();

        let glyph = font.glyphs.get("aa_simple_angleinstroke").unwrap();
        let hints = &glyph.layers[0].hints;

        assert_eq!(hints.len(), 1);
        assert_eq!(hints[0].name, "_corner.one");
        assert_eq!(hints[0].shape_index, 0);
        assert_eq!(hints[0].node_index, 0);
        assert_eq!(hints[0].type_, HintType::Corner);
        assert_eq!(hints[0].scale, Default::default());
        assert_eq!(hints[0].alignment, Alignment::OutStroke);
    }

    #[test]
    fn parse_corner_component_hint_with_scale() {
        let font = Font::load_raw(glyphs3_dir().join("CornerComponents.glyphs")).unwrap();

        let glyph = font.glyphs.get("ac_scale").unwrap();
        let hints = &glyph.layers[0].hints;

        assert_eq!(hints.len(), 1);
        assert_eq!(hints[0].name, "_corner.one");
        assert_eq!(hints[0].shape_index, 0);
        assert_eq!(hints[0].node_index, 0);
        assert_eq!(hints[0].type_, HintType::Corner);
        assert_eq!(hints[0].scale, (Scale::new(1.2, 1.5)));
        assert_eq!(hints[0].alignment, Alignment::OutStroke);
    }

    #[test]
    fn parse_corner_component_hint_with_alignment() {
        let font = Font::load_raw(glyphs3_dir().join("CornerComponents.glyphs")).unwrap();

        let glyph = font.glyphs.get("aj_right_alignment").unwrap();
        let hints = &glyph.layers[0].hints;

        assert_eq!(hints.len(), 1);
        assert_eq!(hints[0].name, "_corner.one");
        assert_eq!(hints[0].shape_index, 0);
        assert_eq!(hints[0].node_index, 1);
        assert_eq!(hints[0].type_, HintType::Corner);
        assert_eq!(hints[0].scale, Default::default());
        assert_eq!(hints[0].alignment, Alignment::InStroke);
    }

    #[test]
    fn parse_v2_corner_component() {
        let hint_plist = r#"
{
origin = "{0, 0}";
scale = "{0.7, 1}";
type = Corner;
name = _corner.hi;
}
        "#;

        let hint = RawHint::parse_plist(hint_plist).unwrap().to_hint().unwrap();
        assert_eq!(hint.scale.x, 0.7);
        assert_eq!(hint.scale.y, 1.0);
    }

    #[test]
    fn link_metrics_with_first_master_parsing() {
        let font = Font::load(&glyphs3_dir().join("LinkMetricsWithFirstMaster.glyphs")).unwrap();
        assert_eq!(font.masters.len(), 2);

        // First master should NOT have linked metrics
        assert_eq!(
            font.masters[0]
                .custom_parameters
                .link_metrics_with_first_master,
            None
        );
        // Second master should have "Link Metrics With First Master" set to true
        assert_eq!(
            font.masters[1]
                .custom_parameters
                .link_metrics_with_first_master,
            Some(true)
        );
    }

    #[test]
    fn link_metrics_with_master_parsing() {
        let font = Font::load(&glyphs3_dir().join("LinkMetricsWithMaster.glyphs")).unwrap();
        assert_eq!(font.masters.len(), 3);

        // First two masters should NOT have linked metrics
        assert_eq!(
            font.masters[0].custom_parameters.link_metrics_with_master,
            None
        );
        assert_eq!(
            font.masters[1].custom_parameters.link_metrics_with_master,
            None
        );
        // Third master (Black) should link to Bold's master ID
        let link_target = font.masters[2]
            .custom_parameters
            .link_metrics_with_master
            .as_deref();
        assert_eq!(link_target, Some("m02"));
        assert_eq!(font.masters[1].id, "m02");
        assert_eq!(font.masters[1].name, "Bold");
    }

    #[test]
    fn metrics_source_id_with_first_master() {
        let font = Font::load(&glyphs3_dir().join("LinkMetricsWithFirstMaster.glyphs")).unwrap();

        // First master should return None (uses its own metrics)
        assert_eq!(font.masters[0].metrics_source_id, None);
        // Second master should return first master's ID
        assert_eq!(
            font.masters[1].metrics_source_id.as_ref(),
            Some(&font.masters[0].id)
        );
    }

    #[test]
    fn metrics_source_id_with_master_by_id() {
        let font = Font::load(&glyphs3_dir().join("LinkMetricsWithMaster.glyphs")).unwrap();

        assert_eq!(font.masters[0].metrics_source_id, None);
        assert_eq!(font.masters[1].metrics_source_id, None);
        // Third master (Black) should return second master's ID (Bold)
        assert_eq!(
            font.masters[2].metrics_source_id.as_ref(),
            Some(&font.masters[1].id)
        );
    }

    #[test]
    fn metrics_source_id_with_master_by_name() {
        // Glyphs 2 format uses master names instead of IDs for "Link Metrics With Master"
        let font = Font::load(&glyphs2_dir().join("LinkMetricsWithMasterByName.glyphs")).unwrap();

        assert_eq!(font.masters[0].metrics_source_id, None);
        assert_eq!(font.masters[1].metrics_source_id, None);
        // Third master (Black) links by name "Bold", should resolve to second master's ID
        assert_eq!(
            font.masters[2]
                .custom_parameters
                .link_metrics_with_master
                .as_deref(),
            Some("Bold")
        );
        assert_eq!(
            font.masters[2].metrics_source_id.as_ref(),
            Some(&font.masters[1].id)
        );
    }

    #[test]
    fn metrics_source_id_with_missing_master() {
        let font = Font::load(&glyphs3_dir().join("LinkMetricsWithMissingMaster.glyphs")).unwrap();

        // Second master links to "NonExistent" which doesn't exist
        assert_eq!(
            font.masters[1]
                .custom_parameters
                .link_metrics_with_master
                .as_deref(),
            Some("NonExistent")
        );
        // it should return None and log a warning like glyphsLib does
        assert_eq!(font.masters[1].metrics_source_id, None);
    }

    #[test]
    fn duplicate_custom_params_uses_first_value() {
        // Test that when duplicate custom parameters exist, the first value is used.
        // This matches glyphsLib's behavior where customParameters["key"] returns the
        // first matching item via a simple for-loop iteration.
        let raw_params = RawCustomParameters(vec![
            RawCustomParameterValue {
                name: "Link Metrics With Master".into(),
                value: Plist::String("first_master_id".into()),
                disabled: None,
            },
            RawCustomParameterValue {
                name: "Link Metrics With Master".into(),
                value: Plist::String("second_master_id".into()),
                disabled: None,
            },
        ]);

        let params = raw_params.to_custom_params().unwrap();

        // The first value should win, not the second
        assert_eq!(
            params.link_metrics_with_master.as_deref(),
            Some("first_master_id")
        );
    }

    // from https://github.com/googlefonts/glyphsLib/blob/d42d3b15/tests/builder/custom_params_test.py#L536
    #[test]
    fn parsing_name_table_entries() {
        assert_eq!(
            NameTableEntry::from_str("1024; FOO; BAZ").unwrap(),
            NameTableEntry {
                name_id: 1024,
                platform_id: 3,
                encoding_id: 1,
                lang_id: 0x409,
                value: "FOO; BAZ".into()
            }
        );
        assert_eq!(
            NameTableEntry::from_str("2048 1; FOO").unwrap(),
            NameTableEntry {
                name_id: 2048,
                platform_id: 1,
                encoding_id: 0,
                lang_id: 0,
                value: "FOO".into()
            }
        );
        assert_eq!(
            NameTableEntry::from_str("4096 1 2; FOO").unwrap(),
            NameTableEntry {
                name_id: 4096,
                platform_id: 1,
                encoding_id: 2,
                lang_id: 0,
                value: "FOO".into()
            }
        );
        assert_eq!(
            NameTableEntry::from_str("8192 1 2 3; FOO").unwrap(),
            NameTableEntry {
                name_id: 8192,
                platform_id: 1,
                encoding_id: 2,
                lang_id: 3,
                value: "FOO".into()
            }
        );
        assert_eq!(
            NameTableEntry::from_str("27 3 1 0x404; HEX").unwrap(),
            NameTableEntry {
                name_id: 27,
                platform_id: 3,
                encoding_id: 1,
                lang_id: 0x404,
                value: "HEX".into()
            }
        )
        // this is included in the python but I'm not sure it's well formed?
        // we at least test the hex bit above..
        //assert_eq!(
        //NameTableEntry::from_str("0x4000 074; BAZ").unwrap(),
        //NameTableEntry {
        //name_id: 16384,
        //platform_id: 60,
        //encoding_id: 1,
        //lang_id: 0x409,
        //value: "BAZ".into()
        //}
        //);
    }

    #[test]
    fn parse_color_palette_numeric() {
        let plist = r#"{ colorPalette = 2; }"#;
        let attrs = LayerAttributes::parse_plist(plist).unwrap();
        assert_eq!(attrs.color_palette, Some(2));
    }

    #[test]
    fn parse_color_palette_star() {
        let plist = r#"{ colorPalette = "*"; }"#;
        let attrs = LayerAttributes::parse_plist(plist).unwrap();
        assert_eq!(attrs.color_palette, Some(0xFFFF));
    }

    #[test]
    fn ensure_lang_map_is_sorted() {
        assert!(GLYPHS_TO_OPENTYPE_LANGUAGE_ID.is_sorted())
    }

    #[test]
    fn codepage_bits_from_integers() {
        let plist = Plist::Array(vec![Plist::Integer(1252), Plist::Integer(1258)]);
        assert_eq!(
            plist.as_codepage_bits(),
            Some(BTreeSet::from([0, 8])) // 1252→bit 0 (Latin 1), 1258→bit 8 (Vietnamese)
        );
    }

    #[test]
    fn codepage_bits_from_strings() {
        // "bit N" encodes a raw OS/2 bit position, used e.g. for bit 29 (Macintosh).
        let plist = Plist::Array(vec![
            Plist::String("1252".into()),
            Plist::String("1258".into()),
            Plist::String("bit 29".into()),
        ]);
        assert_eq!(plist.as_codepage_bits(), Some(BTreeSet::from([0, 8, 29])));
    }

    #[test]
    fn read_codepage_range_bits_from_file() {
        // WghtVar_OS2.glyphs has codePageRanges = ("1252", "1250", "949", "437")
        let font = Font::load(&glyphs2_dir().join("WghtVar_OS2.glyphs")).unwrap();
        assert_eq!(
            font.custom_parameters.codepage_range_bits,
            Some(BTreeSet::from([0, 1, 19, 63]))
        );
    }

    #[test]
    fn v2_instance_interpolation_custom_third_axis() {
        // In Glyphs v2, instances store the third axis value as interpolationCustom
        // (masters use customValue). Without the interpolationCustom fallback, the
        // third axis value would incorrectly be 0.0.
        let font =
            Font::load(&glyphs2_dir().join("ThreeAxisWithInterpolationCustom.glyphs")).unwrap();
        assert_eq!(
            vec![
                (
                    "Regular Caption",
                    vec![("Weight", 400.0), ("Width", 100.0), ("Optical Size", 12.0)]
                ),
                (
                    "Bold Display",
                    vec![("Weight", 700.0), ("Width", 100.0), ("Optical Size", 72.0)]
                ),
            ],
            font.instances
                .iter()
                .map(|inst| (
                    inst.name.as_str(),
                    font.axes
                        .iter()
                        .zip(&inst.axes_values)
                        .map(|(a, v)| (a.name.as_str(), v.0))
                        .collect::<Vec<_>>()
                ))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn retains_font_level_user_data() {
        // Font-level userData is retained verbatim; glyphs2fontir interprets the
        // featureWriters key from it.
        let font = Font::load_from_string(
            r#"{
.formatVersion = 3;
fontMaster = (
{
id = "m01";
}
);
unitsPerEm = 1000;
userData = {
com.github.googlei18n.ufo2ft.featureWriters = (
{
class = KernFeatureWriter;
options = {
mode = append;
};
}
);
};
}"#,
        )
        .unwrap();
        let writers = font
            .user_data
            .get("com.github.googlei18n.ufo2ft.featureWriters")
            .and_then(Plist::as_array)
            .expect("featureWriters retained as an array");
        assert_eq!(writers.len(), 1);
        assert_eq!(
            writers[0].get("class").and_then(Plist::as_str),
            Some("KernFeatureWriter")
        );
    }
}