f-office-docx 0.2.2

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
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
use f_office_units::Length;

use f_office_fonts::FamilyName;
use f_office_paint::{Join, Outline, Rgb};

use super::{
    Edges, MathRoom, ScriptMove, ScriptScale, SpaceKind, SymbolFont, outline, size_and_rise,
    symbol_stand_in,
};
use crate::character_class::CharacterClass;
use crate::props::{
    Limit, MathScript, MathStep, OutlineColor, RunProps, TextOutline, VerticalAlign,
};
use crate::quirks::{
    DisplayFractionRoom, LineHeight, MirroredBracketText, ScriptRoom, ShapedGlyphText, SymbolText,
};

/// One dot of a layout device with `dots` per inch.
fn per_inch(dots: i64) -> crate::grid::Dot {
    crate::grid::Device::per_inch(dots).unwrap().dot_size()
}

/// The size and rise of a run of an equation, with a font that gives limits and delimiters no
/// shift.
fn math_size_and_rise(
    props: &RunProps,
    script: MathScript,
    dot: crate::grid::Dot,
) -> (Length, Length, bool) {
    super::math_size_and_rise(props, script, dot, &|_, _| None, &|_, _| None)
}

/// A black face of the first font with the metrics `metrics`, of the size `size` also for its
/// line, whose line height `line_height` gives, with no lines, rise, background or effects.
fn plain_face(metrics: crate::FaceMetrics, size: Length, line_height: LineHeight) -> super::Face {
    super::Face {
        font: f_office_fonts::FontId::from_index(0),
        metrics,
        size,
        line_size: size,
        single_line: super::SingleLine::of(line_height),
        color: Rgb::BLACK,
        lines: super::RunLines::default(),
        background: None,
        rise: Length::ZERO,
        raised: Length::ZERO,
        math: crate::text::MathFace::default(),
        outline: None,
        text_fill: super::DrawnTextFill::Solid,
        effect: false,
        shadow_room: super::ShadowRoom::default(),
        shadow: None,
        glow: None,
        reflection: None,
        relief: None,
        kerned: false,
        east_asian_script: None,
        ligatures: false,
        scale: None,
        standing: super::Standing::default(),
    }
}

/// A font whose glyph IDs are the characters, 100 of 1000 units wide. "fi" joins into
/// glyph 500, which is 150 units wide and kerns with "x" by -20. The pair "f" and "i"
/// would kern by -999, which a ligature must skip.
struct Joining;

impl crate::Fonts for Joining {
    /// One regular face, so that bold text is synthetic bold.
    fn face(&self, _family: &FamilyName, bold: bool, _italic: bool) -> Option<crate::ChosenFace> {
        Some(crate::ChosenFace {
            font: f_office_fonts::FontId::from_index(0),
            metrics: crate::FaceMetrics {
                units_per_em: 1000,
                hhea_ascender: 800,
                hhea_descender: -200,
                hhea_line_gap: 0,
                descent: 200,
                underline_position: -100,
                underline_thickness: 50,
                strikeout_position: 250,
                strikeout_thickness: 50,
                superscript_offset: 0,
                subscript_offset: 0,
                superscript_size: 0,
                subscript_size: 0,
                line_top: 800,
                script_top: 800,
                east_asian: false,
                average_width: 500,
            },
            synthetic_bold: bold,
            synthetic_italic: false,
            stands_in: false,
        })
    }

    fn glyph(&self, _font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Some(u32::from(ch))
    }

    fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Some(if glyph == 500 { 150 } else { 100 })
    }

    fn kerning(
        &self,
        _font: f_office_fonts::FontId,
        left: u32,
        right: u32,
        _table: crate::KerningTable,
    ) -> i32 {
        match (left, char::from_u32(right)) {
            (500, Some('x')) => -20,
            (102, Some('i')) => -999,
            _ => 0,
        }
    }

    fn ligatures(
        &self,
        _font: f_office_fonts::FontId,
        glyphs: &[u32],
    ) -> Vec<f_office_fonts::Ligature> {
        glyphs
            .windows(2)
            .enumerate()
            .filter(|(_, pair)| pair == &[102, 105])
            .map(|(start, _)| f_office_fonts::Ligature {
                start,
                len: 2,
                glyph: 500,
            })
            .collect()
    }
}

/// Fonts that have only the families in the list, each as the font with its index.
struct Only(&'static [&'static str]);

impl crate::Fonts for Only {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        let index = self.0.iter().position(|name| family.is(name))?;
        let font = f_office_fonts::FontId::from_index(u32::try_from(index).ok()?);
        Joining
            .face(family, bold, italic)
            .map(|chosen| crate::ChosenFace { font, ..chosen })
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }

    fn family_name(&self, font: f_office_fonts::FontId) -> Option<String> {
        let index = usize::try_from(font.index()).ok()?;
        self.0.get(index).map(|name| (*name).to_owned())
    }
}

/// The index of the font that a run of the named font gets from [`Only`] fonts.
/// A name of `+minor` stands for the theme's minor font.
fn chosen(fonts: &Only, theme: &crate::styles::Theme, name: Option<&str>) -> u32 {
    use crate::props::FontRef;
    let table = crate::styles::FontTable::default();
    let props = RunProps {
        font_ascii: name.map(|name| match name {
            "+minor" => FontRef::MinorLatin,
            name => FontRef::Name(name.into()),
        }),
        ..RunProps::default()
    };
    let mut shaper = super::Shaper::new(fonts, theme, &table, &super::ShaperSettings::base());
    let face = shaper.face(&props, true).unwrap();
    shaper.faces[face.0].font.index()
}

#[test]
fn only_fonts_measure_like_joining_fonts() {
    use crate::Fonts as _;
    let fonts = Only(&["Cambria"]);
    let font = f_office_fonts::FontId::from_index(0);
    assert!(
        fonts
            .face(&FamilyName::from_static("Missing"), false, false)
            .is_none()
    );
    assert_eq!(fonts.glyph(font, 'a'), Some(97));
    assert_eq!(fonts.advance(font, 97), Some(100));
}

/// The fonts of [`Joining`] with a shaper for the text of a shaped script: a lam with an
/// alef after it is the one glyph 900, 300 units wide, which the font also maps to U+FEFB;
/// a lam with a meem after it is the one glyph 902, which the font maps to no character; a
/// Farsi yeh shares the glyph of the Arabic yeh; a fatha is glyph 901, takes no room
/// and stands 40 units right and 120 up; every other character is its own glyph, 90 units
/// wide where its own advance is 100. The glyphs come in the order of the text.
struct Shaping;

impl crate::Fonts for Shaping {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Joining.face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        match ch {
            '\u{FEFB}' => Some(900),
            '\u{06CC}' => Some(u32::from('\u{064A}')),
            _ => Joining.glyph(font, ch),
        }
    }

    fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Some(if glyph == 900 { 300 } else { 100 })
    }

    fn kerning(
        &self,
        _font: f_office_fonts::FontId,
        _left: u32,
        _right: u32,
        _table: crate::KerningTable,
    ) -> i32 {
        -30
    }

    fn shape(
        &self,
        _font: f_office_fonts::FontId,
        request: &f_office_fonts::ShapeRequest<'_>,
    ) -> Result<Vec<f_office_fonts::ShapedGlyph>, f_office_fonts::ShapeFailure> {
        let shaped = |glyph, advance, offset, cluster| f_office_fonts::ShapedGlyph {
            glyph,
            advance,
            offset,
            cluster,
        };
        let mut glyphs = Vec::new();
        let mut chars = request.text.char_indices().peekable();
        while let Some((at, ch)) = chars.next() {
            match ch {
                'ل' if chars.next_if(|&(_, next)| next == 'ا').is_some() => {
                    glyphs.push(shaped(900, 300, (0, 0), at));
                }
                'ل' if chars.next_if(|&(_, next)| next == 'م').is_some() => {
                    glyphs.push(shaped(902, 90, (0, 0), at));
                }
                '\u{064E}' => {
                    let base = glyphs.last().map_or(at, |g| g.cluster);
                    glyphs.push(shaped(901, 0, (40, 120), base));
                }
                '\u{06CC}' => glyphs.push(shaped(u32::from('\u{064A}'), 90, (0, 0), at)),
                ' ' => glyphs.push(shaped(u32::from(' '), 100, (0, 0), at)),
                _ => glyphs.push(shaped(u32::from(ch), 90, (0, 0), at)),
            }
        }
        Ok(glyphs)
    }
}

#[test]
fn mirrors_brackets_in_right_to_left_runs() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let text = |rtl, complex| {
        let props = RunProps {
            complex,
            rtl,
            ..RunProps::default()
        };
        let mut shaper =
            super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        shaper.measure(&props, "(a) [\u{AB}]", &mut glyphs);
        glyphs.iter().map(|g| g.ch).collect::<String>()
    };
    assert_eq!(text(Some(true), None), ")a( ]\u{BB}[");
    assert_eq!(text(None, None), "(a) [\u{AB}]");
    assert_eq!(text(None, Some(true)), "(a) [\u{AB}]");
}

#[test]
fn writes_the_character_of_the_file_for_a_mirrored_bracket_when_the_quirk_says_so() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let glyphs = |rtl, written| {
        let props = RunProps {
            rtl,
            ..RunProps::default()
        };
        let mut shaper = super::Shaper::new(
            &Joining,
            &theme,
            &table,
            &super::ShaperSettings::base_with(|p| p.with_variant(written)),
        );
        let mut glyphs = Vec::new();
        shaper.measure(&props, "(a] {7\u{BB}", &mut glyphs);
        glyphs
    };
    let text = |glyphs: &[super::Glyph]| glyphs.iter().map(|g| g.ch).collect::<String>();
    let as_in_file = glyphs(Some(true), MirroredBracketText::AsInFile);
    let mirrored = glyphs(Some(true), MirroredBracketText::Mirrored);
    assert_eq!(text(&as_in_file), "(a] {7\u{BB}");
    assert_eq!(text(&mirrored), ")a[ }7\u{AB}");
    // The quirk changes the written character only: the glyph drawn is the mirrored one.
    let drawn = |glyphs: &[super::Glyph]| glyphs.iter().map(|g| g.id).collect::<Vec<_>>();
    assert_eq!(drawn(&as_in_file), drawn(&mirrored));
    // A bracket of a run without `w:rtl` is not mirrored, so the quirk does not touch it.
    let plain = glyphs(None, MirroredBracketText::AsInFile);
    assert_eq!(text(&plain), "(a] {7\u{BB}");
    assert_ne!(drawn(&plain), drawn(&as_in_file));
}

#[test]
fn takes_the_direction_of_a_computed_page_number_from_the_reader_of_fields() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let direction = |rtl, field_rtl| {
        let props = RunProps {
            rtl,
            field_rtl,
            ..RunProps::default()
        };
        let mut shaper =
            super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        shaper.measure(&props, "7", &mut glyphs);
        glyphs.first().map(|g| g.direction)
    };
    let left = Some(super::RunDirection::LeftToRight);
    // The direction that the reader of fields gives decides, whatever the run's own says, and
    // the number keeps its UAX 9 classes.
    let unicode = crate::props::BidiLanguageClass::Unicode;
    let computed = Some(super::RunDirection::of(true, Some(unicode)));
    assert_eq!(direction(None, Some(true)), computed);
    assert_eq!(direction(Some(true), Some(false)), left);
    // Other text has the direction of its own run, with the class of a run without a bidi
    // language.
    let right = Some(super::RunDirection::of(true, None));
    assert_eq!(direction(Some(true), None), right);
    assert_eq!(direction(None, None), left);
}

/// A glyph of [`shaped_run`].
type ShapedRow = (char, u32, i64, bool, (i64, i64));

/// The glyphs of `text` with the fonts `fonts` at 10 pt: the character, the glyph ID, the
/// advance in twentieths of a point, whether it is a part, and the offset in the same unit.
fn shaped_run(fonts: &dyn crate::Fonts, text: &str) -> Vec<ShapedRow> {
    shaped_run_with(fonts, text, &super::ShaperSettings::base())
}

/// The glyphs of `text` as [`shaped_run`] gives them, with the decisions `settings`.
fn shaped_run_with(
    fonts: &dyn crate::Fonts,
    text: &str,
    settings: &super::ShaperSettings,
) -> Vec<ShapedRow> {
    let props = RunProps {
        size: Some(20),
        size_cs: Some(20),
        kern: Some(2),
        ..RunProps::default()
    };
    shaped_run_of(fonts, &props, text, settings)
}

/// The glyphs of `text` in a run of the properties `props`, as [`shaped_run`] gives them, with
/// the decisions `settings`.
fn shaped_run_of(
    fonts: &dyn crate::Fonts,
    props: &RunProps,
    text: &str,
    settings: &super::ShaperSettings,
) -> Vec<ShapedRow> {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let twentieths = |length: Length| length.units() / Length::UNITS_PER_TWIP;
    let mut shaper = super::Shaper::new(fonts, &theme, &table, settings);
    let mut glyphs = Vec::new();
    shaper.measure(props, text, &mut glyphs);
    glyphs
        .iter()
        .map(|g| {
            let offset = (twentieths(g.offset.0), twentieths(g.offset.1));
            (g.ch, g.id, twentieths(g.advance), g.part, offset)
        })
        .collect()
}

#[test]
fn a_stretch_of_a_shaped_script_takes_the_glyphs_of_the_layout_tables() {
    // A beh, a lam with its alef, a space and a beh with a fatha. The letters have the
    // shaper's advance of 90 units, the ligature writes the character that the font maps
    // to its glyph and stands for the alef too, and the mark has its offset. The space
    // between Arabic words stays in the Arabic stretch with its own advance and character,
    // and the kerning of the run does not touch a shaped glyph.
    let glyphs = shaped_run(&Shaping, "بلا ب\u{064E}");
    assert_eq!(
        glyphs,
        [
            ('ب', u32::from('ب'), 18, false, (0, 0)),
            ('\u{FEFB}', 900, 60, false, (0, 0)),
            (' ', u32::from(' '), 20, false, (0, 0)),
            ('ب', u32::from('ب'), 18, false, (0, 0)),
            ('\u{064E}', 901, 0, false, (8, 24)),
        ]
    );
}

#[test]
fn arabic_space_and_punctuation_stay_in_the_arabic_stretch_when_sharing_its_face() {
    /// Fake font whose OpenType shaper kerns `و` before ` ` or `.` by -20 units and ` ` before
    /// `ك` by -30 units, and whose character map maps an Arabic control character onto space so
    /// we verify `LowestMappedCharacter` never rewrites `' '` to an Arabic code point.
    struct ArabicSpaceKern;
    impl crate::Fonts for ArabicSpaceKern {
        fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
            Joining.face(family, bold, italic)
        }
        fn glyph(&self, _font: f_office_fonts::FontId, ch: char) -> Option<u32> {
            Some(if ch == '\u{061C}' {
                u32::from(' ')
            } else {
                u32::from(ch)
            })
        }
        fn advance(&self, _font: f_office_fonts::FontId, _glyph: u32) -> Option<u16> {
            Some(100)
        }
        fn shape(
            &self,
            _font: f_office_fonts::FontId,
            request: &f_office_fonts::ShapeRequest<'_>,
        ) -> Result<Vec<f_office_fonts::ShapedGlyph>, f_office_fonts::ShapeFailure> {
            let chars: Vec<(usize, char)> = request.text.char_indices().collect();
            let mut out = Vec::with_capacity(chars.len());
            for (i, &(at, ch)) in chars.iter().enumerate() {
                let next = chars.get(i + 1).map(|&(_, c)| c);
                let (adv, xoff) = match (ch, next) {
                    ('و', Some(' ' | '.')) => (80, -20),
                    (' ', Some('ك')) => (70, -30),
                    _ => (100, 0),
                };
                out.push(f_office_fonts::ShapedGlyph {
                    glyph: u32::from(ch),
                    advance: adv,
                    offset: (xoff, 0),
                    cluster: at,
                });
            }
            Ok(out)
        }
    }

    let glyphs = shaped_run(&ArabicSpaceKern, "أو كتب");
    assert_eq!(
        glyphs,
        [
            ('أ', u32::from('أ'), 20, false, (0, 0)),
            ('و', u32::from('و'), 16, false, (-4, 0)),
            (' ', u32::from(' '), 14, false, (-6, 0)),
            ('ك', u32::from('ك'), 20, false, (0, 0)),
            ('ت', u32::from('ت'), 20, false, (0, 0)),
            ('ب', u32::from('ب'), 20, false, (0, 0)),
        ]
    );
    let punct = shaped_run(&ArabicSpaceKern, "أو.الم");
    assert_eq!(punct[1], ('و', u32::from('و'), 16, false, (-4, 0)));
    assert_eq!(punct[2], ('.', u32::from('.'), 20, false, (0, 0)));

    // When `rtl` is unset and ASCII vs complex script use different fonts, spaces keep their
    // own ASCII face and do not merge into the Arabic stretch.
    let diff_fonts = Only(&["Latin", "Complex"]);
    let props = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Latin".into())),
        font_hansi: Some(crate::props::FontRef::Name("Latin".into())),
        font_cs: Some(Box::new(crate::props::FontRef::Name("Complex".into()))),
        ..RunProps::default()
    };
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper =
        super::Shaper::new(&diff_fonts, &theme, &table, &super::ShaperSettings::base());
    let mut mixed = Vec::new();
    shaper.measure(&props, "أو الم", &mut mixed);
    assert_eq!(
        mixed
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<_>>(),
        [1, 1, 0, 1, 1, 1]
    );
}

#[test]
fn a_shaped_glyph_writes_the_lowest_character_that_the_font_maps_to_it() {
    // A Farsi yeh draws the glyph that the font shares with the Arabic yeh, and writes the
    // lower of the two. A ligature that the font maps to no character keeps its letters:
    // the second is a part of the glyph.
    let glyphs = shaped_run(&Shaping, "\u{06CC}لم");
    assert_eq!(
        glyphs,
        [
            ('\u{064A}', u32::from('\u{064A}'), 18, false, (0, 0)),
            ('ل', 902, 18, false, (0, 0)),
            ('م', u32::from('م'), 0, true, (0, 0)),
        ]
    );
}

#[test]
fn a_shaped_glyph_writes_the_letters_of_the_document_when_the_quirk_says_so() {
    // A lam with its alef, which the font draws as one glyph that it also maps to U+FEFB, and
    // a Farsi yeh, whose glyph the font shares with the Arabic yeh. The glyphs drawn are the
    // same under both values; only their characters differ.
    let text = "\u{0644}\u{0627}\u{06CC}";
    let letters = shaped_run_with(
        &Shaping,
        text,
        &super::ShaperSettings::base_with(|p| p.with_variant(ShapedGlyphText::ClusterLetters)),
    );
    let lowest = shaped_run_with(
        &Shaping,
        text,
        &super::ShaperSettings::base_with(|p| {
            p.with_variant(ShapedGlyphText::LowestMappedCharacter)
        }),
    );
    // The ligature writes the lam, and the alef becomes a part of it that takes no room.
    assert_eq!(
        letters,
        [
            ('\u{0644}', 900, 60, false, (0, 0)),
            ('\u{0627}', u32::from('\u{0627}'), 0, true, (0, 0)),
            ('\u{06CC}', u32::from('\u{064A}'), 18, false, (0, 0)),
        ]
    );
    assert_eq!(
        lowest,
        [
            ('\u{FEFB}', 900, 60, false, (0, 0)),
            ('\u{064A}', u32::from('\u{064A}'), 18, false, (0, 0)),
        ]
    );
}

#[test]
fn a_part_of_a_ligature_takes_no_character_spacing() {
    // A lam with its alef and a yeh, in a run whose characters are 4 twentieths of a point
    // closer. The ligature takes the spacing once for both its letters, and the alef, a part
    // of it, keeps no room, as the yeh after it takes the spacing once.
    let props = RunProps {
        size: Some(20),
        size_cs: Some(20),
        spacing: Some(Length::from_units(-4 * Length::UNITS_PER_TWIP)),
        ..RunProps::default()
    };
    let settings =
        super::ShaperSettings::base_with(|p| p.with_variant(ShapedGlyphText::ClusterLetters));
    assert_eq!(
        shaped_run_of(&Shaping, &props, "\u{0644}\u{0627}\u{064A}", &settings),
        [
            ('\u{0644}', 900, 56, false, (0, 0)),
            ('\u{0627}', u32::from('\u{0627}'), 0, true, (0, 0)),
            ('\u{064A}', u32::from('\u{064A}'), 14, false, (0, 0)),
        ]
    );
}

#[test]
fn measures_a_text_of_many_shaped_words_with_one_look_at_a_stretch_for_each_character() {
    // 20,000 words of two behs, each with a space after it, make 20,000 stretches. A search
    // of all stretches for each character would look at about 2 · 60,000 · 20,000 of them.
    const WORDS: usize = 20_000;
    let text = "بب ".repeat(WORDS);
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Shaping, &theme, &table, &super::ShaperSettings::base());
    let mut glyphs = Vec::new();
    super::STRETCH_LOOKS.with(|looks| looks.set(0));
    shaper.measure(&RunProps::default(), &text, &mut glyphs);
    let looks = super::STRETCH_LOOKS.with(std::cell::Cell::get);
    assert!(looks <= 3 * WORDS, "{looks} looks");
    // Each beh takes the glyph of the layout tables, and each space the glyph of the
    // character map, in the order of the text.
    let ids: Vec<u32> = glyphs.iter().map(|g| g.id).collect();
    let word = [u32::from('ب'), u32::from('ب'), u32::from(' ')];
    assert_eq!(ids, word.repeat(WORDS));
    // Every beh has the one advance that the shaper gives it.
    let advances: std::collections::BTreeSet<Length> = glyphs
        .iter()
        .filter(|g| g.id == u32::from('ب'))
        .map(|g| g.advance)
        .collect();
    assert_eq!(advances.len(), 1);
}

