f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
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
//! Fonts for runs, and measuring text into glyphs.

use std::borrow::Cow;

use f_office_fonts::{
    FamilyName, FontId, OutlineError, ShapeFailure, ShapeRequest, ShapedGlyph, ShapedScript,
};
use f_office_units::Length;

use crate::character_class::{CharacterClass, in_code_page_1252};
use crate::props::{BidiLanguageClass, EastAsianScript, FontRef, RunProps};
use crate::styles::{
    EastAsianCharset, EntryScript, FontClass, FontEntry, FontTable, PunctuationKerning,
    SpaceBalance, Theme,
};
use crate::{ChosenFace, FaceMetrics, Fonts};

/// Replaces the vertical line-height fields of `dst` with those of the math font `src`, scaled
/// to `dst.units_per_em`, so a non-Cambria alphanumeric glyph inside an equation keeps the math
/// font's line metrics.
fn apply_math_line_metrics(dst: &mut FaceMetrics, src: FaceMetrics) {
    let dst_em = i64::from(dst.units_per_em.max(1));
    let src_em = i64::from(src.units_per_em.max(1));
    let signed = |v: i16| {
        let scaled = f_office_units::div_round(i64::from(v) * dst_em, src_em);
        i16::try_from(scaled).unwrap_or(v)
    };
    let unsigned = |v: u16| {
        let scaled = f_office_units::div_round(i64::from(v) * dst_em, src_em);
        u16::try_from(scaled.max(0)).unwrap_or(v)
    };
    dst.hhea_ascender = signed(src.hhea_ascender);
    dst.hhea_descender = signed(src.hhea_descender);
    dst.hhea_line_gap = signed(src.hhea_line_gap);
    dst.descent = unsigned(src.descent);
    dst.line_top = unsigned(src.line_top);
    dst.script_top = unsigned(src.script_top);
    dst.east_asian = false;
}

/// The font that text falls back to when neither its font nor the theme font is available.
const LAST_RESORT: FamilyName = FamilyName::from_static("Times New Roman");

/// The font that Word draws instead of a missing font in a document with a theme, whatever
/// the theme's minor font is.
const MISSING_WITH_THEME: FamilyName = FamilyName::from_static("Calibri");

/// The font that Word draws instead of a missing font in a document without a theme.
const MISSING_WITHOUT_THEME: FamilyName = FamilyName::from_static("Cambria");

/// The font that Word draws complex script text with, such as Arabic and Hebrew, when the
/// run's complex script font is missing, where the target draws it with Arial.
const MISSING_COMPLEX: FamilyName = FamilyName::from_static("Arial");

/// The font that Word draws complex script text with when the run's complex script font is
/// missing and has no font table entry that counts, or one of the class `roman` that names no
/// Arabic script, where the target decides by the entry.
const MISSING_COMPLEX_SERIF: FamilyName = FamilyName::from_static("Times New Roman");

/// The font that Word draws complex script text with when the run's complex script font is
/// missing and its font table entry of the class `roman` names the Arabic script, where the
/// target decides by the entry.
const MISSING_COMPLEX_ARABIC_SERIF: FamilyName = FamilyName::from_static("Sakkal Majalla");

/// The font that Word draws complex script text with when the run's complex script font is
/// missing and its font table entry of another class than `roman` names no complex script,
/// where the target decides by the entry.
const MISSING_COMPLEX_UNNAMED: FamilyName = FamilyName::from_static("Calibri");

/// The font that Word draws East Asian text with when the run's East Asian font is missing,
/// and the font of the character set GB 2312.
const MISSING_EAST_ASIAN: FamilyName = FamilyName::from_static("Microsoft YaHei");

/// The font of an East Asian theme font that the theme leaves without a typeface, in a document
/// whose settings name no East Asian language, where the target takes the settings' script.
const UNNAMED_THEME_EAST_ASIAN: &str = "MS Mincho";

/// The script by which a shaper resolves an East Asian theme font with an empty typeface.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ThemeScript {
    /// The theme's font of this script; no family for `None`.
    Of(Option<EastAsianScript>),
    /// [`UNNAMED_THEME_EAST_ASIAN`].
    Unnamed,
}

/// A class of the characters that leave the face of a run that splits by the character set of
/// its suffixed font name: the characters of the class that code page 1252
/// lacks take the class's font.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SplitClass {
    /// Letters, which take Calibri.
    Letter,
    /// General Punctuation, which takes Arial.
    Punctuation,
    /// Letterlike Symbols, such as the numero sign, which take Cambria Math.
    Symbol,
}

impl SplitClass {
    /// The class of a character that leaves a split run's face, or `None` for a character
    /// that keeps it: one of code page 1252, or of no class.
    fn of(ch: char) -> Option<Self> {
        if in_code_page_1252(ch) {
            return None;
        }
        [Self::Letter, Self::Punctuation, Self::Symbol]
            .into_iter()
            .find(|class| class.characters().contains(ch))
    }

    /// The characters of the class.
    const fn characters(self) -> CharacterClass {
        match self {
            Self::Letter => CharacterClass::SplitLetter,
            Self::Punctuation => CharacterClass::SplitPunctuation,
            Self::Symbol => CharacterClass::SplitSymbol,
        }
    }

    /// The font that the class's characters take.
    const fn family(self) -> FamilyName {
        match self {
            Self::Letter => FamilyName::from_static("Calibri"),
            Self::Punctuation => FamilyName::from_static("Arial"),
            Self::Symbol => FamilyName::from_static("Cambria Math"),
        }
    }
}

/// The name under which a missing font with a Big5 entry gives the font of GB 2312 in place of
/// the font of Big5.
const BIG5_YAHEI_NAME: FamilyName = FamilyName::from_static("標楷體");

/// The font that Word draws both the East Asian and the Latin text of a missing font with
/// when the font's entry in the font table names an East Asian character set.
fn charset_stand_in(name: &FamilyName, charset: EastAsianCharset) -> FamilyName {
    match charset {
        EastAsianCharset::Big5 if *name == BIG5_YAHEI_NAME => MISSING_EAST_ASIAN,
        EastAsianCharset::Big5 => FamilyName::from_static("Microsoft JhengHei"),
        EastAsianCharset::Gb2312 => MISSING_EAST_ASIAN,
        EastAsianCharset::ShiftJis => FamilyName::from_static("Yu Gothic"),
        EastAsianCharset::Hangul => FamilyName::from_static("Malgun Gothic"),
    }
}

/// The script of the text that a face is chosen for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Script {
    /// Latin and other text that takes the run's ASCII or other font.
    Latin,
    /// Complex script text, such as Arabic and Hebrew, and the text of a right-to-left run.
    Complex,
    /// East Asian text.
    EastAsian,
}

/// The Arabic tatweel, the joining stroke that a kashida draws.
pub(crate) const TATWEEL: char = '\u{0640}';

/// The fonts that Word tries, in order, for an East Asian character that the run's
/// East Asian font has no glyph for.
const EAST_ASIAN_GLYPH_FALLBACK: [&str; 3] = ["MS Mincho", "Microsoft JhengHei", "Yu Gothic"];

/// The character that stands for `w:noBreakHyphen`, which looks like a hyphen-minus but never
/// breaks. It is a private-use character, because Word's PDFs give the element the text of a
/// hyphen-minus, while a U+2011 in the text of a run keeps its own text.
pub const NON_BREAKING_HYPHEN: char = '\u{E011}';

/// The character that stands for `w:softHyphen`: a place where a word may break, which shows a
/// hyphen only when a line ends there. It is a private-use character, because Word draws a
/// U+00AD in the text of a run as an ordinary character.
pub const SOFT_HYPHEN: char = '\u{E0AD}';

/// The character that stands for an automatic hyphenation point of a word: a place where the
/// layout may end a line with a hyphen under the document's automatic hyphenation, which shows
/// a hyphen only when a line ends there. It is a private-use character, and no text holds it.
pub const AUTOMATIC_HYPHEN: char = '\u{E0AE}';

/// The character of the hyphen that a line shows where it ends at an automatic hyphenation
/// point. It draws and reads as a hyphen-minus, but the PDF writer keeps it in the text object
/// of the letters before it, where it draws a typed hyphen-minus as a text object of its own.
pub const LINE_END_HYPHEN: char = '\u{E02D}';

/// The glyphs of a run that come right after a format character (U+200B to U+200F, U+202A
/// to U+202E, U+FEFF), which draws nothing and which the shaper leaves out: their indices in
/// the glyphs that the shaper pushes. The zero width non-joiner among them stops the joining
/// of the letters on its two sides first.
#[derive(Default)]
struct FormatCharacters(Vec<usize>);

impl FormatCharacters {
    /// Notes the character `ch` of the run's text, which the shaper looks at while the next
    /// glyph that it pushes has the index `at`: a format character marks that glyph.
    fn note(&mut self, ch: Option<char>, at: usize) {
        if matches!(
            ch.and_then(script::invisible_kind),
            Some(script::InvisibleKind::Format)
        ) {
            self.0.push(at);
        }
    }

    /// Notes the characters `letters`, none of which the shaper draws, while the next glyph
    /// that it pushes has the index `at`.
    fn note_all(&mut self, letters: &[char], at: usize) {
        for &ch in letters {
            self.note(Some(ch), at);
        }
    }

    /// Marks each noted glyph of `out` (`Glyph::left_out_before`).
    fn mark(self, out: &mut [Glyph]) {
        for at in self.0 {
            if let Some(glyph) = out.get_mut(at) {
                glyph.left_out_before = LeftOutBefore::FormatCharacter;
            }
        }
    }
}

/// The character that stands for the space after a binary operator or a relation at the top
/// level of an equation in a line: a place where the line may break. It is a private-use
/// character, and no text holds it; it shapes as a no-break space of an operator space
/// ([`SpaceKind::Operator`]).
pub const OPERATOR_BREAK_SPACE: char = '\u{E0A0}';

/// The letters by which a face counts as holding the letters of a script: alef of the Hebrew
/// and of the Arabic script.
const HEBREW_ALEF: char = '\u{5D0}';
const ARABIC_ALEF: char = '\u{627}';

mod accent;
mod bar;
mod decisions;
mod face;
mod look;
mod radical;
mod script;
mod script_place;
mod shadow;
mod substitute;
mod symbol_table;
#[cfg(test)]
mod tests;

pub use accent::{AccentBase, AccentLengths, StretchStackLengths};
pub use bar::BarLengths;
use decisions::Invisible;
pub(crate) use decisions::StandInLines;
pub use decisions::{ShaperSettings, SingleLine};
pub(crate) use face::RunBorder;

/// Whether `glyph` is a variation selector's, which the shaper writes only for one that opens
/// its run where the target joins a selector to the character before it: the face's missing
/// glyph, which the layout makes a mark without width when a character comes before it in
/// its paragraph.
pub(crate) fn is_selector(glyph: &Glyph) -> bool {
    matches!(
        script::invisible_kind(glyph.ch),
        Some(script::InvisibleKind::Selector)
    )
}
pub use face::{
    DrawnGlow, DrawnReflection, DrawnShadow, DrawnTextFill, Face, FaceIndex, Faces, FontSide,
    Glyph, LeftOutBefore, LineSizing, MathFace, MathRoom, PunctuationHalf, RunDirection, RunLines,
    ShadowForm, ShadowRoom, SpaceKind, Standing, TextPlace, TextRelief,
};
use look::{
    Edges, ScriptMove, ScriptScale, background, color, full_size, hold_math_spaces, kerned,
    math_ink_below, math_size_and_rise, outline, scale, size_and_rise, spread, superscript_cap,
};
pub use radical::RadicalLengths;
use script::{
    FaceSlot, HintLanguage, HintedLatin, HintedSet, SymbolFont, complex_script, face_slot,
    font_side, mirrored, numeric_at, symbol_stand_in, takes_east_asian_face, upper,
};
pub(crate) use shadow::legacy_offset;

/// The faces that a run's text takes, each `None` when the run has no face for it, as
/// [`Shaper::faces_of`] finds them.
#[derive(Clone, Copy, Debug)]
struct RunFaces {
    /// The face of ASCII characters.
    ascii: Option<FaceIndex>,
    /// The face of other characters.
    other: Option<FaceIndex>,
    /// The face of ASCII characters at the size of small capitals.
    small_ascii: Option<FaceIndex>,
    /// The face of other characters at the size of small capitals.
    small_other: Option<FaceIndex>,
    /// The complex script face.
    complex: Option<FaceIndex>,
    /// The East Asian face.
    east_asian: Option<FaceIndex>,
    /// The face of the digits of a run with `w:rtl`: the ASCII font with the complex script
    /// size, bold and italic.
    rtl_digits: Option<FaceIndex>,
    /// The faces of the characters that leave the run's face when it splits by the character
    /// set of its suffixed font name, or `None` when it does not split.
    split: Option<SplitFaces>,
    /// The characters that the run's East Asian hint moves into the East Asian slot, or `None`
    /// when it moves none.
    hinted: Option<HintedSet>,
    /// The upright math font face (`Cambria Math`) for operators, delimiters, punctuation,
    /// spaces, and alphanumeric characters that a math run's own non-Cambria font lacks.
    math_fallback: Option<FaceIndex>,
}

/// The faces that the characters of each [`SplitClass`] take in a run that splits, each `None`
/// when the run's text holds no such character or the caller has no face for it, as
/// [`Shaper::split_faces`] finds them.
#[derive(Clone, Copy, Debug)]
struct SplitFaces {
    /// The face of letters.
    letter: Option<FaceIndex>,
    /// The face of General Punctuation.
    punctuation: Option<FaceIndex>,
    /// The face of Letterlike Symbols.
    symbol: Option<FaceIndex>,
}

impl SplitFaces {
    /// The face of a character that leaves the run's face, or `None` for one that keeps it.
    fn face(self, ch: char) -> Option<FaceIndex> {
        match SplitClass::of(ch)? {
            SplitClass::Letter => self.letter,
            SplitClass::Punctuation => self.punctuation,
            SplitClass::Symbol => self.symbol,
        }
    }
}

impl RunFaces {
    /// The face of a slot.
    const fn get(&self, slot: FaceSlot) -> Option<FaceIndex> {
        match slot {
            FaceSlot::Ascii => self.ascii,
            FaceSlot::Other => self.other,
            FaceSlot::SmallAscii => self.small_ascii,
            FaceSlot::SmallOther => self.small_other,
            FaceSlot::Complex => self.complex,
            FaceSlot::EastAsian => self.east_asian,
        }
    }
}