#[test]
fn a_caller_without_a_shaper_draws_the_characters_and_the_shaper_keeps_the_cause() {
    let glyphs = shaped_run(&Joining, "بلا");
    let ids: Vec<u32> = glyphs.iter().map(|g| g.1).collect();
    assert_eq!(ids, "بلا".chars().map(u32::from).collect::<Vec<_>>());
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
    shaper.measure(&RunProps::default(), "ب", &mut Vec::new());
    let notes = shaper.take_notes();
    let causes: Vec<_> = notes.unshaped.iter().map(|&(_, c)| c).collect();
    assert_eq!(causes, [f_office_fonts::ShapeFailure::NoShaper]);
    assert_eq!(shaper.take_notes(), super::FontNotes::default());
}

#[test]
fn a_fork_starts_with_no_notes_and_gives_its_own_back() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
    shaper.measure(&RunProps::default(), "ب", &mut Vec::new());
    let mut fork = shaper.fork();
    assert_eq!(fork.take_notes(), super::FontNotes::default());
    fork.measure(&RunProps::default(), "ب", &mut Vec::new());
    let own = shaper.take_notes();
    shaper.add_notes(own.clone());
    shaper.add_notes(fork.take_notes());
    // The same note from both is one note, as in a set.
    assert_eq!(shaper.take_notes(), own);
}

#[test]
fn draws_complex_script_characters_with_the_complex_script_font() {
    use crate::props::FontRef;
    let fonts = Only(&["Latin", "Complex"]);
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let props = RunProps {
        font_ascii: Some(FontRef::Name("Latin".into())),
        font_hansi: Some(FontRef::Name("Latin".into())),
        font_cs: Some(Box::new(FontRef::Name("Complex".into()))),
        ..RunProps::default()
    };
    let fonts_of = |props: &RunProps, text: &str| {
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        shaper.measure(props, text, &mut glyphs);
        glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<_>>()
    };
    // Hebrew and Arabic letters take the complex script font, Latin letters and spaces
    // their own.
    assert_eq!(fonts_of(&props, "a \u{05D0}\u{0628}"), [0, 0, 1, 1]);
    // Chinese, Japanese and Korean characters take the East Asian font, and without one
    // the run's other font.
    let east_asian = RunProps {
        font_east_asia: Some(Box::new(FontRef::Name("Complex".into()))),
        ..props.clone()
    };
    assert_eq!(
        fonts_of(&east_asian, "a\u{4E2D}\u{3042}\u{AC00}"),
        [0, 1, 1, 1]
    );
    assert_eq!(fonts_of(&props, "a\u{4E2D}"), [0, 0]);
    // In a right-to-left run, every character takes it.
    let rtl = RunProps {
        complex: Some(true),
        ..props.clone()
    };
    assert_eq!(fonts_of(&rtl, "a \u{05D0}"), [1, 1, 1]);
}

/// [`Only`] fonts in which the first font has no glyphs for East Asian characters.
struct LatinFirst(&'static [&'static str]);

impl crate::Fonts for LatinFirst {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Only(self.0).face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        if font.index() == 0 && CharacterClass::EastAsianFont.contains(ch) {
            return None;
        }
        Only(self.0).glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Only(self.0).advance(font, glyph)
    }
}

#[test]
fn draws_east_asian_glyphs_that_the_font_lacks_with_the_fallback_fonts() {
    use crate::props::FontRef;
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    // The East Asian font is the Latin one, which has no glyph for the ideograph.
    let latin = Some(FontRef::Name("Latin".into()));
    let props = RunProps {
        font_ascii: latin.clone(),
        font_east_asia: latin.map(Box::new),
        ..RunProps::default()
    };
    let drawn = |fonts: &LatinFirst| {
        let mut shaper = super::Shaper::new(fonts, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        shaper.measure(&props, "a\u{4E2D}", &mut glyphs);
        glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<_>>()
    };
    // MS Mincho comes first, and without it Microsoft JhengHei.
    let all = LatinFirst(&["Latin", "Microsoft JhengHei", "MS Mincho"]);
    assert_eq!(drawn(&all), [0, 2]);
    assert_eq!(drawn(&LatinFirst(&["Latin", "Microsoft JhengHei"])), [0, 1]);
}

#[test]
fn draws_east_asian_text_of_a_missing_font_with_microsoft_yahei() {
    use crate::props::FontRef;
    let fonts = Only(&["Latin", "Microsoft YaHei"]);
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let props = RunProps {
        font_ascii: Some(FontRef::Name("Latin".into())),
        font_east_asia: Some(Box::new(FontRef::Name("Missing".into()))),
        ..RunProps::default()
    };
    let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
    let mut glyphs = Vec::new();
    shaper.measure(&props, "a\u{4E2D}", &mut glyphs);
    let drawn: Vec<u32> = glyphs
        .iter()
        .map(|g| shaper.faces[g.face.0].font.index())
        .collect();
    // The Latin letter keeps its font, and the Chinese character takes Microsoft YaHei.
    assert_eq!(drawn, [0, 1]);
}

#[test]
fn draws_a_missing_font_with_the_font_of_its_east_asian_character_set() {
    use crate::props::FontRef;
    let fonts = Only(&[
        "Latin",
        "Microsoft YaHei",
        "Microsoft JhengHei",
        "Yu Gothic",
        "Malgun Gothic",
    ]);
    let xml = format!(
        r#"<w:fonts xmlns:w="{}"><w:font w:name="Big5"><w:charset w:val="88"/></w:font><w:font w:name="標楷體"><w:charset w:val="88"/></w:font><w:font w:name="GB"><w:charset w:val="86"/></w:font><w:font w:name="JIS"><w:charset w:val="80"/></w:font><w:font w:name="Hangul"><w:charset w:val="81"/></w:font><w:font w:name="Ansi"><w:charset w:val="00"/></w:font></w:fonts>"#,
        crate::ns::W
    );
    let doc =
        f_office_xml::Document::parse(xml.as_bytes(), &f_office_xml::Limits::default()).unwrap();
    let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
    let theme = crate::styles::Theme::default();
    let drawn = |name: &str| {
        let props = RunProps {
            font_ascii: Some(FontRef::Name(name.into())),
            font_east_asia: Some(Box::new(FontRef::Name(name.into()))),
            ..RunProps::default()
        };
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        shaper.measure(&props, "a\u{4E2D}", &mut glyphs);
        glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<u32>>()
    };
    // Both the Latin letter and the Chinese character take the character set's font.
    assert_eq!(drawn("Big5"), [2, 2]);
    assert_eq!(drawn("標楷體"), [1, 1]);
    assert_eq!(drawn("GB"), [1, 1]);
    assert_eq!(drawn("JIS"), [3, 3]);
    assert_eq!(drawn("Hangul"), [4, 4]);
    // An entry without an East Asian character set sends only the Chinese character to
    // Microsoft YaHei; the Latin letter takes Word's default, which this set lacks.
    assert_eq!(drawn("Ansi").last(), Some(&1));
}

#[test]
fn draws_shared_punctuation_with_the_east_asian_font_only_with_the_east_asian_hint() {
    use crate::props::FontRef;
    let fonts = Only(&["Latin", "East"]);
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let drawn = |hint: Option<bool>| {
        let props = RunProps {
            font_ascii: Some(FontRef::Name("Latin".into())),
            font_hansi: Some(FontRef::Name("Latin".into())),
            font_east_asia: Some(Box::new(FontRef::Name("East".into()))),
            east_asian_hint: hint,
            ..RunProps::default()
        };
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        shaper.measure(
            &props,
            "A \u{2018}B\u{2019}\u{203B}\u{2026}\u{2014}\u{00B7}",
            &mut glyphs,
        );
        glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<u32>>()
    };
    // With the hint, the quotes, the reference mark, the ellipsis, the em dash and the middle
    // dot take the East Asian font; the letters and the space keep the Latin font.
    assert_eq!(drawn(Some(true)), [0, 0, 1, 0, 1, 1, 1, 1, 1]);
    assert_eq!(drawn(Some(false)), [0; 9]);
    assert_eq!(drawn(None), [0; 9]);
}

#[test]
fn draws_hinted_symbols_with_the_east_asian_font_unless_it_is_times_new_roman() {
    use crate::props::FontRef;
    use crate::quirks::HintedSlot;
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let drawn = |families: &'static [&'static str], variant| {
        let fonts = Only(families);
        let props = RunProps {
            font_ascii: Some(FontRef::Name("Latin".into())),
            font_hansi: Some(FontRef::Name("Latin".into())),
            font_east_asia: Some(Box::new(FontRef::Name(families[1].into()))),
            east_asian_hint: Some(true),
            ..RunProps::default()
        };
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
        let mut glyphs = Vec::new();
        shaper.measure(
            &props,
            "A\u{03C9}\u{0416}\u{2191}\u{2502} \u{2014}",
            &mut glyphs,
        );
        glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<u32>>()
    };
    // Greek, Cyrillic, the arrow and the box drawing join the em dash in the East Asian font;
    // the letter and the space keep the Latin font.
    assert_eq!(
        drawn(&["Latin", "East"], HintedSlot::Symbols),
        [0, 1, 1, 1, 1, 0, 1]
    );
    assert_eq!(
        drawn(&["Latin", "East"], HintedSlot::Punctuation),
        [0, 0, 0, 0, 0, 0, 1]
    );
    // Under Times New Roman the hint moves nothing, not even the em dash.
    assert_eq!(
        drawn(&["Latin", "Times New Roman"], HintedSlot::Symbols),
        [0; 7]
    );
}

#[test]
fn draws_complex_script_text_of_a_missing_font_with_the_font_of_the_quirk() {
    use crate::ns::W;
    use crate::props::FontRef;
    use crate::quirks::MissingComplexFont::{self, Arial, ByFontTable};
    use f_office_xml::{Document, Limits};
    let fonts = Only(&[
        "Latin",
        "Arial",
        "Calibri",
        "Times New Roman",
        "Sakkal Majalla",
    ]);
    let theme = crate::styles::Theme {
        latin: crate::styles::MinorMajor {
            minor: Some("Calibri".into()),
            major: None,
        },
        ..crate::styles::Theme::default()
    };
    let long = "A Missing Font Name Of 32 Chars.";
    assert_eq!(long.len(), 32);
    let entries = [
        (
            "Hebrew Swiss",
            r#"<w:charset w:val="B1"/><w:family w:val="swiss"/>"#,
        ),
        (
            "Arabic Roman",
            r#"<w:charset w:val="B2"/><w:family w:val="roman"/>"#,
        ),
        (
            "Paged Roman",
            r#"<w:charset w:val="00"/><w:family w:val="roman"/><w:sig w:usb0="00002001" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000041" w:csb1="00000000"/>"#,
        ),
        (
            "Paged Auto",
            r#"<w:charset w:val="00"/><w:family w:val="auto"/><w:sig w:usb0="00002001" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000041" w:csb1="00000000"/>"#,
        ),
        (
            "Ranged Auto",
            r#"<w:charset w:val="00"/><w:family w:val="auto"/><w:sig w:usb0="00002001" w:usb1="00000000" w:usb2="00000000" w:usb3="00000000" w:csb0="00000001" w:csb1="00000000"/>"#,
        ),
        (
            "Plain Roman",
            r#"<w:charset w:val="00"/><w:family w:val="roman"/>"#,
        ),
        (long, r#"<w:charset w:val="B2"/><w:family w:val="swiss"/>"#),
    ];
    let table = entries
        .iter()
        .fold(String::new(), |mut table, (name, parts)| {
            table.push_str(r#"<w:font w:name=""#);
            table.push_str(name);
            table.push_str(r#"">"#);
            table.push_str(parts);
            table.push_str("</w:font>");
            table
        });
    let xml = format!(r#"<w:fonts xmlns:w="{W}">{table}</w:fonts>"#);
    let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
    let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
    let drawn = |quirk: MissingComplexFont, complex: &str| {
        let props = RunProps {
            font_ascii: Some(FontRef::Name("Latin".into())),
            font_cs: Some(Box::new(FontRef::Name(complex.into()))),
            ..RunProps::default()
        };
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(quirk));
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
        let mut glyphs = Vec::new();
        shaper.measure(&props, "a \u{05D0}", &mut glyphs);
        let faces: Vec<u32> = glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect();
        (faces.first().copied(), faces.last().copied())
    };
    // The Latin letter keeps its font. The Hebrew letter takes Arial whatever the entry says,
    // or, by the entry: Times New Roman without one or for a name too long to read it; Arial
    // for an entry of another class than roman that names a complex script by its character
    // set or the code page 1256; Calibri for one that names none; and for a roman entry,
    // Sakkal Majalla when it names the Arabic script and Times New Roman otherwise.
    let cases = [
        ("Missing", 3),
        ("Hebrew Swiss", 1),
        ("Arabic Roman", 4),
        ("Paged Roman", 4),
        ("Paged Auto", 1),
        ("Ranged Auto", 2),
        ("Plain Roman", 3),
        (long, 3),
    ];
    for (missing, face) in cases {
        assert_eq!(drawn(Arial, missing), (Some(0), Some(1)), "{missing}");
        assert_eq!(
            drawn(ByFontTable, missing),
            (Some(0), Some(face)),
            "{missing}"
        );
    }
}

/// Has the families "Named", "Arial", "Calibri" and "Times New Roman" as fonts 0 to 3, and
/// draws the missing family "Other" with "Named" as font 9, its target's substitute.
struct Substituting;

impl crate::Fonts for Substituting {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Only(&["Named", "Arial", "Calibri", "Times New Roman"]).face(family, bold, italic)
    }

    fn substitute(
        &self,
        _family: &FamilyName,
        _bold: bool,
        _italic: bool,
    ) -> Option<crate::ChosenFace> {
        None
    }

    fn family_substitute(
        &self,
        family: &FamilyName,
        bold: bool,
        italic: bool,
    ) -> Option<crate::ChosenFace> {
        if !family.is("Other") {
            return None;
        }
        let chosen = self.face(&FamilyName::from_static("Named"), bold, italic)?;
        Some(crate::ChosenFace {
            font: f_office_fonts::FontId::from_index(9),
            ..chosen
        })
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }
}

#[test]
fn draws_complex_script_text_of_a_missing_family_with_its_substitute_first() {
    use crate::props::FontRef;
    use crate::quirks::MissingComplexFont::{Arial, ByFontTable};
    let table = crate::styles::FontTable::default();
    let theme = crate::styles::Theme::default();
    let drawn = |quirk, text: &str| {
        let props = RunProps {
            font_ascii: Some(FontRef::Name("Other".into())),
            font_cs: Some(Box::new(FontRef::Name("Other".into()))),
            ..RunProps::default()
        };
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(quirk));
        let mut shaper = super::Shaper::new(&Substituting, &theme, &table, &settings);
        let mut glyphs = Vec::new();
        shaper.measure(&props, text, &mut glyphs);
        glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<u32>>()
    };
    for quirk in [Arial, ByFontTable] {
        // The target's substitute of the family, font 9, comes before Arial or Times New
        // Roman, the fallbacks of a missing complex script font, for a Hebrew letter, as it
        // comes for a Latin letter.
        assert_eq!(drawn(quirk, "\u{05D0}"), [9], "{quirk:?}");
        assert_eq!(drawn(quirk, "a"), [9], "{quirk:?}");
    }
}

#[test]
fn draws_the_digits_of_a_right_to_left_run_with_its_ascii_font() {
    use crate::props::FontRef;
    let fonts = Only(&["Latin", "Arial", "Calibri"]);
    let theme = crate::styles::Theme {
        latin: crate::styles::MinorMajor {
            minor: Some("Calibri".into()),
            major: None,
        },
        ..crate::styles::Theme::default()
    };
    let table = crate::styles::FontTable::default();
    let drawn = |ascii: &str, (rtl, complex): (bool, bool), text: &str| {
        let props = RunProps {
            font_ascii: Some(FontRef::Name(ascii.into())),
            font_cs: Some(Box::new(FontRef::Name("Missing".into()))),
            rtl: rtl.then_some(true),
            complex: complex.then_some(true),
            ..RunProps::default()
        };
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        shaper.measure(&props, text, &mut glyphs);
        glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<_>>()
    };
    // The Hebrew letter and the hyphen take Arial for the missing complex script font, and the
    // digits the run's ASCII font, also with `w:cs` beside `w:rtl`.
    assert_eq!(drawn("Latin", (true, false), "\u{05D0}1-2"), [1, 0, 1, 0]);
    assert_eq!(drawn("Latin", (true, true), "\u{05D0}1-2"), [1, 0, 1, 0]);
    // A full stop, a comma and a colon between two digits take the face of the digits; a full
    // stop after the digits takes the complex script font.
    assert_eq!(
        drawn("Latin", (true, false), "5.0,6:1."),
        [0, 0, 0, 0, 0, 0, 0, 1]
    );
    assert_eq!(drawn("Latin", (true, false), ".5 :"), [1, 0, 1, 1]);
    // In a run with `w:cs` alone, the digits take the complex script font as the letters do.
    assert_eq!(drawn("Latin", (false, true), "\u{05D0}1.2"), [1, 1, 1, 1]);
    // When the ASCII font is missing too, the digits keep Arial.
    assert_eq!(drawn("Gone", (true, false), "\u{05D0}1-2"), [1, 1, 1, 1]);
}

#[test]
fn draws_the_digits_of_a_hebrew_right_to_left_run_with_its_complex_script_font() {
    use crate::props::{BidiScript, FontRef};
    let fonts = Only(&["Latin", "Arial"]);
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let drawn = |language: &str| {
        let props = RunProps {
            font_ascii: Some(FontRef::Name("Latin".into())),
            font_cs: Some(Box::new(FontRef::Name("Arial".into()))),
            rtl: Some(true),
            bidi_script: Some(BidiScript::of(language)),
            ..RunProps::default()
        };
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        shaper.measure(&props, "\u{05D0}1.2", &mut glyphs);
        glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<_>>()
    };
    // A bidi language that is not Hebrew leaves the digits and the full stop between them in
    // the ASCII font; with a Hebrew one they take the complex script font.
    assert_eq!(drawn("fa-IR"), [1, 0, 0, 0]);
    assert_eq!(drawn("ar-SA"), [1, 0, 0, 0]);
    assert_eq!(drawn("he-IL"), [1, 1, 1, 1]);
    assert_eq!(drawn("HE"), [1, 1, 1, 1]);
}

#[test]
fn draws_the_digits_of_a_right_to_left_run_at_the_complex_script_size_and_bold() {
    use crate::props::FontRef;
    let fonts = Only(&["Latin", "Arial"]);
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let props = RunProps {
        font_ascii: Some(FontRef::Name("Latin".into())),
        font_cs: Some(Box::new(FontRef::Name("Arial".into()))),
        size: Some(28),
        size_cs: Some(18),
        bold: Some(true),
        rtl: Some(true),
        ..RunProps::default()
    };
    let mut shaper = super::Shaper::new(&fonts, &theme, &table, &super::ShaperSettings::base());
    let mut glyphs = Vec::new();
    shaper.measure(&props, "5", &mut glyphs);
    // The digit has the ASCII font at `w:szCs`, with the bold of `w:bCs` and not of `w:b`.
    let face = &shaper.faces[glyphs[0].face.0];
    assert_eq!(face.font.index(), 0);
    assert_eq!(Some(face.size), Length::from_points(9));
    let plain = glyphs[0].face;
    glyphs.clear();
    let bold = RunProps {
        bold: None,
        bold_cs: Some(true),
        ..props
    };
    shaper.measure(&bold, "5", &mut glyphs);
    assert_ne!(glyphs[0].face, plain);
}

#[test]
fn draws_a_missing_font_with_cambria_only_in_a_document_without_a_theme() {
    use crate::styles::Theme;
    let fonts = Only(&["Times New Roman", "Cambria", "Carlito"]);
    let font = |theme: &Theme, name: Option<&str>| chosen(&fonts, theme, name);
    let none = Theme::default();
    assert_eq!(font(&none, Some("Missing")), 1);
    assert_eq!(font(&none, Some("\"Calibri\", Arial, sans-serif")), 1);
    assert_eq!(font(&none, Some("Times New Roman")), 0);
    assert_eq!(font(&none, None), 0);
    assert_eq!(font(&none, Some("+minor")), 0);
}

/// Has one family, "Named", which `face` gives as font 0 and `substitute` as font 1.
struct Standing;

impl crate::Fonts for Standing {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Only(&["Named", "Yu Gothic"]).face(family, bold, italic)
    }

    fn substitute(
        &self,
        family: &FamilyName,
        bold: bool,
        italic: bool,
    ) -> Option<crate::ChosenFace> {
        let chosen = self.face(family, bold, italic)?;
        let font = f_office_fonts::FontId::from_index(1);
        Some(crate::ChosenFace { font, ..chosen })
    }

    fn family_substitute(
        &self,
        family: &FamilyName,
        bold: bool,
        italic: bool,
    ) -> Option<crate::ChosenFace> {
        if !["Other", "Missing", "CharsetMissing"]
            .iter()
            .any(|name| family.is(name))
        {
            return None;
        }
        let chosen = self.face(&FamilyName::from_static("Named"), bold, italic)?;
        Some(crate::ChosenFace {
            font: f_office_fonts::FontId::from_index(2),
            ..chosen
        })
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }
}

#[test]
fn takes_a_substitute_for_the_first_font_of_a_list_and_for_an_alternate_name() {
    use crate::ns::W;
    use crate::props::FontRef;
    use f_office_xml::{Document, Limits};
    let xml = format!(
        r#"<w:fonts xmlns:w="{W}"><w:font w:name="Other"><w:altName w:val="Named"/></w:font><w:font w:name="CharsetMissing"><w:charset w:val="80"/></w:font></w:fonts>"#
    );
    let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
    let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
    let theme = crate::styles::Theme::default();
    let font = |name: &str| {
        let props = RunProps {
            font_ascii: Some(FontRef::Name(name.into())),
            ..RunProps::default()
        };
        let mut shaper =
            super::Shaper::new(&Standing, &theme, &table, &super::ShaperSettings::base());
        let face = shaper.face(&props, true).unwrap();
        shaper.faces[face.0].font.index()
    };
    assert_eq!(font("Named"), 0);
    assert_eq!(font("Named, Arial, sans-serif"), 1);
    assert_eq!(font("Other"), 1);
    assert_eq!(font("Missing"), 2);
    assert_eq!(font("CharsetMissing"), 1);
}

#[test]
fn keeps_times_new_roman_for_text_without_a_font_also_with_a_theme() {
    let fonts = Only(&["Times New Roman", "Cambria", "Carlito", "Calibri"]);
    let themed = crate::styles::Theme {
        latin: crate::styles::MinorMajor {
            minor: Some("Carlito".into()),
            major: None,
        },
        ..crate::styles::Theme::default()
    };
    let font = |name: Option<&str>| chosen(&fonts, &themed, name);
    assert_eq!(font(None), 0);
    assert_eq!(font(Some("+minor")), 2);
}

#[test]
fn draws_a_missing_font_with_calibri_in_a_document_with_a_theme() {
    let fonts = Only(&["Times New Roman", "Cambria", "Carlito", "Calibri"]);
    let theme = |minor: &str| crate::styles::Theme {
        latin: crate::styles::MinorMajor {
            minor: Some(minor.into()),
            major: None,
        },
        ..crate::styles::Theme::default()
    };
    // Not the theme's minor font, also when the document has that font or names it.
    assert_eq!(chosen(&fonts, &theme("Cambria"), Some("Missing")), 3);
    assert_eq!(chosen(&fonts, &theme("Missing"), Some("Missing")), 3);
    // Without Calibri, Times New Roman keeps the text visible.
    let without = Only(&["Times New Roman", "Cambria"]);
    assert_eq!(chosen(&without, &theme("Cambria"), Some("Missing")), 0);
}

/// The face that a run in the font `name` takes among Times New Roman, Cambria, Carlito and
/// Calibri, by a font table of a `roman` entry, a `swiss` entry and an entry without a class,
/// with the fallback `fallback` and with a theme of Carlito or without a theme.
fn fallback_face(fallback: crate::quirks::MissingFontFallback, themed: bool, name: &str) -> u32 {
    use crate::ns::W;
    use crate::props::FontRef;
    use f_office_xml::{Document, Limits};
    let fonts = Only(&["Times New Roman", "Cambria", "Carlito", "Calibri"]);
    let xml = format!(
        r#"<w:fonts xmlns:w="{W}"><w:font w:name="Roman"><w:family w:val="roman"/></w:font><w:font w:name="Swiss"><w:family w:val="swiss"/></w:font><w:font w:name="NoClass"><w:charset w:val="00"/></w:font></w:fonts>"#
    );
    let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
    let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
    let theme = crate::styles::Theme {
        latin: crate::styles::MinorMajor {
            minor: themed.then(|| "Carlito".into()),
            major: None,
        },
        ..crate::styles::Theme::default()
    };
    let props = RunProps {
        font_ascii: Some(FontRef::Name(name.into())),
        ..RunProps::default()
    };
    let settings = super::ShaperSettings::base_with(|p| p.with_variant(fallback));
    let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
    let face = shaper.face(&props, true).unwrap();
    shaper.faces[face.0].font.index()
}

#[test]
fn draws_a_missing_font_by_its_font_table_entry_where_the_target_does() {
    use crate::quirks::MissingFontFallback::ByFontTable;
    // Cambria for no entry and for a roman entry, Calibri for another class or none, with a
    // theme and without one.
    for themed in [true, false] {
        let faces = ["Absent", "Roman", "Swiss", "NoClass"]
            .map(|name| fallback_face(ByFontTable, themed, name));
        assert_eq!(faces, [1, 1, 3, 3]);
    }
}

#[test]
fn draws_a_missing_font_by_the_theme_where_the_target_does() {
    use crate::quirks::MissingFontFallback::ByTheme;
    // Calibri with a theme and Cambria without, whatever the entry says.
    for name in ["Absent", "Roman", "Swiss"] {
        assert_eq!(
            [true, false].map(|themed| fallback_face(ByTheme, themed, name)),
            [3, 1]
        );
    }
}

/// The fonts of each glyph of `text` in a run in the font `name`, among Times New Roman,
/// Cambria, Calibri, Arial and Cambria Math, by a font table whose entries give
/// `Times New Roman CYR` and `Missing CYR` the Cyrillic character set, `Times New Roman CE`
/// the ANSI one and `Times New Roman Greek` the Cyrillic one and an alternate, each of the
/// class `roman`, with the fallback of a missing font by its font table entry.
fn suffixed_faces(names: crate::quirks::SuffixedFontNames, name: &str, text: &str) -> Vec<u32> {
    use crate::ns::W;
    use crate::props::FontRef;
    use f_office_xml::{Document, Limits};
    let fonts = Only(&[
        "Times New Roman",
        "Cambria",
        "Calibri",
        "Arial",
        "Cambria Math",
    ]);
    let entry = |name: &str, charset: &str, alternate: &str| {
        format!(
            r#"<w:font w:name="{name}">{alternate}<w:charset w:val="{charset}"/><w:family w:val="roman"/></w:font>"#
        )
    };
    let xml = format!(
        r#"<w:fonts xmlns:w="{W}">{}{}{}{}</w:fonts>"#,
        entry("Times New Roman CYR", "CC", ""),
        entry("Missing CYR", "CC", ""),
        entry("Times New Roman CE", "00", ""),
        entry(
            "Times New Roman Greek",
            "CC",
            r#"<w:altName w:val="Arial"/>"#
        ),
    );
    let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
    let table = crate::styles::FontTable::read(&doc, doc.root().unwrap());
    let theme = crate::styles::Theme::default();
    let font = Some(FontRef::Name(name.into()));
    let props = RunProps {
        font_ascii: font.clone(),
        font_hansi: font,
        ..RunProps::default()
    };
    let settings = super::ShaperSettings::base_with(|p| {
        p.with_variant(crate::quirks::MissingFontFallback::ByFontTable)
            .with_variant(names)
    });
    let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
    let mut glyphs = Vec::new();
    shaper.measure(&props, text, &mut glyphs);
    glyphs
        .iter()
        .map(|glyph| shaper.faces[glyph.face.0].font.index())
        .collect()
}

/// A, e acute, c caron, Cyrillic A, horizontal bar, numero sign: two characters of code page
/// 1252 and one of each class of a split run.
const SPLIT_TEXT: &str = "A\u{E9}\u{10D}\u{410}\u{2015}\u{2116}";

#[test]
fn splits_a_run_of_a_suffixed_font_name_whose_entry_gives_its_character_set() {
    use crate::quirks::SuffixedFontNames::DrawBase;
    // Code page 1252 keeps Times New Roman, letters take Calibri, General Punctuation Arial,
    // and the numero sign Cambria Math.
    assert_eq!(
        suffixed_faces(DrawBase, "Times New Roman CYR", SPLIT_TEXT),
        [0, 0, 2, 2, 3, 4]
    );
    // The suffix compares without regard to case.
    assert_eq!(
        suffixed_faces(DrawBase, "Times New Roman cyr", "A\u{410}"),
        [0, 2]
    );
}

#[test]
fn draws_a_suffixed_font_name_whole_with_its_family_without_that_entry() {
    use crate::quirks::SuffixedFontNames::DrawBase;
    // With an entry of another character set, or none, the family draws every character.
    assert_eq!(
        suffixed_faces(DrawBase, "Times New Roman CE", SPLIT_TEXT),
        [0; 6]
    );
    assert_eq!(
        suffixed_faces(DrawBase, "Times New Roman TUR", SPLIT_TEXT),
        [0; 6]
    );
    // A name whose family the caller lacks is a missing font: Cambria for its roman entry.
    assert_eq!(suffixed_faces(DrawBase, "Missing CYR", SPLIT_TEXT), [1; 6]);
    // The entry's alternate stands for the name first, and the run does not split.
    assert_eq!(
        suffixed_faces(DrawBase, "Times New Roman Greek", SPLIT_TEXT),
        [3; 6]
    );
}

#[test]
fn draws_a_suffixed_font_name_as_a_missing_font_where_the_target_does_not() {
    use crate::quirks::SuffixedFontNames::Missing;
    for name in ["Times New Roman CYR", "Times New Roman TUR"] {
        assert_eq!(suffixed_faces(Missing, name, SPLIT_TEXT), [1; 6], "{name}");
    }
}

#[test]
fn a_ligature_takes_its_own_advance_and_kerns_with_the_glyph_after_it() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    // A document in mode 14 or later, in which runs may turn on ligatures.
    let settings = super::ShaperSettings {
        ligatures: true,
        ..super::ShaperSettings::base()
    };
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings);
    let props = |ligatures| RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        ligatures,
        kern: Some(2),
        ..RunProps::default()
    };
    let measured = |shaper: &mut super::Shaper<'_>, ligatures| {
        let mut glyphs = Vec::new();
        shaper.measure(&props(ligatures), "fix", &mut glyphs);
        glyphs
            .iter()
            .map(|g| (g.id, g.advance.units(), g.part))
            .collect::<Vec<_>>()
    };
    // At 10 pt, 100 units are 25,400 and 1 unit is 254.
    assert_eq!(
        measured(&mut shaper, Some(true)),
        [
            (500, 150 * 254 - 20 * 254, false),
            (105, 0, true),
            (120, 25_400, false)
        ]
    );
    assert_eq!(
        measured(&mut shaper, None),
        [
            (102, 25_400 - 999 * 254, false),
            (105, 25_400, false),
            (120, 25_400, false)
        ]
    );
    // A kerned glyph keeps its own width for the PDF writer, 100 or 150 thousandths of an em;
    // a glyph that no kerning follows writes the rounding of its advance.
    let mut glyphs = Vec::new();
    shaper.measure(&props(None), "fix", &mut glyphs);
    let written: Vec<Option<u16>> = glyphs.iter().map(|g| g.written).collect();
    assert_eq!(written, [Some(100), None, None]);
    let mut glyphs = Vec::new();
    shaper.measure(&props(Some(true)), "fix", &mut glyphs);
    assert_eq!(glyphs.first().map(|g| g.written), Some(Some(150)));
    // Character spacing keeps the letters apart, also with ligatures turned on.
    let spaced = RunProps {
        spacing: Some(Length::from_units(-12_700)),
        ..props(Some(true))
    };
    let mut glyphs = Vec::new();
    shaper.measure(&spaced, "fix", &mut glyphs);
    let ids: Vec<u32> = glyphs.iter().map(|g| g.id).collect();
    assert_eq!(ids, [102, 105, 120]);
}

#[test]
fn an_older_compatibility_mode_keeps_the_letters_apart() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let shaper = super::Shaper::new(
        &Joining,
        &theme,
        &table,
        &super::ShaperSettings {
            ligatures: false,
            ..super::ShaperSettings::base()
        },
    );
    let props = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        ligatures: Some(true),
        ..RunProps::default()
    };
    // A shaper for another story of the document keeps the setting.
    for mut shaper in [shaper.fork(), shaper] {
        let mut glyphs = Vec::new();
        shaper.measure(&props, "fix", &mut glyphs);
        let ids: Vec<u32> = glyphs.iter().map(|g| g.id).collect();
        assert_eq!(ids, [102, 105, 120]);
    }
}

#[test]
fn scales_the_characters_before_their_spacing() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
    let props = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        scale: Some(150),
        spacing: Some(Length::from_units(1_000)),
        ..RunProps::default()
    };
    let mut glyphs = Vec::new();
    shaper.measure(&props, "ab", &mut glyphs);
    // At 10 pt, a glyph of 100 units is 25,400 wide, so 38,100 at 150%, and the spacing
    // comes on top unscaled.
    let advances: Vec<i64> = glyphs.iter().map(|g| g.advance.units()).collect();
    assert_eq!(advances, [39_100, 39_100]);
}

#[test]
fn a_space_typed_in_a_math_run_holds_the_line_together_and_keeps_its_glyph() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
    let text = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        ..RunProps::default()
    };
    let math = RunProps {
        math: Some(true),
        ..text.clone()
    };
    let normal_math = RunProps {
        math: Some(false),
        ..text.clone()
    };
    let (mut prose, mut equation, mut normal) = (Vec::new(), Vec::new(), Vec::new());
    shaper.measure(&text, "a b", &mut prose);
    shaper.measure(&math, "a b", &mut equation);
    shaper.measure(&normal_math, "a b", &mut normal);
    let kinds: Vec<SpaceKind> = equation.iter().map(|g| g.space).collect();
    assert_eq!(
        kinds,
        [SpaceKind::Free, SpaceKind::Equation, SpaceKind::Free]
    );
    assert_eq!(
        normal.iter().map(|g| g.space).collect::<Vec<_>>(),
        [SpaceKind::Free, SpaceKind::Equation, SpaceKind::Free]
    );
    assert!(crate::lines::is_space(&crate::lines::Piece::Glyph(
        prose[1]
    )));
    assert!(!crate::lines::is_space(&crate::lines::Piece::Glyph(
        equation[1]
    )));
    assert_eq!(equation[1].ch, ' ');
    assert_eq!(equation[1].id, prose[1].id);
    assert_eq!(equation[1].advance, prose[1].advance);
}

#[test]
fn an_operator_break_space_shapes_as_the_no_break_space_of_an_operator() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
    let math = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        math: Some(true),
        ..RunProps::default()
    };
    let (mut no_break, mut operator) = (Vec::new(), Vec::new());
    shaper.measure(&math, "+\u{a0}", &mut no_break);
    shaper.measure(
        &math,
        &format!("+{}", super::OPERATOR_BREAK_SPACE),
        &mut operator,
    );
    assert_eq!(operator[1].ch, '\u{a0}');
    assert_eq!(operator[1].space, SpaceKind::Operator);
    assert_eq!(operator[1].id, no_break[1].id);
    assert_eq!(operator[1].advance, no_break[1].advance);
}

#[test]
fn a_spaced_glyph_keeps_its_own_written_width_and_carries_its_spacing() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let props = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        spacing: Some(Length::from_units(-12_700)),
        ..RunProps::default()
    };
    // A target that keeps the spacing in the advance writes the advance's rounding and
    // carries no spacing apart.
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
    let mut glyphs = Vec::new();
    shaper.measure(&props, "ab", &mut glyphs);
    assert!(
        glyphs
            .iter()
            .all(|g| g.written.is_none() && g.spacing == Length::ZERO)
    );
    // A shaper for another story of the document keeps the setting.
    let settings = super::ShaperSettings::base_with(|p| {
        p.with_variant(crate::quirks::DeviceAdvance::ExtrasOnTheirOwn)
    });
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings).fork();
    let mut glyphs = Vec::new();
    shaper.measure(&props, "ab", &mut glyphs);
    // At 10 pt, a glyph of 100 units is 25,400 wide, and condensed by 0.5 pt it steps 12,700.
    // The PDF writer writes its own width, 100 thousandths of an em, and the glyph keeps the
    // spacing apart for the device's steps.
    let measured: Vec<(i64, Option<u16>, i64)> = glyphs
        .iter()
        .map(|g| (g.advance.units(), g.written, g.spacing.units()))
        .collect();
    assert_eq!(
        measured,
        [(12_700, Some(100), -12_700), (12_700, Some(100), -12_700)]
    );
    // A run without spacing leaves the written width to the writer's rounding.
    let mut glyphs = Vec::new();
    let plain = RunProps {
        spacing: None,
        ..props
    };
    shaper.measure(&plain, "ab", &mut glyphs);
    assert!(
        glyphs
            .iter()
            .all(|g| g.written.is_none() && g.spacing == Length::ZERO)
    );
}

#[test]
fn clamps_condensed_character_spacing_at_zero_advance() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    // At 10 pt, a glyph of 100 units is 25,400 wide; condensing by 2 pt (-50,800) clamps
    // advance to 0 and caps spacing at -25,400 so ExtrasOnTheirOwn steps 0 rather than backward.
    let props = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        spacing: Length::from_twips(-40),
        ..RunProps::default()
    };
    let settings = super::ShaperSettings::base_with(|p| {
        p.with_variant(crate::quirks::DeviceAdvance::ExtrasOnTheirOwn)
    });
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings);
    let mut glyphs = Vec::new();
    shaper.measure(&props, "a ", &mut glyphs);
    let measured: Vec<(i64, i64)> = glyphs
        .iter()
        .map(|g| (g.advance.units(), g.spacing.units()))
        .collect();
    assert_eq!(measured, [(0, -25_400), (0, -25_400)]);
}

#[test]
fn gives_full_width_characters_the_spacing_twice_when_byte_widths_balance() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let props = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        font_east_asia: Some(Box::new(crate::props::FontRef::Name("Any".into()))),
        spacing: Some(Length::from_units(1_000)),
        ..RunProps::default()
    };
    let advances = |spacing: crate::styles::FullWidthSpacing| {
        let mut shaper = super::Shaper::new(
            &Joining,
            &theme,
            &table,
            &super::ShaperSettings {
                full_width_spacing: spacing,
                ..super::ShaperSettings::base()
            },
        );
        let mut glyphs = Vec::new();
        shaper.measure(&props, "测、Aa", &mut glyphs);
        glyphs
            .iter()
            .map(|g| g.advance.units())
            .collect::<Vec<i64>>()
    };
    // At 10 pt, a glyph of 100 units is 25,400 wide.
    assert_eq!(
        advances(crate::styles::FullWidthSpacing::Twice),
        [27_400, 27_400, 27_400, 26_400]
    );
    assert_eq!(
        advances(crate::styles::FullWidthSpacing::Once),
        [26_400, 26_400, 26_400, 26_400]
    );
}

#[test]
fn widens_synthetic_bold_glyphs_but_not_spaces_by_a_fiftieth_of_the_size() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    // The joining fonts have one regular face, so bold text is synthetic bold.
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
    let advances = |shaper: &mut super::Shaper<'_>, bold| {
        let props = RunProps {
            font_ascii: Some(crate::props::FontRef::Name("Any".into())),
            bold: Some(bold),
            ..RunProps::default()
        };
        let mut glyphs = Vec::new();
        shaper.measure(&props, "a b", &mut glyphs);
        glyphs.iter().map(|g| g.advance.units()).collect::<Vec<_>>()
    };
    // At 10 pt, a glyph of 100 units is 25,400 wide, and a fiftieth of 10 pt is 5,080.
    assert_eq!(advances(&mut shaper, false), [25_400, 25_400, 25_400]);
    assert_eq!(advances(&mut shaper, true), [30_480, 25_400, 30_480]);
    // A target whose synthetic bold keeps the regular widths does not widen it, nor does a
    // shaper forked from it.
    let settings = super::ShaperSettings::base_with(|p| {
        p.with_variant(crate::quirks::SyntheticBoldWidth::KeepsWidths)
    });
    let keeps = super::Shaper::new(&Joining, &theme, &table, &settings);
    assert_eq!(advances(&mut keeps.fork(), true), [25_400, 25_400, 25_400]);
}

#[test]
fn draws_small_capitals_at_four_fifths_of_the_size_to_the_nearest_half_point() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
    let advances = |shaper: &mut super::Shaper<'_>, half_points| {
        let props = RunProps {
            font_ascii: Some(crate::props::FontRef::Name("Any".into())),
            size: Some(half_points),
            small_caps: Some(true),
            ..RunProps::default()
        };
        let mut glyphs = Vec::new();
        shaper.measure(&props, "Ab 1+", &mut glyphs);
        glyphs.iter().map(|g| g.advance.units()).collect::<Vec<_>>()
    };
    // A glyph of 100 units is a tenth of the size: 1.6 pt at 16 pt, and 1.3 pt at 13 pt,
    // which is 4/5 of 16 pt (12.8 pt) to the nearest half point. 4/5 of 12 pt (9.6 pt)
    // goes to 9.5 pt. The letter "b" and the space are small, and the capital, the digit
    // and the plus sign keep the full size.
    assert_eq!(
        advances(&mut shaper, 32),
        [40_640, 33_020, 33_020, 40_640, 40_640]
    );
    assert_eq!(
        advances(&mut shaper, 24),
        [30_480, 24_130, 24_130, 30_480, 30_480]
    );
}

#[test]
fn leaves_out_the_format_characters_that_word_does_not_draw() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base());
    let props = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        ..RunProps::default()
    };
    let mut glyphs = Vec::new();
    shaper.measure(
        &props,
        "\u{FEFF}a\u{200B}b\u{200D}\u{2060}c\u{FE0F}\u{202C}",
        &mut glyphs,
    );
    let text: String = glyphs.iter().map(|g| g.ch).collect();
    assert_eq!(text, "abc");
}

/// The shaper leaves each format character out and marks the glyph after it, in a stretch of
/// Arabic letters, whose shaper takes the zero width non-joiner, and in other text alike; no
/// other glyph is marked, and an invisible operator marks none.
#[test]
fn marks_the_glyph_after_each_format_character() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let settings = super::ShaperSettings::base();
    let mut shaper = super::Shaper::new(&Shaping, &theme, &table, &settings);
    let props = RunProps {
        size: Some(20),
        size_cs: Some(20),
        ..RunProps::default()
    };
    let mut marked = |text: &str| {
        let mut glyphs = Vec::new();
        shaper.measure(&props, text, &mut glyphs);
        glyphs
            .iter()
            .map(|g| {
                (
                    g.ch,
                    g.left_out_before == super::LeftOutBefore::FormatCharacter,
                )
            })
            .collect::<Vec<_>>()
    };
    assert_eq!(
        marked("\u{0628}\u{0646}\u{200C}\u{0645}\u{0647}"),
        [
            ('\u{0628}', false),
            ('\u{0646}', false),
            ('\u{0645}', true),
            ('\u{0647}', false),
        ]
    );
    assert_eq!(
        marked("ab\u{200C}c \u{200C}d"),
        [
            ('a', false),
            ('b', false),
            ('c', true),
            (' ', false),
            ('d', true),
        ]
    );
    let format = ('\u{200B}'..='\u{200F}')
        .chain('\u{202A}'..='\u{202E}')
        .chain(['\u{FEFF}']);
    for ch in format {
        assert_eq!(
            marked(&format!("ab{ch}c")),
            [('a', false), ('b', false), ('c', true)],
            "U+{:04X}",
            u32::from(ch)
        );
        assert_eq!(
            marked(&format!("\u{0628}{ch}\u{0646}")),
            [('\u{0628}', false), ('\u{0646}', true)],
            "U+{:04X}",
            u32::from(ch)
        );
    }
    assert!(
        marked("\u{0628}\u{0646} ab\u{2060}c")
            .iter()
            .all(|&(_, after)| !after)
    );
}