/// A place that a face of a run's text may come from, as [`Shaper::face_sources`] lists them.
/// A source borrows the family that the run asks for and the font table's alternate name, so
/// that a face lookup copies no name that the run or the table already holds.
#[derive(Clone, Debug, PartialEq, Eq)]
enum FaceSource<'a> {
    /// The family that the run asks for.
    Own(Cow<'a, FamilyName>),
    /// A name that stands for the family that the run asks for: the font table's alternate
    /// name, the first font of a name that lists fonts, or the family of a suffixed font name
    /// ([`Fonts::substitute`]).
    ///
    /// [`Fonts::substitute`]: crate::Fonts::substitute
    StandIn(Cow<'a, FamilyName>),
    /// The target's observed substitute of the missing family that the run asks for
    /// ([`Fonts::family_substitute`]).
    ///
    /// [`Fonts::family_substitute`]: crate::Fonts::family_substitute
    FamilySubstitute(Cow<'a, FamilyName>),
    /// A family that Word draws in place of a missing one.
    Fallback(Cow<'a, FamilyName>),
}

impl FaceSource<'_> {
    /// The family that the source names.
    fn family(&self) -> &FamilyName {
        match self {
            Self::Own(family)
            | Self::StandIn(family)
            | Self::FamilySubstitute(family)
            | Self::Fallback(family) => family,
        }
    }
}

/// The font slot of a run's ASCII characters, or of its other characters: each falls back to
/// the other when the run leaves it out.
fn font_slot(props: &RunProps, ascii: bool) -> Option<&FontRef> {
    if ascii {
        props.font_ascii.as_ref().or(props.font_hansi.as_ref())
    } else {
        props.font_hansi.as_ref().or(props.font_ascii.as_ref())
    }
}

/// Whether the run's ASCII and High ANSI font slots differ at the slot/reference level: two
/// explicit names match ASCII case-insensitively, an omitted slot matches the default
/// [`LAST_RESORT`] (`Times New Roman`), and theme slots match only the same theme slot (not an
/// explicit family name or another theme slot).
fn ascii_hansi_differ(props: &RunProps) -> bool {
    !match (props.font_ascii.as_ref(), props.font_hansi.as_ref()) {
        (None, None) => true,
        (Some(FontRef::Name(a)), Some(FontRef::Name(b))) => FamilyName::new(a.as_str()).is(b),
        (Some(FontRef::Name(name)), None) | (None, Some(FontRef::Name(name))) => {
            LAST_RESORT.is(name)
        }
        (Some(a), Some(b)) => a == b,
        (Some(_), None) | (None, Some(_)) => false,
    }
}

/// A stretch of characters of one shaped script in a run's text, by character index.
struct Stretch {
    range: std::ops::Range<usize>,
    script: ShapedScript,
}

/// Neutral characters (spaces and non-mirrored punctuation) that stay inside an Arabic
/// shaped stretch when they share its face, so OpenType `GPOS`/`GSUB` lookups referencing
/// `space` or punctuation apply across Arabic words.
fn is_arabic_shaped_neutral(ch: char) -> bool {
    matches!(
        ch,
        ' ' | '\u{00A0}' | '.' | ':' | '!' | '/' | '،' | '؛' | '؟'
    )
}

/// Extends the trailing stretch when it ends at `start` with the same `script`, or starts a new
/// stretch covering `start..index + 1`.
fn push_stretch(stretches: &mut Vec<Stretch>, start: usize, index: usize, script: ShapedScript) {
    match stretches.last_mut() {
        Some(last) if last.range.end == start && last.script == script => {
            last.range.end = index + 1;
        }
        _ => stretches.push(Stretch {
            range: start..index + 1,
            script,
        }),
    }
}

/// The stretches of a text whose characters have a shaped script: each is as long as the
/// characters of one script go on without another character between them. For Arabic, neutral
/// spaces and non-mirrored punctuation that satisfy `arabic_neutral` stay inside adjacent
/// Arabic stretches so OpenType `GPOS`/`GSUB` lookups across word boundaries apply.
fn shaped_stretches(chars: &[char], mut arabic_neutral: impl FnMut(char) -> bool) -> Vec<Stretch> {
    let mut stretches: Vec<Stretch> = Vec::new();
    let mut pending_neutral: Option<usize> = None;
    for (index, &ch) in chars.iter().enumerate() {
        if let Some(script) = ShapedScript::of(ch) {
            let start = if script == ShapedScript::Arabic {
                pending_neutral.take().unwrap_or(index)
            } else {
                pending_neutral = None;
                index
            };
            push_stretch(&mut stretches, start, index, script);
        } else if is_arabic_shaped_neutral(ch) && arabic_neutral(ch) {
            match stretches.last_mut() {
                Some(last) if last.range.end == index && last.script == ShapedScript::Arabic => {
                    last.range.end = index + 1;
                }
                _ => {
                    pending_neutral.get_or_insert(index);
                }
            }
        } else {
            pending_neutral = None;
        }
    }
    stretches
}

#[cfg(test)]
thread_local! {
    /// The looks at a stretch of a shaped script on this thread: one each time that
    /// [`Shaper::measure`] asks whether a stretch starts at a character. A test bounds the
    /// work of a long text by this count, and not by a time.
    static STRETCH_LOOKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Counts a look at a stretch (`STRETCH_LOOKS`). Only a test build keeps the count.
fn count_stretch_look() {
    #[cfg(test)]
    STRETCH_LOOKS.with(|looks| looks.set(looks.get() + 1));
}

/// How a substituted font was resolved by [`Shaper`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum FontResolution {
    /// Resolved through a named stand-in for the requested family (Compatifont stand-in,
    /// font-table alternate, comma-list head, suffixed base, or family substitute).
    StandIn,
    /// Resolved through Word's missing-font fallback (theme/font-table fallback, script
    /// fallback, or last resort).
    Fallback,
}

/// Which source resolved a face lookup in [`Shaper::find`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FaceOrigin {
    /// Matched the requested family directly (may still have `chosen.stands_in == true`).
    Own,
    /// Resolved through an alternate name, comma-list head, suffixed base, or family substitute.
    StandIn,
    /// Resolved through missing-font fallback.
    Fallback,
}

/// The fonts that a shaper matched or drew in another way than the runs ask, for the warnings
/// and fidelity report of a layout.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FontNotes {
    /// Each family that a run asked for and that resolved natively (not a stand-in or fallback).
    pub matched: std::collections::BTreeSet<(String, FontId)>,
    /// Each family that a run asks for, with the font of the face that draws it in its place and
    /// whether it came from a stand-in or missing-font fallback.
    pub substituted: std::collections::BTreeMap<(String, FontId), FontResolution>,
    /// Each font whose text of a shaped script the caller could not shape, with the cause. Its
    /// characters have the glyphs of the font's character map.
    pub unshaped: std::collections::BTreeSet<(FontId, ShapeFailure)>,
    /// Each font with a glyph whose ink the layout asked for and the caller could not measure,
    /// with the cause. The layout places that glyph as one without ink.
    pub ink_not_measured: std::collections::BTreeSet<(FontId, OutlineError)>,
    /// Rendered `.notdef` glyphs grouped by `(font, UnicodeBlock)` with occurrence counts.
    pub missing_glyphs: std::collections::BTreeMap<(Option<FontId>, crate::UnicodeBlock), u32>,
    /// Each family whose text the layout left out because the caller has no face for it, nor
    /// for a family that Word draws in its place: the family that the text asks for, `None`
    /// for text that names no font, with the families tried, in order.
    pub not_drawn: std::collections::BTreeSet<(Option<String>, Vec<String>)>,
    /// Each family that the layout looked for a face of and found none, nor of a family that
    /// Word draws in its place: the family of a paragraph mark, a tab or a line break, which
    /// then takes no face, or a family of a glyph fallback, which a character that its run's
    /// font lacks then does not take. The family asked for, `None` where the run names no font,
    /// with the families tried, in order.
    pub faceless: std::collections::BTreeSet<(Option<String>, Vec<String>)>,
}

impl FontNotes {
    /// Adds the notes of `other`; a note that both hold stays one.
    pub fn add(&mut self, other: Self) {
        self.matched.extend(other.matched);
        for (key, resolution) in other.substituted {
            self.substituted
                .entry(key)
                .and_modify(|existing| *existing = (*existing).max(resolution))
                .or_insert(resolution);
        }
        self.unshaped.extend(other.unshaped);
        self.ink_not_measured.extend(other.ink_not_measured);
        for (key, count) in other.missing_glyphs {
            self.missing_glyphs
                .entry(key)
                .and_modify(|existing| *existing = existing.saturating_add(count))
                .or_insert(count);
        }
        self.not_drawn.extend(other.not_drawn);
        self.faceless.extend(other.faceless);
    }
}

/// Chooses faces for runs and measures their text.
pub struct Shaper<'a> {
    fonts: &'a dyn Fonts,
    theme: &'a Theme,
    table: &'a FontTable,
    /// Every face used so far, which only [`Self::intern`] adds to.
    faces: Vec<Face>,
    /// The index of each face in `faces`, which only [`Self::intern`] adds to.
    face_indices: std::collections::HashMap<Face, FaceIndex>,
    /// Interned Word 2010 linear gradient text fills referenced by [`DrawnTextFill::Gradient`].
    text_gradients: Vec<f_office_drawingml::gradient::LinearGradient>,
    /// What the shaper drew in another way than the runs ask, for the warnings of the
    /// layout. A fork starts with none, and the layout that uses it gives them back to the
    /// shaper that it forked from ([`Self::add_notes`]). A cell, since the measures of ink
    /// that note a failure are asked through a shared shaper ([`Self::font_ink`]).
    notes: std::cell::RefCell<FontNotes>,
    /// For a glyph of a font, the lowest code point of the Arabic blocks that the font maps
    /// to it, if any ([`Self::written_char`]).
    written_chars: std::collections::HashMap<(FontId, u32), Option<char>>,
    /// The fonts used so far that are the target's own faces: their device widths come from
    /// their instructions.
    own_faces: std::collections::HashSet<FontId>,
    /// What the shaper applies to every run.
    settings: ShaperSettings,
    /// Whether the text that the shaper measures is a list label ([`Self::measure_label`]).
    label: bool,
}

/// Owned, lifetime-free shaper state preserved across incremental layout steps.
pub(crate) struct ShaperState {
    faces: Vec<Face>,
    face_indices: std::collections::HashMap<Face, FaceIndex>,
    text_gradients: Vec<f_office_drawingml::gradient::LinearGradient>,
    notes: FontNotes,
    written_chars: std::collections::HashMap<(FontId, u32), Option<char>>,
    own_faces: std::collections::HashSet<FontId>,
    settings: ShaperSettings,
    label: bool,
}

impl<'a> Shaper<'a> {
    /// Detaches the shaper's owned caches and font notes from its borrowed font/theme tables.
    pub(crate) fn into_state(self) -> ShaperState {
        ShaperState {
            faces: self.faces,
            face_indices: self.face_indices,
            text_gradients: self.text_gradients,
            notes: self.notes.into_inner(),
            written_chars: self.written_chars,
            own_faces: self.own_faces,
            settings: self.settings,
            label: self.label,
        }
    }

    /// Rehydrates a shaper from previously detached [`ShaperState`].
    #[must_use]
    pub(crate) fn from_state(
        fonts: &'a dyn Fonts,
        theme: &'a Theme,
        table: &'a FontTable,
        state: ShaperState,
    ) -> Self {
        Self {
            fonts,
            theme,
            table,
            faces: state.faces,
            face_indices: state.face_indices,
            text_gradients: state.text_gradients,
            notes: std::cell::RefCell::new(state.notes),
            written_chars: state.written_chars,
            own_faces: state.own_faces,
            settings: state.settings,
            label: state.label,
        }
    }

    /// Collects the `(asked, tried)` font needs for a run with `props` and optional `text`
    /// without shaping glyphs or laying out lines.
    pub(crate) fn collect_run_needs(
        &self,
        props: &RunProps,
        text: &str,
        out: &mut Vec<(Option<String>, Vec<String>)>,
    ) {
        let mut push = |need: (Option<String>, Vec<String>)| {
            if !out.contains(&need) {
                out.push(need);
            }
        };
        push(self.asked_and_tried(font_slot(props, true), props, Script::Latin));
        let mut saw_other = false;
        let mut saw_ea = false;
        let mut saw_complex = false;
        for ch in text.chars() {
            if ch.is_ascii() {
                continue;
            }
            if takes_east_asian_face(ch, None) {
                saw_ea = true;
            } else if complex_script(ch) {
                saw_complex = true;
            } else {
                saw_other = true;
            }
        }
        if saw_other || props.font_hansi.is_some() {
            push(self.asked_and_tried(font_slot(props, false), props, Script::Latin));
        }
        if saw_ea || props.font_east_asia.is_some() {
            let ea = props.east_asian();
            push(self.asked_and_tried(font_slot(&ea, true), &ea, Script::EastAsian));
        }
        if saw_complex || props.font_cs.is_some() || props.rtl.unwrap_or(false) {
            let cs = props.complex_script();
            push(self.asked_and_tried(font_slot(&cs, true), &cs, Script::Complex));
        }
    }

    /// Collects the `(asked, tried)` font needs for the target's math font using the same
    /// [`Self::math_font_props`] path that layout uses for equations.
    pub(crate) fn collect_math_needs(
        &self,
        props: &RunProps,
        out: &mut Vec<(Option<String>, Vec<String>)>,
    ) {
        let math_props = Self::math_font_props(props);
        self.collect_run_needs(&math_props, "x", out);
    }

    /// Makes a shaper that applies `settings` to every run.
    #[must_use]
    pub fn new(
        fonts: &'a dyn Fonts,
        theme: &'a Theme,
        table: &'a FontTable,
        settings: &ShaperSettings,
    ) -> Self {
        Self {
            fonts,
            theme,
            table,
            faces: Vec::new(),
            face_indices: std::collections::HashMap::new(),
            text_gradients: Vec::new(),
            notes: std::cell::RefCell::default(),
            written_chars: std::collections::HashMap::new(),
            own_faces: std::collections::HashSet::new(),
            settings: *settings,
            label: false,
        }
    }

    /// The largest height above the baseline and the largest depth below it, in pixels and with
    /// the signs that the font stores, that the `VDMX` table of the font of the face `face`
    /// gives at `pels` pixels per em, when it has a group for square pixels that lists `pels`.
    pub(crate) fn pixel_heights(&self, face: FaceIndex, pels: u16) -> Option<(i16, i16)> {
        let face = self.faces().get(face)?;
        self.fonts.device_heights(face.font, pels)
    }

    /// The height above the baseline and the depth below it, both positive and in whole
    /// pixels, of the face `face` at `pels` pixels per em: its `VDMX` heights there
    /// ([`Self::pixel_heights`]), or else its win top and descent at that size, each rounded to
    /// the nearest pixel. `None` for an unknown face.
    pub(crate) fn whole_pixel_heights(&self, face: FaceIndex, pels: u16) -> Option<(i64, i64)> {
        let metrics = self.faces().get(face)?.metrics;
        let em = i64::from(metrics.units_per_em.max(1));
        let rounded = |font_units: u16| {
            f_office_units::div_round(i64::from(font_units) * i64::from(pels), em)
        };
        Some(self.pixel_heights(face, pels).map_or_else(
            || (rounded(metrics.script_top), rounded(metrics.descent)),
            |(y_max, y_min)| (i64::from(y_max), -i64::from(y_min)),
        ))
    }

    /// The target's device width of the glyph `glyph` of the face `face` at `per_em` device
    /// dots per em, in dots, with the glyph's advance at the size `size` in half-EMUs: for the
    /// target's own face, the width that the face's instructions give in the interpreter's
    /// device-width mode. Nothing for another face, so
    /// that it steps by the advance rounded, and nothing in a kerned run that steps without
    /// device widths.
    pub(crate) fn device_width(
        &self,
        face: FaceIndex,
        glyph: u32,
        (size, per_em): (i64, i64),
    ) -> Option<(i64, i64)> {
        let face = self.faces().get(face)?;
        self.settings
            .kerned_device_width(self.kerned_run(face), Some(()))?;
        if !self.own_faces.contains(&face.font) {
            return None;
        }
        let ppem = u16::try_from(per_em).ok()?;
        let width = i64::from(self.fonts.device_width(face.font, glyph, ppem)?);
        let units = i64::from(self.fonts.advance(face.font, glyph)?);
        let em = i64::from(face.metrics.units_per_em.max(1));
        Some((width, f_office_units::div_round(units * size, em)))
    }

    /// The advance that a glyph's font gives it at its face's size, in half-EMUs, which the
    /// shaper takes away from a mark: nothing for a glyph whose font gives none.
    pub(crate) fn own_advance(&self, glyph: &Glyph) -> Option<Length> {
        let face = self.faces().get(glyph.face)?;
        let units = i64::from(self.fonts.advance(face.font, glyph.id)?);
        let em = i64::from(face.metrics.units_per_em.max(1));
        let scaled = f_office_units::div_round(units * face.size.units(), em);
        Some(Length::from_units(scaled))
    }