#[test]
fn draws_the_operators_and_joins_the_selectors_where_the_target_does() {
    use crate::quirks::InvisibleCharacters;
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let settings = super::ShaperSettings::base_with(|p| {
        p.with_variant(InvisibleCharacters::OperatorsDrawnSelectorsJoined)
    });
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings);
    let props = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        ..RunProps::default()
    };
    let math = RunProps {
        math: Some(true),
        ..props.clone()
    };
    let mut measured_in = |props: &RunProps, text: &str| {
        let mut glyphs = Vec::new();
        shaper.measure(props, text, &mut glyphs);
        glyphs
    };
    // Text of an equation leaves every invisible character out.
    let in_math = measured_in(&math, "\u{FE00}f\u{2061}x\u{2060}\u{FE0F}");
    let mut measured = |text: &str| measured_in(&props, text);
    // The format characters are left out, the operators are drawn, and a selector inside its
    // run joins the character before it.
    let shown = |glyphs: &[super::Glyph]| glyphs.iter().map(|g| g.ch).collect::<String>();
    assert_eq!(shown(&in_math), "fx");
    assert_eq!(
        shown(&measured(
            "\u{FEFF}a\u{200B}b\u{200D}\u{2060}c\u{FE0F}\u{202C}"
        )),
        "ab\u{2060}c"
    );
    // A selector that opens its run, also after a format character, is drawn for the layout to
    // join or keep.
    let opening = measured("\u{200B}\u{FE00}d\u{2061}");
    assert_eq!(shown(&opening), "\u{FE00}d\u{2061}");
    let selectors: Vec<bool> = opening.iter().map(super::is_selector).collect();
    assert_eq!(selectors, [true, false, false]);
}

#[test]
fn decides_what_each_kind_of_invisible_character_does() {
    use super::decisions::Invisible;
    use crate::quirks::InvisibleCharacters;
    let chars = [
        'x', '\u{200C}', '\u{202E}', '\u{FEFF}', '\u{2060}', '\u{2064}', '\u{FE0F}',
    ];
    let decided = |variant, math| {
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
        chars.map(|ch| settings.invisible(ch, math))
    };
    let (drawn, left, joined) = (Invisible::Drawn, Invisible::Left, Invisible::Joined);
    let none_drawn = [drawn, left, left, left, left, left, left];
    for math in [false, true] {
        assert_eq!(decided(InvisibleCharacters::TakeNoRoom, math), none_drawn);
    }
    assert_eq!(
        decided(InvisibleCharacters::OperatorsDrawnSelectorsJoined, false),
        [drawn, left, left, left, drawn, drawn, joined]
    );
    // Text of an equation leaves every invisible character out.
    assert_eq!(
        decided(InvisibleCharacters::OperatorsDrawnSelectorsJoined, true),
        none_drawn
    );
}

#[test]
fn draws_outlines_with_a_theme_color_in_yellow() {
    let width = Length::from_emus(9_525).unwrap();
    let run = |outline| RunProps {
        outline,
        ..RunProps::default()
    };
    let solid = |color| Some(TextOutline::Solid { width, color });
    assert_eq!(
        outline(&run(solid(OutlineColor::Scheme))),
        Some(Outline {
            width,
            color: Rgb {
                r: 255,
                g: 255,
                b: 0
            },
            join: Join::Round,
        })
    );
    assert_eq!(
        outline(&run(solid(OutlineColor::Rgb([1, 2, 3])))),
        Some(Outline {
            width,
            color: Rgb { r: 1, g: 2, b: 3 },
            join: Join::Round,
        })
    );
    assert_eq!(outline(&run(Some(TextOutline::None))), None);
    assert_eq!(outline(&run(None)), None);
}

#[test]
fn scripts_of_equations_take_the_math_font_sizes_and_shifts() {
    use crate::props::MathScript;
    // Lengths in hundredths of a point.
    let pt = |hundredths: i64| Length::from_units(hundredths * Length::UNITS_PER_POINT / 100);
    let run = RunProps {
        size: Some(24),
        ..RunProps::default()
    };
    // Devices of a dot of a quarter point and of 0.24 pt.
    let (quarter, mac) = (per_inch(288), per_inch(300));
    let sup = MathScript::default().inside(MathStep::Superscript, None);
    let sub = MathScript::default().inside(MathStep::Subscript, None);
    // 73% of 12 pt is 8.76 pt, so 8.5 pt. A superscript rises 750/2048 of 12 pt, 4.39 pt, and a
    // subscript drops 418/2048 of it, 2.45 pt, each to the nearest dot.
    // A script is not a part of a fraction.
    let script = |size, rise| (pt(size), pt(rise), false);
    assert_eq!(math_size_and_rise(&run, sup, quarter), script(850, 450));
    assert_eq!(math_size_and_rise(&run, sub, quarter), script(850, -250));
    assert_eq!(math_size_and_rise(&run, sup, mac), script(850, 432));
    assert_eq!(math_size_and_rise(&run, sub, mac), script(850, -240));
    // A subscript inside the superscript takes 60%, 7.2 pt, so 7 pt, and drops 418/2048 of
    // its base's 8.5 pt from the superscript's baseline: 4.39 - 1.73 = 2.66, so 2.75.
    let inner = sup.inside(MathStep::Subscript, None);
    assert_eq!(math_size_and_rise(&run, inner, quarter), script(700, 275));
    // Raised text moves by its own distance as well.
    let raised = RunProps {
        position: Some(pt(100)),
        ..run.clone()
    };
    assert_eq!(math_size_and_rise(&raised, sup, quarter).1, pt(550));
    // A script of a display has the same size and shift.
    let display = MathScript::display();
    assert_eq!(
        math_size_and_rise(&run, display.inside(MathStep::Superscript, None), quarter),
        script(850, 450)
    );
}

#[test]
fn parts_of_fractions_take_the_math_font_sizes_and_shifts() {
    use crate::props::MathScript;
    let pt = |hundredths: i64| Length::from_units(hundredths * Length::UNITS_PER_POINT / 100);
    let quarter = per_inch(288);
    let run = |half_points| RunProps {
        size: Some(half_points),
        ..RunProps::default()
    };
    let part = |size, rise| (pt(size), pt(rise), true);
    let inline = MathScript::default();
    // In a line of text at 11 pt, the parts take script size, 8 pt; the numerator rises
    // 1200/2048 of 11 pt, 6.45 pt, and the denominator drops 1030/2048 of it, 5.53 pt.
    assert_eq!(
        math_size_and_rise(&run(22), inline.inside(MathStep::Numerator, None), quarter),
        part(800, 650)
    );
    assert_eq!(
        math_size_and_rise(
            &run(22),
            inline.inside(MathStep::Denominator, None),
            quarter
        ),
        part(800, -550)
    );
    // In a display at 12 pt, the parts keep the size, and shift 1550/2048 and 1370/2048 of it:
    // 9.08 and 8.03 pt.
    let display = MathScript::display();
    let numerator = display.inside(MathStep::Numerator, None);
    assert_eq!(
        math_size_and_rise(&run(24), numerator, quarter),
        part(1200, 900)
    );
    assert_eq!(
        math_size_and_rise(
            &run(24),
            display.inside(MathStep::Denominator, None),
            quarter
        ),
        part(1200, -800)
    );
    // A fraction in the numerator of a display stays in text style at full size (12 pt) unless
    // `m:smallFrac` is on, when it steps to script size (8.5 pt); either way its numerator rises
    // 1200/2048 of 12 pt more, 9.08 + 7.03 = 16.11 pt, so 16 pt.
    assert_eq!(
        math_size_and_rise(
            &run(24),
            numerator.inside(MathStep::Numerator, None),
            quarter
        ),
        part(1200, 1600)
    );
    assert_eq!(
        math_size_and_rise(
            &run(24),
            display
                .with_small_frac(crate::props::SmallFractions::On)
                .inside(MathStep::Numerator, None)
                .inside(MathStep::Numerator, None),
            quarter
        ),
        part(850, 1600)
    );
    // A superscript inside a numerator is still a part of the fraction.
    let inner = inline
        .inside(MathStep::Numerator, None)
        .inside(MathStep::Superscript, None);
    assert!(math_size_and_rise(&run(22), inner, quarter).2);
}

#[test]
fn structures_shift_their_parts_at_the_size_of_their_control_properties() {
    use crate::props::MathScript;
    let pt = |hundredths: i64| Length::from_units(hundredths * Length::UNITS_PER_POINT / 100);
    let quarter = per_inch(288);
    // Runs at 10 pt in a display fraction whose control properties are 14 pt: the parts keep
    // 10 pt, and shift 1550/2048 and 1370/2048 of 14 pt, 10.60 and 9.37 pt.
    let run = RunProps {
        size: Some(20),
        ..RunProps::default()
    };
    let display = MathScript::display();
    let numerator = display.inside(MathStep::Numerator, Some(28));
    let denominator = display.inside(MathStep::Denominator, Some(28));
    assert_eq!(
        math_size_and_rise(&run, numerator, quarter),
        (pt(1000), pt(1050), true)
    );
    assert_eq!(
        math_size_and_rise(&run, denominator, quarter),
        (pt(1000), pt(-925), true)
    );
    // A superscript in the numerator, of a structure whose control properties are 8 pt, rises
    // 750/2048 of 8 pt more, 2.93 pt: 13.53 pt in all, so 13.5. The superscript of a structure
    // without a control size rises at the size of its base's run, 10 pt: 3.66 pt, so 14.25.
    let sized = numerator.inside(MathStep::Superscript, Some(16));
    assert_eq!(math_size_and_rise(&run, sized, quarter).1, pt(1350));
    let plain = numerator.inside(MathStep::Superscript, None);
    assert_eq!(math_size_and_rise(&run, plain, quarter).1, pt(1425));
}

#[test]
fn superscripts_in_a_denominator_take_the_cramped_shift() {
    use crate::props::MathScript;
    let pt = |hundredths: i64| Length::from_units(hundredths * Length::UNITS_PER_POINT / 100);
    let quarter = per_inch(288);
    let run = RunProps {
        size: Some(24),
        ..RunProps::default()
    };
    let rise = |script| math_size_and_rise(&run, script, quarter).1;
    let display = MathScript::display();
    let numerator = display.inside(MathStep::Numerator, None);
    let denominator = display.inside(MathStep::Denominator, None);
    // In a display at 12 pt, the denominator drops 8.03 pt, to -8 on quarter points. A
    // superscript in it rises 615/2048 of 12 pt, 3.60 pt: -8.03 + 3.60 = -4.43, so -4.5. In
    // the numerator one rises 750/2048, 4.39 pt: 9.08 + 4.39 = 13.47, so 13.5.
    assert_eq!(rise(denominator), pt(-800));
    assert_eq!(
        rise(denominator.inside(MathStep::Superscript, None)),
        pt(-450)
    );
    assert_eq!(
        rise(numerator.inside(MathStep::Superscript, None)),
        pt(1350)
    );
    // Deeper in the denominator the part stays cramped: a superscript in the numerator of a
    // fraction in the denominator stays at 12 pt without `m:smallFrac` (-8.03 + 7.03 + 3.60 =
    // 2.60, so 2.5 pt), and takes script size 8.5 pt with `m:smallFrac` (-8.03 + 7.03 + 2.55 =
    // 1.55, so 1.5 pt).
    let inner = denominator.inside(MathStep::Numerator, None);
    let small_inner = display
        .with_small_frac(crate::props::SmallFractions::On)
        .inside(MathStep::Denominator, None)
        .inside(MathStep::Numerator, None);
    assert_eq!(
        (
            rise(inner.inside(MathStep::Superscript, None)),
            rise(small_inner.inside(MathStep::Superscript, None)),
        ),
        (pt(250), pt(150))
    );
    // A superscript beside a subscript keeps the shift of a superscript: -8.03 + 4.39 = -3.64,
    // so -3.75.
    let beside = denominator.inside(MathStep::SuperscriptBesideSubscript, None);
    assert_eq!(rise(beside), pt(-375));
    // The element of a radical is cramped: a superscript in it rises 3.60 pt, so 3.5, where
    // one outside rises 4.39, so 4.5.
    let element = display.cramped();
    assert_eq!(rise(element.inside(MathStep::Superscript, None)), pt(350));
    assert_eq!(rise(display.inside(MathStep::Superscript, None)), pt(450));
}

#[test]
fn superscripts_take_two_thirds_in_whole_half_points() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    let run = |size, vertical| RunProps {
        size: Some(size),
        vertical,
        ..RunProps::default()
    };
    let sup = Some(VerticalAlign::Superscript);
    let lost = ScriptMove::LostSize(None);
    // 22 half-points: two thirds is 14.67, so 14.
    assert_eq!(
        size_and_rise(&run(22, sup), lost, ScriptScale::TwoThirds).0,
        points(14)
    );
    assert_eq!(
        size_and_rise(&run(24, sup), lost, ScriptScale::TwoThirds).0,
        points(16)
    );
    let sub = size_and_rise(
        &run(24, Some(VerticalAlign::Subscript)),
        lost,
        ScriptScale::TwoThirds,
    );
    assert_eq!(sub, (points(16), Length::from_units(-points(2).units())));
    assert_eq!(
        size_and_rise(&run(22, None), lost, ScriptScale::TwoThirds),
        (points(22), Length::ZERO)
    );
    // At 10 pt the run loses 3.5 pt: a superscript rises by that, a subscript drops a
    // quarter of it.
    assert_eq!(
        size_and_rise(&run(20, sup), lost, ScriptScale::TwoThirds),
        (points(13), points(7))
    );
    let sub = size_and_rise(
        &run(20, Some(VerticalAlign::Subscript)),
        lost,
        ScriptScale::TwoThirds,
    )
    .1;
    assert_eq!(sub, Length::from_units(-points(7).units() / 4));
}

fn script_size_in(
    half_points: i64,
    vertical: VerticalAlign,
    metrics: &crate::FaceMetrics,
) -> Length {
    let run = RunProps {
        size: Some(half_points),
        vertical: Some(vertical),
        ..RunProps::default()
    };
    let scale = ScriptScale::of_face(metrics, Some(vertical));
    size_and_rise(&run, ScriptMove::LostSize(None), scale).0
}

fn script_face(
    em: u16,
    superscript_size: i16,
    subscript_size: i16,
    superscript_offset: i16,
) -> crate::FaceMetrics {
    crate::FaceMetrics {
        units_per_em: em,
        superscript_size,
        subscript_size,
        superscript_offset,
        ..crate::FaceMetrics::default()
    }
}

#[test]
fn scripts_take_the_sizes_of_their_font_within_the_values_seen_to_keep_them() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    let (sup, sub) = (VerticalAlign::Superscript, VerticalAlign::Subscript);
    // 1,229 of 2,048 units at 11 pt: 13.2 half-points, so 6.5 pt, where two thirds gives 7.
    let six_tenths = script_face(2048, 1229, 1229, 717);
    assert_eq!(script_size_in(22, sup, &six_tenths), points(13));
    // 1,331 of 2,048 units at 12 pt: 15.6 half-points, so 8 pt.
    assert_eq!(
        script_size_in(24, sup, &script_face(2048, 1331, 1331, 928)),
        points(16)
    );
    // A subscript takes the font's subscript size: 1,180 of 2,048 units at 12 pt is 13.8
    // half-points, so 7 pt, where the superscript is 7.5 pt.
    let apart = script_face(2048, 1250, 1180, 760);
    assert_eq!(script_size_in(24, sup, &apart), points(15));
    assert_eq!(script_size_in(24, sub, &apart), points(14));
    // Half an em with an offset of half an em keeps its own size: 6 pt at 12 pt.
    assert_eq!(
        script_size_in(24, sup, &script_face(256, 128, 128, 128)),
        points(12)
    );
}

#[test]
fn scripts_in_a_font_of_odd_values_take_three_fifths_of_the_size() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    // A superscript size of 0.3174 of the em (4 pt at 12 pt, a third of the line), an offset
    // of 0.8594 of the em, an offset of 0 or a font that gives no sizes takes three fifths:
    // 7 pt at 12 pt.
    for odd in [
        script_face(2048, 650, 650, 500),
        script_face(2048, 1579, 1579, 0),
        script_face(256, 128, 128, 220),
        script_face(2048, 1331, 1331, 0),
        script_face(1000, 0, 0, 0),
    ] {
        assert_eq!(
            script_size_in(24, VerticalAlign::Superscript, &odd),
            points(14)
        );
        assert_eq!(
            script_size_in(24, VerticalAlign::Subscript, &odd),
            points(14)
        );
    }
}

#[test]
fn scripts_of_at_most_a_third_of_their_line_take_three_fifths_line_by_line() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    let (sup, sub) = (VerticalAlign::Superscript, VerticalAlign::Subscript);
    // 683 of 2,048 units: 7 half-points at 10 pt, more than a third, keeps; 7 at 10.5 pt and
    // 8 at 12 pt, a third, fall back to 6.5 and 7 pt.
    let third = script_face(2048, 683, 683, 976);
    assert_eq!(script_size_in(20, sup, &third), points(7));
    assert_eq!(script_size_in(21, sup, &third), points(13));
    assert_eq!(script_size_in(24, sub, &third), points(14));
    // 67 half-points at 100 pt keeps, 67 at 100.5 pt falls back.
    assert_eq!(script_size_in(200, sup, &third), points(67));
    assert_eq!(script_size_in(201, sup, &third), points(121));
}

#[test]
fn scripts_keep_sizes_of_the_font_up_to_its_em() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    // 0.90 and 1.00 of the em at 12 pt: 21.6 half-points, so 11 pt, and 12 pt.
    for (size, half_points) in [(1843, 22), (2048, 24)] {
        assert_eq!(
            script_size_in(
                24,
                VerticalAlign::Superscript,
                &script_face(2048, size, size, 976)
            ),
            points(half_points)
        );
    }
}

#[test]
fn scripts_meet_the_edges_of_their_line_on_dots_and_half_points() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    let run = |size, vertical| RunProps {
        size: Some(size),
        vertical: Some(vertical),
        ..RunProps::default()
    };
    // The win metrics of Calibri, on a device of 288 dots per inch. The target with this
    // placement raises its superscripts at 10, 11 and 12 pt by 3, 3.5 and 4 pt, and drops its
    // subscripts by 1 pt.
    let dot = per_inch(288);
    let calibri = crate::FaceMetrics {
        units_per_em: 2048,
        line_top: 1950,
        script_top: 1950,
        descent: 550,
        ..crate::FaceMetrics::default()
    };
    let moved = |size, vertical, metrics| {
        let edges = Edges {
            metrics,
            dot,
            heights: &|_| None,
            room: 0,
        };
        size_and_rise(
            &run(size, vertical),
            ScriptMove::LineEdges(edges),
            ScriptScale::TwoThirds,
        )
        .1
    };
    for (size, rise) in [(20, 6), (22, 7), (24, 8)] {
        assert_eq!(
            moved(size, VerticalAlign::Superscript, &calibri),
            points(rise)
        );
        let drop = moved(size, VerticalAlign::Subscript, &calibri);
        assert_eq!(drop, Length::from_units(-points(2).units()));
    }
    // A font that raises superscripts by a quarter of an em and lowers subscripts by a tenth
    // keeps them there: at 14 pt, 3.5 pt and 1.5 pt, each to the nearest half-point.
    let low = crate::FaceMetrics {
        units_per_em: 1000,
        line_top: 1000,
        script_top: 1000,
        descent: 500,
        superscript_offset: 250,
        subscript_offset: 100,
        ..crate::FaceMetrics::default()
    };
    assert_eq!(moved(28, VerticalAlign::Superscript, &low), points(7));
    let drop = moved(28, VerticalAlign::Subscript, &low);
    assert_eq!(drop, Length::from_units(-points(3).units()));
}

#[test]
fn superscripts_whose_font_values_are_not_used_meet_the_line_top_within_the_em_without_a_cap() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    let rise = |half_points: i64, metrics: &crate::FaceMetrics| {
        let run = RunProps {
            size: Some(half_points),
            vertical: Some(VerticalAlign::Superscript),
            ..RunProps::default()
        };
        let edges = Edges {
            metrics,
            dot: per_inch(600),
            heights: &|_| None,
            room: 0,
        };
        let scale = ScriptScale::of_face(metrics, Some(VerticalAlign::Superscript));
        size_and_rise(&run, ScriptMove::LineEdges(edges), scale).1
    };
    let with_top = |top: u16, offset: i16, size: i16, east_asian: bool| crate::FaceMetrics {
        line_top: top,
        script_top: top,
        descent: 500,
        east_asian,
        ..script_face(2048, size, size, offset)
    };
    // 0.317 of the em falls back at 12 pt: 7 pt, which loses 5 pt. A top of 0.928 of the em
    // meets the line's top 4.5 pt higher (11 pt against 6.5 pt), above the 3 pt to which an
    // offset of 0.244 of the em would cap it.
    assert_eq!(rise(24, &with_top(1900, 500, 650, false)), points(9));
    // A top above the em counts as the em, so the superscript rises by the size that it loses.
    assert_eq!(rise(24, &with_top(2300, 500, 650, false)), points(10));
    assert_eq!(rise(16, &with_top(2300, 0, 1331, false)), points(6));
    // So does a superscript in a font made for East Asian text, whatever its top.
    assert_eq!(rise(24, &with_top(1900, 0, 1331, true)), points(10));
    // A font that keeps its own size meets the line's top no higher than its offset: 0.3335 of
    // the em keeps 3.5 pt at 10 pt and rises by 5 pt, not the 6.5 pt that it loses.
    assert_eq!(rise(20, &with_top(1900, 976, 683, false)), points(10));
}

#[test]
fn subscripts_meet_the_line_bottom_by_their_font_values_and_the_east_asian_room() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    let drop = |half_points: i64, metrics: &crate::FaceMetrics, room: i64| {
        let run = RunProps {
            size: Some(half_points),
            vertical: Some(VerticalAlign::Subscript),
            ..RunProps::default()
        };
        let edges = Edges {
            metrics,
            dot: per_inch(600),
            heights: &|_| None,
            room,
        };
        let scale = ScriptScale::of_face(metrics, Some(VerticalAlign::Subscript));
        Length::ZERO - size_and_rise(&run, ScriptMove::LineEdges(edges), scale).1
    };
    let face = |superscript_offset: i16, subscript_offset: i16| crate::FaceMetrics {
        line_top: 1638,
        script_top: 1638,
        descent: 600,
        subscript_offset,
        ..script_face(2048, 1331, 1331, superscript_offset)
    };
    // A font that keeps its values: at 12 pt the subscript of 8 pt meets the line's bottom
    // 1 pt lower (3.5 pt against 2.5 pt), and an offset of 100 units caps it at 0.5 pt.
    assert_eq!(drop(24, &face(600, 100), 0), points(1));
    // With a subscript offset of 0 it does not move.
    assert_eq!(drop(24, &face(600, 0), 0), Length::ZERO);
    // A font whose values are not used takes 7 pt and meets the bottom with no cap: 1.5 pt.
    assert_eq!(drop(24, &face(0, 100), 0), points(3));
    // The room of a font made for East Asian text lies below its descent: 150 more units put
    // the bottoms at 4.5 pt and 2.5 pt.
    assert_eq!(drop(24, &face(0, 100), 150), points(4));
    // With 600 more units they lie at 7 pt and 4 pt, but a fifth of the line, 2.4 pt to the
    // nearest half-point, caps the drop at 2.5 pt.
    assert_eq!(drop(24, &face(0, 100), 600), points(5));
}

#[test]
fn scripts_take_the_heights_of_the_vdmx_table_when_the_font_gives_them() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    let run = |vertical| RunProps {
        size: Some(24),
        vertical: Some(vertical),
        ..RunProps::default()
    };
    // Times New Roman's win metrics and line gap, and the heights of its VDMX table at 32
    // and 48 pixels per em: 8 pt and 12 pt at 288 dots per inch. The target raises a
    // superscript at 12 pt by 4.5 pt and drops a subscript by 1 pt; the win metrics alone give
    // 4 pt and 0.5 pt.
    let dot = per_inch(288);
    let times = crate::FaceMetrics {
        units_per_em: 2048,
        line_top: 1912,
        script_top: 1825,
        descent: 443,
        ..crate::FaceMetrics::default()
    };
    let vdmx = |pels: u16| match pels {
        32 => Some((28, -8)),
        48 => Some((43, -12)),
        _ => None,
    };
    let moved = |vertical, heights: &dyn Fn(u16) -> Option<(i16, i16)>| {
        let edges = Edges {
            metrics: &times,
            dot,
            heights,
            room: 0,
        };
        size_and_rise(
            &run(vertical),
            ScriptMove::LineEdges(edges),
            ScriptScale::TwoThirds,
        )
        .1
    };
    let down = |half_points| Length::from_units(-points(half_points).units());
    assert_eq!(moved(VerticalAlign::Superscript, &vdmx), points(9));
    assert_eq!(moved(VerticalAlign::Subscript, &vdmx), down(2));
    assert_eq!(moved(VerticalAlign::Superscript, &|_| None), points(8));
    assert_eq!(moved(VerticalAlign::Subscript, &|_| None), down(1));
}

#[test]
fn superscripts_rise_no_higher_than_their_font_raises_them() {
    let points = |half_points: i64| Length::from_half_points(half_points).unwrap();
    let sup = RunProps {
        size: Some(28),
        vertical: Some(VerticalAlign::Superscript),
        ..RunProps::default()
    };
    // At 14 pt the run loses 5 pt. A font that raises superscripts by 0.25 em gives
    // 3.5 pt, and one that raises them by 0.5 em leaves the 5 pt.
    let metrics = |offset| crate::FaceMetrics {
        units_per_em: 1000,
        superscript_offset: offset,
        ..crate::FaceMetrics::default()
    };
    let rise = |offset| {
        let cap = super::superscript_cap(&sup, &metrics(offset));
        size_and_rise(&sup, ScriptMove::LostSize(cap), ScriptScale::TwoThirds).1
    };
    assert_eq!(rise(250), points(7));
    assert_eq!(rise(500), points(10));
    // A font that does not say keeps the lost size.
    assert_eq!(rise(0), points(10));
    let sub = RunProps {
        vertical: Some(VerticalAlign::Subscript),
        ..sup
    };
    let cap = super::superscript_cap(&sub, &metrics(250));
    assert_eq!(
        size_and_rise(&sub, ScriptMove::LostSize(cap), ScriptScale::TwoThirds).1,
        Length::from_units(-points(10).units() / 4)
    );
}

#[test]
fn symbol_characters_read_as_word_writes_them() {
    let symbol = Some(SymbolFont::Symbol);
    let cases = [
        ('\u{F0B7}', symbol, 1, '\u{2022}'),
        ('\u{F0B7}', None, 1, '\u{B7}'),
        ('\u{F0A7}', Some(SymbolFont::Wingdings), 1, '\u{A7}'),
        ('\u{F071}', symbol, 1, 'q'),
        ('a', symbol, 1, 'a'),
        ('\u{A7}', Some(SymbolFont::Wingdings), 1, '\u{A7}'),
        ('\u{F100}', None, 1, '\u{F100}'),
        // A character that the font draws with its missing glyph has no text of its own.
        ('\u{F07F}', symbol, 0, '\u{FFFD}'),
        ('a', None, 0, 'a'),
        // In the Symbol font, a middle dot stands for the Symbol bullet.
        ('\u{B7}', symbol, 1, '\u{2022}'),
        ('\u{B7}', None, 1, '\u{B7}'),
    ];
    for (ch, font, id, text) in cases {
        assert_eq!(
            super::ShaperSettings::base_with(|p| p.with_variant(SymbolText::LowByte))
                .symbol_text(ch, font, id),
            text,
            "{ch:?}"
        );
    }
}

#[test]
fn knows_the_symbol_fonts_by_name_and_stands_in_for_their_bullets() {
    let with_codes =
        |family| SymbolFont::of(family).filter(|&font| super::symbol_table::has_codes(font));
    assert_eq!(
        (with_codes("wingdings"), with_codes("Wingdings 2")),
        (Some(SymbolFont::Wingdings), None)
    );
    assert_eq!(
        (symbol_stand_in('\u{F0B7}'), symbol_stand_in('a')),
        (Some('\u{2022}'), None)
    );
}

#[test]
fn symbol_characters_read_as_the_table_gives_them_where_the_target_says_so() {
    let (symbol, wingdings) = (Some(SymbolFont::Symbol), Some(SymbolFont::Wingdings));
    let cases = [
        ('\u{F0A7}', wingdings, 1, '\u{25AA}'),
        ('\u{F0FC}', wingdings, 1, '\u{2713}'),
        ('\u{F0B7}', symbol, 1, '\u{2022}'),
        ('\u{F02D}', symbol, 1, '\u{2212}'),
        // A code that the table lacks keeps the character of the area.
        ('\u{F0A8}', wingdings, 1, '\u{F0A8}'),
        ('\u{F0AF}', symbol, 1, '\u{F0AF}'),
        ('\u{F061}', symbol, 1, '\u{F061}'),
        // A font that the table lacks, such as Wingdings 2, keeps every character.
        ('\u{F051}', None, 1, '\u{F051}'),
        ('a', None, 1, 'a'),
        // A character that draws the missing glyph keeps the character of the area too.
        ('\u{F07F}', symbol, 0, '\u{F07F}'),
        // A character of one byte in the Symbol or Wingdings font stands for its symbol,
        // and one that the table lacks reads as on the other targets.
        ('\u{B7}', symbol, 1, '\u{2022}'),
        ('\u{E8}', wingdings, 1, '\u{2794}'),
        ('\u{A7}', wingdings, 1, '\u{25AA}'),
        ('a', symbol, 1, 'a'),
        ('\u{A8}', wingdings, 1, '\u{A8}'),
        ('\u{E8}', None, 1, '\u{E8}'),
    ];
    for (ch, font, id, text) in cases {
        let written =
            super::ShaperSettings::base_with(|p| p.with_variant(SymbolText::TableOrSymbol))
                .symbol_text(ch, font, id);
        assert_eq!(written, text, "{ch:?}");
    }
}

#[test]
fn starts_a_piece_at_each_256th_character_of_a_run_or_of_a_page() {
    let at = |in_run, in_paragraph| super::TextPlace {
        in_run,
        in_paragraph,
        starts_buffer: false,
        run: None,
    };
    // From the start of the run.
    assert!(at(256, 300).starts_piece(0, 256));
    assert!(at(512, 512).starts_piece(0, 256));
    assert!(!at(0, 256).starts_piece(0, 256));
    assert!(!at(255, 255).starts_piece(0, 256));
    // From the paragraph's first character on a new page, at 100.
    assert!(!at(512, 512).starts_piece(100, 256));
    assert!(at(356, 356).starts_piece(100, 256));
    // A run that starts after it counts from its own start.
    assert!(at(256, 900).starts_piece(100, 256));
}

#[test]
fn takes_the_hhea_line_or_the_taller_line_as_the_profile_says() {
    // The hhea values 1523, -525 and 425 make a line of 2,473 units. The win line of 1,950
    // and 550 units is 2,500 units, so the line's top lies 1,950 units above the baseline.
    let metrics = crate::FaceMetrics {
        units_per_em: 2048,
        hhea_ascender: 1523,
        hhea_descender: -525,
        hhea_line_gap: 425,
        descent: 550,
        line_top: 1950,
        script_top: 1950,
        ..crate::FaceMetrics::default()
    };
    let size = Length::from_units(2048 * 100);
    let face = |line_height| plain_face(metrics, size, line_height);
    let hhea = face(LineHeight::TakesHheaLine);
    let taller = face(LineHeight::TakesTallerLine);
    assert_eq!(hhea.line_height().units(), 247_300);
    assert_eq!(taller.line_height().units(), 250_000);
    // The descent stays, and the ascent takes the rest of the line.
    assert_eq!(hhea.descent().units(), 55_000);
    assert_eq!(taller.descent().units(), 55_000);
    assert_eq!(taller.ascent().units(), 195_000);
}

#[test]
fn leaves_out_the_line_gap_of_a_font_made_for_east_asian_text() {
    // SimSun's metrics: a hhea line of 220 and 36 units with a gap of 36, over a win line of
    // 220 and 36. Its own line is 256 units without the gap on both lines of the profiles,
    // and its room above and below is 0.15 of that, 38 units, so the line is 332 units.
    let metrics = crate::FaceMetrics {
        units_per_em: 256,
        hhea_ascender: 220,
        hhea_descender: -36,
        hhea_line_gap: 36,
        descent: 36,
        line_top: 256,
        script_top: 220,
        east_asian: true,
        ..crate::FaceMetrics::default()
    };
    let size = Length::from_units(256 * 100);
    let face = |metrics, line_height| plain_face(metrics, size, line_height);
    for line_height in [
        LineHeight::TakesHheaLine,
        LineHeight::TakesTallerLine,
        LineHeight::TakesTallerLineEastAsianWin,
    ] {
        let face = face(metrics, line_height);
        assert_eq!(face.line_height().units(), 33_200);
        assert_eq!(face.descent().units(), 7_400);
        assert_eq!(face.ascent().units(), 25_800);
    }
    // A hhea line of 200 and 56 units with a gap of 36 over a win line of 230 and 50: without
    // the gap, the win line of 280 units is the taller line, and the line is 1.3 times that.
    let win = crate::FaceMetrics {
        hhea_ascender: 200,
        hhea_descender: -56,
        descent: 50,
        line_top: 242,
        script_top: 230,
        ..metrics
    };
    assert_eq!(
        face(win, LineHeight::TakesTallerLine).line_height().units(),
        36_400
    );
    assert_eq!(
        face(win, LineHeight::TakesHheaLine).line_height().units(),
        33_200
    );
    // A font that is not made for East Asian text keeps the gap.
    let latin = crate::FaceMetrics {
        east_asian: false,
        ..metrics
    };
    assert_eq!(
        face(latin, LineHeight::TakesHheaLine).line_height().units(),
        29_200
    );
}

#[test]
fn takes_the_win_line_of_an_east_asian_font_whose_hhea_line_is_taller_where_the_target_does() {
    // STFangsong's metrics in thousandths of the em: a hhea line of 986 and 315 without a gap
    // over a win line of 860 and 260. The taller line is the hhea line, 1301 units with a
    // room of 195 above and below; the win line is 1120 units with a room of 168.
    let metrics = crate::FaceMetrics {
        units_per_em: 1000,
        hhea_ascender: 986,
        hhea_descender: -315,
        hhea_line_gap: 0,
        descent: 260,
        line_top: 1041,
        script_top: 860,
        east_asian: true,
        ..crate::FaceMetrics::default()
    };
    let size = Length::from_units(1000 * 100);
    let taller = plain_face(metrics, size, LineHeight::TakesTallerLine);
    let win = plain_face(metrics, size, LineHeight::TakesTallerLineEastAsianWin);
    assert_eq!(taller.line_height().units(), 169_100);
    assert_eq!(taller.descent().units(), 45_500);
    assert_eq!(win.line_height().units(), 145_600);
    assert_eq!(win.descent().units(), 42_800);
    assert_eq!(win.ascent().units(), 102_800);
    // A font that is not made for East Asian text keeps the taller line.
    let latin = crate::FaceMetrics {
        east_asian: false,
        ..metrics
    };
    assert_eq!(
        plain_face(latin, size, LineHeight::TakesTallerLineEastAsianWin)
            .line_height()
            .units(),
        130_100
    );
}

#[test]
fn cuts_pieces_of_256_characters_from_mode_15_and_of_512_before() {
    let at = |in_run| super::TextPlace {
        in_run,
        in_paragraph: in_run,
        starts_buffer: false,
        run: None,
    };
    assert!(!at(256).starts_piece(0, 512));
    assert!(at(1024).starts_piece(0, 512));
}

/// [`Joining`] fonts whose bi-level advance at 1000 pixels per em is 101 pixels for "a" and
/// 100 pixels, the rounded advance, for every other glyph, and which are the target's own
/// face `Face-One` of version 2.5.
struct Hinted;

impl crate::Fonts for Hinted {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Joining.face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }

    fn bi_level_advance(
        &self,
        _font: f_office_fonts::FontId,
        glyph: u32,
        ppem: u16,
    ) -> Option<i32> {
        (ppem == 1000).then_some(if glyph == u32::from('a') { 101 } else { 100 })
    }

    fn target_face(&self, _font: f_office_fonts::FontId) -> Option<(String, String)> {
        Some(("Face-One".to_owned(), "Version 2.5".to_owned()))
    }
}

/// [`Joining`] fonts that kern the pair of a small r and a hyphen-minus by -76 units, and no pair
/// with U+2011.
struct HyphenPairs;

impl crate::Fonts for HyphenPairs {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Joining.face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }

    fn kerning(
        &self,
        _font: f_office_fonts::FontId,
        left: u32,
        right: u32,
        _table: crate::KerningTable,
    ) -> i32 {
        if (left, right) == (u32::from('r'), u32::from('-')) {
            -76
        } else {
            0
        }
    }
}

/// A non-breaking hyphen drawn as a hyphen-minus keeps the kerning pairs of the face's glyph for
/// U+2011, so a small r before it kerns under neither variant, while it kerns before a
/// hyphen-minus.
#[test]
fn kerns_a_non_breaking_hyphen_with_the_pairs_of_its_own_glyph() {
    use crate::quirks::NonBreakingHyphen;
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let props = RunProps {
        size: Some(20),
        kern: Some(2),
        ..RunProps::default()
    };
    let kerning = |variant, text: &str| {
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
        let mut shaper = super::Shaper::new(&HyphenPairs, &theme, &table, &settings);
        let mut glyphs = Vec::new();
        shaper.measure(&props, text, &mut glyphs);
        glyphs.first().map(|g| g.kerning.units())
    };
    let element = format!("r{}G", super::NON_BREAKING_HYPHEN);
    for variant in [
        NonBreakingHyphen::OwnGlyph,
        NonBreakingHyphen::AsHyphenMinus,
    ] {
        assert_eq!(kerning(variant, &element), Some(0));
        // At 10 pt, -76 units of 2048 are -19,304 half-EMUs.
        assert_ne!(kerning(variant, "r-G"), Some(0));
    }
}

/// A non-breaking hyphen takes the face's glyph for U+2011 under `NonBreakingHyphen::OwnGlyph`
/// and the glyph of the hyphen-minus under `NonBreakingHyphen::AsHyphenMinus`.
#[test]
fn draws_a_non_breaking_hyphen_with_the_glyph_that_the_quirk_names() {
    use crate::quirks::NonBreakingHyphen;
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let id = |variant| {
        let mut shaper = super::Shaper::new(
            &Joining,
            &theme,
            &table,
            &super::ShaperSettings::base_with(|p| p.with_variant(variant)),
        );
        let face = shaper.face(&RunProps::default(), true).unwrap();
        shaper.glyph(face, super::NON_BREAKING_HYPHEN).unwrap().id
    };
    assert_eq!(id(NonBreakingHyphen::OwnGlyph), 0x2011);
    assert_eq!(id(NonBreakingHyphen::AsHyphenMinus), u32::from('-'));
}

#[test]
fn writes_the_bi_level_width_where_it_differs_from_the_rounded_advance() {
    use crate::quirks::WrittenWidths;
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let written = |widths, ch| {
        let mut shaper = super::Shaper::new(
            &Hinted,
            &theme,
            &table,
            &super::ShaperSettings::base_with(|p| p.with_variant(widths)),
        );
        let face = shaper.face(&RunProps::default(), true).unwrap();
        shaper.glyph(face, ch).unwrap().written
    };
    assert_eq!(written(WrittenWidths::HintedAdvanceAt1000, 'a'), Some(101));
    assert_eq!(written(WrittenWidths::HintedAdvanceAt1000, 'b'), None);
    assert_eq!(written(WrittenWidths::RoundsAdvance, 'a'), None);
}

/// [`Joining`] fonts in an em of 2,000 units whose every glyph is 1,181 units wide, 590.5
/// thousandths of an em, but the ligature of "fi", 1,500 units wide, and which F-Office cannot
/// hint.
struct HalfWidths;

impl crate::Fonts for HalfWidths {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        let mut face = Joining.face(family, bold, italic)?;
        face.metrics.units_per_em = 2000;
        Some(face)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Some(if glyph == 500 { 1500 } else { 1181 })
    }

    fn ligatures(
        &self,
        font: f_office_fonts::FontId,
        glyphs: &[u32],
    ) -> Vec<f_office_fonts::Ligature> {
        Joining.ligatures(font, glyphs)
    }
}

#[test]
fn writes_a_width_of_a_half_thousandth_from_font_units() {
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let settings = super::ShaperSettings::base_with(|p| {
        p.with_variant(crate::quirks::WrittenWidths::HintedAdvanceAt1000)
    });
    let mut shaper = super::Shaper::new(&HalfWidths, &theme, &table, &settings);
    let props = RunProps {
        size: Some(24),
        ..RunProps::default()
    };
    let face = shaper.face(&props, true).unwrap();
    let glyph = shaper.glyph(face, 'T').unwrap();
    // At 12 pt the advance is 179,984.4 half-EMUs, kept as 179,984, which counts 590.4987
    // thousandths of the em and rounds to 590. The writer writes 591 from font units
    //.
    let size = 24 * 12_700;
    assert_eq!(glyph.advance.units(), 179_984);
    assert_eq!(f_office_units::div_round(179_984 * 1000, size), 590);
    assert_eq!(glyph.written, Some(591));
    // At 12.5 pt the advance is 187,483.75 half-EMUs, kept as 187,484, which rounds to 591:
    // the text object's rounding is the writer's width, and the glyph takes none.
    let props = RunProps {
        size: Some(25),
        ..RunProps::default()
    };
    let face = shaper.face(&props, true).unwrap();
    assert_eq!(shaper.glyph(face, 'T').unwrap().written, None);
}

#[test]
fn a_ligature_writes_its_own_width_and_not_its_first_letters() {
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let settings = super::ShaperSettings {
        ligatures: true,
        ..super::ShaperSettings::base_with(|p| {
            p.with_variant(crate::quirks::WrittenWidths::HintedAdvanceAt1000)
        })
    };
    let mut shaper = super::Shaper::new(&HalfWidths, &theme, &table, &settings);
    let props = RunProps {
        font_ascii: Some(crate::props::FontRef::Name("Any".into())),
        size: Some(24),
        ligatures: Some(true),
        ..RunProps::default()
    };
    let mut glyphs = Vec::new();
    shaper.measure(&props, "fix", &mut glyphs);
    // At 12 pt the "f" alone would write 591 (590.5 rounded up from font units); the ligature
    // of 750 thousandths takes the text object's rounding of its own advance.
    let first = glyphs.first().unwrap();
    assert_eq!((first.id, first.written), (500, None));
    let mut glyphs = Vec::new();
    shaper.measure(
        &RunProps {
            ligatures: None,
            ..props
        },
        "fix",
        &mut glyphs,
    );
    assert_eq!(
        glyphs.first().map(|g| (g.id, g.written)),
        Some((102, Some(591)))
    );
}

/// [`Hinted`] with an interpreter that gives every glyph a device width of 17 dots, whose
/// face is the target's own when `own` is true, whose pair kerning comes from `source`, and
/// which kerns the pair `AV` by -50 units.
struct Instructed {
    own: bool,
    source: f_office_fonts::KerningSource,
}

impl Instructed {
    /// The target's own face, or another face when `own` is false, as a legacy-kern face.
    const fn legacy(own: bool) -> Self {
        Self {
            own,
            source: f_office_fonts::KerningSource::KernTable,
        }
    }
}

impl crate::Fonts for Instructed {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Hinted.face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Hinted.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Hinted.advance(font, glyph)
    }

    fn kerning_source(&self, _font: f_office_fonts::FontId) -> f_office_fonts::KerningSource {
        self.source
    }

    fn target_face(&self, font: f_office_fonts::FontId) -> Option<(String, String)> {
        self.own.then(|| Hinted.target_face(font)).flatten()
    }

    fn device_width(&self, _font: f_office_fonts::FontId, _glyph: u32, _ppem: u16) -> Option<i32> {
        Some(17)
    }

    fn kerning(
        &self,
        _font: f_office_fonts::FontId,
        left: u32,
        right: u32,
        _table: crate::KerningTable,
    ) -> i32 {
        if (left, right) == (u32::from('A'), u32::from('V')) {
            -50
        } else {
            0
        }
    }
}