    /// What rounding takes from a glyph's own advance at its face's size, as a numerator over a
    /// denominator in half-EMUs: the exact advance that the edge check counts (the font's
    /// advance in font units at the size, as [`ShaperSettings::counted_advance`] counts it)
    /// less the advance rounded to whole half-EMUs that the glyph keeps. Nothing for a later
    /// part of a ligature, which has no advance, or for a glyph whose font gives none.
    /// Kerning, character spacing and a synthetic bold add to the kept advance in whole
    /// half-EMUs and take nothing here.
    pub(crate) fn advance_rounding(&self, glyph: &Glyph) -> Option<(i64, i64)> {
        let face = self.faces().get(glyph.face).filter(|_| !glyph.part)?;
        let units = i64::from(self.fonts.advance(face.font, self.width_glyph(glyph))?);
        let em = i64::from(face.metrics.units_per_em.max(1));
        let scaled = units * face.size.units();
        let kept = f_office_units::div_round(scaled, em);
        let (exact, per) = self.settings.counted_advance((scaled, em));
        Some((exact - per * kept, per))
    }

    /// The pair kerning in the advance of `glyph` that the device steps in whole dots on its
    /// own, as character spacing, in a kerned run that steps so
    /// (`KernedDeviceWidths::OwnWithKerningOnItsOwn` after `KernedDeviceWidths::in_run`); zero
    /// elsewhere.
    pub(crate) fn kerning_on_its_own(&self, glyph: &Glyph) -> Length {
        let kerned = self
            .faces()
            .get(glyph.face)
            .and_then(|face| self.kerned_run(face));
        self.settings.kerning_on_its_own(kerned, glyph.kerning)
    }

    /// Whether the device steps the glyphs of the face `face` by their exact distances
    /// rounded without the bias: the glyphs of a kerned run that so steps
    /// (`KernedDeviceWidths::Nearest` after `KernedDeviceWidths::in_run`).
    pub(crate) fn steps_without_bias(&self, face: FaceIndex) -> bool {
        let kerned = self
            .faces()
            .get(face)
            .and_then(|face| self.kerned_run(face));
        self.settings.steps_without_bias(kerned)
    }

    /// The kerning source of the face `face` of a run that steps as a kerned run and whether it
    /// steps as a face that stands in for the run's font, which decide how its glyphs step
    /// ([`ShaperSettings::kerned_device_width`]). Nothing for a run that steps as one without
    /// kerning ([`ShaperSettings::kerned_steps_of`]).
    fn kerned_run(&self, face: &Face) -> Option<(f_office_fonts::KerningSource, bool)> {
        self.settings
            .kerned_steps_of(face.kerned, face.ligatures, face.standing.font)
            .map(|stands_in| (self.fonts.kerning_source(face.font), stands_in))
    }

    /// Whether the spaces next to East Asian text advance half an em.
    #[must_use]
    pub fn balances_spaces(&self) -> bool {
        self.settings.space_balance == SpaceBalance::HalfEm
    }

    /// Gives a space next to East Asian text half an em of its face as its advance. The space
    /// keeps its own width for the PDF writer, as a kerned glyph does.
    pub fn balance_space(&self, glyph: &mut Glyph) {
        let Some(size) = self.faces().get(glyph.face).map(|face| face.size) else {
            return;
        };
        self.kern_glyph(glyph, size.div_toward_zero(2) - glyph.advance);
    }

    /// Whether the target draws the `w14:shadow`, `w14:glow`, `w14:reflection`, and legacy
    /// WordprocessingML text effects (`w:shadow`, `w:outline`, `w:emboss`, `w:imprint`) of a run
    /// with `props`, so that the run shows no unsupported warning for the drawn effects.
    pub(crate) fn draws_text_effects(&self, props: &RunProps) -> (bool, bool, bool, bool) {
        let effects = self.settings.drawn_text_effects(
            props,
            outline(props),
            Length::ZERO,
            (Length::ZERO, Length::ZERO, Length::ZERO),
        );
        (
            effects.w14_shadow,
            effects.glow.is_some(),
            effects.reflection.is_some(),
            effects.legacy,
        )
    }