#[test]
fn takes_the_device_width_of_the_targets_own_face_from_its_instructions() {
    use crate::quirks::GridAdvances::{RightEdgeSteps, RoundToPdfSteps};
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let size = 11 * f_office_units::Length::UNITS_PER_POINT;
    let width = |own, advances| {
        let fonts = Instructed::legacy(own);
        let settings = on_steps(|p| p.with_variant(advances));
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
        let fork = shaper.fork().face(&RunProps::default(), true).unwrap();
        let face = shaper.face(&RunProps::default(), true).unwrap();
        let face = super::FaceIndex(face.0.max(fork.0));
        shaper.device_width(face, u32::from('I'), (size, 44))
    };
    // Joining's glyphs are 100 of 1000 units wide.
    assert_eq!(width(true, RightEdgeSteps), Some((17, size / 10)));
    // A face that is not the target's own, and a target without whole-dot steps, keep the
    // advance rounded.
    assert_eq!(width(false, RightEdgeSteps), None);
    assert_eq!(width(true, RoundToPdfSteps), None);
}

#[test]
fn keeps_or_drops_the_device_width_of_a_kerned_run_by_the_targets_variant() {
    use crate::quirks::KernedDeviceWidths;
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let size = 11 * f_office_units::Length::UNITS_PER_POINT;
    let fonts = Instructed {
        own: true,
        source: f_office_fonts::KerningSource::Gpos,
    };
    let mode_15 = crate::mode::ModeRules::of(crate::mode::CompatibilityMode::Mode15);
    let width = |kerned, kern: Option<i64>| {
        let settings = super::ShaperSettings {
            mode_rules: mode_15,
            ..device_steps(kerned)
        };
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
        let props = RunProps {
            kern,
            ..RunProps::default()
        };
        let face = shaper.face(&props, true).unwrap();
        shaper
            .device_width(face, u32::from('I'), (size, 44))
            .map(|(width, _)| width)
    };
    let own = KernedDeviceWidths::Own;
    let on_its_own = KernedDeviceWidths::OwnWithKerningOnItsOwn;
    let nearest = KernedDeviceWidths::Nearest;
    // A kerned run that steps at the nearest dot has no device width of its own.
    assert_eq!(width(nearest, Some(2)), None);
    // A run without kerning, or below the kerned size, keeps its width.
    assert_eq!(width(nearest, None), Some(17));
    assert_eq!(width(nearest, Some(400)), Some(17));
    // The other variants keep the width of a run without kerning.
    assert_eq!(width(own, Some(2)), width(own, None));
    assert_eq!(width(on_its_own, Some(2)), Some(17));
}

/// The settings on the profile of a target whose device steps glyphs by whole dots
/// (`GridAdvances::RightEdgeSteps`), whose kerned runs step as `kerned` says.
fn device_steps(kerned: crate::quirks::KernedDeviceWidths) -> super::ShaperSettings {
    on_steps(|p| p.with_variant(kerned))
}

/// The settings on the profile of a target whose device steps glyphs by whole dots
/// (`GridAdvances::RightEdgeSteps`), with some quirks of another variant (`change`). Its
/// kerning comes from each face's own source, under the face's own steps also for a stand-in
/// (`KerningTableRead::FaceSource`, `DeviceAdvance::ExactAdvances`), so that the steps of a kerned
/// run follow from `KernedDeviceWidths` alone.
fn on_steps(
    change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
) -> super::ShaperSettings {
    let steps = crate::Target::all()
        .map(|target| crate::profile::Profile::of(target).unwrap())
        .find(|profile| {
            profile.quirks().grid_advances == crate::quirks::GridAdvances::RightEdgeSteps
        })
        .expect("a target steps glyphs by whole dots");
    let profile = change(
        &steps
            .with_variant(crate::quirks::KerningTableRead::FaceSource)
            .with_variant(crate::quirks::DeviceAdvance::ExactAdvances),
    );
    super::ShaperSettings::of(
        &crate::styles::Settings::default(),
        &profile.quirks(),
        profile.device().dot_size(),
    )
}

/// Whether a run with the kerning `kern` steps without the bias, and its device width, for
/// the target's variant `kerned` in a document of `mode` and a face whose kerning comes from
/// `source`, asked of a fork of the shaper.
fn kerned_steps(
    kerned: crate::quirks::KernedDeviceWidths,
    (mode, source): (
        crate::mode::CompatibilityMode,
        f_office_fonts::KerningSource,
    ),
    kern: Option<i64>,
) -> (bool, Option<i64>) {
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let size = 11 * f_office_units::Length::UNITS_PER_POINT;
    let fonts = Instructed { own: true, source };
    let settings = super::ShaperSettings {
        mode_rules: crate::mode::ModeRules::of(mode),
        ..device_steps(kerned)
    };
    let shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
    let props = RunProps {
        kern,
        ..RunProps::default()
    };
    // A fork keeps the mode rules.
    let mut shaper = shaper.fork();
    let face = shaper.face(&props, true).unwrap();
    let width = shaper.device_width(face, u32::from('I'), (size, 44));
    (
        shaper.steps_without_bias(face),
        width.map(|(width, _)| width),
    )
}

/// Whether a run with standard ligatures on and the kerning `kern` steps without the bias in a
/// document of mode 15 and a GPOS-kerned face, on a target whose kerned runs step at the
/// nearest dot and whose runs with ligatures step as `ligatures` says.
fn ligature_steps_without_bias(ligatures: crate::quirks::LigatureSteps, kern: Option<i64>) -> bool {
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let fonts = Instructed {
        own: true,
        source: f_office_fonts::KerningSource::Gpos,
    };
    let settings = super::ShaperSettings {
        mode_rules: crate::mode::ModeRules::of(crate::mode::CompatibilityMode::Mode15),
        ligatures: true,
        ..on_steps(|p| {
            p.with_variant(crate::quirks::KernedDeviceWidths::Nearest)
                .with_variant(ligatures)
        })
    };
    let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
    let props = RunProps {
        kern,
        ligatures: Some(true),
        ..RunProps::default()
    };
    let face = shaper.face(&props, true).unwrap();
    shaper.steps_without_bias(face)
}

#[test]
fn steps_a_run_with_ligatures_as_a_kerned_run_where_the_target_does() {
    use crate::quirks::LigatureSteps;
    assert!(ligature_steps_without_bias(
        LigatureSteps::AsKernedRun,
        None
    ));
    assert!(ligature_steps_without_bias(
        LigatureSteps::AsKernedRun,
        Some(2)
    ));
    assert!(!ligature_steps_without_bias(
        LigatureSteps::AsTheirRun,
        None
    ));
    assert!(ligature_steps_without_bias(
        LigatureSteps::AsTheirRun,
        Some(2)
    ));
}

#[test]
fn steps_a_kerned_run_without_the_bias_where_the_target_does() {
    use crate::quirks::KernedDeviceWidths;
    let nearest = KernedDeviceWidths::Nearest;
    let gpos_15 = (
        crate::mode::CompatibilityMode::Mode15,
        f_office_fonts::KerningSource::Gpos,
    );
    // A kerned run in a GPOS-kerned face of a document of mode 15, of a target whose kerned
    // runs step at the nearest dot, steps without the bias and without a device width.
    assert_eq!(kerned_steps(nearest, gpos_15, Some(2)), (true, None));
    // A run without kerning, or below the kerned size, keeps the bias and its width.
    assert_eq!(kerned_steps(nearest, gpos_15, None), (false, Some(17)));
    assert_eq!(kerned_steps(nearest, gpos_15, Some(400)), (false, Some(17)));
    // `OwnWithKerningOnItsOwn` and `Own` keep the width and the bias.
    let on_its_own = KernedDeviceWidths::OwnWithKerningOnItsOwn;
    assert_eq!(
        kerned_steps(on_its_own, gpos_15, Some(2)),
        (false, Some(17))
    );
    let own = KernedDeviceWidths::Own;
    assert_eq!(kerned_steps(own, gpos_15, Some(2)), (false, Some(17)));
    // `Rounded` has no device width and keeps the bias.
    let rounded = KernedDeviceWidths::Rounded;
    assert_eq!(kerned_steps(rounded, gpos_15, Some(2)), (false, None));
}

#[test]
fn steps_a_kerned_run_by_its_device_widths_before_mode_15_and_rounded_in_a_legacy_kern_face_from_it()
 {
    use crate::mode::CompatibilityMode;
    use f_office_fonts::KerningSource;
    let nearest = crate::quirks::KernedDeviceWidths::Nearest;
    // Before mode 15, with the bias and the device width of a run without kerning, in either
    // kind of face.
    let own = (false, Some(17));
    for mode in [CompatibilityMode::Mode14, CompatibilityMode::Below14] {
        for source in [KerningSource::Gpos, KerningSource::KernTable] {
            assert_eq!(kerned_steps(nearest, (mode, source), Some(2)), own);
        }
    }
    // From mode 15, a legacy-kern face rounds the advance with the bias, without a width.
    let legacy_15 = (CompatibilityMode::Mode15, KerningSource::KernTable);
    assert_eq!(kerned_steps(nearest, legacy_15, Some(2)), (false, None));
}

#[test]
fn keeps_a_pairs_kerning_apart_for_the_steps_where_the_kerned_run_steps_so() {
    use crate::mode::{CompatibilityMode, ModeRules};
    use crate::quirks::KernedDeviceWidths::{Nearest, Own};
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let fonts = Instructed {
        own: true,
        source: f_office_fonts::KerningSource::Gpos,
    };
    // The kerning that the first glyph of `AV` keeps, and what each glyph steps on its own.
    let kerning = |kerned, mode| {
        let settings = super::ShaperSettings {
            mode_rules: ModeRules::of(mode),
            ..device_steps(kerned)
        };
        let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
        let props = RunProps {
            kern: Some(2),
            ..RunProps::default()
        };
        let mut glyphs = Vec::new();
        shaper.measure(&props, "AV", &mut glyphs);
        let steps: Vec<Length> = glyphs
            .iter()
            .map(|g| shaper.kerning_on_its_own(g))
            .collect();
        (glyphs.first().map(|g| g.kerning), steps)
    };
    let (kept, steps) = kerning(Nearest, CompatibilityMode::Mode14);
    let kept = kept.unwrap();
    assert!(kept < Length::ZERO);
    // Below mode 15, the kerned run steps the pair's kerning on its own after the first glyph.
    assert_eq!(steps, [kept, Length::ZERO]);
    // From mode 15 on it steps at the nearest dot, and `Own` keeps the kerning in the advance.
    let zero = vec![Length::ZERO, Length::ZERO];
    assert_eq!(kerning(Nearest, CompatibilityMode::Mode15).1, zero);
    assert_eq!(kerning(Own, CompatibilityMode::Mode14).1, zero);
}

#[test]
fn steps_a_kerned_run_as_own_where_nearest_or_own_does_not_step_at_the_nearest_dot() {
    use crate::mode::CompatibilityMode;
    use f_office_fonts::KerningSource;
    let either = crate::quirks::KernedDeviceWidths::NearestOrOwn;
    // In a GPOS-kerned face from mode 15 on, without the bias and without a device width.
    let gpos_15 = (CompatibilityMode::Mode15, KerningSource::Gpos);
    assert_eq!(kerned_steps(either, gpos_15, Some(2)), (true, None));
    // Elsewhere with the bias and its own device width, as a run without kerning.
    let own = (false, Some(17));
    for mode in [CompatibilityMode::Mode14, CompatibilityMode::Below14] {
        assert_eq!(
            kerned_steps(either, (mode, KerningSource::Gpos), Some(2)),
            own
        );
    }
    let legacy_15 = (CompatibilityMode::Mode15, KerningSource::KernTable);
    assert_eq!(kerned_steps(either, legacy_15, Some(2)), own);
}

/// A math font: [`Joining`] with a `MATH` table, whose sum (U+2211) has the display variant
/// 9000, 1500 units wide, with ink from -700 to 1250 of its 1000 units per em and an italic
/// correction of 400, and whose `x` has the script glyphs 7001 and 7002. Its opening parenthesis
/// has ink from -250 to 750, and the vertical variants 8000 (1600 units tall, 200 wide, ink from
/// -500 to 1100) and 8001 (2400 tall, 300 wide, ink from -900 to 1500).
struct Operators;

impl crate::Fonts for Operators {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Joining.face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Some(match glyph {
            9000 => 1500,
            8000 => 200,
            8001 => 300,
            _ => 100,
        })
    }

    fn ink(
        &self,
        _font: f_office_fonts::FontId,
        glyph: u32,
    ) -> Result<Option<(i32, i32)>, f_office_fonts::OutlineError> {
        Ok(match glyph {
            9000 => Some((-700, 1250)),
            0x28 => Some((-250, 750)),
            8000 => Some((-500, 1100)),
            8001 => Some((-900, 1500)),
            _ => None,
        })
    }

    fn math_limits(&self, _font: f_office_fonts::FontId) -> Option<f_office_fonts::MathLimits> {
        Some(f_office_fonts::MathLimits {
            math_leading: 125,
            display_operator_min_height: 1300,
            upper_limit_baseline_rise_min: 250,
            lower_limit_baseline_drop_min: 500,
            superscript_baseline_drop_max: 290,
            subscript_baseline_drop_min: 200,
            delimited_sub_formula_min_height: 1465,
        })
    }

    fn display_variant(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u32> {
        (glyph == 0x2211).then_some(9000)
    }

    fn vertical_variant(
        &self,
        _font: f_office_fonts::FontId,
        glyph: u32,
        least: i32,
    ) -> Option<(u32, bool)> {
        let variants = [(0x28, 1000), (8000, 1600), (8001, 2400)];
        if glyph != 0x28 {
            return None;
        }
        variants
            .iter()
            .find(|&&(_, height)| height >= least)
            .map(|&(variant, _)| (variant, true))
            .or(Some((8001, false)))
    }

    fn italic_correction(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<i32> {
        (glyph == 9000).then_some(400)
    }

    fn script_glyph(
        &self,
        _font: f_office_fonts::FontId,
        glyph: u32,
        level: f_office_fonts::ScriptLevel,
    ) -> Option<u32> {
        let script = match level {
            f_office_fonts::ScriptLevel::Script => 7001,
            f_office_fonts::ScriptLevel::ScriptOfScript => 7002,
        };
        (glyph == u32::from('x')).then_some(script)
    }
}

/// A length in hundredths of a point.
fn hundredths(n: i64) -> Length {
    Length::from_units(n * Length::UNITS_PER_POINT / 100)
}

/// A 12 pt run in the parts `script` of an equation.
fn math_run(script: MathScript) -> RunProps {
    RunProps {
        size: Some(24),
        math_script: Some(script),
        ..RunProps::default()
    }
}

#[test]
fn draws_a_display_operator_large_with_the_room_of_its_ink() {
    use crate::Fonts as _;
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let sum = |fonts: &dyn crate::Fonts| {
        let mut shaper = super::Shaper::new(fonts, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        let run = math_run(MathScript::display().large());
        shaper.measure(&run, "\u{2211}", &mut glyphs);
        let face = shaper.faces[glyphs[0].face.0].math;
        (glyphs[0].id, glyphs[0].advance, face.large, face.room)
    };
    // The display's sum is the variant, 1500/1000 of 12 pt wide, and its line gets the room
    // of its ink with MathLeading over it: 125/1000 of 12 pt, 1.5 pt.
    let leading = hundredths(150);
    assert_eq!(
        sum(&Operators),
        (9000, hundredths(1800), true, MathRoom::Ink { leading })
    );
    // A font without the table keeps the character's glyph and the room of its lines.
    assert_eq!(
        sum(&Joining),
        (0x2211, hundredths(120), true, MathRoom::Lines)
    );
    let font = f_office_fonts::FontId::from_index(0);
    assert_eq!(Operators.display_variant(font, 97), None);
}

#[test]
fn draws_the_script_glyphs_of_the_level_that_the_style_gives() {
    use crate::Fonts as _;
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let glyph = |fonts: &dyn crate::Fonts, script: MathScript| {
        let mut shaper = super::Shaper::new(fonts, &theme, &table, &super::ShaperSettings::base());
        let mut glyphs = Vec::new();
        shaper.measure(&math_run(script), "xy", &mut glyphs);
        (glyphs[0].id, glyphs[1].id)
    };
    let (x, y) = (u32::from('x'), u32::from('y'));
    let sup = MathStep::Superscript;
    // A display, a script, a script of a script, and a fraction's part, which takes text
    // style in a display and script style in a line.
    let display = MathScript::display();
    assert_eq!(glyph(&Operators, display), (x, y));
    assert_eq!(glyph(&Operators, display.inside(sup, None)), (7001, y));
    let twice = display.inside(sup, None).inside(MathStep::Subscript, None);
    assert_eq!(glyph(&Operators, twice), (7002, y));
    let numerator = MathStep::Numerator;
    assert_eq!(glyph(&Operators, display.inside(numerator, None)), (x, y));
    let inline = MathScript::default().inside(numerator, None);
    assert_eq!(glyph(&Operators, inline), (7001, y));
    // A font without the feature keeps the base glyph.
    assert_eq!(glyph(&Joining, display.inside(sup, None)), (x, y));
    assert_eq!(
        Joining.script_glyph(
            f_office_fonts::FontId::from_index(0),
            x,
            f_office_fonts::ScriptLevel::Script
        ),
        None
    );
}

#[test]
fn gives_a_part_of_a_fraction_the_room_of_its_ink_in_a_math_font() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let room_on = |fonts: &dyn crate::Fonts, script: MathScript, display: DisplayFractionRoom| {
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(display));
        let mut shaper = super::Shaper::new(fonts, &theme, &table, &settings);
        let face = shaper.face(&math_run(script), true).unwrap();
        let face = &shaper.faces[face.0];
        (face.size, face.math.room)
    };
    let room = |fonts: &dyn crate::Fonts, script: MathScript| {
        room_on(fonts, script, DisplayFractionRoom::FontLines)
    };
    // In a line, the numerator takes 73 % of 12 pt, down to a half point, 8.5 pt, and the room
    // of its ink with MathLeading at the equation's size over it: 125/1000 of 12 pt, 1.5 pt.
    let inline = MathScript::default().inside(MathStep::Numerator, None);
    let leading = hundredths(150);
    assert_eq!(
        room(&Operators, inline),
        (hundredths(850), MathRoom::Ink { leading })
    );
    // A font without a `MATH` table takes the room of its ink below the line only.
    assert_eq!(room(&Joining, inline).1, MathRoom::InkBelow);
    // On a target whose variant is `DisplayFractionRoom::Ink`, the parts of a fraction in a
    // display, and a script inside one, take the room of their ink with the same MathLeading
    // over it; a font without a `MATH` table keeps the room of its lines there. The other
    // variant keeps the room of the font's lines.
    let ink = DisplayFractionRoom::Ink;
    let display = MathScript::display().inside(MathStep::Numerator, None);
    assert_eq!(
        room_on(&Operators, display, ink).1,
        MathRoom::Ink { leading }
    );
    let script = MathScript::display()
        .inside(MathStep::Denominator, None)
        .inside(MathStep::Subscript, None);
    assert_eq!(
        room_on(&Operators, script, ink).1,
        MathRoom::Ink { leading }
    );
    assert_eq!(room_on(&Joining, display, ink).1, MathRoom::Lines);
    assert_eq!(room(&Operators, display).1, MathRoom::Lines);
}

#[test]
fn gives_a_script_of_an_inline_equation_the_room_of_its_lines_and_its_ink_on_a_target_that_asks() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let room = |fonts: &dyn crate::Fonts, script: MathScript, variant: ScriptRoom| {
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
        let mut shaper = super::Shaper::new(fonts, &theme, &table, &settings);
        let face = shaper.face(&math_run(script), true).unwrap();
        shaper.faces[face.0].math.room
    };
    // On a target whose variant is `ScriptRoom::Ink`, a superscript, a subscript and a script
    // of a script of an inline equation or a display take the room of their font's lines and of
    // their ink, with MathLeading at the equation's size over it: 125/1000 of 12 pt, 1.5 pt.
    let both = MathRoom::LinesAndInk {
        leading: hundredths(150),
    };
    let inline = MathScript::default();
    let superscript = inline.inside(MathStep::Superscript, None);
    for script in [
        superscript,
        inline.inside(MathStep::Subscript, None),
        inline.inside(MathStep::SuperscriptBesideSubscript, None),
        superscript.inside(MathStep::Subscript, None),
        MathScript::display().inside(MathStep::Subscript, None),
    ] {
        assert_eq!(
            room(&Operators, script, ScriptRoom::Ink),
            both,
            "{script:?}"
        );
        // The other variant keeps the room of the font's lines.
        assert_eq!(
            room(&Operators, script, ScriptRoom::FontLines),
            MathRoom::Lines
        );
    }
    // A font without a `MATH` table, the base of a script and a script inside a fraction,
    // which takes the room of a fraction's part, keep their rooms.
    let ink = ScriptRoom::Ink;
    assert_eq!(room(&Joining, superscript, ink), MathRoom::Lines);
    assert_eq!(room(&Operators, inline, ink), MathRoom::Lines);
    let in_fraction = inline
        .inside(MathStep::Numerator, None)
        .inside(MathStep::Superscript, None);
    assert_eq!(
        room(&Operators, in_fraction, ink),
        MathRoom::Ink {
            leading: hundredths(150)
        }
    );
}

#[test]
fn places_the_limits_of_a_display_operator_by_its_ink() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Operators, &theme, &table, &super::ShaperSettings::base());
    let mut limit = |step| {
        let face = shaper
            .face(&math_run(MathScript::display().inside(step, None)), true)
            .unwrap();
        let face = &shaper.faces[face.0];
        (face.size, face.rise, face.math.room)
    };
    // The limits take 8.5 pt. The upper one's baseline stands 1250 + 250 units of 12 pt above
    // the operator's, 18 pt, and the lower one's 700 + 500 units below it, 14.4 pt, and both
    // get the room of their ink with 1.5 pt over it.
    let room = MathRoom::Ink {
        leading: hundredths(150),
    };
    let stacked = Limit {
        operator: '\u{2211}',
        beside: false,
    };
    assert_eq!(
        limit(MathStep::UpperLimit(stacked)),
        (hundredths(850), hundredths(1800), room)
    );
    assert_eq!(
        limit(MathStep::LowerLimit(stacked)),
        (hundredths(850), hundredths(-1440), room)
    );
    // Beside the operator, the upper limit's baseline stands 1250 - 290 units above the
    // operator's, 11.52 pt, and the lower one's 700 + 200 units below it, 10.8 pt.
    let beside = Limit {
        beside: true,
        ..stacked
    };
    assert_eq!(
        limit(MathStep::UpperLimit(beside)),
        (hundredths(850), hundredths(1152), room)
    );
    assert_eq!(
        limit(MathStep::LowerLimit(beside)),
        (hundredths(850), hundredths(-1080), room)
    );
    // A script of a display keeps the room of its lines.
    assert_eq!(limit(MathStep::Superscript).2, MathRoom::Lines);
}

#[test]
fn stands_a_delimiter_with_the_middle_of_its_ink_on_the_math_axis() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Operators, &theme, &table, &super::ShaperSettings::base());
    let mut rise = |script: MathScript| {
        let face = shaper.face(&math_run(script), true).unwrap();
        shaper.faces[face.0].rise
    };
    // The parenthesis's ink runs from -250 to 750 of 1000 units, so its middle lies 3 pt above
    // the baseline at 12 pt, and the math axis 585/2048 of 12 pt, 3.43 pt: the parenthesis
    // rises 0.43 pt, 0.48 pt in whole dots of 0.24 pt.
    let inline = MathScript::default();
    assert_eq!(rise(inline.on_axis('(')), hundredths(48));
    assert_eq!(rise(MathScript::display().on_axis('(')), hundredths(48));
    // In a numerator it rises with the numerator: 1550/2048 of 12 pt and 0.43 pt, 9.51 pt, in
    // whole dots 9.60 pt, where the numerator's other runs rise 9.12 pt.
    let numerator = MathScript::display().inside(MathStep::Numerator, None);
    assert_eq!(rise(numerator), hundredths(912));
    assert_eq!(rise(numerator.on_axis('(')), hundredths(960));
    // A glyph without ink, and a run that is no delimiter, do not move.
    assert_eq!(rise(inline.on_axis('x')), Length::ZERO);
    assert_eq!(rise(inline), Length::ZERO);
}

#[test]
fn grows_a_delimiter_into_the_first_variant_that_reaches_a_share_of_its_need_or_its_need_less_the_shortfall()
 {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Operators, &theme, &table, &super::ShaperSettings::base());
    let face = shaper.face(&math_run(MathScript::display()), true).unwrap();
    let leading = hundredths(150);
    let mut grow = |need: Length| {
        let mut glyph = shaper.glyph(face, '(').unwrap();
        let sub_formula = shaper.grow(&mut glyph, (need, Length::ZERO), leading);
        let grown = shaper.faces[glyph.face.0];
        (
            glyph.id,
            glyph.advance,
            grown.rise,
            grown.raised,
            grown.math.room,
            sub_formula,
        )
    };
    let room = MathRoom::Ink { leading };
    // The shortfall is 900/2048 of 12 pt, 439 of the font's 1000 units, and the share 0.8308.
    // A need of 1.8 em, 1800 units, asks for the larger of 1495 and 1361 units: the variant
    // 8000, 1600 tall and 200/1000 of 12 pt wide. The middle of its ink, 300 units, 3.6 pt,
    // comes to the axis, 585/2048 of 12 pt, 3.43 pt: it lies 0.17 pt lower, 0.24 pt in whole
    // dots of 0.24 pt. The need reaches the font's 1465 units of a subformula.
    assert_eq!(
        grow(hundredths(2160)),
        (
            8000,
            hundredths(240),
            hundredths(-24),
            hundredths(-24),
            room,
            true
        )
    );
    // A need of 1.95 em asks for 1620 units by the share, more than its 1511 units less the
    // shortfall: the variant 8001, whose ink's middle lies at 300 units too.
    assert_eq!(grow(hundredths(2340)).0, 8001);
    // A need beyond the tallest variant takes the tallest.
    assert_eq!(grow(hundredths(6000)).0, 8001);
    // A need of one em asks for 831 units, which the base glyph reaches: it keeps its glyph
    // and width and stands with its ink's middle, 250 units, on the axis, 0.43 pt higher,
    // 0.48 pt in whole dots. It is no subformula.
    assert_eq!(
        grow(hundredths(1200)),
        (
            0x28,
            hundredths(120),
            hundredths(48),
            hundredths(48),
            room,
            false
        )
    );
    // A glyph without vertical variants stays as it is.
    let mut x = shaper.glyph(face, 'x').unwrap();
    let before = x;
    shaper.grow(&mut x, (hundredths(2400), Length::ZERO), leading);
    assert_eq!(x, before);
}

#[test]
fn moves_the_lower_limit_beside_a_display_operator_by_its_italic_correction() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let correction = |fonts: &dyn crate::Fonts, operator| {
        let mut shaper = super::Shaper::new(fonts, &theme, &table, &super::ShaperSettings::base());
        let face = shaper.face(&math_run(MathScript::display()), true).unwrap();
        shaper.italic_correction(face, operator)
    };
    // The display variant's 400 units of 12 pt: 4.8 pt.
    assert_eq!(correction(&Operators, '\u{2211}'), hundredths(480));
    // A glyph that the table does not list, and a font without the table, move nothing.
    assert_eq!(correction(&Operators, 'x'), Length::ZERO);
    assert_eq!(correction(&Joining, '\u{2211}'), Length::ZERO);
}

/// [`Joining`] fonts without pair kerning or ligatures: the family "Plain" is a second font,
/// and the first font's `MATH` table gives "x" and "y" an italic correction of 300 units, and
/// no other glyph one.
struct Slanted;

impl crate::Fonts for Slanted {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        let mut face = Joining.face(family, bold, italic)?;
        if family.is("Plain") {
            face.font = f_office_fonts::FontId::from_index(1);
        }
        Some(face)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }

    fn italic_correction(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<i32> {
        (font.index() == 0 && matches!(char::from_u32(glyph), Some('x' | 'y'))).then_some(300)
    }
}

#[test]
fn adds_the_italic_correction_before_another_font_but_not_before_a_script() {
    use crate::props::FontRef;
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let mut shaper = super::Shaper::new(&Slanted, &theme, &table, &super::ShaperSettings::base());
    let props = RunProps::default();
    let mut slanted = Vec::new();
    shaper.measure(&props, "x", &mut slanted);
    let plain = slanted[0].advance.units();
    // The text after an equation, in another font, gets the correction.
    let text = RunProps {
        font_ascii: Some(FontRef::Name("Plain".into())),
        font_hansi: Some(FontRef::Name("Plain".into())),
        ..RunProps::default()
    };
    let mut after = Vec::new();
    shaper.measure(&text, " ", &mut after);
    let mut last = slanted[0];
    shaper.correct_italic(&mut last, &after[0]);
    assert_eq!(last.advance.units(), plain * 4);
    // A glyph of the same font at another size, as a script's, does not.
    let script = RunProps {
        size: Some(16),
        ..RunProps::default()
    };
    let mut small = Vec::new();
    shaper.measure(&script, "=", &mut small);
    let mut base = slanted[0];
    shaper.correct_italic(&mut base, &small[0]);
    assert_eq!(base.advance.units(), plain);
}

#[test]
fn adds_the_italic_correction_of_a_slanted_glyph_before_an_upright_one() {
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let mut shaper = super::Shaper::new(&Slanted, &theme, &table, &super::ShaperSettings::base());
    let props = RunProps::default();
    let mut glyphs = Vec::new();
    shaper.measure(&props, "xy=x", &mut glyphs);
    let advances: Vec<i64> = glyphs.iter().map(|g| g.advance.units()).collect();
    let plain = advances[0];
    // "x" before the slanted "y" keeps its advance, "y" before "=" gains three times it, and
    // the last "x" has nothing after it.
    assert_eq!(advances, [plain, plain * 4, plain, plain]);
    // The glyph before the first of the next run's glyphs gets the correction too.
    let mut next = Vec::new();
    shaper.measure(&props, "=", &mut next);
    let mut last = glyphs[3];
    shaper.correct_italic(&mut last, &next[0]);
    assert_eq!(last.advance.units(), plain * 4);
    // Before an ordinary glyph, such as a digit, of the same run it has none, but before the
    // first of the next run's glyphs it does.
    let mut digit = Vec::new();
    shaper.measure(&props, "x2", &mut digit);
    assert_eq!(digit[0].advance.units(), plain);
    let mut last = glyphs[3];
    shaper.correct_italic(&mut last, &digit[1]);
    assert_eq!(last.advance.units(), plain * 4);
    // Without the table's values, as in fonts that are not for equations, nothing changes.
    let mut joined = Vec::new();
    super::Shaper::new(&Joining, &theme, &table, &super::ShaperSettings::base()).measure(
        &props,
        "y=",
        &mut joined,
    );
    assert_eq!(joined[0].advance.units(), plain);
}

/// A character takes the face slot of its script, and the size of small capitals moves ASCII
/// and other characters to their small faces; complex formatting and the East Asian hint come
/// before both. The hint's set of symbols also moves Greek, Cyrillic and the symbols, but not
/// spaces, combining marks or Latin letters.
#[test]
fn gives_each_character_the_face_slot_of_its_script_and_size() {
    use super::{FaceSlot, HintedSet, face_slot};
    let plain = (false, None);
    let punctuation = (false, Some(HintedSet::Punctuation));
    let symbols = (false, Some(HintedSet::Symbols));
    let cases = [
        ('a', false, plain, FaceSlot::Ascii),
        ('\u{00E9}', false, plain, FaceSlot::Other),
        ('a', true, plain, FaceSlot::SmallAscii),
        ('\u{00E9}', true, plain, FaceSlot::SmallOther),
        ('\u{0628}', false, plain, FaceSlot::Complex),
        ('a', true, (true, None), FaceSlot::Complex),
        ('\u{4E2D}', true, plain, FaceSlot::EastAsian),
        ('\u{2019}', false, plain, FaceSlot::Other),
        ('\u{2019}', false, punctuation, FaceSlot::EastAsian),
        ('\u{03C9}', false, punctuation, FaceSlot::Other),
        ('\u{03C9}', false, symbols, FaceSlot::EastAsian),
        ('\u{0416}', false, symbols, FaceSlot::EastAsian),
        ('\u{02C7}', false, symbols, FaceSlot::EastAsian),
        ('\u{2502}', false, symbols, FaceSlot::EastAsian),
        ('\u{2713}', false, symbols, FaceSlot::EastAsian),
        ('\u{2019}', false, symbols, FaceSlot::EastAsian),
        ('\u{2002}', false, symbols, FaceSlot::Other),
        ('\u{0301}', false, symbols, FaceSlot::Other),
        ('\u{00E9}', false, symbols, FaceSlot::Other),
    ];
    for (ch, small, context, slot) in cases {
        assert_eq!(face_slot(ch, small, context), slot, "{ch:?} small {small}");
    }
}

/// A character of the class of the East Asian font lies on the East Asian side; without the
/// hint every other character lies on the other side, and with it ASCII stays there while the
/// middle dot, the section sign and the characters outside Latin-1 but the Latin letters and
/// Greek Extended move to the East Asian side. Spaces, complex script characters, and with the
/// hint the other characters of Latin-1, the Latin letters outside it and Greek Extended are
/// open where the hint leaves them open.
#[test]
fn gives_each_character_its_font_side() {
    use super::FontSide::{EastAsian, Open, Other};
    use super::font_side;
    use super::script::HintedLatin;
    let (plain, hint, complex) = (
        (false, None),
        (false, Some(HintedLatin::Open)),
        (true, None),
    );
    let cases = [
        ('\u{4E00}', plain, EastAsian),
        ('\u{FF17}', plain, EastAsian),
        ('\u{3002}', hint, EastAsian),
        ('7', plain, Other),
        ('7', hint, Other),
        ('k', hint, Other),
        ('\u{00E9}', plain, Other),
        ('\u{0101}', plain, Other),
        ('\u{201C}', plain, Other),
        ('\u{03B1}', plain, Other),
        ('\u{00B7}', hint, EastAsian),
        ('\u{00A7}', hint, EastAsian),
        ('\u{201C}', hint, EastAsian),
        ('\u{2026}', hint, EastAsian),
        ('\u{203B}', hint, EastAsian),
        ('\u{2192}', hint, EastAsian),
        ('\u{2460}', hint, EastAsian),
        ('\u{03B1}', hint, EastAsian),
        ('\u{0434}', hint, EastAsian),
        ('\u{00E9}', hint, Open),
        ('\u{0101}', hint, Open),
        ('\u{1F00}', hint, Open),
        ('\u{1F00}', plain, Other),
        (' ', plain, Open),
        ('\u{0628}', plain, Open),
        ('a', complex, Open),
    ];
    for (ch, (all_complex, hint), side) in cases {
        let found = font_side(ch, all_complex, hint, |_| true);
        assert_eq!(found, side, "{ch:?} {all_complex} {hint:?}");
    }
}

/// With the hint read by language, the Latin-1 characters of the first list of the table of the
/// East Asian hint (ECMA-376 Part 1, 17.3.2.26) take the East Asian side in every run; its Latin-1 letters for Chinese and Latin Extended
/// Additional only in a Chinese run; Latin Extended-A, Latin Extended-B and the IPA Extensions
/// in a Chinese run or under a Chinese character set; and the other characters of Latin-1 and
/// Greek Extended the other side. A character that the face of its side lacks stays open, and
/// the characters outside these blocks keep their sides.
#[test]
fn gives_hinted_latin_characters_the_side_of_their_language() {
    use super::FontSide::{EastAsian, Open, Other};
    use super::font_side;
    use super::script::{HintLanguage, HintedLatin};
    let [chinese, set, other] = [
        HintLanguage::Chinese,
        HintLanguage::ChineseSet,
        HintLanguage::Other,
    ];
    let cases = [
        ('\u{00B0}', [EastAsian, EastAsian, EastAsian]),
        ('\u{00D7}', [EastAsian, EastAsian, EastAsian]),
        ('\u{00E9}', [EastAsian, Other, Other]),
        ('\u{00FC}', [EastAsian, Other, Other]),
        ('\u{1EA1}', [EastAsian, Other, Other]),
        ('\u{0101}', [EastAsian, EastAsian, Other]),
        ('\u{01CE}', [EastAsian, EastAsian, Other]),
        ('\u{0251}', [EastAsian, EastAsian, Other]),
        ('\u{00A9}', [Other, Other, Other]),
        ('\u{00F1}', [Other, Other, Other]),
        ('\u{00E4}', [Other, Other, Other]),
        ('\u{1F00}', [Other, Other, Other]),
        ('\u{00A7}', [EastAsian, EastAsian, EastAsian]),
        ('\u{03B1}', [EastAsian, EastAsian, EastAsian]),
        ('\u{4E00}', [EastAsian, EastAsian, EastAsian]),
        ('k', [Other, Other, Other]),
        (' ', [Open, Open, Open]),
    ];
    for (ch, sides) in cases {
        for (language, side) in [chinese, set, other].into_iter().zip(sides) {
            let hint = Some(HintedLatin::ByLanguage(language));
            assert_eq!(
                font_side(ch, false, hint, |_| true),
                side,
                "{ch:?} {language:?}"
            );
        }
    }
    // The face of the side has no glyph: the character stays open, and the question names
    // the side whose face is asked.
    let hint = Some(HintedLatin::ByLanguage(chinese));
    let mut asked = None;
    let side = font_side('\u{00E9}', false, hint, |side| {
        asked = Some(side);
        false
    });
    assert_eq!((side, asked), (Open, Some(EastAsian)));
    // A character that the hint does not read never asks for a face.
    let side = font_side('\u{00A7}', false, hint, |_| false);
    assert_eq!(side, EastAsian);
}

/// A run's East Asian language decides Chinese for either Chinese script, and the character set
/// of its East Asian font decides only when the language is not Chinese.
#[test]
fn reads_the_hint_language_of_a_run() {
    use super::script::HintLanguage;
    use crate::props::EastAsianScript;
    use crate::styles::EastAsianCharset;
    let cases = [
        (
            Some(EastAsianScript::Simplified),
            None,
            HintLanguage::Chinese,
        ),
        (
            Some(EastAsianScript::Traditional),
            Some(EastAsianCharset::ShiftJis),
            HintLanguage::Chinese,
        ),
        (
            Some(EastAsianScript::Japanese),
            Some(EastAsianCharset::Gb2312),
            HintLanguage::ChineseSet,
        ),
        (None, Some(EastAsianCharset::Big5), HintLanguage::ChineseSet),
        (None, Some(EastAsianCharset::ShiftJis), HintLanguage::Other),
        (Some(EastAsianScript::Korean), None, HintLanguage::Other),
        (None, None, HintLanguage::Other),
    ];
    for (script, charset, language) in cases {
        assert_eq!(
            HintLanguage::of(script, charset),
            language,
            "{script:?} {charset:?}"
        );
    }
}

/// Fonts that have only the families in the list, as [`Only`] does, where the first family has
/// no glyph for the characters of `lacks`.
struct Lacking(&'static [&'static str], &'static [char]);

impl crate::Fonts for Lacking {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Only(self.0).face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        if font.index() == 0 && self.1.contains(&ch) {
            return None;
        }
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }
}

/// In a Chinese run with the hint, a letter between ideographs takes the East Asian side where
/// the run's East Asian face has its glyph, and stays open where that face lacks it even when
/// the face that draws the letter has it; in a Japanese run the letter takes the other side by
/// the face that draws it. A target that leaves such letters open keeps them open.
#[test]
fn asks_the_face_of_the_side_for_a_hinted_letter() {
    use super::FontSide::{EastAsian, Open, Other};
    use crate::props::{EastAsianScript, FontRef};
    use crate::quirks::HintedFontSide;
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let run = |script| RunProps {
        font_ascii: Some(FontRef::Name("Latin".into())),
        font_hansi: Some(FontRef::Name("Latin".into())),
        font_east_asia: Some(Box::new(FontRef::Name("East".into()))),
        east_asian_hint: Some(true),
        east_asian_script: Some(script),
        ..RunProps::default()
    };
    let sides = |fonts: &Lacking, script, variant| {
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
        let mut shaper = super::Shaper::new(fonts, &theme, &table, &settings);
        let mut glyphs = Vec::new();
        shaper.measure(&run(script), "\u{4E00}\u{00E9}\u{4E8C}", &mut glyphs);
        glyphs.iter().map(|g| g.side).collect::<Vec<_>>()
    };
    let (chinese, japanese) = (EastAsianScript::Simplified, EastAsianScript::Japanese);
    let by_language = HintedFontSide::ByLanguage;
    let full = Lacking(&["East", "Latin"], &[]);
    assert_eq!(
        sides(&full, chinese, by_language),
        [EastAsian, EastAsian, EastAsian]
    );
    assert_eq!(
        sides(&full, japanese, by_language),
        [EastAsian, Other, EastAsian]
    );
    let lacking = Lacking(&["East", "Latin"], &['\u{00E9}']);
    assert_eq!(
        sides(&lacking, chinese, by_language),
        [EastAsian, Open, EastAsian]
    );
    assert_eq!(
        sides(&lacking, japanese, by_language),
        [EastAsian, Other, EastAsian]
    );
    let latin_lacking = Lacking(&["Latin", "East"], &['\u{00E9}']);
    assert_eq!(
        sides(&latin_lacking, japanese, by_language),
        [EastAsian, Open, EastAsian]
    );
    assert_eq!(
        sides(&full, chinese, HintedFontSide::Open),
        [EastAsian, Open, EastAsian]
    );
}

/// [`Joining`] with a second kerning table: the face's kerning source kerns every pair by -20
/// units and its `kern` table by -50.
struct TwoTables;

impl crate::Fonts for TwoTables {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Joining.face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }

    fn kerning(
        &self,
        _font: f_office_fonts::FontId,
        _left: u32,
        _right: u32,
        table: crate::KerningTable,
    ) -> i32 {
        match table {
            crate::KerningTable::FaceSource => -20,
            crate::KerningTable::KernTable => -50,
        }
    }
}

#[test]
fn kerns_by_the_kern_table_before_mode_15_where_the_target_does() {
    use crate::mode::{CompatibilityMode, ModeRules};
    use crate::quirks::KerningTableRead::{FaceSource, KernTableBeforeMode};
    let units = |read, value, open_type| {
        let theme = crate::styles::Theme::default();
        let table = crate::styles::FontTable::default();
        let rules = ModeRules::of(CompatibilityMode::read(value));
        let settings = super::ShaperSettings {
            mode_rules: rules.with_open_type_features(open_type),
            ..super::ShaperSettings::base_with(|p| p.with_variant(read))
        };
        let shaper = super::Shaper::new(&TwoTables, &theme, &table, &settings);
        let metrics = crate::FaceMetrics::default();
        let face = plain_face(metrics, Length::from_units(1000), LineHeight::TakesHheaLine);
        shaper.kerning_units(&face, 1, 2)
    };
    // Before mode 15, the target that reads the `kern` table there takes its value in a
    // document without the OpenType features setting, and the face's kerning source with it;
    // from mode 15 on, both take the face's kerning source.
    let cases = [
        (None, false, -50),
        (Some(12), false, -50),
        (Some(14), false, -50),
        (Some(14), true, -20),
        (None, true, -20),
        (Some(15), false, -20),
        (Some(16), true, -20),
    ];
    for (value, open_type, kerning) in cases {
        assert_eq!(units(KernTableBeforeMode, value, open_type), kerning);
        assert_eq!(units(FaceSource, value, open_type), -20);
    }
}

/// Two families of four faces each, as the fonts of [`Joining`] with an index of their own:
/// font `4 * family + 2 * italic + bold`. The upright faces hold Hebrew and Arabic letters;
/// the italic faces of "Serif" hold Hebrew letters but no Arabic letter, and those of "Sans"
/// hold neither.
struct Styled;