    /// Every face used so far, at the face indices that glyphs and the pieces of lines name.
    #[must_use]
    pub fn faces(&self) -> Faces<'_> {
        Faces(&self.faces)
    }

    /// Makes another shaper with the same fonts and settings, no faces and no notes yet.
    #[must_use]
    pub fn fork(&self) -> Self {
        Self::new(self.fonts, self.theme, self.table, &self.settings)
    }

    /// Takes the fonts that this shaper drew in another way than the runs ask, for the warnings
    /// of the layout, and leaves it none.
    pub fn take_notes(&mut self) -> FontNotes {
        std::mem::take(self.notes.get_mut())
    }

    /// Adds the notes of a fork of this shaper, as when the layout of a story ends.
    pub fn add_notes(&mut self, notes: FontNotes) {
        self.notes.get_mut().add(notes);
    }

    /// The width in whole thousandths of an em that the target's PDF writer writes for a glyph
    /// of a face, where it differs from the text object's rounding of the glyph's own advance
    /// ([`crate::grid::TextObject::push_at`]). With `HintedAdvanceAt1000` the writer counts the
    /// width from the glyph's advance in font units: the bi-level advance at 1000 pixels per
    /// em, one pixel to the thousandth, or for a face that F-Office cannot hint the advance
    /// times 1000 over the units per em, a half rounded up. The text object rounds the advance
    /// kept at the size in whole half-EMUs, which can take the half of a width that ends in
    /// exactly half a thousandth, such as an odd advance in an em of 2,000 units, so the glyph takes the writer's width where it differs from that rounding or
    /// from the plain rounding in font units. `None` leaves the text object's rounding of the
    /// glyph's placed advance, which holds what a synthetic bold, a character scale or East
    /// Asian spacing adds to it: with `RoundsAdvance`, where the writer's width is that
    /// rounding, and for a glyph that the font gives no advance.
    fn written_width(&self, face: &Face, glyph: u32) -> Option<u16> {
        self.settings.written_width(|| {
            let thousandths = f_office_units::scale::THOUSANDTHS;
            let units = i64::from(self.fonts.advance(face.font, glyph)?);
            let em = i64::from(face.metrics.units_per_em.max(1));
            let linear = f_office_units::div_round(units * thousandths, em);
            let ppem = u16::try_from(thousandths).ok()?;
            let width = self
                .fonts
                .bi_level_advance(face.font, glyph, ppem)
                .map_or(linear, i64::from);
            let size = face.size.units();
            let kept = (size > 0)
                .then(|| f_office_units::div_round(face.scale(units).units() * thousandths, size));
            Some((linear, width, kept))
        })
    }

    /// The advance of a glyph of a font in font units.
    #[must_use]
    pub fn font_advance(&self, font: FontId, glyph: u32) -> Option<u16> {
        self.fonts.advance(font, glyph)
    }

    /// The lowest and the highest point of a glyph's ink, at the size of its face and from
    /// the face's baseline, up positive; none for a glyph without ink or without an outline.
    #[must_use]
    pub fn ink(&self, glyph: &Glyph) -> Option<(Length, Length)> {
        let face = self.faces().get(glyph.face)?;
        let (low, high) = self.font_ink(face.font, glyph.id)?;
        let em = i64::from(face.metrics.units_per_em.max(1));
        let at_size = |units: i32| {
            Length::from_units(f_office_units::div_round(
                i64::from(units) * face.size.units(),
                em,
            ))
        };
        Some((at_size(low), at_size(high)))
    }

    /// The lowest and the highest point of the ink of the glyph `glyph` of the font `font`, in
    /// font units from the baseline, up positive; none for a glyph without ink. Ink that the
    /// caller cannot measure counts as none, and the shaper notes the font and the cause for
    /// the layout's warning.
    fn font_ink(&self, font: FontId, glyph: u32) -> Option<(i32, i32)> {
        self.fonts.ink(font, glyph).unwrap_or_else(|cause| {
            self.notes
                .borrow_mut()
                .ink_not_measured
                .insert((font, cause));
            None
        })
    }

    /// The face `face` with its baseline raised by `by`, or lowered when `by` is negative, as
    /// a part of a fraction moves away from its bar: a face that takes its line raised or
    /// lowered with its text moves its line as well.
    pub fn moved(&mut self, face: FaceIndex, by: Length) -> FaceIndex {
        let Some(mut moved) = self.faces().get(face).copied() else {
            return face;
        };
        moved.rise += by;
        if moved.math.in_fraction {
            moved.raised += by;
        }
        self.intern(&moved)
    }

    /// The face `face` raised by `by`, or lowered when it is negative, as [`Self::moved`] moves
    /// it, as a row of a matrix moves: in a font with a `MATH` table the line gives it the room
    /// of its ink as drawn, with the font's `MathLeading` at the face's size above it, and not
    /// the room of its font's lines; in another font the room of its lines moves with it.
    pub fn lifted(&mut self, face: FaceIndex, by: Length) -> FaceIndex {
        let Some(mut moved) = self.faces().get(face).copied() else {
            return face;
        };
        moved.rise += by;
        moved.raised += by;
        if let Some(limits) = self.fonts.math_limits(moved.font) {
            moved.math.room = MathRoom::Ink {
                leading: moved.scale(i64::from(limits.math_leading)),
            };
        }
        self.intern(&moved)
    }

    /// As [`Self::lifted`], but with `leading` as the room above the lifted ink (the equation's
    /// `MathLeading` at the enclosing size rather than the script's size).
    pub fn lifted_with_leading(
        &mut self,
        face: FaceIndex,
        by: Length,
        leading: Length,
    ) -> FaceIndex {
        let Some(mut moved) = self.faces().get(face).copied() else {
            return face;
        };
        moved.rise += by;
        moved.raised += by;
        if self.fonts.math_limits(moved.font).is_some() {
            moved.math.room = MathRoom::Ink { leading };
        }
        self.intern(&moved)
    }

    /// The document's theme.
    #[must_use]
    pub fn theme(&self) -> &'a Theme {
        self.theme
    }

    /// The interned linear gradient text fill at `index`, if any.
    pub(crate) fn text_gradient(
        &self,
        index: usize,
    ) -> Option<&f_office_drawingml::gradient::LinearGradient> {
        self.text_gradients.get(index)
    }

    /// Resolves `props.text_fill` against the document theme into `(color, text_fill)`.
    fn resolve_text_fill(&mut self, props: &RunProps) -> (f_office_paint::Rgb, DrawnTextFill) {
        match props.text_fill.as_ref() {
            Some(crate::props::TextFill::None) => (color(props), DrawnTextFill::None),
            Some(crate::props::TextFill::Solid(draw_color)) => {
                match draw_color.resolve(&self.theme.shapes.colors) {
                    Some((rgb, opacity)) if opacity == f_office_paint::Opacity::FULL => {
                        (rgb, DrawnTextFill::Solid)
                    }
                    Some((rgb, opacity)) if opacity.share() == 0 => (rgb, DrawnTextFill::None),
                    Some((rgb, opacity)) => (rgb, DrawnTextFill::Translucent(opacity)),
                    None => (color(props), DrawnTextFill::Solid),
                }
            }
            Some(crate::props::TextFill::Gradient(gradient)) => {
                let id = self.intern_text_gradient(gradient);
                (color(props), DrawnTextFill::Gradient(id))
            }
            None => (color(props), DrawnTextFill::Solid),
        }
    }

    /// Interns `gradient` and returns its index in [`Self::text_gradients`].
    fn intern_text_gradient(
        &mut self,
        gradient: &f_office_drawingml::gradient::LinearGradient,
    ) -> usize {
        if let Some(index) = self
            .text_gradients
            .iter()
            .position(|existing| existing == gradient)
        {
            return index;
        }
        let index = self.text_gradients.len();
        self.text_gradients.push(gradient.clone());
        index
    }

    /// The font services of the layout.
    pub(crate) fn fonts(&self) -> &'a dyn Fonts {
        self.fonts
    }

    /// Returns the face for ASCII or for other Latin characters of a run.
    pub fn face(&mut self, props: &RunProps, ascii: bool) -> Option<FaceIndex> {
        self.face_at(props, ascii, false, Script::Latin)
    }

    /// Returns the face for the complex script characters of a run: its complex script font,
    /// size, bold and italic, as every character of a run with complex formatting takes them.
    /// Where the target's quirk says so, an italic run takes the upright face of its weight
    /// instead ([`Self::upright_for_language`]).
    pub fn complex_face(&mut self, props: &RunProps) -> Option<FaceIndex> {
        let complex = props.complex_script();
        let face = self.face_at(&complex, true, false, Script::Complex)?;
        let settings = self.settings;
        if complex.italic == Some(true)
            && complex.math != Some(true)
            && let Some(upright) =
                settings.complex_upright(|| self.upright_for_language(&complex, face))
        {
            return Some(self.slanted(upright));
        }
        Some(face)
    }

    /// The face `face` as an upright face that stands in for an italic one, which the target
    /// slants as it slants the face of a family without an italic face.
    fn slanted(&mut self, face: FaceIndex) -> FaceIndex {
        let Some(&upright) = self.faces().get(face) else {
            return face;
        };
        self.intern(&Face {
            standing: Standing {
                synthetic_italic: true,
                ..upright.standing
            },
            ..upright
        })
    }

    /// The upright face of the same family and weight as `italic`, the italic complex script
    /// face of a run whose complex script properties are `complex`: when `italic` holds
    /// letters of a complex script but not the alef of the script of the run's bidi language
    /// (Arabic when the run and the document defaults name none), and the upright face holds
    /// it. Otherwise `None`, and the run keeps its italic face.
    fn upright_for_language(&mut self, complex: &RunProps, italic: FaceIndex) -> Option<FaceIndex> {
        let letter = if complex.hebrew_language() {
            HEBREW_ALEF
        } else {
            ARABIC_ALEF
        };
        let complex_letters =
            self.has_glyph(italic, HEBREW_ALEF) || self.has_glyph(italic, ARABIC_ALEF);
        if !complex_letters || self.has_glyph(italic, letter) {
            return None;
        }
        let upright = RunProps {
            italic: Some(false),
            ..complex.clone()
        };
        let face = self.face_at(&upright, true, false, Script::Complex)?;
        let family = |shaper: &Self, face: FaceIndex| {
            let font = shaper.faces().get(face)?.font;
            shaper.fonts.family_name(font)
        };
        (self.has_glyph(face, letter) && family(self, face) == family(self, italic)).then_some(face)
    }

    /// Notes the face that [`Self::find`] chose for a run: either a native match, a stand-in, or
    /// a missing-font fallback. Text that asks for no family gives no note.
    fn note_face(
        &mut self,
        slot: Option<&FontRef>,
        props: &RunProps,
        (chosen, origin): (&ChosenFace, FaceOrigin),
    ) {
        let Some(family) = self.asked_family(slot, props) else {
            return;
        };
        let family = family.to_owned();
        let notes = self.notes.get_mut();
        match origin {
            FaceOrigin::Own if !chosen.stands_in => {
                notes.matched.insert((family, chosen.font));
            }
            FaceOrigin::Fallback => {
                notes
                    .substituted
                    .insert((family, chosen.font), FontResolution::Fallback);
            }
            FaceOrigin::Own | FaceOrigin::StandIn => {
                notes
                    .substituted
                    .entry((family, chosen.font))
                    .or_insert(FontResolution::StandIn);
            }
        }
    }

    /// Returns a face of a run for text of `script`, at 4/5 of its size for small capitals.
    fn face_at(
        &mut self,
        props: &RunProps,
        ascii: bool,
        small: bool,
        script: Script,
    ) -> Option<FaceIndex> {
        let slot = font_slot(props, ascii);
        let (mut chosen, origin) = self.find_noted(slot, props, script)?;
        self.note_face(slot, props, (&chosen, origin));
        // A font made for East Asian text gives the lines of its East Asian and Latin text
        // more room, and not those of its complex script text.
        if script == Script::Complex {
            chosen.metrics.east_asian = false;
        }
        let font = chosen.font;
        let (math_font, math_em) = self.math_metrics_for(slot, props, &mut chosen);
        let heights = |pels| self.fonts.device_heights(font, pels);
        let dot = self.settings.dot;
        let room = self.settings.single_line().east_asian_room(&chosen.metrics);
        let how = self.settings.script_move(
            || superscript_cap(props, &chosen.metrics),
            || Edges {
                metrics: &chosen.metrics,
                dot,
                heights: &heights,
                room,
            },
        );
        // A part of a fraction takes its line at its own size, raised or lowered with its text.
        let (size, rise, in_fraction) = if let Some(script) = props.math_script {
            let limit = |step, base| self.limit_shift(math_font, math_em, step, base);
            let axis = |ch, size| self.axis_shift(math_font, math_em, ch, size);
            math_size_and_rise(props, script, dot, &limit, &axis)
        } else {
            let scale = self
                .settings
                .script_scale(|| ScriptScale::of_face(&chosen.metrics, props.vertical));
            let (size, rise) = size_and_rise(props, how, scale);
            (size, rise, false)
        };
        let (line_size, raised) = if in_fraction {
            (size, rise)
        } else {
            (full_size(props), props.position.unwrap_or(Length::ZERO))
        };
        let size = if small {
            // 4/5 of the size, to the nearest whole half-point.
            let (part, whole) = crate::params::SMALL_CAPS_SCALE;
            let step = whole * Length::UNITS_PER_HALF_POINT;
            let halves = (size.units() * part + step / 2) / step;
            Length::from_units(halves * Length::UNITS_PER_HALF_POINT)
        } else {
            size
        };
        let mut face = Face {
            font: chosen.font,
            metrics: chosen.metrics,
            size,
            line_size,
            single_line: self.settings.single_line(),
            color: f_office_paint::Rgb::BLACK,
            lines: self.settings.run_lines(
                (props.underline, props.strike),
                props.changed.unwrap_or(false),
            ),
            background: background(props),
            rise,
            raised,
            math: MathFace {
                in_fraction,
                large: props
                    .math_script
                    .is_some_and(crate::props::MathScript::is_large),
                script_level: props
                    .math_script
                    .filter(|script| script.shifted_at(props.drawn_half_points()))
                    .and_then(|script| script.style().script_level()),
                room: self.math_room(props, in_fraction, math_font, math_em),
                phantom: props.phantom.unwrap_or(false),
            },
            outline: None,
            text_fill: DrawnTextFill::Solid,
            effect: props.effect.unwrap_or(false),
            shadow_room: ShadowRoom::default(),
            shadow: None,
            glow: None,
            reflection: None,
            relief: None,
            kerned: kerned(props),
            east_asian_script: props
                .east_asian_script()
                .or(self.settings.east_asian_script),
            ligatures: self.settings.ligatures && props.ligatures.unwrap_or(false),
            scale: props.scale,
            border: if props.bordered.unwrap_or(false) {
                face::RunBorder::Active
            } else {
                face::RunBorder::None
            },
            standing: Standing {
                synthetic_bold: chosen.synthetic_bold,
                synthetic_italic: chosen.synthetic_italic,
                font: origin != FaceOrigin::Own,
            },
        };
        self.apply_face_effects(&mut face, props);
        Some(self.intern(&face))
    }

    /// Resolves and writes color, text fill, outline, shadow room, and drawn text effects onto
    /// `face`.
    fn apply_face_effects(&mut self, face: &mut Face, props: &RunProps) {
        let line_metrics = (face.ascent(), face.descent(), face.line_size);
        let (color, mut text_fill) = self.resolve_text_fill(props);
        let mut drawn_outline = outline(props);
        let effects =
            self.settings
                .drawn_text_effects(props, drawn_outline, face.size, line_metrics);
        if effects.legacy_outline {
            drawn_outline = Some(f_office_paint::Outline {
                width: crate::params::LEGACY_TEXT_OUTLINE_WIDTH,
                color,
                join: f_office_paint::Join::Round,
            });
            if props.text_fill.is_none() {
                text_fill = if effects.shadow.is_some() {
                    DrawnTextFill::White
                } else {
                    DrawnTextFill::None
                };
            }
        }
        face.color = color;
        face.text_fill = text_fill;
        face.outline = drawn_outline;
        face.shadow_room = self.settings.shadow_room(
            (
                props.shadow,
                props.glow,
                props.reflection.as_deref().copied(),
            ),
            line_metrics,
        );
        face.shadow = effects.shadow;
        face.glow = effects.glow;
        face.reflection = effects.reflection;
        face.relief = effects.relief;
    }

    /// Whether `slot` on `props` resolves to the default math font (`Cambria Math`) or has no
    /// named family.
    fn is_math_font_slot(&self, slot: Option<&FontRef>, props: &RunProps) -> bool {
        self.asked_family(slot, props)
            .map(FamilyName::new)
            .is_none_or(|f| f.is(crate::math::MATH_FONT))
    }

    /// A copy of `props` asking for the upright regular math font (`Cambria Math`).
    fn math_font_props(props: &RunProps) -> RunProps {
        let font = FontRef::Name(crate::math::MATH_FONT.to_owned());
        let mut plain = props.clone();
        plain.font_ascii = Some(font.clone());
        plain.font_hansi = Some(font);
        plain.bold = Some(false);
        plain.italic = Some(false);
        plain
    }

    /// The `FontId` and em of the math font for `props`, replacing the vertical line-height
    /// fields of `chosen.metrics` with the math font's when a math run draws in another font.
    fn math_metrics_for(
        &self,
        slot: Option<&FontRef>,
        props: &RunProps,
        chosen: &mut ChosenFace,
    ) -> (FontId, i64) {
        if props.math == Some(true)
            && !self.is_math_font_slot(slot, props)
            && let Some((math_font, math_metrics)) = self.math_font_base(props)
        {
            apply_math_line_metrics(&mut chosen.metrics, math_metrics);
            return (math_font, i64::from(math_metrics.units_per_em.max(1)));
        }
        (chosen.font, i64::from(chosen.metrics.units_per_em.max(1)))
    }

    /// The `FontId` and metrics of the upright math font for `props`, when available.
    fn math_font_base(&self, props: &RunProps) -> Option<(FontId, FaceMetrics)> {
        let plain = Self::math_font_props(props);
        self.find(plain.font_ascii.as_ref(), &plain, Script::Latin)
            .map(|(chosen, _)| (chosen.font, chosen.metrics))
    }

    /// The faces that a run's text takes: for ASCII and other characters, the same at the
    /// size of small capitals, for complex script characters, for East Asian characters, and
    /// for the digits of a run with `w:rtl`. Complex script characters, and every character
    /// of a right-to-left or complex script run, take the complex script font, size, bold and
    /// italic; the digits of a run with `w:rtl` take the ASCII font with the complex script
    /// size, bold and italic, unless the run's bidi language is Hebrew.
    fn faces_of(&mut self, props: &RunProps, text: &str, small_caps: bool) -> RunFaces {
        let small = |shaper: &mut Self, ascii| {
            small_caps
                .then(|| shaper.face_at(props, ascii, true, Script::Latin))
                .flatten()
        };
        let complex = props.uses_complex_formatting() || text.chars().any(complex_script);
        let hinted = self.hinted_set(props);
        let east_asian = text.chars().any(|ch| takes_east_asian_face(ch, hinted));
        let math_fallback = (props.math == Some(true)
            && (!self.is_math_font_slot(font_slot(props, true), props)
                || !self.is_math_font_slot(font_slot(props, false), props)))
        .then(|| self.face(&Self::math_font_props(props), true))
        .flatten();
        RunFaces {
            ascii: self.face(props, true),
            other: self.face(props, false),
            small_ascii: small(self, true),
            small_other: small(self, false),
            complex: complex.then(|| self.complex_face(props)).flatten(),
            east_asian: east_asian
                .then(|| self.face_at(&props.east_asian(), true, false, Script::EastAsian))
                .flatten(),
            rtl_digits: props
                .has_digit_face()
                .then(|| self.face(&props.complex_digits(), true))
                .flatten(),
            split: self.split_faces(props, text),
            hinted,
            math_fallback,
        }
    }

    /// The faces of the characters of a run's text that leave its face when the run splits by
    /// the character set of its suffixed font name, or `None` when it does
    /// not split. A run splits on a target where the family of a suffixed font name stands for
    /// it, when its font for characters outside ASCII is such a name that the caller lacks,
    /// whose font table entry names the suffix's character set and no alternate, and whose
    /// family the caller has. Each class's font comes in the run's style.
    fn split_faces(&mut self, props: &RunProps, text: &str) -> Option<SplitFaces> {
        if !text.chars().any(|ch| SplitClass::of(ch).is_some()) {
            return None;
        }
        let written = self.asked_family(font_slot(props, false), props)?;
        let (base, set) = self.settings.suffixed_base(written)?;
        let name = FamilyName::new(written);
        let splits = self.table.suffix_charset(&name) == Some(set)
            && self.table.alternate(&name).is_none()
            && self.fonts.face(&name, false, false).is_none()
            && self
                .fonts
                .substitute(&FamilyName::new(base), false, false)
                .is_some();
        if !splits {
            return None;
        }
        let mut face = |class: SplitClass| {
            if !text.chars().any(|ch| SplitClass::of(ch) == Some(class)) {
                return None;
            }
            let named = Some(FontRef::Name(class.family().as_str().to_owned()));
            let other = RunProps {
                font_ascii: named.clone(),
                font_hansi: named,
                ..props.clone()
            };
            self.face_at(&other, false, false, Script::Latin)
        };
        Some(SplitFaces {
            letter: face(SplitClass::Letter),
            punctuation: face(SplitClass::Punctuation),
            symbol: face(SplitClass::Symbol),
        })
    }

    /// Measures the text of a list label into glyphs, as [`Self::measure`] does with the
    /// substitute faces of labels.
    pub fn measure_label(&mut self, props: &RunProps, text: &str, out: &mut Vec<Glyph>) {
        self.label = true;
        self.measure(props, text, out);
        self.label = false;
    }

    /// Measures text into glyphs. Hidden text has no glyphs.
    pub fn measure(&mut self, props: &RunProps, text: &str, out: &mut Vec<Glyph>) {
        if props.hidden.unwrap_or(false) {
            return;
        }
        let caps = props.caps.unwrap_or(false);
        let small_caps = !caps && props.small_caps.unwrap_or(false);
        let faces = self.faces_of(props, text, small_caps);
        let all_complex = props.uses_complex_formatting();
        let right_to_left = props.rtl.unwrap_or(false);
        let text = mirrored(text, right_to_left);
        let text = text.as_ref();
        let start = out.len();
        let symbol_font = self.symbol_font(props);
        let chars: Vec<char> = text.chars().collect();
        // A stretch of characters of a shaped script takes its glyphs from the font's layout
        // tables; every other character takes the glyph of the font's character map. The
        // stretches are in the order of the text and do not overlap, so one walk over them
        // finds the stretch that starts at each character and the end of the one that holds
        // it: each character looks at one stretch only.
        let arabic_face = self.arabic_stretch_face(
            &chars,
            &faces,
            props,
            small_caps || props.math == Some(true) || symbol_font.is_some(),
        );
        let stretches = shaped_stretches(&chars, |ch| {
            let Some(face) = arabic_face else {
                return false;
            };
            !self.settings.leaves_out(ch, false)
                && self.char_face(&faces, (ch, false, all_complex, false), props) == Some(face)
                && self.has_glyph(face, ch)
        });
        let mut ahead = stretches.iter().peekable();
        let mut shaped_end = 0;
        let mut format_characters = FormatCharacters::default();
        for (index, &original) in chars.iter().enumerate() {
            let starts = ahead.next_if(|stretch| {
                count_stretch_look();
                stretch.range.start == index
            });
            if let Some(stretch) = starts {
                self.measure_stretch(
                    &chars,
                    stretch,
                    &faces,
                    props,
                    (out, &mut format_characters),
                );
                shaped_end = stretch.range.end;
            }
            if index < shaped_end
                || self.push_invisible(
                    &faces,
                    original,
                    props,
                    start,
                    (out, &mut format_characters),
                )
            {
                continue;
            }
            let numeric = numeric_at(&chars, index);
            // Lower-case letters and spaces are small; capitals, digits and punctuation keep
            // the full size.
            let small = small_caps && (original.is_lowercase() || original.is_whitespace());
            for ch in upper(original, caps || small) {
                let face = self.char_face(&faces, (ch, small, all_complex, numeric), props);
                if let Some(mut glyph) = face.and_then(|f| self.glyph(f, ch)) {
                    glyph.sizing = self.line_sizing(&faces, (ch, small, all_complex), glyph.face);
                    glyph.ch = self.settings.symbol_text(ch, symbol_font, glyph.id);
                    if right_to_left {
                        glyph.ch = self.settings.bracket_text(glyph.ch);
                    }
                    out.push(glyph);
                }
            }
        }
        format_characters.mark(out);
        self.finish_run(props, out.get_mut(start..).unwrap_or_default());
    }

    /// Holds equation run spaces and sizes operator spaces for math runs.
    fn finish_math_spaces(&self, math: Option<bool>, measured: &mut [Glyph]) {
        let Some(italic_math) = math else {
            return;
        };
        hold_math_spaces(measured);
        if italic_math {
            self.size_operator_spaces(measured);
        }
    }

    /// Applies the run's direction, optional ligatures and spacing to its measured glyphs.
    fn finish_run(&self, props: &RunProps, measured: &mut [Glyph]) {
        // A page number that Word computes has the direction that the reader of fields gives
        // it, in place of that of its own run.
        // Such a number keeps its UAX 9 classes with every bidi language.
        let direction = match props.field_rtl {
            Some(rtl) => RunDirection::of(rtl, Some(BidiLanguageClass::Unicode)),
            None => RunDirection::of(props.rtl.unwrap_or(false), props.bidi_class),
        };
        let all_complex = props.uses_complex_formatting();
        let hint = self.hinted_latin(props);
        let split_latin = ascii_hansi_differ(props);
        // The font of the run's East Asian face, found when a character first asks for it.
        let mut east_asian: Option<Option<FontId>> = None;
        for glyph in measured.iter_mut() {
            glyph.direction = direction;
            glyph.east_asian_language = props.east_asian_language;
            let (ch, face) = (glyph.ch, glyph.face);
            let has_glyph = |side| match side {
                FontSide::EastAsian => east_asian
                    .get_or_insert_with(|| self.east_asian_font(props))
                    .is_some_and(|font| self.fonts.glyph(font, ch).is_some()),
                FontSide::HighAnsi | FontSide::Other | FontSide::Open => self.has_glyph(face, ch),
            };
            glyph.side = font_side(ch, all_complex, hint, split_latin, has_glyph);
        }
        self.finish_math_spaces(props.math, measured);
        // Character spacing keeps the letters apart.
        let spaced = props.spacing.is_some_and(|s| s != Length::ZERO);
        if self.settings.ligatures && props.ligatures.unwrap_or(false) && !spaced {
            self.join_ligatures(measured);
        }
        if kerned(props) {
            self.kern(measured);
        }
        self.correct_italics(measured, props.math == Some(true));
        self.embolden(measured);
        self.count_bold_units(measured);
        scale(measured, props.scale);
        // On a target that keeps the spacing apart, the PDF writer writes a spaced glyph's own
        // width and puts the spacing into the adjustment after it, as it does with kerning, and
        // the glyph carries its spacing for the device's steps.
        if self.settings.spacing_on_its_own(spaced) == Some(true) {
            for glyph in measured.iter_mut() {
                self.keep_own_width(glyph);
            }
        }
        spread(measured, props.spacing, &self.settings);
    }

    /// The face that an Arabic stretch in `chars` uses, when `chars` contains at least one
    /// drawn Arabic character and neutral spaces/punctuation may join it (`!exclude`).
    fn arabic_stretch_face(
        &mut self,
        chars: &[char],
        faces: &RunFaces,
        props: &RunProps,
        exclude: bool,
    ) -> Option<FaceIndex> {
        if exclude {
            return None;
        }
        let settings = self.settings;
        let &lead = chars.iter().find(|&&ch| {
            ShapedScript::of(ch) == Some(ShapedScript::Arabic) && !settings.leaves_out(ch, false)
        })?;
        let slot = face_slot(lead, false, (props.uses_complex_formatting(), faces.hinted));
        let face = faces.get(slot)?;
        let face = settings
            .block_substitute(|| {
                (!self.has_glyph(face, lead))
                    .then(|| self.block_substitute(face, slot, props, lead))
                    .flatten()
            })
            .unwrap_or(face);
        Some(face)
    }

    /// Measures a stretch of characters of a shaped script: the glyphs that the font's layout
    /// tables give for it, in the order of the text, in the face of its first shaped character.
    /// When the caller cannot shape the text, each character takes the glyph of the character
    /// map, and the shaper keeps the cause.
    fn measure_stretch(
        &mut self,
        chars: &[char],
        stretch: &Stretch,
        faces: &RunFaces,
        props: &RunProps,
        (out, format_characters): (&mut Vec<Glyph>, &mut FormatCharacters),
    ) {
        let letters = chars.get(stretch.range.clone()).unwrap_or_default();
        let settings = self.settings;
        let math = props.math == Some(true);
        let Some(&lead) = letters.iter().find(|&&ch| {
            ShapedScript::of(ch) == Some(stretch.script) && !settings.leaves_out(ch, math)
        }) else {
            format_characters.note_all(letters, out.len());
            return;
        };
        let slot = face_slot(lead, false, (props.uses_complex_formatting(), faces.hinted));
        let Some(face) = faces.get(slot) else {
            self.note_not_drawn(props, slot);
            return;
        };
        let face = settings
            .block_substitute(|| {
                (!self.has_glyph(face, lead))
                    .then(|| self.block_substitute(face, slot, props, lead))
                    .flatten()
            })
            .unwrap_or(face);
        let Some(font) = self.faces().get(face).map(|f| f.font) else {
            return;
        };
        let text: String = letters.iter().collect();
        let request = ShapeRequest {
            text: &text,
            script: stretch.script,
            direction: stretch.script.direction(),
            language: None,
        };
        match self.fonts.shape(font, &request) {
            Ok(glyphs) => self.push_shaped(face, (&text, &glyphs), math, (out, format_characters)),
            Err(cause) => {
                self.notes.get_mut().unshaped.insert((font, cause));
                for &ch in letters {
                    format_characters.note(Some(ch), out.len());
                    if !settings.leaves_out(ch, math) {
                        out.extend(self.glyph(face, ch));
                    }
                }
            }
        }
    }

    /// The lowest code point of the Arabic blocks that the font maps to the glyph `id`, or
    /// nothing when the font maps none to it: the character that a target with
    /// `ShapedGlyphText::LowestMappedCharacter` writes for the glyph.
    fn written_char(&mut self, face: FaceIndex, id: u32) -> Option<char> {
        let font = self.faces().get(face)?.font;
        if let Some(&ch) = self.written_chars.get(&(font, id)) {
            return ch;
        }
        let blocks = [
            '\u{0600}'..='\u{06FF}',
            '\u{FB50}'..='\u{FDFF}',
            '\u{FE70}'..='\u{FEFF}',
        ];
        let ch = blocks
            .into_iter()
            .flatten()
            .find(|&c| self.fonts.glyph(font, c) == Some(id));
        self.written_chars.insert((font, id), ch);
        ch
    }

    /// Adds the glyphs of a shaped text. The glyphs of one group of characters take the
    /// group's characters in their order. Where the target writes the lowest character that
    /// the font maps to a glyph, each glyph writes that character ([`Self::written_char`])
    /// when there is one; else it writes its own character of the group. A character that has
    /// no glyph of its own, such as the alef of a lam-alef ligature, becomes a part of the
    /// glyph before it, unless that glyph is the only one of the group and writes a character
    /// that the font maps to it: the font's character for the ligature then stands for the
    /// whole group. A character that
    /// the shaper does not draw as any other, in text of an equation when `math` holds, adds
    /// no glyph. `format_characters` gets the index in `out` of the glyph that comes after each
    /// format character.
    fn push_shaped(
        &mut self,
        face: FaceIndex,
        (text, glyphs): (&str, &[ShapedGlyph]),
        math: bool,
        (out, format_characters): (&mut Vec<Glyph>, &mut FormatCharacters),
    ) {
        let settings = self.settings;
        let mut at = 0;
        while let Some(first) = glyphs.get(at) {
            let rest = glyphs.get(at..).unwrap_or_default();
            let len = rest
                .iter()
                .take_while(|g| g.cluster == first.cluster)
                .count();
            let end = rest.get(len).map_or(text.len(), |g| g.cluster);
            let group: Vec<char> = text
                .get(first.cluster..end)
                .unwrap_or_default()
                .chars()
                .collect();
            let mut whole = false;
            for (index, shaped) in rest.iter().take(len).enumerate() {
                let ch = group.get(index).or(group.last()).copied();
                format_characters.note(ch, out.len());
                let Some(ch) = ch.filter(|&ch| !settings.leaves_out(ch, math)) else {
                    continue;
                };
                let written = if settings.writes_lowest_mapped_character()
                    && ShapedScript::of(ch).is_some()
                {
                    self.written_char(face, shaped.glyph)
                } else {
                    None
                };
                whole = len == 1 && written.is_some();
                out.extend(self.shaped_glyph(face, written.unwrap_or(ch), shaped));
            }
            let parts = if whole { group.len() } else { len };
            for &ch in group.iter().skip(parts) {
                format_characters.note(Some(ch), out.len());
                if settings.leaves_out(ch, math) {
                    continue;
                }
                if let Some(mut part) = self.glyph(face, ch) {
                    part.part = true;
                    part.advance = Length::ZERO;
                    out.push(part);
                }
            }
            at += len.max(1);
        }
    }

    /// One glyph of a shaped text for the character `ch`. An advance other than the glyph's
    /// own is a change after the glyph's own width, as kerning is.
    fn shaped_glyph(&self, face: FaceIndex, ch: char, shaped: &ShapedGlyph) -> Option<Glyph> {
        let f = self.faces().get(face)?;
        let units = self.advance_units(f.font, ch, shaped.glyph);
        let own = f.scale(i64::from(units));
        let mut glyph = Glyph {
            face,
            ch,
            id: shaped.glyph,
            advance: own,
            offset: (
                f.scale(i64::from(shaped.offset.0)),
                f.scale(i64::from(shaped.offset.1)),
            ),
            spacing: Length::ZERO,
            kerning: Length::ZERO,
            auto_space: Length::ZERO,
            trailing_auto_space: Length::ZERO,
            counted: Length::ZERO,
            written: self.written_width(f, shaped.glyph),
            part: false,
            label: false,
            space: SpaceKind::Free,
            starts_run: false,
            left_out_before: LeftOutBefore::Nothing,
            direction: RunDirection::LeftToRight,
            side: FontSide::Open,
            place: TextPlace::default(),
            sizing: LineSizing::ByFace,
            punctuation_half: PunctuationHalf::Open,
            east_asian_language: None,
        };
        let glyph_units = self.fonts.advance(f.font, shaped.glyph).unwrap_or(0);
        let advance =
            f.scale(i64::from(shaped.advance) + i64::from(units) - i64::from(glyph_units));
        self.kern_glyph(&mut glyph, advance - own);
        Some(glyph)
    }

    /// The glyph of `font` whose widths the glyph `id` that draws `ch` takes, in the layout and
    /// in the device's steps: the glyph itself, or for a space that the target lays out with the
    /// advance of another character (`ShaperSettings::width_of`), that character's glyph, where
    /// the font has it.
    fn width_glyph_of(&self, font: f_office_fonts::FontId, ch: char, id: u32) -> u32 {
        self.settings
            .width_of(ch)
            .and_then(|other| self.fonts.glyph(font, other))
            .filter(|&other| self.fonts.advance(font, other).is_some())
            .unwrap_or(id)
    }

    /// The glyph whose widths the glyph `glyph` takes ([`Self::width_glyph_of`]): its own id
    /// for a face that the shaper does not know.
    pub(crate) fn width_glyph(&self, glyph: &Glyph) -> u32 {
        self.faces().get(glyph.face).map_or(glyph.id, |face| {
            self.width_glyph_of(face.font, glyph.ch, glyph.id)
        })
    }

    /// The advance in font units of the glyph `id` of `font` that draws `ch`, as wide as the
    /// glyph whose widths it takes ([`Self::width_glyph_of`]).
    fn advance_units(&self, font: f_office_fonts::FontId, ch: char, id: u32) -> u16 {
        self.fonts
            .advance(font, self.width_glyph_of(font, ch, id))
            .unwrap_or(0)
    }

    /// Replaces the standard ligatures in each stretch of glyphs of one face. The ligature takes
    /// the place of its first glyph, and the other glyphs become parts of it.
    fn join_ligatures(&self, glyphs: &mut [Glyph]) {
        let mut start = 0;
        while let Some(face) = glyphs.get(start).map(|g| g.face) {
            let rest = glyphs.get_mut(start..).unwrap_or_default();
            let len = rest.iter().take_while(|g| g.face == face).count();
            if let (Some(stretch), Some(f)) = (rest.get_mut(..len), self.faces().get(face)) {
                let ids: Vec<u32> = stretch.iter().map(|g| g.id).collect();
                for ligature in self.fonts.ligatures(f.font, &ids) {
                    let end = ligature.start + ligature.len;
                    let Some(joined) = stretch.get_mut(ligature.start..end) else {
                        continue;
                    };
                    let advance = self.fonts.advance(f.font, ligature.glyph).unwrap_or(0);
                    // The writer writes the ligature's own width, not its first letter's.
                    let written = self.written_width(f, ligature.glyph);
                    for (index, glyph) in joined.iter_mut().enumerate() {
                        if index == 0 {
                            glyph.id = ligature.glyph;
                            glyph.advance = f.scale(i64::from(advance));
                            glyph.written = written;
                        } else {
                            glyph.part = true;
                            glyph.advance = Length::ZERO;
                        }
                    }
                }
            }
            start += len;
        }
    }

    /// Widens each glyph of a synthetic bold face, except spaces and the later parts of a
    /// ligature, by a fiftieth of the font size, when the target's variant widens it.
    fn embolden(&self, glyphs: &mut [Glyph]) {
        for glyph in glyphs.iter_mut().filter(|g| !g.part && g.ch != ' ') {
            if let Some(widening) = self
                .faces()
                .get(glyph.face)
                .filter(|f| f.standing.synthetic_bold)
                .and_then(|face| self.settings.bold_widening(face.size))
            {
                glyph.advance += widening;
            }
        }
    }

    /// Gives the spaces that stand around the operators of a math run their widths in shares
    /// of their face's em, rounded to half-EMUs: the space of a binary operator its share, and
    /// the hair space that a relation's space adds the rest of the relation's share, in place
    /// of the advances of the font's characters that stand for them.
    fn size_operator_spaces(&self, glyphs: &mut [Glyph]) {
        for glyph in glyphs.iter_mut() {
            let (part, whole) = match glyph.ch {
                crate::math::OPERATOR_SPACE => crate::params::MATH_OPERATOR_SPACE,
                crate::math::HAIR_SPACE => crate::params::MATH_RELATION_SPACE_EXTRA,
                _ => continue,
            };
            if let Some(face) = self.faces().get(glyph.face) {
                glyph.advance =
                    Length::from_units(f_office_units::div_round(face.size.units() * part, whole));
            }
        }
    }

    /// Gives each glyph of a synthetic bold face what line breaking counts beside its advance,
    /// rounded to half-EMUs: what the edge check counts ([`Self::bold_counted_extra`]).
    fn count_bold_units(&self, glyphs: &mut [Glyph]) {
        for glyph in glyphs.iter_mut() {
            if let Some((size, per)) = self.bold_counted_extra(glyph) {
                glyph.counted = Length::from_units((2 * size + per) / (2 * per));
            }
        }
    }

    /// What the edge check and the segment rule count beside the advance of `glyph`, a
    /// numerator over a denominator in half-EMUs: one font unit of the face, the font size over
    /// its units per em, for a glyph of a synthetic bold face under the variant
    /// `CountsAFontUnit`, a space too, except a later part of a ligature, and nothing otherwise.
    pub(crate) fn bold_counted_extra(&self, glyph: &Glyph) -> Option<(i64, i64)> {
        self.faces()
            .get(glyph.face)
            .filter(|f| !glyph.part && f.standing.synthetic_bold)
            .and_then(|face| {
                self.settings.bold_counted_unit(
                    face.size.units(),
                    i64::from(face.metrics.units_per_em.max(1)),
                )
            })
    }

    /// Whether a run's characters come from a symbol font that the table of symbol text has
    /// codes for, Symbol or Wingdings.
    #[must_use]
    pub fn names_symbol_font(&self, props: &RunProps) -> bool {
        self.symbol_font(props).is_some()
    }

    /// The symbol font that a run's characters come from, if they come from one that the table
    /// of symbol text has codes for.
    fn symbol_font(&self, props: &RunProps) -> Option<SymbolFont> {
        props
            .font_hansi
            .as_ref()
            .or(props.font_ascii.as_ref())
            .and_then(|f| self.theme.family(f))
            .and_then(SymbolFont::of)
            .filter(|&font| symbol_table::has_codes(font))
    }

    /// Adds the pair kerning and East Asian punctuation kerning of each glyph and the next one
    /// to the first glyph's advance. The parts of a ligature are skipped, so the ligature kerns
    /// with the glyph after it.
    fn kern(&self, glyphs: &mut [Glyph]) {
        let mut left_index: Option<usize> = None;
        for index in 0..glyphs.len() {
            if glyphs.get(index).is_none_or(|g| g.part) {
                continue;
            }
            if let Some(at) = left_index
                && let Some((head, tail)) = glyphs.split_at_mut_checked(index)
                && let (Some(left), Some(right)) = (head.get_mut(at), tail.first_mut())
            {
                let adjust = self.pair_kerning(left, right);
                self.kern_pair(left, adjust);
                self.punctuation_kerning(left, right);
            }
            left_index = Some(index);
        }
    }

    /// Adds `adjust` of pair kerning to a glyph's advance, and keeps it apart in the glyph's
    /// kerning.
    fn kern_pair(&self, glyph: &mut Glyph, adjust: Length) {
        self.kern_glyph(glyph, adjust);
        glyph.kerning += adjust;
    }

    /// Subtracts `punct` of East Asian punctuation kerning from a glyph's advance; under
    /// `DeviceAdvance::ExtrasOnTheirOwn` keeps it in `glyph.auto_space` so the device steps it
    /// in whole dots on its own in every compatibility mode, else keeps it in `glyph.kerning`.
    fn kern_punctuation(&self, glyph: &mut Glyph, punct: Length) {
        if punct == Length::ZERO {
            return;
        }
        let adjust = -punct;
        self.kern_glyph(glyph, adjust);
        if let Some(extra) = self.settings.spacing_on_its_own(adjust) {
            glyph.auto_space += extra;
        } else {
            glyph.kerning += adjust;
        }
    }

    /// Adds `adjust` of kerning to a glyph's advance. A kerned glyph keeps its own width for
    /// the PDF writer: the writer writes the font's width of the glyph and puts the kerning
    /// into the adjustment after it, so a glyph without a written width of the target's gets
    /// its own advance, rounded to whole thousandths of an em, as its written width.
    fn kern_glyph(&self, glyph: &mut Glyph, adjust: Length) {
        if adjust == Length::ZERO {
            return;
        }
        self.keep_own_width(glyph);
        glyph.advance += adjust;
    }

    /// Gives a glyph without a written width of the target's its own advance, rounded to whole
    /// thousandths of an em, as its written width, before kerning or character spacing changes
    /// the advance: the PDF writer writes the font's width of the glyph and puts the change
    /// into the adjustment after it.
    fn keep_own_width(&self, glyph: &mut Glyph) {
        if glyph.written.is_some() {
            return;
        }
        let size = self.faces().get(glyph.face).map_or(0, |f| f.size.units());
        if size > 0 {
            let thousandths = f_office_units::scale::THOUSANDTHS;
            let width = f_office_units::div_round(glyph.advance.units() * thousandths, size);
            glyph.written = u16::try_from(width).ok();
        }
    }

    /// The tatweel glyph (U+0640) of the face `face`, with the advance `advance` where one is
    /// given, as a kashida draws it: an advance other than the glyph's own is a change after its
    /// width, as kerning is. `None` when the face's font has no tatweel.
    pub(crate) fn tatweel(&self, face: FaceIndex, advance: Option<Length>) -> Option<Glyph> {
        let f = self.faces().get(face)?;
        self.fonts.glyph(f.font, TATWEEL).filter(|&id| id != 0)?;
        let mut glyph = self.glyph(face, TATWEEL)?;
        if let Some(advance) = advance {
            let own = glyph.advance;
            self.kern_glyph(&mut glyph, advance - own);
        }
        Some(glyph)
    }

    /// Kerns the last glyph of one run with the first glyph of the next run, when both runs
    /// are kerned and at the same size (font pair kerning only when both draw the same font;
    /// East Asian punctuation kerning also across fallback faces of the same size).
    pub fn kern_across(&self, left: &mut Glyph, right: &mut Glyph) {
        let (Some(l), Some(r)) = (self.faces().get(left.face), self.faces().get(right.face)) else {
            return;
        };
        if l.kerned && r.kerned && l.size == r.size && !right.part {
            if l.font == r.font {
                let units =
                    self.kerning_units(l, self.kerning_id(l, left), self.kerning_id(r, right));
                self.kern_pair(left, l.scale(i64::from(units)));
            }
            self.punctuation_kerning(left, right);
        }
    }

    /// Adds the italic correction of a slanted glyph, from the `MATH` table of its font, when an
    /// upright glyph follows it: one of the same font and size to which the table gives none, or
    /// one of another font, such as the text after an equation. Two slanted glyphs keep their
    /// advances, and so does a glyph before one of its own font at another size, a script's.
    pub fn correct_italic(&self, left: &mut Glyph, right: &Glyph) {
        let (Some(l), Some(r)) = (self.faces().get(left.face), self.faces().get(right.face)) else {
            return;
        };
        if (l.font == r.font && l.size != r.size) || right.part {
            return;
        }
        let Some(correction) = self.glyph_italic_correction(left) else {
            return;
        };
        if self.fonts.italic_correction(r.font, right.id).is_none() {
            self.kern_glyph(left, correction);
        }
    }

    /// The italic correction of `glyph` at its size, from the `MATH` table of its font; none for
    /// a glyph that the table does not list.
    pub fn glyph_italic_correction(&self, glyph: &Glyph) -> Option<Length> {
        let face = self.faces().get(glyph.face)?;
        let units = self.fonts.italic_correction(face.font, glyph.id)?;
        Some(face.scale(i64::from(units)))
    }

    /// The italic corrections inside one run's glyphs, by [`Self::correct_italic`], except before
    /// an ordinary glyph of the slanted glyph's own font, such as a digit or `∞`; a delimiter,
    /// punctuation, an operator, a unary sign such as `¬` or a space keeps it. The first glyph
    /// of the next run is no such exception, as [`Self::correct_italic_at_join`] adds.
    fn correct_italics(&self, glyphs: &mut [Glyph], math: bool) {
        let mut left: Option<usize> = None;
        for index in 0..glyphs.len() {
            let Some(right) = glyphs.get(index).copied().filter(|g| !g.part) else {
                continue;
            };
            if let Some(left) = left.and_then(|at| glyphs.get_mut(at))
                && !(crate::math::ordinary(right.ch) && (math || self.same_font(left, &right)))
            {
                self.correct_italic(left, &right);
            }
            left = Some(index);
        }
    }

    /// Adds the italic correction that [`Self::correct_italics`] leaves out inside one run, when
    /// `right` is the first glyph of a run measured in one text with the run of `left`.
    pub fn correct_italic_at_join(&self, left: &mut Glyph, right: &Glyph) {
        if crate::math::ordinary(right.ch) {
            self.correct_italic(left, right);
        }
    }

    /// Whether `left` and `right` are drawn in the same font.
    fn same_font(&self, left: &Glyph, right: &Glyph) -> bool {
        let faces = self.faces();
        matches!(
            (faces.get(left.face), faces.get(right.face)),
            (Some(l), Some(r)) if l.font == r.font
        )
    }

    /// The kerning of a pair of glyphs of `face` in font units, from the table that the target
    /// reads in the document's mode and compatibility settings.
    fn kerning_units(&self, face: &Face, left: u32, right: u32) -> i32 {
        let table = self.settings.kerning_table();
        self.fonts.kerning(face.font, left, right, table)
    }

    /// The glyph of `face` whose kerning pairs `glyph` takes: the glyph itself, but for a
    /// non-breaking hyphen that the target draws as a hyphen-minus, which keeps the pairs of the
    /// glyph that it is drawn with under `NonBreakingHyphen::OwnGlyph`: the face's glyph for
    /// U+2011, or else its hyphen-minus.
    fn kerning_id(&self, face: &Face, glyph: &Glyph) -> u32 {
        self.settings
            .kerning_chars(glyph.ch)
            .map_or(glyph.id, |chars| {
                chars
                    .iter()
                    .find_map(|ch| self.fonts.glyph(face.font, *ch))
                    .unwrap_or(glyph.id)
            })
    }

    /// The font-table pair kerning between two glyphs, or 0 when they are in different faces.
    fn pair_kerning(&self, left: &Glyph, right: &Glyph) -> Length {
        self.faces()
            .get(left.face)
            .filter(|_| left.face == right.face)
            // The layout tables kerned the glyphs of a shaped script already.
            .filter(|_| ShapedScript::of(left.ch).is_none() && ShapedScript::of(right.ch).is_none())
            .map_or(Length::ZERO, |face| {
                let units = self.kerning_units(
                    face,
                    self.kerning_id(face, left),
                    self.kerning_id(face, right),
                );
                face.scale(i64::from(units))
            })
    }

    /// Applies East Asian punctuation kerning to a pair of same-size glyphs, closing the blank
    /// half of whichever mark gave it up so justified punctuation compression does not shrink it
    /// a second time.
    fn punctuation_kerning(&self, left: &mut Glyph, right: &mut Glyph) {
        if self.settings.punctuation_kerning != PunctuationKerning::On {
            return;
        }
        let (Some(l), Some(r)) = (self.faces().get(left.face), self.faces().get(right.face)) else {
            return;
        };
        if l.size != r.size {
            return;
        }
        let Some(closed) = crate::lines::kerned_pair(left.ch, right.ch, l.east_asian_script) else {
            return;
        };
        let half = l.size.div_toward_zero(2);
        self.kern_punctuation(left, half);
        match closed {
            crate::lines::KernedMark::Left => left.punctuation_half = PunctuationHalf::Closed,
            crate::lines::KernedMark::Right => {
                if left.punctuation_half == PunctuationHalf::Open {
                    left.punctuation_half = PunctuationHalf::OpenShortened(half);
                }
                right.punctuation_half = PunctuationHalf::Closed;
            }
        }
    }

    /// The side that a run's East Asian hint gives the characters of Latin-1, the Latin letters
    /// outside it and Greek Extended, or `None` for a run without the hint.
    fn hinted_latin(&self, props: &RunProps) -> Option<HintedLatin> {
        if !props.east_asian_hint.unwrap_or(false) {
            return None;
        }
        Some(self.settings.hinted_latin(|| {
            let charset = self
                .asked_family(props.font_east_asia.as_deref(), props)
                .and_then(|family| self.table.east_asian_charset(&FamilyName::new(family)));
            HintLanguage::of(props.east_asian_script(), charset)
        }))
    }

    /// The characters that a run's East Asian hint moves into the East Asian slot, by the
    /// target's set and whether the run's East Asian face is Times New Roman, or `None` for a run
    /// without the hint.
    fn hinted_set(&self, props: &RunProps) -> Option<HintedSet> {
        if !props.east_asian_hint.unwrap_or(false) {
            return None;
        }
        self.settings.hinted_set(|| {
            self.east_asian_font(props).is_some_and(|font| {
                let family = self.fonts.layout_family(font).unwrap_or_default();
                FamilyName::new(&family).is("Times New Roman")
            })
        })
    }

    /// The font of the face that a run's East Asian font gives its text, without noting a
    /// substitution: the face that the run's East Asian characters take.
    fn east_asian_font(&self, props: &RunProps) -> Option<FontId> {
        let east_asian = props.east_asian();
        self.find(font_slot(&east_asian, true), &east_asian, Script::EastAsian)
            .map(|(chosen, _)| chosen.font)
    }

    /// Adds what the shaper draws for `ch` when it does not draw it as any other character,
    /// and gives whether it does not: a character that it leaves out adds nothing, and a
    /// variation selector joins the character before it, so that one inside its run adds
    /// nothing and one that opens its run, whose glyphs start at `start` of `out`, adds its
    /// face's missing glyph. `format_characters` notes a format character that it leaves out.
    fn push_invisible(
        &mut self,
        faces: &RunFaces,
        ch: char,
        props: &RunProps,
        start: usize,
        (out, format_characters): (&mut Vec<Glyph>, &mut FormatCharacters),
    ) -> bool {
        match self.settings.invisible(ch, props.math == Some(true)) {
            Invisible::Drawn => false,
            Invisible::Left => {
                format_characters.note(Some(ch), out.len());
                true
            }
            Invisible::Joined => {
                if out.len() == start {
                    out.extend(self.selector_glyph(faces, ch, props));
                }
                true
            }
        }
    }

    /// The glyph of a variation selector that opens its run: the missing glyph of the face of
    /// its slot, without a substitute face, with that glyph's advance.
    fn selector_glyph(&mut self, faces: &RunFaces, ch: char, props: &RunProps) -> Option<Glyph> {
        let slot = face_slot(ch, false, (props.uses_complex_formatting(), faces.hinted));
        let Some(face) = faces.get(slot) else {
            self.note_not_drawn(props, slot);
            return None;
        };
        self.glyph(face, ch)
    }

    /// Measures one character in a face.
    #[must_use]
    /// The face of a character from the faces of its run, with the substitute face for a
    /// character that the face of its slot has no glyph for.
    fn char_face(
        &mut self,
        faces: &RunFaces,
        (ch, small, all_complex, numeric): (char, bool, bool, bool),
        props: &RunProps,
    ) -> Option<FaceIndex> {
        let slot = face_slot(ch, small, (all_complex, faces.hinted));
        let Some(face) = faces.get(slot) else {
            self.note_not_drawn(props, slot);
            return None;
        };
        if slot == FaceSlot::Other
            && let Some(split) = faces.split.and_then(|split| split.face(ch))
        {
            return Some(split);
        }
        let face = self.digit_face(faces, (face, slot), numeric);
        if let Some(math_face) = faces.math_fallback
            && matches!(
                slot,
                FaceSlot::Ascii | FaceSlot::Other | FaceSlot::SmallAscii | FaceSlot::SmallOther
            )
        {
            return Some(if ch.is_alphanumeric() && self.has_glyph(face, ch) {
                face
            } else {
                math_face
            });
        }
        let settings = self.settings;
        if slot == FaceSlot::EastAsian
            && let Some(substitute) = settings.block_substitute(|| {
                (!self.keeps_east_asian(face))
                    .then(|| {
                        self.substitute_face(&substitute::EAST_ASIAN_SUBSTITUTE, slot, props, ch)
                    })
                    .flatten()
            })
        {
            return Some(substitute);
        }
        if self.has_glyph(face, ch) {
            return Some(face);
        }
        if let Some(substitute) =
            settings.block_substitute(|| self.block_substitute(face, slot, props, ch))
        {
            return Some(substitute);
        }
        if slot == FaceSlot::EastAsian {
            return self.east_asian_fallback(props, ch).or(Some(face));
        }
        Some(face)
    }

    /// Whether the glyph of `ch` that the face `drawn` draws sizes its line: an en or em space
    /// that the face of its slot lacks, drawn by another, a substitute face, sizes none.
    fn line_sizing(
        &self,
        faces: &RunFaces,
        (ch, small, all_complex): (char, bool, bool),
        drawn: FaceIndex,
    ) -> LineSizing {
        if !matches!(ch, '\u{2002}' | '\u{2003}') {
            return LineSizing::ByFace;
        }
        let substituted = faces
            .get(face_slot(ch, small, (all_complex, faces.hinted)))
            .is_some_and(|own| own != drawn && !self.has_glyph(own, ch));
        if substituted {
            LineSizing::Nothing
        } else {
            LineSizing::ByFace
        }
    }

    /// Whether the face of the East Asian slot keeps a character that MS Mincho has, by the
    /// family whose layout its font has and the classification of its font
    /// ([`substitute::keeps_east_asian`]).
    fn keeps_east_asian(&self, face: FaceIndex) -> bool {
        let Some(font) = self.faces().get(face).map(|f| f.font) else {
            return true;
        };
        let family = self.fonts.layout_family(font).unwrap_or_default();
        substitute::keeps_east_asian(&family, self.fonts.classification(font))
    }

    /// The substitute face of `ch` that the table of substitute faces gives for `face`, which
    /// lacks it, or in a list label the label's substitute: the first of the table's faces for
    /// `ch` (its row, or its group's steps) that has it.
    fn block_substitute(
        &mut self,
        face: FaceIndex,
        slot: FaceSlot,
        props: &RunProps,
        ch: char,
    ) -> Option<FaceIndex> {
        if props.form_text == Some(true) && substitute::kept_in_form_text(ch) {
            return None;
        }
        let font = self.faces().get(face)?.font;
        let family = self.fonts.layout_family(font).unwrap_or_default();
        let latin = match slot {
            FaceSlot::Complex => false,
            FaceSlot::EastAsian => !CharacterClass::EastAsianFont.contains(ch),
            _ => true,
        };
        let substitutes = match self
            .label
            .then(|| substitute::label_substitute(ch))
            .flatten()
        {
            Some(label) => vec![label],
            None => substitute::substitutes((&family, self.fonts.classification(font)), ch, latin),
        };
        substitutes
            .iter()
            .find_map(|substitute| self.substitute_face(substitute, slot, props, ch))
    }

    /// The face of the family `family` for `ch` of `slot`, with the run's properties of that
    /// slot, when the caller has the family and it has a glyph for `ch`.
    fn substitute_face(
        &mut self,
        family: &FamilyName,
        slot: FaceSlot,
        props: &RunProps,
        ch: char,
    ) -> Option<FaceIndex> {
        let (base, script) = match slot {
            FaceSlot::Complex => (props.complex_script(), Script::Complex),
            FaceSlot::EastAsian => (props.east_asian(), Script::Latin),
            _ => (props.clone(), Script::Latin),
        };
        let (bold, italic) = (base.bold.unwrap_or(false), base.italic.unwrap_or(false));
        let chosen = self.fallback_family_face(family, bold, italic)?;
        self.fonts.glyph(chosen.font, ch)?;
        let named = Some(FontRef::Name(family.as_str().to_owned()));
        let other = RunProps {
            font_ascii: named.clone(),
            font_hansi: named,
            font_cs: None,
            ..base
        };
        let small = matches!(slot, FaceSlot::SmallAscii | FaceSlot::SmallOther);
        self.face_at(&other, true, small, script)
    }

    /// The face of a character that takes `face` from `slot`. In a run with `w:rtl`, a digit,
    /// and a full stop, comma or colon between two digits (`numeric`), takes the run's ASCII
    /// font with the complex script size, bold and italic, unless that face stands in for a
    /// font that is missing. In a run with `w:cs` alone they keep the complex script face.
    fn digit_face(
        &self,
        faces: &RunFaces,
        (face, slot): (FaceIndex, FaceSlot),
        numeric: bool,
    ) -> FaceIndex {
        if slot != FaceSlot::Complex || !numeric {
            return face;
        }
        faces
            .rtl_digits
            .filter(|&ascii| self.faces().get(ascii).is_some_and(|f| !f.standing.font))
            .unwrap_or(face)
    }

    /// Whether the font of a face has a glyph for a character.
    fn has_glyph(&self, face: FaceIndex, ch: char) -> bool {
        self.faces()
            .get(face)
            .is_some_and(|f| self.fonts.glyph(f.font, ch).is_some())
    }

    /// The caller's face of a family that a glyph fallback looks in, in the style asked for,
    /// or none. A family that the caller lacks is noted as one without a face.
    fn fallback_family_face(
        &self,
        family: &FamilyName,
        bold: bool,
        italic: bool,
    ) -> Option<ChosenFace> {
        let chosen = self.fonts.face(family, bold, italic);
        if chosen.is_none() {
            let name = family.as_str().to_owned();
            let faceless = (Some(name.clone()), vec![name]);
            self.notes.borrow_mut().faceless.insert(faceless);
        }
        chosen
    }

    /// The face for an East Asian character that the run's East Asian font has no glyph for:
    /// the first font of Word's list that the caller has and that has the glyph.
    fn east_asian_fallback(&mut self, props: &RunProps, ch: char) -> Option<FaceIndex> {
        let (bold, italic) = (props.bold.unwrap_or(false), props.italic.unwrap_or(false));
        let family = EAST_ASIAN_GLYPH_FALLBACK.into_iter().find(|family| {
            self.fallback_family_face(&FamilyName::from_static(family), bold, italic)
                .is_some_and(|chosen| self.fonts.glyph(chosen.font, ch).is_some())
        })?;
        let named = Some(FontRef::Name(family.to_owned()));
        let other = RunProps {
            font_ascii: named.clone(),
            font_hansi: named,
            ..props.east_asian()
        };
        self.face_at(&other, true, false, Script::Latin)
    }

    pub fn glyph(&self, face: FaceIndex, ch: char) -> Option<Glyph> {
        let f = self.faces().get(face)?;
        // A soft hyphen shows the hyphen-minus when a line ends there.
        // A non-breaking hyphen shows the font's U+2011, or else its hyphen-minus, or the
        // hyphen-minus itself, as the target's quirk says.
        let shown = self.settings.shown_char(ch);
        let id = self
            .fonts
            .glyph(f.font, shown)
            .or_else(|| symbol_stand_in(ch).and_then(|c| self.fonts.glyph(f.font, c)))
            .or_else(|| {
                (shown == '\u{2011}')
                    .then(|| self.fonts.glyph(f.font, '-'))
                    .flatten()
            })
            .unwrap_or(0);
        // A display draws an n-ary operator with the larger variant of its glyph.
        let id = if f.math.large {
            self.fonts.display_variant(f.font, id).unwrap_or(id)
        } else {
            id
        };
        // A script and a script of a script draw the font's script glyphs.
        let id = f
            .math
            .script_level
            .and_then(|level| self.fonts.script_glyph(f.font, id, level))
            .unwrap_or(id);
        let advance = f.scale(i64::from(self.advance_units(f.font, ch, id)));
        let written = self.written_width(f, id);
        Some(Glyph {
            face,
            ch,
            id,
            advance,
            offset: (Length::ZERO, Length::ZERO),
            spacing: Length::ZERO,
            kerning: Length::ZERO,
            auto_space: Length::ZERO,
            trailing_auto_space: Length::ZERO,
            counted: Length::ZERO,
            written,
            part: false,
            label: false,
            space: SpaceKind::Free,
            starts_run: false,
            left_out_before: LeftOutBefore::Nothing,
            direction: RunDirection::LeftToRight,
            side: FontSide::Open,
            place: TextPlace::default(),
            sizing: LineSizing::ByFace,
            punctuation_half: PunctuationHalf::Open,
            east_asian_language: None,
        })
    }

    /// The italic correction of the glyph that a display draws for the n-ary operator
    /// `operator` in the face `face`, the larger variant of its glyph or else the glyph, at the
    /// face's size: how far the lower limit beside the operator starts left of the upper one.
    /// Nothing when the face's font has no `MATH` table that lists the glyph.
    pub fn italic_correction(&self, face: FaceIndex, operator: char) -> Length {
        let Some(f) = self.faces().get(face) else {
            return Length::ZERO;
        };
        let correction = self.fonts.glyph(f.font, operator).and_then(|glyph| {
            let glyph = self.fonts.display_variant(f.font, glyph).unwrap_or(glyph);
            self.fonts.italic_correction(f.font, glyph)
        });
        correction.map_or(Length::ZERO, |units| f.scale(i64::from(units)))
    }

    /// How far the limits of an integral inside a line stand from its ink, in the face `face` of
    /// the operator, at the face's size: the upper limit's baseline at most the math font's
    /// `SuperscriptBaselineDropMax` below the top of the ink, and the lower limit's at least its
    /// `SubscriptBaselineDropMin` below the bottom. Nothing when the face's font has no `MATH`
    /// table.
    pub fn limit_drops(&self, face: FaceIndex) -> Option<(Length, Length)> {
        let f = self.faces().get(face)?;
        let limits = self.fonts.math_limits(f.font)?;
        Some((
            f.scale(i64::from(limits.superscript_baseline_drop_max)),
            f.scale(i64::from(limits.subscript_baseline_drop_min)),
        ))
    }

    /// The shift of a limit of an n-ary operator that a display draws with the larger variant of
    /// its glyph (`step`), whose base has the size `base`, up positive, from the ink of that
    /// variant at the size of the base. A limit over the operator rises from the top of the ink by
    /// the math font's `UpperLimitBaselineRiseMin`, and one under it drops from the bottom by
    /// `LowerLimitBaselineDropMin`. A limit beside the operator rises to the top of the ink less
    /// `SuperscriptBaselineDropMax`, or drops to the bottom less `SubscriptBaselineDropMin`.
    /// Nothing for another step, or when the font of the limit, `font` with `em` units per em,
    /// lacks the operator or its `MATH` table.
    fn limit_shift(
        &self,
        font: FontId,
        em: i64,
        step: crate::props::MathStep,
        base: Length,
    ) -> Option<Length> {
        use crate::props::MathStep;
        let (limit, upper) = match step {
            MathStep::UpperLimit(limit) => (limit, true),
            MathStep::LowerLimit(limit) => (limit, false),
            _ => return None,
        };
        let limits = self.fonts.math_limits(font)?;
        let glyph = self.fonts.glyph(font, limit.operator)?;
        let glyph = self.fonts.display_variant(font, glyph).unwrap_or(glyph);
        let (low, high) = self.font_ink(font, glyph)?;
        let (edge, gap) = match (upper, limit.beside) {
            (true, false) => (high, limits.upper_limit_baseline_rise_min),
            (false, false) => (low, -limits.lower_limit_baseline_drop_min),
            (true, true) => (high, -limits.superscript_baseline_drop_max),
            (false, true) => (low, -limits.subscript_baseline_drop_min),
        };
        let units = i64::from(edge) + i64::from(gap);
        Some((base * units).div_round(em))
    }

    /// The shift of the glyph of `ch` in the font `font`, with `em` units per em, at the size
    /// `size`, up positive, that puts the middle of its ink on the math axis: the axis height
    /// ([`crate::params::MATH_AXIS_HEIGHT`]) less the middle of the ink. Nothing when the font
    /// lacks the character or the glyph has no ink.
    fn axis_shift(&self, font: FontId, em: i64, ch: char, size: Length) -> Option<Length> {
        let glyph = self.fonts.glyph(font, ch)?;
        let (low, high) = self.font_ink(font, glyph)?;
        let (axis, axis_em) = crate::params::MATH_AXIS_HEIGHT;
        let middle = (size * (i64::from(low) + i64::from(high))).div_round(2 * em);
        Some((size * axis).div_round(axis_em) - middle)
    }

    /// How the line gives a run its room: a display's n-ary operator drawn with the larger
    /// variant of its glyph, a run in a limit over or under it, a part of a fraction
    /// (`in_fraction`) of an inline equation, and on a target whose quirk variant is
    /// `DisplayFractionRoom::Ink` a part of a fraction of a display, the room of their ink with
    /// the `MathLeading` of the math font `font`, with `em` units per em, at the size of the
    /// equation above it, when the font has a `MATH` table; a part of a fraction of an inline
    /// equation in a font without one, the room of its ink below the line; and on a target
    /// whose quirk variant is `ScriptRoom::Ink` a superscript or a subscript outside a
    /// fraction, of an inline equation or a display, the room of its font's lines and of its
    /// ink with the same `MathLeading` above it, in a font with a `MATH` table.
    fn math_room(&self, props: &RunProps, in_fraction: bool, font: FontId, em: i64) -> MathRoom {
        let operator = props
            .math_script
            .is_some_and(|s| s.is_display() && (s.is_large() || s.in_limit()));
        let part = math_ink_below(props, in_fraction);
        let script = props
            .math_script
            .is_some_and(crate::props::MathScript::in_script);
        self.settings
            .math_room((operator, part, in_fraction, script), || {
                self.math_leading(props, font, em)
            })
    }

    /// The `MathLeading` of the math font `font`, with `em` units per em, at the size of the
    /// equation of a run with `props`; none for a font without a `MATH` table.
    fn math_leading(&self, props: &RunProps, font: FontId, em: i64) -> Option<Length> {
        self.fonts
            .math_limits(font)
            .map(|limits| (full_size(props) * i64::from(limits.math_leading)).div_round(em))
    }

    /// The `MathLeading` of the math font of a run with `props` at the size of its equation;
    /// none for a font without a `MATH` table.
    pub fn equation_leading(&mut self, props: &RunProps) -> Option<Length> {
        let face = self.face(props, true)?;
        let f = self.faces().get(face)?;
        let (font, em) = (f.font, i64::from(f.metrics.units_per_em.max(1)));
        self.math_leading(props, font, em)
    }

    /// Whether the content of a delimiter whose character draws `glyph` counts as a subformula:
    /// whether its `need` reaches the font's `DelimitedSubFormulaMinHeight` at the glyph's size.
    pub fn counts_as_sub_formula(&self, glyph: &Glyph, need: Length) -> bool {
        self.faces().get(glyph.face).is_some_and(|f| {
            let em = i64::from(f.metrics.units_per_em.max(1));
            self.fonts.math_limits(f.font).is_some_and(|limits| {
                need >= (f.size * i64::from(limits.delimited_sub_formula_min_height)).div_round(em)
            })
        })
    }

    /// Draws `glyph`, a character of a delimiter that grows around content whose ink needs
    /// `need` about the math axis (twice the larger of its ink above and below the axis): the
    /// first vertical variant of the character's glyph in the font's `MATH` table whose height
    /// reaches the larger of `need` times `params::MATH_DELIMITER_SHARE` and `need` less
    /// `params::MATH_DELIMITER_SHORTFALL` at the glyph's size, or else the tallest one, with the
    /// middle of its ink on the axis, to the nearest dot, and the room of its ink as drawn, with
    /// `leading` above it. A glyph whose font has no vertical variants of it stays as it is.
    /// Where the chosen variant is the base glyph, a script keeps its script glyph.
    ///
    /// A delimiter nested in the content whose need is `nested` makes the variant reach
    /// `params::MATH_NESTED_DELIMITER_GROWTH` times the height that `nested` alone asks, when
    /// that is taller.
    ///
    /// Returns whether the content counts as a subformula ([`Shaper::counts_as_sub_formula`]).
    pub fn grow(
        &mut self,
        glyph: &mut Glyph,
        (need, nested): (Length, Length),
        leading: Length,
    ) -> bool {
        let sub_formula = self.counts_as_sub_formula(glyph, need);
        let Some(f) = self.faces().get(glyph.face).copied() else {
            return false;
        };
        let em = i64::from(f.metrics.units_per_em.max(1));
        let Some(base) = self.fonts.glyph(f.font, glyph.ch) else {
            return sub_formula;
        };
        let (growth, growth_of) = crate::params::MATH_NESTED_DELIMITER_GROWTH;
        let least = least_height(f.size, need)
            .max((least_height(f.size, nested) * growth).div_round(growth_of));
        let least = f_office_units::div_round(least.units() * em, f.size.units().max(1));
        let least = i32::try_from(least.max(0)).unwrap_or(i32::MAX);
        let Some((variant, _)) = self.fonts.vertical_variant(f.font, base, least) else {
            return sub_formula;
        };
        let id = if variant == base { glyph.id } else { variant };
        let Some((low, high)) = self.font_ink(f.font, id) else {
            return sub_formula;
        };
        let (axis, axis_em) = crate::params::MATH_AXIS_HEIGHT;
        let middle = (f.size * (i64::from(low) + i64::from(high))).div_round(2 * em);
        // The glyph stands in whole dots, as a delimiter of base glyphs does.
        let by = (f.size * axis).div_round(axis_em) - middle;
        let mut grown = f;
        grown.rise = self.settings.dot.snap(f.rise + by);
        grown.raised = grown.rise;
        grown.math.room = MathRoom::Ink { leading };
        self.draw_variant(glyph, (f, grown), id);
        sub_formula
    }

    /// The horizontal and vertical gaps of a skewed fraction at the size of `face`, from the
    /// font's `MATH` table (`SkewedFractionHorizontalGap` and `SkewedFractionVerticalGap`);
    /// none for a font without them.
    pub fn skewed_fraction_gaps(&self, face: FaceIndex) -> Option<(Length, Length)> {
        let f = self.faces().get(face)?;
        let gaps = self.fonts.math_skewed_fraction(f.font)?;
        Some((
            f.scale(i64::from(gaps.horizontal_gap)),
            f.scale(i64::from(gaps.vertical_gap)),
        ))
    }

    /// The baseline drop/rise and ink gap minimums for a lower or upper limit structure at the
    /// size of `props`, from the font's `MATH` table: `(baseline_min, gap_min)` and the face's
    /// baseline rise, or none for a font without `MATH` limit constants.
    pub fn limit_lengths(
        &mut self,
        props: &RunProps,
        lower: bool,
    ) -> Option<(Length, Length, Length)> {
        let face = self.face(props, true)?;
        let f = self.faces().get(face).copied()?;
        let limits = self.fonts.math_limits(f.font)?;
        let gaps = self.fonts.math_limit_gaps(f.font);
        let (baseline_min, gap_min) = if lower {
            (
                f.scale(i64::from(limits.lower_limit_baseline_drop_min)),
                f.scale(i64::from(gaps.map_or(0, |g| g.lower_limit_gap_min))),
            )
        } else {
            (
                f.scale(i64::from(limits.upper_limit_baseline_rise_min)),
                f.scale(i64::from(gaps.map_or(0, |g| g.upper_limit_gap_min))),
            )
        };
        Some((baseline_min, gap_min, f.rise))
    }

    /// Sizes and places `glyph`, the fraction slash (`U+2044`) of a linear or skewed fraction,
    /// about the math axis `axis` (above the line's baseline), where the fraction's ink reaches
    /// `above` above `axis` and `below` below `axis`.
    ///
    /// Chooses the first vertical variant of the slash whose height reaches `(above + below)`
    /// less `params::MATH_DELIMITER_SHORTFALL` (and at least one em when `skewed`), or else the
    /// tallest variant. For a linear fraction, centers the variant's ink vertically on `axis`
    /// and keeps the base glyph's line room when the base glyph is drawn. For a skewed fraction,
    /// splits the variant's ink height about `axis` in the ratio of `above` to `below` and takes
    /// the room of its ink with `leading` above it.
    pub fn place_fraction_slash(
        &mut self,
        glyph: &mut Glyph,
        axis: Length,
        (above, below): (Length, Length),
        skewed: bool,
        leading: Length,
    ) {
        let Some(f) = self.faces().get(glyph.face).copied() else {
            return;
        };
        let em = i64::from(f.metrics.units_per_em.max(1));
        let Some(base) = self.fonts.glyph(f.font, glyph.ch) else {
            return;
        };
        let span = above + below;
        let (shortfall, shortfall_em) = crate::params::MATH_DELIMITER_SHORTFALL;
        let least = (span - (f.size * shortfall).div_round(shortfall_em)).max(Length::ZERO);
        let mut least_units = f_office_units::div_round(least.units() * em, f.size.units().max(1));
        if skewed {
            least_units = least_units.max(em);
        }
        let least_units = i32::try_from(least_units.max(0)).unwrap_or(i32::MAX);
        let id = self
            .fonts
            .vertical_variant(f.font, base, least_units)
            .map_or(
                glyph.id,
                |(variant, _)| {
                    if variant == base { glyph.id } else { variant }
                },
            );
        let Some((low, high)) = self.font_ink(f.font, id) else {
            return;
        };
        let middle = (f.size * (i64::from(low) + i64::from(high))).div_round(2 * em);
        let target_mid = if skewed && span > Length::ZERO {
            let slash_h = (f.size * (i64::from(high) - i64::from(low))).div_round(em);
            let shift = f_office_units::div_round_i128(
                i128::from(slash_h.units()) * i128::from((above - below).units()),
                2 * i128::from(span.units()),
            );
            axis + Length::from_units(i64::try_from(shift).unwrap_or(0))
        } else {
            axis
        };
        let mut grown = f;
        grown.rise = self.settings.dot.snap(target_mid - middle);
        if skewed || id != glyph.id {
            grown.raised = grown.rise;
            grown.math.room = MathRoom::Ink { leading };
        }
        self.draw_variant(glyph, (f, grown), id);
    }

    /// Whether `glyph`, a character of a delimiter, draws a taller vertical variant than its
    /// character's base glyph, as [`Self::grow`] makes a grown delimiter do: its glyph is
    /// neither the base glyph nor that glyph's script glyph.
    pub fn draws_grown_glyph(&self, glyph: &Glyph) -> bool {
        let Some(f) = self.faces().get(glyph.face) else {
            return false;
        };
        let Some(base) = self.fonts.glyph(f.font, glyph.ch) else {
            return false;
        };
        let script = f
            .math
            .script_level
            .and_then(|level| self.fonts.script_glyph(f.font, base, level));
        glyph.id != base && Some(glyph.id) != script
    }

    /// Draws `glyph`, of the face `own`, as the glyph `id` of the same font in the face `drawn`:
    /// its advance changes by the difference of the two glyphs' advances at the size of `own`.
    fn draw_variant(&mut self, glyph: &mut Glyph, (own, drawn): (Face, Face), id: u32) {
        let advance = |id| own.scale(i64::from(self.fonts.advance(own.font, id).unwrap_or(0)));
        glyph.advance += advance(id) - advance(glyph.id);
        glyph.written = self.written_width(&own, id);
        glyph.id = id;
        glyph.face = self.intern(&drawn);
    }

    /// How many glyphs [`Self::measure`] makes for `text` with `props`.
    pub fn count(&mut self, props: &RunProps, text: &str) -> usize {
        let mut glyphs = Vec::new();
        self.measure(props, text, &mut glyphs);
        glyphs.len()
    }

    /// Whether the East Asian font of the document defaults `defaults` is a font made for East
    /// Asian text. A theme font counts, also one that the theme leaves without a face; a font
    /// name counts when its own face, or the face that stands for it, covers an East Asian code
    /// page, or when the caller has neither and the font table's entry names an East Asian
    /// character set. No font, a Latin face and a name that no font has do not count.
    pub(crate) fn names_east_asian_default(&self, defaults: &RunProps) -> bool {
        let Some(slot) = defaults.font_east_asia.as_deref() else {
            return false;
        };
        let Some(written) = self.theme_family(slot, defaults.east_asian_script()) else {
            return !matches!(slot, FontRef::Name(_));
        };
        let family = FamilyName::new(written);
        self.face_sources(Some(written), Some(&family), Script::EastAsian)
            .filter(|source| matches!(source, FaceSource::Own(_) | FaceSource::StandIn(_)))
            .find_map(|source| self.face_of(&source, false, false))
            .map_or_else(
                || self.table.east_asian_charset(&family).is_some(),
                |chosen| chosen.metrics.east_asian,
            )
    }

    /// The family that a run's font slot asks for, with a theme font resolved.
    fn asked_family<'s>(&'s self, slot: Option<&'s FontRef>, props: &RunProps) -> Option<&'s str> {
        slot.and_then(|s| self.theme_family(s, props.east_asian_script()))
    }

    /// The family that a font reference stands for, for text whose East Asian language has the
    /// script `run`, with an East Asian theme font of an empty typeface resolved by
    /// [`ShaperSettings::theme_script`].
    fn theme_family<'s>(
        &'s self,
        font: &'s FontRef,
        run: Option<EastAsianScript>,
    ) -> Option<&'s str> {
        match self.settings.theme_script(run) {
            ThemeScript::Of(script) => self.theme.family_for(font, script),
            ThemeScript::Unnamed => self.theme.family_for(font, None).or_else(|| {
                matches!(font, FontRef::MinorEastAsia | FontRef::MajorEastAsia)
                    .then_some(UNNAMED_THEME_EAST_ASIAN)
            }),
        }
    }

    /// The face of a run's text of `script`, from the first of its [face sources] that the
    /// caller has, together with whether it came from the requested family, a stand-in, or a
    /// missing-font fallback.
    ///
    /// [face sources]: Self::face_sources
    fn find(
        &self,
        slot: Option<&FontRef>,
        props: &RunProps,
        script: Script,
    ) -> Option<(ChosenFace, FaceOrigin)> {
        let written = self.asked_family(slot, props);
        let family = written.map(FamilyName::new);
        // The math font itself asks for the upright regular face: its bold and italic are the
        // mathematical alphanumeric letters. Another font named on a math run keeps its bold and
        // italic face for alphanumeric characters that stay in that font.
        let math_font = props.math == Some(true)
            && family.as_ref().is_none_or(|f| f.is(crate::math::MATH_FONT));
        let bold = props.bold.unwrap_or(false) && !math_font;
        let italic = props.italic.unwrap_or(false) && !math_font;
        self.face_sources(written, family.as_ref(), script)
            .find_map(|source| {
                let chosen = self.face_of(&source, bold, italic)?;
                let origin = match source {
                    FaceSource::Own(_) => FaceOrigin::Own,
                    FaceSource::StandIn(_) | FaceSource::FamilySubstitute(_) => FaceOrigin::StandIn,
                    FaceSource::Fallback(_) => FaceOrigin::Fallback,
                };
                Some((chosen, origin))
            })
    }

    /// The face that [`Self::find`] finds, or none, which notes the family as one without a
    /// face.
    fn find_noted(
        &mut self,
        slot: Option<&FontRef>,
        props: &RunProps,
        script: Script,
    ) -> Option<(ChosenFace, FaceOrigin)> {
        let found = self.find(slot, props, script);
        if found.is_none() {
            let faceless = self.asked_and_tried(slot, props, script);
            self.notes.get_mut().faceless.insert(faceless);
        }
        found
    }

    /// The caller's face of one face source, in the style asked for or else regular; a
    /// family's substitute comes in the style asked for only.
    fn face_of(&self, source: &FaceSource, bold: bool, italic: bool) -> Option<ChosenFace> {
        match source {
            FaceSource::Own(name) | FaceSource::Fallback(name) => self
                .fonts
                .face(name, bold, italic)
                .or_else(|| self.fonts.face(name, false, false)),
            FaceSource::StandIn(name) => self
                .fonts
                .substitute(name, bold, italic)
                .or_else(|| self.fonts.substitute(name, false, false)),
            FaceSource::FamilySubstitute(name) => self.fonts.family_substitute(name, bold, italic),
        }
    }

    /// The places that a face of a run's text of `script` may come from, in the order that
    /// Word tries them: the family that the run asks for, the names that stand for it, the
    /// fallback of the script, the target's substitute of the family, the family of a
    /// suffixed font name, the fallback of a missing font, and Word's own default. `written`
    /// is the family as the run asks for it ([`Self::asked_family`]), and `family` its name.
    fn face_sources<'s>(
        &'s self,
        written: Option<&'s str>,
        family: Option<&'s FamilyName>,
        script: Script,
    ) -> impl Iterator<Item = FaceSource<'s>> + 's {
        // Text that names no font at all keeps Times New Roman, even with a theme. A font that
        // is missing gives way to Calibri in a document with a theme, and to Cambria without;
        // or, where the target decides by the font table, to Cambria when the table has no
        // entry for it or its entry's font class is roman, and to Calibri otherwise. When even
        // that font is missing, Word's own default keeps the text visible.
        let fallback = family.map_or(LAST_RESORT, |family| {
            let themed = self.theme.latin.minor.is_some();
            self.settings
                .missing_font_fallback(themed, || self.table.entry(family))
        });
        // The font table's alternate name and the first font of a list stand for the name.
        let alternate = family.and_then(|f| self.table.alternate(f));
        // A name that lists fonts with commas stands for its first font.
        let first = written
            .and_then(|f| f.split_once(','))
            .map(|(head, _)| FamilyName::new(head.trim()));
        // A missing font whose font table entry names an East Asian character set gives way
        // to that set's font for East Asian and Latin text, and any other missing East Asian
        // font to Microsoft YaHei for East Asian text.
        // A named complex script font that is missing gives way to Arial for complex script
        // text, or, where the target decides by the font table, to a font by its entry; text
        // that names no font keeps Word's default.
        let complex = |family: &FamilyName| {
            self.settings
                .missing_complex_font(|| self.missing_complex_by_table(family))
        };
        let charset = family.and_then(|family| {
            let set = self.table.east_asian_charset(family)?;
            Some(charset_stand_in(family, set))
        });
        let of_script = match script {
            Script::EastAsian => [charset, Some(MISSING_EAST_ASIAN)],
            Script::Complex => [family.map(complex), None],
            Script::Latin => [charset, None],
        };
        // Where the target draws a suffixed font name, such as Times New Roman CYR, with the
        // family before the suffix, that family stands for it.
        let base = written
            .and_then(|written| self.settings.suffixed_base(written))
            .map(|(base, _)| FamilyName::new(base));
        let own = family.map(|f| FaceSource::Own(Cow::Borrowed(f)));
        // The target's substitute of a family comes before the fallback of complex script
        // text, which it overrides whatever the font table says, and after the fallbacks of
        // the other scripts.
        let substitute = family.map(|f| FaceSource::FamilySubstitute(Cow::Borrowed(f)));
        let (substitute_first, substitute_last) = match script {
            Script::Complex => (substitute, None),
            Script::EastAsian | Script::Latin => (None, substitute),
        };
        own.into_iter()
            .chain(alternate.map(|f| FaceSource::StandIn(Cow::Borrowed(f))))
            .chain(first.map(|f| FaceSource::StandIn(Cow::Owned(f))))
            .chain(substitute_first)
            .chain(
                of_script
                    .into_iter()
                    .flatten()
                    .map(|f| FaceSource::Fallback(Cow::Owned(f))),
            )
            .chain(substitute_last)
            .chain(base.map(|f| FaceSource::StandIn(Cow::Owned(f))))
            .chain([
                FaceSource::Fallback(Cow::Owned(fallback)),
                FaceSource::Fallback(Cow::Owned(LAST_RESORT)),
            ])
    }

    /// The font of the complex script text of the missing font `family` where the target
    /// decides by its font table entry. Word reads the entry only of a name that a face name
    /// of the font interface of Windows holds; a longer name counts as one without an entry.
    fn missing_complex_by_table(&self, family: &FamilyName) -> FamilyName {
        let read = family.as_str().encode_utf16().count() <= crate::params::LONGEST_READ_FONT_NAME;
        let entry = if read {
            self.table.entry(family)
        } else {
            FontEntry::Absent
        };
        let script = self.table.complex_script(family);
        match (entry, script) {
            (FontEntry::Class(FontClass::Roman), Some(EntryScript::Arabic)) => {
                MISSING_COMPLEX_ARABIC_SERIF
            }
            (FontEntry::Absent | FontEntry::Class(FontClass::Roman), _) => MISSING_COMPLEX_SERIF,
            (FontEntry::NoClass | FontEntry::Class(_), Some(_)) => MISSING_COMPLEX,
            (FontEntry::NoClass | FontEntry::Class(_), None) => MISSING_COMPLEX_UNNAMED,
        }
    }

    /// Notes that the characters of `slot` in a run with `props` are left out: the caller has
    /// no face for them from any of their face sources.
    fn note_not_drawn(&mut self, props: &RunProps, slot: FaceSlot) {
        let other;
        let (props, ascii, script) = match slot {
            FaceSlot::Ascii | FaceSlot::SmallAscii => (props, true, Script::Latin),
            FaceSlot::Other | FaceSlot::SmallOther => (props, false, Script::Latin),
            FaceSlot::Complex => {
                other = props.complex_script();
                (&other, true, Script::Complex)
            }
            FaceSlot::EastAsian => {
                other = props.east_asian();
                (&other, true, Script::EastAsian)
            }
        };
        let not_drawn = self.asked_and_tried(font_slot(props, ascii), props, script);
        self.notes.get_mut().not_drawn.insert(not_drawn);
    }

    /// The family that the font slot `slot` of a run with `props` asks for, `None` when the run
    /// names no font, with the families that the layout tries for it in `script`, each once,
    /// in order.
    fn asked_and_tried(
        &self,
        slot: Option<&FontRef>,
        props: &RunProps,
        script: Script,
    ) -> (Option<String>, Vec<String>) {
        let written = self.asked_family(slot, props);
        let family = written.map(FamilyName::new);
        let mut tried: Vec<FamilyName> = Vec::new();
        for source in self.face_sources(written, family.as_ref(), script) {
            if !tried.contains(source.family()) {
                tried.push(source.family().clone());
            }
        }
        let asked = written.map(str::to_owned);
        (asked, tried.iter().map(|f| f.as_str().to_owned()).collect())
    }

    /// The face of a line of text whose characters all take one face, such as a line of
    /// metafile text: the ASCII face of `props`. When there is none, the text is noted as not
    /// drawn.
    pub fn line_face(&mut self, props: &RunProps) -> Option<FaceIndex> {
        let face = self.face(props, true);
        if face.is_none() {
            self.note_not_drawn(props, FaceSlot::Ascii);
        }
        face
    }

    /// The index of `face` in `faces`, which adds it when it is new.
    fn intern(&mut self, face: &Face) -> FaceIndex {
        if let Some(&index) = self.face_indices.get(face) {
            return index;
        }
        if !self.own_faces.contains(&face.font)
            && self
                .settings
                .device_width_face(|| self.fonts.target_face(face.font))
                .is_some()
        {
            self.own_faces.insert(face.font);
        }
        let index = FaceIndex(self.faces.len());
        self.faces.push(*face);
        self.face_indices.insert(*face, index);
        index
    }
}

/// The least height that a variant of a growing delimiter at `size` must reach around content
/// whose ink needs `need`: the larger of `need` times `params::MATH_DELIMITER_SHARE` and `need`
/// less `params::MATH_DELIMITER_SHORTFALL`.
fn least_height(size: Length, need: Length) -> Length {
    let (shortfall, shortfall_em) = crate::params::MATH_DELIMITER_SHORTFALL;
    let (share, share_of) = crate::params::MATH_DELIMITER_SHARE;
    (need - (size * shortfall).div_round(shortfall_em)).max((need * share).div_round(share_of))
}