impl Styled {
    const FAMILIES: [&'static str; 2] = ["Serif", "Sans"];
}

impl crate::Fonts for Styled {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        let index = Self::FAMILIES.iter().position(|name| family.is(name))?;
        let index = u32::try_from(4 * index).ok()? + 2 * u32::from(italic) + u32::from(bold);
        let font = f_office_fonts::FontId::from_index(index);
        Joining
            .face(family, false, false)
            .map(|chosen| crate::ChosenFace { font, ..chosen })
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        let (sans, italic) = (font.index() >= 4, font.index() % 4 >= 2);
        let missing = match ch {
            '\u{590}'..='\u{5FF}' => italic && sans,
            '\u{600}'..='\u{6FF}' => italic,
            _ => false,
        };
        (!missing).then(|| u32::from(ch))
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }

    fn family_name(&self, font: f_office_fonts::FontId) -> Option<String> {
        let index = usize::try_from(font.index() / 4).ok()?;
        Self::FAMILIES.get(index).map(|name| (*name).to_owned())
    }
}

#[test]
fn an_italic_complex_run_takes_the_upright_face_where_its_italic_face_lacks_the_language_script() {
    use crate::props::{BidiScript, FontRef};
    use crate::quirks::ComplexItalicFace::{Italic, UprightForLanguage};
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let font = |family: &str, bold: bool, language: Option<BidiScript>, quirk| {
        let props = RunProps {
            font_cs: Some(Box::new(FontRef::Name(family.into()))),
            bold_cs: Some(bold),
            italic_cs: Some(true),
            bidi_script: language,
            ..RunProps::default()
        };
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(quirk));
        let mut shaper = super::Shaper::new(&Styled, &theme, &table, &settings);
        let face = shaper.complex_face(&props).unwrap();
        let face = shaper.faces[face.0];
        // Only the upright face of an italic run stands in for the italic face.
        let upright = face.font.index() % 4 < 2;
        assert_eq!(face.standing.synthetic_italic, upright, "{family} {bold}");
        face.font.index()
    };
    // The italic faces of "Serif" lack Arabic letters, the script of a run without a bidi
    // language: the upright face of the same weight.
    assert_eq!(font("Serif", false, None, UprightForLanguage), 0);
    assert_eq!(font("Serif", true, None, UprightForLanguage), 1);
    assert_eq!(
        font("Serif", false, Some(BidiScript::Other), UprightForLanguage),
        0
    );
    // They hold the Hebrew letters of a run whose bidi language is Hebrew.
    assert_eq!(
        font("Serif", false, Some(BidiScript::Hebrew), UprightForLanguage),
        2
    );
    // The italic faces of "Sans" hold no letter of a complex script, and stay.
    assert_eq!(font("Sans", false, None, UprightForLanguage), 6);
    // Under the other variant, every italic run keeps its italic face.
    assert_eq!(font("Serif", true, None, Italic), 3);
}

/// Fonts whose families have no italic face: an italic run takes the upright face, which
/// stands in for the italic one.
struct UprightOnly;

impl crate::Fonts for UprightOnly {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Joining
            .face(family, bold, italic)
            .map(|chosen| crate::ChosenFace {
                synthetic_italic: italic,
                ..chosen
            })
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }
}

#[test]
fn text_of_an_equation_asks_for_the_upright_face() {
    use crate::props::FontRef;
    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let synthetic = |math: Option<bool>| {
        let props = RunProps {
            font_ascii: Some(FontRef::Name("Cambria Math".into())),
            italic: Some(true),
            math,
            ..RunProps::default()
        };
        let mut shaper =
            super::Shaper::new(&UprightOnly, &theme, &table, &super::ShaperSettings::base());
        let face = shaper.face(&props, true).unwrap();
        shaper.faces[face.0].standing.synthetic_italic
    };
    // An italic run of a family without an italic face is a synthetic italic, and text of an
    // equation with the same italic is not.
    assert!(synthetic(None));
    assert!(!synthetic(Some(true)));
}

#[test]
fn math_run_uses_own_non_cambria_font_for_supported_alphanumerics_only() {
    use crate::props::FontRef;
    struct MathAndCalibri;
    impl crate::Fonts for MathAndCalibri {
        fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
            let index = match (family.as_str(), bold, italic) {
                ("Cambria Math", false, false) => 1,
                ("Calibri", false, true) => 2,
                ("Calibri", false, false) => 3,
                _ => return None,
            };
            let id = f_office_fonts::FontId::from_index(index);
            let metrics = if index == 1 {
                crate::FaceMetrics {
                    units_per_em: 2048,
                    hhea_ascender: 1950,
                    hhea_descender: -450,
                    descent: 450,
                    line_top: 1950,
                    script_top: 1950,
                    ..crate::FaceMetrics::default()
                }
            } else {
                crate::FaceMetrics {
                    units_per_em: 2048,
                    hhea_ascender: 2100,
                    hhea_descender: -600,
                    descent: 600,
                    line_top: 2100,
                    script_top: 2100,
                    ..crate::FaceMetrics::default()
                }
            };
            Some(crate::ChosenFace {
                font: id,
                metrics,
                synthetic_bold: false,
                synthetic_italic: false,
                stands_in: false,
            })
        }

        fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
            if font.index() == 1 {
                return Some(u32::from(ch));
            }
            // Calibri has BMP digits and '+' but not Mathematical Italic '𝑥' (U+1D465).
            (ch.is_ascii_digit() || ch == '+').then_some(u32::from(ch))
        }

        fn advance(&self, _font: f_office_fonts::FontId, _glyph: u32) -> Option<u16> {
            Some(1000)
        }
    }

    let theme = crate::styles::Theme::default();
    let table = crate::styles::FontTable::default();
    let props = RunProps {
        font_ascii: Some(FontRef::Name("Calibri".into())),
        font_hansi: Some(FontRef::Name("Calibri".into())),
        italic: Some(true),
        math: Some(true),
        size: Some(32),
        ..RunProps::default()
    };
    let mut shaper = super::Shaper::new(
        &MathAndCalibri,
        &theme,
        &table,
        &super::ShaperSettings::base(),
    );
    let mut glyphs = Vec::new();
    shaper.measure(&props, "\u{1D465}1+", &mut glyphs);
    assert_eq!(glyphs.len(), 3);
    // '𝑥' (missing from Calibri) -> Cambria Math; '1' (alphanumeric in Calibri) -> Calibri-Italic;
    // '+' (operator, even though Calibri has it) -> Cambria Math.
    assert_eq!(shaper.faces[glyphs[0].face.0].font.index(), 1);
    assert_eq!(shaper.faces[glyphs[1].face.0].font.index(), 2);
    assert_eq!(shaper.faces[glyphs[2].face.0].font.index(), 1);
    // Non-Cambria math face keeps Cambria Math's line metrics.
    assert_eq!(shaper.faces[glyphs[1].face.0].metrics.line_top, 1950);
    assert_eq!(shaper.faces[glyphs[1].face.0].metrics.descent, 450);
}

/// [`Only`] fonts that know their family names, in which the first font has no Devanagari
/// glyphs.
struct NamedWithoutDevanagari(&'static [&'static str]);

impl crate::Fonts for NamedWithoutDevanagari {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Only(self.0).face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        if font.index() == 0 && ('\u{0900}'..='\u{097F}').contains(&ch) {
            return None;
        }
        Only(self.0).glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Only(self.0).advance(font, glyph)
    }

    fn family_name(&self, font: f_office_fonts::FontId) -> Option<String> {
        let index = usize::try_from(font.index()).ok()?;
        self.0.get(index).map(|name| (*name).to_owned())
    }
}

#[test]
fn draws_a_devanagari_digit_of_a_label_that_its_font_lacks_with_mangal() {
    use crate::props::FontRef;
    use crate::quirks::SubstituteFaces;
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let fonts = NamedWithoutDevanagari(&["Tahoma", "Nirmala UI", "Mangal"]);
    let tahoma = Some(FontRef::Name("Tahoma".into()));
    let props = RunProps {
        font_ascii: tahoma.clone(),
        font_hansi: tahoma.clone(),
        font_cs: tahoma.map(Box::new),
        ..RunProps::default()
    };
    let settings = super::ShaperSettings::base_with(|p| p.with_variant(SubstituteFaces::ByBlock));
    let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
    let mut drawn = |label: bool| {
        let mut glyphs = Vec::new();
        if label {
            shaper.measure_label(&props, "\u{0967}.", &mut glyphs);
        } else {
            shaper.measure(&props, "\u{0967}.", &mut glyphs);
        }
        glyphs
            .iter()
            .map(|g| shaper.faces[g.face.0].font.index())
            .collect::<Vec<_>>()
    };
    // Body text takes the row of the table, and a label Mangal.
    assert_eq!(drawn(false), [1, 0]);
    assert_eq!(drawn(true), [2, 0]);
}

/// [`Only`] fonts that know their family names, in which the first font has no en or em space.
struct NamedWithoutFixedSpaces(&'static [&'static str]);

impl crate::Fonts for NamedWithoutFixedSpaces {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Only(self.0).face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        if font.index() == 0 && matches!(ch, '\u{2002}' | '\u{2003}') {
            return None;
        }
        Only(self.0).glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Only(self.0).advance(font, glyph)
    }

    fn family_name(&self, font: f_office_fonts::FontId) -> Option<String> {
        let index = usize::try_from(font.index()).ok()?;
        self.0.get(index).map(|name| (*name).to_owned())
    }
}

#[test]
fn keeps_an_en_space_in_its_own_face_in_a_text_form_field() {
    use super::LineSizing;
    use crate::props::FontRef;
    use crate::quirks::SubstituteFaces;
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let fonts = NamedWithoutFixedSpaces(&[
        "Arial Narrow",
        "Arial",
        "Times New Roman",
        "Courier New",
        "Cambria Math",
    ]);
    let narrow = Some(FontRef::Name("Arial Narrow".into()));
    let settings = super::ShaperSettings::base_with(|p| p.with_variant(SubstituteFaces::ByBlock));
    let mut shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
    let mut drawn = |form_text: Option<bool>| {
        let props = RunProps {
            font_ascii: narrow.clone(),
            font_hansi: narrow.clone(),
            form_text,
            ..RunProps::default()
        };
        let mut glyphs = Vec::new();
        shaper.measure(&props, "\u{2002}", &mut glyphs);
        let glyph = glyphs.first().unwrap();
        (shaper.faces[glyph.face.0].font.index(), glyph.sizing)
    };
    // Elsewhere a substitute face draws the space, which sizes no line; in the result of a
    // text form field the space stays in its own face, which lacks it.
    let (font, sizing) = drawn(None);
    assert_ne!(font, 0);
    assert_eq!(sizing, LineSizing::Nothing);
    assert_eq!(drawn(Some(true)), (0, LineSizing::ByFace));
}

/// [`Joining`] fonts, with an em of 1,000 units, a win top of 800 and a descent of 200, whose
/// `VDMX` table lists only 13 pixels per em.
struct Vdmx13;

impl crate::Fonts for Vdmx13 {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Joining.face(family, bold, italic)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Joining.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Joining.advance(font, glyph)
    }

    fn device_heights(&self, _font: f_office_fonts::FontId, pels: u16) -> Option<(i16, i16)> {
        (pels == 13).then_some((12, -4))
    }
}

#[test]
fn gives_whole_pixel_heights_from_the_vdmx_table_or_else_rounded_from_the_win_heights() {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let mut shaper = super::Shaper::new(&Vdmx13, &theme, &table, &super::ShaperSettings::base());
    let face = shaper.face(&RunProps::default(), true).unwrap();
    assert_eq!(shaper.whole_pixel_heights(face, 13), Some((12, 4)));
    // 800 and 200 units of 1,000 at 14 pixels: 11.2 and 2.8 pixels.
    assert_eq!(shaper.whole_pixel_heights(face, 14), Some((11, 3)));
}

#[test]
fn the_exact_edge_check_cuts_each_advance_to_whole_parts_of_a_point() {
    let size = Length::from_points(11).unwrap().units();
    let point = Length::UNITS_PER_POINT;
    let exact =
        super::ShaperSettings::base_with(|p| p.with_variant(crate::quirks::GlyphEdgeCheck::Exact));
    // 556 units of a face of 1,000 units per em at 11 pt are 25,051.136 4,096ths of a point.
    assert_eq!(
        exact.counted_advance((556 * size, 1_000)),
        (25_051 * point, 4_096)
    );
    // 1,139 units of a face of 2,048 units per em at 11 pt are 25,058 of them exactly.
    let whole = exact.counted_advance((1_139 * size, 2_048));
    assert_eq!(whole, (25_058 * point, 4_096));
    assert_eq!(whole.0 * 2_048, 1_139 * size * whole.1);
    let tied = super::ShaperSettings::base_with(|p| {
        p.with_variant(crate::quirks::GlyphEdgeCheck::RoundedWithTie)
    });
    assert_eq!(
        tied.counted_advance((556 * size, 1_000)),
        (556 * size, 1_000)
    );
}

/// The fonts of [`Joining`] whose en space is 500 units wide and its en dash 498, and whose em
/// space is 1,000 and its em dash 900; every other glyph is 100.
struct Dashes;

impl crate::Fonts for Dashes {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<crate::ChosenFace> {
        Joining.face(family, bold, italic)
    }

    fn glyph(&self, _font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        Some(u32::from(ch))
    }

    fn advance(&self, _font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        Some(match char::from_u32(glyph) {
            Some('\u{2002}') => 500,
            Some('\u{2013}') => 498,
            Some('\u{2003}') => 1_000,
            Some('\u{2014}') => 900,
            _ => 100,
        })
    }
}

#[test]
fn lays_out_en_and_em_spaces_with_their_dashes_widths_where_the_target_does() {
    use crate::quirks::FixedSpaceWidths;
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let measured = |widths: FixedSpaceWidths| {
        let settings = super::ShaperSettings::base_with(|p| p.with_variant(widths));
        let mut shaper = super::Shaper::new(&Dashes, &theme, &table, &settings);
        let mut glyphs = Vec::new();
        shaper.measure(
            &RunProps::default(),
            "\u{2002}\u{2013}\u{2003}\u{2014}",
            &mut glyphs,
        );
        glyphs
            .iter()
            .map(|g| (g.advance, g.kerning))
            .collect::<Vec<_>>()
    };
    let own = measured(FixedSpaceWidths::OwnGlyphs);
    let dashes = measured(FixedSpaceWidths::DashWidths);
    assert_ne!(own[0].0, own[1].0);
    assert_ne!(own[2].0, own[3].0);
    // Each space takes its dash's advance as its own width, with no kerning.
    assert_eq!(dashes[0], dashes[1]);
    assert_eq!(dashes[2], dashes[3]);
    assert_eq!(dashes[0].1, Length::ZERO);
    assert_eq!(&dashes[1..2], &own[1..2]);
}

#[test]
fn resolves_an_east_asian_theme_font_without_typeface_by_the_language_of_the_variant() {
    use crate::props::{EastAsianScript, FontRef};
    use crate::quirks::ThemeEastAsian;
    let theme = crate::styles::Theme {
        scripts: crate::styles::MinorMajor {
            minor: vec![
                ("Jpan".into(), "Jpan Face".into()),
                ("Hans".into(), "Hans Face".into()),
            ],
            major: Vec::new(),
        },
        ..crate::styles::Theme::default()
    };
    let table = crate::styles::FontTable::default();
    let fonts = Only(&["Latin"]);
    let family = |variant, settings_script| {
        let settings = super::ShaperSettings {
            east_asian_script: settings_script,
            ..super::ShaperSettings::base_with(|p| p.with_variant(variant))
        };
        let shaper = super::Shaper::new(&fonts, &theme, &table, &settings);
        shaper
            .theme_family(&FontRef::MinorEastAsia, Some(EastAsianScript::Japanese))
            .map(str::to_owned)
    };
    let simplified = Some(EastAsianScript::Simplified);
    assert_eq!(
        family(ThemeEastAsian::RunLanguage, simplified).as_deref(),
        Some("Jpan Face")
    );
    assert_eq!(
        family(ThemeEastAsian::SettingsLanguage, simplified).as_deref(),
        Some("Hans Face")
    );
    assert_eq!(
        family(ThemeEastAsian::SettingsLanguage, None).as_deref(),
        Some("MS Mincho")
    );
}

#[test]
fn legacy_text_offset_rounds_to_shadow_box_steps() {
    let pt = |n, d| Length::from_units(f_office_units::div_round(n * Length::UNITS_PER_POINT, d));
    assert_eq!(
        super::legacy_offset(Length::from_points(12).unwrap()),
        pt(48, 100)
    );
    assert_eq!(
        super::legacy_offset(Length::from_points(24).unwrap()),
        pt(96, 100)
    );
    assert_eq!(
        super::legacy_offset(Length::from_points(48).unwrap()),
        pt(204, 100)
    );
    assert_eq!(super::legacy_offset(Length::ZERO), pt(12, 100));
}

fn measure_legacy_face(
    variant: crate::quirks::TextShadows,
    props: &RunProps,
) -> (super::Face, (bool, bool, bool, bool)) {
    let (theme, table) = (
        crate::styles::Theme::default(),
        crate::styles::FontTable::default(),
    );
    let settings = super::ShaperSettings::base_with(|p| p.with_variant(variant));
    let mut shaper = super::Shaper::new(&Joining, &theme, &table, &settings);
    let mut glyphs = Vec::new();
    shaper.measure(props, "A", &mut glyphs);
    let face = *shaper.faces().get(glyphs[0].face).unwrap();
    let drawn = shaper.draws_text_effects(props);
    (face, drawn)
}

#[test]
fn draws_legacy_shadow_when_text_shadows_scale() {
    use crate::props::Color;
    use crate::quirks::TextShadows;
    let base_props = RunProps {
        size: Some(48),
        color: Some(Color::Rgb([0xC0, 0x00, 0x00])),
        ..RunProps::default()
    };
    let (base_face, base_drawn) = measure_legacy_face(
        TextShadows::Unknown,
        &RunProps {
            legacy_shadow: Some(true),
            legacy_outline: Some(true),
            ..base_props.clone()
        },
    );
    assert_eq!(
        (
            base_face.shadow,
            base_face.outline,
            base_face.text_fill,
            base_drawn.3
        ),
        (None, None, super::DrawnTextFill::Solid, false)
    );

    let (shadow_face, shadow_drawn) = measure_legacy_face(
        TextShadows::Scaled,
        &RunProps {
            legacy_shadow: Some(true),
            ..base_props
        },
    );
    let offset = super::legacy_offset(Length::from_points(24).unwrap());
    assert_eq!(
        shadow_face.shadow,
        Some(super::DrawnShadow {
            across: offset,
            down: offset,
            color: Rgb {
                r: 192,
                g: 192,
                b: 192,
            },
            form: super::ShadowForm::Paths,
        })
    );
    assert!(shadow_drawn.3);
}

#[test]
fn draws_legacy_outline_when_text_shadows_scale() {
    use crate::props::Color;
    use crate::quirks::TextShadows;
    let base_props = RunProps {
        size: Some(48),
        color: Some(Color::Rgb([0xC0, 0x00, 0x00])),
        ..RunProps::default()
    };
    let (outline_face, _) = measure_legacy_face(
        TextShadows::Scaled,
        &RunProps {
            legacy_outline: Some(true),
            ..base_props.clone()
        },
    );
    assert_eq!(
        (outline_face.outline, outline_face.text_fill),
        (
            Some(f_office_paint::Outline {
                width: crate::params::LEGACY_TEXT_OUTLINE_WIDTH,
                color: Rgb {
                    r: 0xC0,
                    g: 0x00,
                    b: 0x00,
                },
                join: f_office_paint::Join::Round,
            }),
            super::DrawnTextFill::None,
        )
    );

    let (both_face, _) = measure_legacy_face(
        TextShadows::Scaled,
        &RunProps {
            legacy_outline: Some(true),
            legacy_shadow: Some(true),
            ..base_props
        },
    );
    assert_eq!(both_face.text_fill, super::DrawnTextFill::White);
}

#[test]
fn draws_legacy_emboss_and_imprint_when_text_shadows_scale() {
    use crate::quirks::TextShadows;
    let base_props = RunProps {
        size: Some(48),
        ..RunProps::default()
    };

    // w:emboss and w:imprint set TextRelief and suppress legacy shadow/outline.
    let (emboss_face, _) = measure_legacy_face(
        TextShadows::Scaled,
        &RunProps {
            emboss: Some(true),
            legacy_shadow: Some(true),
            legacy_outline: Some(true),
            ..base_props.clone()
        },
    );
    assert_eq!(emboss_face.relief, Some(super::TextRelief::Emboss));
    assert_eq!(emboss_face.shadow, None);
    assert_eq!(emboss_face.outline, None);

    let (imprint_face, _) = measure_legacy_face(
        TextShadows::Scaled,
        &RunProps {
            imprint: Some(true),
            ..base_props
        },
    );
    assert_eq!(imprint_face.relief, Some(super::TextRelief::Imprint));
}

#[test]
fn draws_text_reflection_and_expands_descent_when_text_shadows_scale() {
    use crate::props::TextReflection;
    use crate::quirks::TextShadows;
    let refl = TextReflection {
        blur: Length::from_points(4).unwrap(),
        distance: Length::from_points(4).unwrap(),
        start_alpha: 50_000,
        start_pos: 0,
        end_alpha: 0,
        end_pos: 50_000,
        downward: true,
    };
    let props = RunProps {
        size: Some(56),
        reflection: Some(Box::new(refl)),
        ..RunProps::default()
    };
    let (base_face, base_drawn) = measure_legacy_face(TextShadows::Unknown, &props);
    assert_eq!(
        (base_face.reflection, base_face.shadow_room, base_drawn.2),
        (None, super::ShadowRoom::default(), false)
    );

    let (scaled_face, scaled_drawn) = measure_legacy_face(TextShadows::Scaled, &props);
    let drawn = scaled_face.reflection.expect("reflection drawn");
    assert!(scaled_drawn.2);
    assert!(drawn.pivot > Length::ZERO && drawn.blur > Length::ZERO);
    assert_eq!(scaled_face.shadow_room.above, Length::ZERO);
    assert!(scaled_face.shadow_room.below > Length::ZERO);
}