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
//! Drawing a line: its glyph runs, where the PDF writer draws each glyph, and its inline
//! pictures, drawings and leaders.

use f_office_drawingml::color::on_white;
use f_office_paint::{
    FillRule, Glyph as PaintGlyph, GlyphRun, Item, Join, Outline, PathItem, Point, Rect, Turn,
};
use f_office_units::Length;
use f_office_units::scale::THOUSANDTHS;

use super::Origin;
use super::aligned_tabs::TabTexts;
use super::rules;
use super::shadow_path::{self, DevicePlace};
use super::shift::{inner_mark_shrink_before, spread_gap};
use crate::character_class::CharacterClass;
use crate::grid::{self, Device, Rounding};
use crate::layout::floating::Size;
use crate::layout::metafile::PictureCut;
use crate::layout::table::after;
use crate::layout::{Layout, TurnedGlyphs, Within, decisions};
use crate::lines::{Line, Piece, Placed, Step, is_space, stretches};
use crate::params;
use crate::props::TabKind;
use crate::text::{
    DrawnTextFill, Face, FaceIndex, FontSide, LINE_END_HYPHEN, NON_BREAKING_HYPHEN, TextRelief,
};

/// The visual order of a line's pieces as [`crate::layout::bidi::visual`] produced it, along
/// with the logical (reading-order) bounds that decide which spaces a justified line stretches.
#[derive(Clone, Copy)]
pub(super) struct VisualOrder<'a> {
    /// For each piece in visual order, whether it lies at a right-to-left bidi level (empty
    /// when every piece is left to right).
    pub(super) rtl: &'a [bool],
    /// How many pieces at the start of the visual line hold its written text.
    pub(super) written: usize,
    /// For each visual piece, its index in the logical (reading-order) line; empty when visual
    /// order equals logical order.
    pub(super) logical: &'a [usize],
    /// `(first_stretched, last_visible)` of the logical (reading-order) line, before bidi
    /// reordering.
    pub(super) stretched_bounds: (usize, Option<usize>),
}

impl VisualOrder<'_> {
    /// Visual order for a purely left-to-right line whose visual and logical orders match.
    pub(super) fn ltr(line: &Line) -> Self {
        Self {
            rtl: &[],
            written: line.written(),
            logical: &[],
            stretched_bounds: (line.first_stretched(), line.last_visible()),
        }
    }

    fn logical_index(self, visual_index: usize) -> usize {
        self.logical
            .get(visual_index)
            .copied()
            .unwrap_or(visual_index)
    }

    fn is_stretched(self, piece: &Piece, visual_index: usize) -> bool {
        stretched_space(
            piece,
            self.logical_index(visual_index),
            self.stretched_bounds,
        )
    }
}

impl Layout<'_> {
    /// Whether the glyph at `place` starts a piece of its paragraph's text, counted from
    /// `from`, and with it a new text object. In the body lines of a section with line
    /// numbers no piece starts a text object.
    fn starts_piece(&self, place: crate::text::TextPlace, from: u32) -> bool {
        let numbered = self.section.line_numbers.is_some() && self.column.cell.is_none();
        !numbered && place.starts_piece(from, self.settings.mode_rules.text_piece_length())
    }

    /// Whether the PDF writer counts `glyph` as the start of a run of text in reading order: at
    /// a run of the document, at a piece of its paragraph's text counted from `from`, and
    /// after a format character that the shaper leaves out where the target starts a text
    /// object there.
    fn starts_text(&self, glyph: &crate::text::Glyph, from: u32) -> bool {
        self.device.writer_run_start(
            glyph.starts_run || self.starts_piece(glyph.place, from),
            glyph.left_out_before,
        )
    }

    /// Draws a line of a paragraph from `origin`, in the visual order of its paragraph's
    /// direction.
    pub(super) fn emit_visual(
        &mut self,
        line: &Line,
        origin: Origin,
    ) -> (DrawnSteps, Option<Length>) {
        let stretched_bounds = (line.first_stretched(), line.last_visible());
        let visual = crate::layout::bidi::visual(line, origin.right_to_left.is_some());
        let order = VisualOrder {
            rtl: &visual.right_to_left,
            written: visual.written,
            logical: &visual.order,
            stretched_bounds,
        };
        let (mut drawn, end) = self.emit(&visual.line, order, origin);
        drawn.order = visual.order;
        (drawn, end)
    }

    /// Draws the pieces of a line in visual order from `origin`, where `order` gives each
    /// piece's bidi direction, the written piece count, and the logical stretched-space bounds.
    /// Returns what lies before each glyph that it draws and the glyph's character spacing,
    /// with the place where the device's steps end the line's written text (`None` on a
    /// target that keeps the PDF writer's steps). The glyph places count in `Length` up to the
    /// writer's steps ([`drawn_x`]) and the device's steps ([`EdgeGlyphs`]), which count in
    /// half-EMUs as the grid does.
    pub(super) fn emit(
        &mut self,
        line: &Line,
        order: VisualOrder<'_>,
        origin: Origin,
    ) -> (DrawnSteps, Option<Length>) {
        let tabs = self.tab_texts(line, order, origin);
        let (drawn, end, _) = self.emit_with(line, order, origin, tabs);
        (drawn, end)
    }

    /// Draws the pieces of a line as [`Self::emit`] does, where `tabs` finds or places the
    /// text after its tabs to right and center stops, and returns it with what `emit` returns.
    pub(super) fn emit_with(
        &mut self,
        line: &Line,
        order: VisualOrder<'_>,
        origin: Origin,
        tabs: TabTexts,
    ) -> (DrawnSteps, Option<Length>, TabTexts) {
        let (rtl, written) = (order.rtl, order.written);
        self.east_asian_axis = self.east_asian_axis(line);
        // A run's fill and lines span the glyphs before the spaces at the line's visual end.
        let spanned = line.written();
        let mut run: Option<RunBuilder> = None;
        let mut drawn: Option<Drawn> = None;
        let mut objects = grid::TextObjects::default();
        let mut edge_steps = EdgeGlyphs::of_line(&self.device, (&origin, line, order), tabs);
        let (mut steps, mut parts) = (Steps::default(), LigatureParts::default());
        let departures = self.width_departures(line, order, origin.space_extra);
        let exact = exact_places(line, order, origin, &departures);
        let trailing = self.trailing_space(line, (&exact, rtl), &origin);
        let stretches = self.right_to_left_stretches(line, &exact, rtl, origin.mark);
        let marks = self.object_marks(line, (rtl, &stretches), &origin, &edge_steps);
        let mut stretches = stretches.into_iter().peekable();
        let mut from_right = RightToLeftPlaces::of(line.placed.len());
        self.glyph_places.clear();
        // Whether the glyph before lies in right-to-left text, and whether it starts a run or
        // a piece of the text.
        let mut before: Option<(bool, bool)> = None;
        for (index, (placed, &(x, stretch))) in line.placed.iter().zip(&exact).enumerate() {
            steps.piece(
                placed,
                origin.space_extra != Length::ZERO && order.is_stretched(&placed.piece, index),
            );
            self.tab(
                (placed, x),
                origin.baseline,
                (&mut edge_steps, &mut steps),
                &mut run,
            );
            self.picture(placed.piece, x, origin);
            self.inline_drawing(placed.piece, x, origin);
            self.draw_lines_of(placed.piece, x, origin.baseline);
            let Some(glyph) = self.drawn_glyph(placed.piece) else {
                drawn = None;
                objects.restart();
                edge_steps.gap(&self.device, (index, placed, &origin), run.as_mut());
                continue;
            };
            edge_steps.after_label = glyph.label;
            if parts.take(&glyph, rtl.get(index) == Some(&true), run.as_mut()) {
                continue;
            }
            if run.as_ref().is_some_and(|r| r.face != glyph.face) {
                edge_steps.finish(run.as_mut());
                self.flush(run.take(), origin.baseline);
                drawn = None;
            }
            let (size, em, stand_in) = self.face_numbers(&glyph);
            // quirk: GridAdvances (src/quirks.rs), whose variant the device carries.
            // In a face that stands in for the named font, a size off the grid keeps its exact
            // places: there Word's places drift from the exact ones in a way that is still open.
            let off_grid = self.device.snap(size) != size;
            let text_start = self.starts_text(&glyph, origin.text_from);
            let right_to_left = edge_steps.numbers.is_some() && rtl.get(index) == Some(&true);
            let starts = run.is_none() || visual_start(text_start, right_to_left, before);
            before = Some((right_to_left, text_start));
            marks.tell(index, &mut objects, &mut edge_steps.objects);
            // The writer starts each text object at its first glyph's exact place.
            if self.starts_object(&mut objects, &mut steps, &glyph, (starts, run.is_none())) {
                drawn = None;
            }
            if let Some(stretch) =
                stretches.next_if(|s| s.glyphs.first().is_some_and(|g| g.piece == index))
            {
                edge_steps.place_stretch(&self.device, &stretch, &mut from_right);
            }
            let previous = drawn.filter(|_| !stand_in || !off_grid);
            let stepped = edge_steps.numbers.is_some() && from_right.place(index).is_none();
            let pdf_steps = drawn_x(&self.device, previous, (x, placed.advance), (size, em));
            // A glyph of right-to-left text took its device step in its stretch's steps.
            if from_right.place(index).is_none() {
                edge_steps.tell(self.device_step(&glyph, size), index);
            }
            edge_steps.last_glyph = steps.trailing(&glyph, index, trailing);
            edge_steps.nominal_steps = self.steps_at_nominal_size(&glyph);
            let at = edge_steps
                .place(
                    &self.device,
                    (x, placed.advance, size, stretch),
                    (
                        glyph.ch,
                        glyph.side,
                        starts,
                        glyph.written,
                        self.steps_extra(&glyph),
                    ),
                    (index, from_right.place(index), marks.is_off_baseline(index)),
                    run.as_mut(),
                )
                .unwrap_or(pdf_steps.at);
            let records = edge_steps.records(stepped, from_right.take_check(index));
            drawn = Some(Drawn { at, ..pdf_steps });
            if stepped {
                steps.placed(edge_steps.edge.started(), glyph.ch.is_whitespace());
            }
            steps.glyph(&glyph, (x, at), records);
            let builder = run.get_or_insert_with(|| RunBuilder::new(glyph.face));
            edge_steps.after_written(index >= written, at);
            let glyph_of_piece = (glyph.ch, glyph.id, Some(index));
            builder.push(glyph_of_piece, at, placed, index >= spanned);
            builder.shift_last(self.placement(&glyph, (placed.advance, size), right_to_left));
            parts.join_to(builder);
        }
        let closed = self.close_line(line, &exact, run, (steps, edge_steps), origin, written);
        self.east_asian_axis = None;
        closed
    }

    /// Ends the drawing of `line` from `origin`, whose pieces lie at `exact` and whose first
    /// `written` pieces are written: draws its last `run` and its tab texts, and returns its
    /// drawn steps with the edges of its pieces, where its drawn text ends, and its tab texts.
    fn close_line(
        &mut self,
        line: &Line,
        exact: &[(Length, Length)],
        mut run: Option<RunBuilder>,
        (mut steps, mut edge_steps): (Steps, EdgeGlyphs),
        origin: Origin,
        written: usize,
    ) -> (DrawnSteps, Option<Length>, TabTexts) {
        edge_steps.finish(run.as_mut());
        self.flush(run, origin.baseline);
        edge_steps.tabs.close(&self.device, &edge_steps.edge);
        let end = edge_steps.end(&self.device, written_end(line, exact, (origin.x, written)));
        steps.drawn.edges = piece_edges(line, exact, std::mem::take(&mut self.glyph_places));
        (steps.drawn, end, edge_steps.tabs)
    }

    /// The size of the face of `glyph`, its units per em and whether it stands in for the named
    /// font: zero, 1 and false for a face that the shaper does not hold.
    fn face_numbers(&self, glyph: &crate::text::Glyph) -> (Length, i64, bool) {
        self.shaper
            .faces()
            .get(glyph.face)
            .map_or((Length::ZERO, 1, false), |face| {
                (
                    face.size,
                    i64::from(face.metrics.units_per_em),
                    face.standing.font,
                )
            })
    }

    /// How far the device draws `glyph` off its step, of `advance` in its line at `size`: its
    /// shaped placement as [`Device::placement`] takes it, in right-to-left text or not.
    fn placement(
        &self,
        glyph: &crate::text::Glyph,
        (advance, size): (Length, Length),
        right_to_left: bool,
    ) -> (Length, Length) {
        let placed = grid::PlacedGlyph {
            right_to_left,
            advance,
            own: self.shaper.own_advance(glyph).unwrap_or(Length::ZERO),
            size,
        };
        self.device.placement(glyph.offset, placed)
    }

    /// Whether `glyph` steps at its nominal size: a glyph of a run with a character scale
    /// (`w:w`) other than 100% on a target whose device counts those steps so.
    fn steps_at_nominal_size(&self, glyph: &crate::text::Glyph) -> bool {
        let scale = self
            .shaper
            .faces()
            .get(glyph.face)
            .and_then(|face| face.scale);
        decisions::nominal_steps(&self.context.quirks, scale)
            .is_some_and(|percent| percent > 0 && percent != f_office_units::scale::PERCENT)
    }

    /// What the device steps in whole dots on its own after `glyph`: the character spacing that
    /// the glyph carries, the pair kerning of a kerned run that steps so
    /// ([`crate::text::Shaper::kerning_on_its_own`]), and any East Asian auto-space stepped on its
    /// own (`EastAsianAutoSpace::AverageWidthHalf`).
    fn steps_extra(&self, glyph: &crate::text::Glyph) -> Length {
        glyph.spacing + self.shaper.kerning_on_its_own(glyph) + glyph.auto_space
    }

    /// The width of `glyphs` on the device when each lies one step after the glyph before and
    /// no edge check moves one: the sum of their steps ([`grid::EdgeSteps::alone_step`]), each
    /// with the bias of the device's steps unless its face steps without it.
    pub(super) fn alone_width(&self, glyphs: &[crate::text::Glyph]) -> Length {
        let bias = match self.device.advances() {
            crate::grid::Advances::RightEdge { bias, .. } => bias,
            crate::grid::Advances::PdfSteps => Length::ZERO,
        };
        glyphs.iter().fold(Length::ZERO, |width, glyph| {
            let (size, _, _) = self.face_numbers(glyph);
            let step = self.device_step(glyph, size);
            let bias = if step.without_bias {
                Length::ZERO
            } else {
                bias
            };
            let measured = step.measured.map(|(dots, _)| dots);
            width + grid::EdgeSteps::alone_step(&self.device, (size, glyph.advance), measured, bias)
        })
    }

    /// How the device steps `glyph` at `size` ([`DeviceStep`]): by the target's device width in
    /// dots with the glyph's advance, for a face whose instructions give it
    /// ([`crate::text::Shaper::device_width`]), whether without the bias
    /// ([`crate::text::Shaper::steps_without_bias`]), and what rounding took from the glyph's
    /// advance, which the edge check counts in its exact places
    /// ([`crate::text::Shaper::advance_rounding`]). The size in dots per em is the size that
    /// the device draws.
    fn device_step(&self, glyph: &crate::text::Glyph, size: Length) -> DeviceStep {
        let per_em = self.device.count(size, Rounding::HalfUp);
        // The shaper gives the glyph's advance in half-EMUs.
        let measured = self
            .shaper
            .device_width(
                glyph.face,
                self.shaper.width_glyph(glyph),
                (size.units(), per_em),
            )
            .map(|(dots, advance)| (dots, Length::from_units(advance)));
        // quirk: SyntheticBoldWidth (src/quirks.rs): a synthetic bold glyph's extra, which the
        // edge check and the segment rule count, and the ease of one dot by which its edge
        // check moves it right sooner.
        let counted_extra = self.shaper.bold_counted_extra(glyph);
        DeviceStep {
            size,
            measured,
            without_bias: self.shaper.steps_without_bias(glyph.face),
            rounding: self.shaper.advance_rounding(glyph),
            spacing: glyph.spacing,
            counted_extra,
            short_ease: if counted_extra.is_some() {
                self.device.dots(1)
            } else {
                Length::ZERO
            },
        }
    }

    /// What each piece of `line` takes beyond the equal share `each` of the line's stretched
    /// spaces ([`width_departures`]), where the target shares the free space by the spaces'
    /// widths first and the mode rules let it: nothing elsewhere, where each space takes the
    /// same share.
    fn width_departures(&self, line: &Line, order: VisualOrder<'_>, each: Length) -> Vec<Length> {
        if !self.settings.mode_rules.shares_stretched_spaces_by_quirk() {
            return Vec::new();
        }
        decisions::width_first_share(&self.context.quirks, || width_departures(line, order, each))
            .unwrap_or_default()
    }

    /// The index of the line's last visible piece and the space after it, by which the device
    /// draws that piece's glyph (`AlignedEnds::OnDots`, or
    /// `SpacedLastGlyph::EdgeLimit` after stretched spaces): on a target with one of those
    /// variants, on a filled justified line of left-to-right text, where the glyph has no
    /// character spacing and a drawn space follows it. `exact` holds the exact places of the
    /// line's pieces, and `rtl` says for each whether it lies in right-to-left text. What comes
    /// right before the glyph decides which rule moves it ([`Steps::trailing`]).
    fn trailing_space(
        &self,
        line: &Line,
        (exact, rtl): (&[(Length, Length)], &[bool]),
        origin: &Origin,
    ) -> Option<(usize, TrailingSpace)> {
        let justified = origin.space_extra != Length::ZERO && origin.right_to_left.is_none();
        let index = self
            .device
            .last_glyph_to_move(line.last_visible())
            .filter(|_| justified)?;
        let in_rtl = |at: usize| rtl.get(at) == Some(&true);
        let last = line
            .placed
            .get(index)
            .filter(|_| !in_rtl(index) && !in_rtl(index + 1))?;
        self.drawn_glyph(last.piece)
            .filter(|glyph| glyph.spacing == Length::ZERO)?;
        let next = line.placed.get(index + 1).filter(|p| is_space(&p.piece))?;
        let space = self.drawn_glyph(next.piece).filter(|space| !space.part)?;
        let &(x, _) = exact.get(index + 1)?;
        let step = self.device_step(&space, self.size_of(&space));
        Some((
            index,
            TrailingSpace {
                x,
                end: x + origin.space_rest,
                edge: origin.edge,
                advance: next.advance,
                spacing: space.spacing,
                step,
            },
        ))
    }

    /// The size of the face of `glyph`, or zero when the shaper has no such face.
    fn size_of(&self, glyph: &crate::text::Glyph) -> Length {
        self.shaper
            .faces()
            .get(glyph.face)
            .map_or(Length::ZERO, |face| face.size)
    }

    /// The pieces of `line` whose text-object boundaries come from reading-order counting in
    /// each of its `stretches` of right-to-left text ([`Device::right_to_left_object_starts`]),
    /// where `from` is the text place at which the line's text starts.
    fn right_to_left_object_marks(
        &self,
        line: &Line,
        stretches: &[Stretch],
        from: u32,
    ) -> RtlObjectMarks {
        let mut marks = RtlObjectMarks::of(line.placed.len());
        for stretch in stretches {
            let drawn: Vec<Option<crate::text::Glyph>> = stretch
                .glyphs
                .iter()
                .map(|g| {
                    line.placed
                        .get(g.piece)
                        .and_then(|placed| self.drawn_glyph(placed.piece))
                })
                .collect();
            let glyphs: Vec<(char, FontSide, bool)> = drawn
                .iter()
                .enumerate()
                .map(|(at, glyph)| {
                    let Some(glyph) = glyph else {
                        return ('\0', FontSide::Open, false);
                    };
                    let face_change = drawn
                        .get(at + 1)
                        .and_then(|next| next.as_ref())
                        .is_some_and(|next| next.face != glyph.face);
                    (
                        self.device.writer_char(glyph.ch),
                        self.device.writer_side(glyph.side),
                        face_change || self.starts_text(glyph, from),
                    )
                })
                .collect();
            let starts = self.device.right_to_left_object_starts(&glyphs);
            if !starts.reading_order {
                continue;
            }
            for ((g, full), after_spaces) in stretch
                .glyphs
                .iter()
                .zip(starts.full)
                .zip(starts.after_spaces)
            {
                if let Some(mark) = marks.reading_order.get_mut(g.piece) {
                    *mark = true;
                }
                if full && let Some(mark) = marks.full.get_mut(g.piece) {
                    *mark = true;
                }
                if after_spaces && let Some(mark) = marks.after_spaces.get_mut(g.piece) {
                    *mark = true;
                }
            }
        }
        marks
    }

    /// Where the PDF writer starts text objects on `line` beside the starts that its drawing
    /// finds glyph by glyph: after a full object or leading spaces in reading order
    /// ([`Self::right_to_left_object_marks`]), and at each glyph of an object of right-to-left
    /// text with a glyph one dot or more off the baseline ([`Device::object_per_glyph`],
    /// [`off_baseline_marks`]). `rtl` says for each piece whether it lies in right-to-left text,
    /// `stretches` are the line's stretches of such text, and `edge_steps` says whether the line
    /// takes the device's steps.
    fn object_marks(
        &self,
        line: &Line,
        (rtl, stretches): (&[bool], &[Stretch]),
        origin: &Origin,
        edge_steps: &EdgeGlyphs,
    ) -> ObjectMarks {
        let rtl_marks = self.right_to_left_object_marks(line, stretches, origin.text_from);
        let steps = edge_steps.numbers.is_some();
        let pieces: Vec<ObjectPiece> = (line.placed.iter().enumerate())
            .map(|(index, placed)| {
                let glyph = self.drawn_glyph(placed.piece);
                match (placed.piece, glyph) {
                    (Piece::Tab(Some(_)) | Piece::PositionTab(Some(_), _), _) => ObjectPiece::Tab,
                    (_, None) => ObjectPiece::Gap,
                    (_, Some(glyph)) => {
                        let in_rtl = rtl.get(index) == Some(&true);
                        let right_to_left = steps && in_rtl;
                        let (size, _, _) = self.face_numbers(&glyph);
                        let facts = ObjectGlyph {
                            face: glyph.face,
                            ch: self.device.writer_char(glyph.ch),
                            side: self.device.writer_side(glyph.side),
                            right_to_left,
                            text_start: self.starts_text(&glyph, origin.text_from),
                            off: (self.device).object_per_glyph(
                                glyph.offset.1,
                                size,
                                right_to_left,
                            ),
                        };
                        if glyph.part {
                            ObjectPiece::Part {
                                in_rtl,
                                glyph: facts,
                            }
                        } else {
                            ObjectPiece::Glyph(facts)
                        }
                    }
                }
            })
            .collect();
        let off_baseline = off_baseline_marks(&pieces, &rtl_marks);
        ObjectMarks {
            rtl: rtl_marks,
            off_baseline,
        }
    }

    /// The stretches of right-to-left text on a line, where `rtl` says for each piece whether
    /// it lies in such text and `mark` that the line ends its paragraph. A piece with a width
    /// that is not a drawn glyph ends a stretch, as it ends the steps of left-to-right text.
    fn right_to_left_stretches(
        &self,
        line: &Line,
        exact: &[(Length, Length)],
        rtl: &[bool],
        mark: bool,
    ) -> Vec<Stretch> {
        let mut stretches: Vec<Stretch> = Vec::new();
        let mut open = false;
        let pieces = line.placed.iter().zip(exact).zip(rtl).enumerate();
        for (index, ((placed, &(x, stretch)), &right_to_left)) in pieces {
            let glyph = self.drawn_glyph(placed.piece);
            let advance = placed.advance + stretch;
            let gap = glyph.is_none() && placed.advance != Length::ZERO;
            if !right_to_left || gap {
                if let Some(last) = stretches.last_mut().filter(|_| open) {
                    last.next = glyph.filter(|g| !g.part).map_or(After::Other, |g| {
                        After::Glyph(advance, self.device_step(&g, self.size_of(&g)))
                    });
                }
                open = false;
                continue;
            }
            let Some(glyph) = glyph.filter(|glyph| !glyph.part) else {
                continue;
            };
            let glyph = StretchGlyph {
                piece: index,
                x,
                advance,
                stretch,
                device: self.device_step(&glyph, self.size_of(&glyph)),
            };
            match stretches.last_mut() {
                Some(last) if open => last.glyphs.push(glyph),
                _ => stretches.push(Stretch {
                    glyphs: vec![glyph],
                    next: if mark { After::Mark } else { After::Other },
                }),
            }
            open = true;
        }
        stretches
    }

    /// The glyph of a piece, when the line draws it. The text of a phantom of an equation that
    /// is not shown takes its room and draws nothing.
    /// Whether the writer starts a text object at `glyph`, where `starts` says that the glyph
    /// starts a run of the document or of the line and `glyph_run` a run of the line's glyphs;
    /// `steps` records why.
    fn starts_object(
        &self,
        objects: &mut crate::grid::TextObjects,
        steps: &mut Steps,
        glyph: &crate::text::Glyph,
        (starts, glyph_run): (bool, bool),
    ) -> bool {
        let started = objects.starts(
            self.device.writer_char(glyph.ch),
            self.device.writer_side(glyph.side),
            starts,
        );
        if started {
            steps.object_started(objects.reason(), glyph_run, glyph);
        }
        started
    }

    fn drawn_glyph(&self, piece: Piece) -> Option<crate::text::Glyph> {
        let Piece::Glyph(glyph) = piece else {
            return None;
        };
        let phantom = self
            .shaper
            .faces()
            .get(glyph.face)
            .is_some_and(|face| face.math.phantom);
        (!phantom).then_some(glyph)
    }

    /// Paints the picture of an inline object that starts at `x`, with the bottom of the
    /// object's box on the exact baseline, or raised or lowered with its run. A picture that
    /// drops stands `drop` lower.
    fn picture(&mut self, piece: Piece, x: Length, origin: Origin) {
        let Piece::Object {
            width,
            height,
            raised,
            picture: Some(index),
            ..
        } = piece
        else {
            return;
        };
        let Some(picture) = self.output.pictures.get(index).cloned() else {
            return;
        };
        let drop = if picture.drops {
            origin.drop
        } else {
            Length::ZERO
        };
        // A picture stands on the exact baseline and starts at the exact place of its line,
        // neither of which lands on the device grid, unless its image lies on the device's dots.
        let top = origin.unrounded_baseline + drop - height - raised;
        let exact_x = x + origin.grid_shift;
        let upright = match self.column.within {
            Within::TurnedFrame(_, turn, _) => {
                decisions::upright_picture(&self.context.quirks, turn)
            }
            Within::Page | Within::Cell(_) => None,
        };
        // A picture that reaches past its line's box can show only inside it; in a text box or
        // a frame, only inside the box's text area.
        let line_band = self.line_band;
        let story = self.story.as_ref().map(|story| &story.kind);
        let band = decisions::inline_picture_cut(&self.context.quirks, || match story {
            Some(
                crate::layout::StoryKind::TextBox { inside, .. }
                | crate::layout::StoryKind::Frame { inside },
            ) => inside.map(PictureCut::Box),
            _ => line_band.map(|(top, bottom)| PictureCut::Line(top, bottom)),
        });
        let items = match upright {
            Some(turn) => self.upright_picture(&picture, (exact_x, top, width, height), turn),
            None if picture.lies_on_device_dots() => {
                let bottom = origin.baseline + drop - raised;
                self.picture_on_dots(&picture, (x, bottom), (top, band))
            }
            None => self.picture_items_in(&picture, exact_x, top, band),
        };
        self.items.extend(items);
    }

    /// Draws a picture whose image lies on the device's dots (`Picture::lies_on_device_dots`): its
    /// left edge on the dot of its place `x` on its line, its bottom on the dot of `bottom`, the
    /// line's baseline on the device with the picture's drop and raise, and its width and
    /// height in the nearest whole dots, a half up; then each edge in the nearest twip, a half
    /// up. Its image shows nothing outside `band`, where it has one, taken along with the
    /// picture from its exact place, whose room has its top at `exact_top`.
    fn picture_on_dots(
        &mut self,
        picture: &crate::picture::Picture,
        (x, bottom): (Length, Length),
        (exact_top, band): (Length, Option<PictureCut>),
    ) -> Vec<Item> {
        let device = self.device;
        let (left, bottom) = (device.snap(x), device.snap(bottom));
        let (right, top) = (
            left + device.snap(picture.width),
            bottom - device.snap(picture.height),
        );
        let [left, top, right, bottom] =
            [left, top, right, bottom].map(|edge| edge.nearest_whole(Length::UNITS_PER_TWIP));
        let mut drawn = picture.clone();
        (drawn.width, drawn.height) = (right - left, bottom - top);
        // A line's box moves with the picture's own edges, so that it cuts the picture on the
        // dots where it cuts the picture at its exact place.
        let exact_top = exact_top + picture.top;
        let exact_bottom = exact_top + picture.height;
        let band = band.map(|band| band.moved((top - exact_top, bottom - exact_bottom)));
        self.picture_items_in(&drawn, left - picture.left, top - picture.top, band)
    }

    /// Draws a picture in the frame of a turned cell whose turn onto the page is `turn`, in its
    /// room from `(x, top)`, `width` long on its line and `height` across it, which takes the
    /// picture's height along the line and its width across. The picture stays upright on the
    /// page, and the frame's turn moves only its centre, so its own box is drawn about the
    /// centre of its room. For text that reads up the room lies at its mirror place along the
    /// frame: as far from the frame's end as the line puts it from the start.
    fn upright_picture(
        &mut self,
        picture: &crate::picture::Picture,
        (x, top, width, height): (Length, Length, Length, Length),
        turn: f_office_paint::Turn,
    ) -> Vec<Item> {
        let half = |length: Length| length.div_toward_zero(2);
        let along = x + half(width);
        let along = if turn == crate::layout::table::UP {
            self.column.left + self.column.left + self.column.width - along
        } else {
            along
        };
        // The picture's own box is as wide as its room is high, and as high as the room is
        // long.
        self.picture_items(
            picture,
            along - half(height),
            top + half(height) - half(width),
        )
    }

    /// Draws the shape and the text box of an inline drawing that starts at `x`, with the
    /// bottom of its room on the baseline, or raised or lowered with its run, in the order of
    /// the text. A drawing that drops stands `drop` lower.
    fn inline_drawing(&mut self, piece: Piece, x: Length, origin: Origin) {
        let Piece::Object {
            height,
            raised,
            drawing: Some(index),
            ..
        } = piece
        else {
            return;
        };
        let Some(drawing) = self.output.drawing(index).cloned() else {
            return;
        };
        let drop = if drawing.drops {
            origin.drop
        } else {
            Length::ZERO
        };
        let size = Size::of(&drawing.shape);
        // A shape with an anchor lock stands inside its outline's room, placed from the room's
        // bottom; another shape that takes such a room stands at its top left corner.
        let (left, top, size) = if let Some((bottom, room)) = origin
            .anchor_bottom
            .filter(|_| drawing.anchor_locked)
            .and_then(|bottom| self.anchor_room(index).map(|room| (bottom, room)))
        {
            // The shape takes the height of its room, and the drawing stays as it is.
            (
                x + room.above,
                bottom.nearest_whole(Length::UNITS_PER_TWIP) - room.below,
                size.with_height(room.height),
            )
        } else {
            (
                x + drawing.left,
                origin.baseline + drop - height - raised + drawing.top,
                size,
            )
        };
        let items = self.draw_sized((&drawing.shape, size), left, top);
        self.items.extend(items);
    }

    /// Draws a tab's leader and its marks at `x`. A tab ends the run before it, so that the
    /// run's fill and lines stop at the tab, and the tab draws those of its own run.
    fn tab(
        &mut self,
        (placed, x): (&Placed, Length),
        baseline: Length,
        (edge_steps, steps): (&mut EdgeGlyphs, &mut Steps),
        run: &mut Option<RunBuilder>,
    ) {
        let (Piece::Tab(Some(face)) | Piece::PositionTab(Some(face), _)) = placed.piece else {
            return;
        };
        let span = (x, placed.advance);
        if let Some(ch) = placed.leader {
            edge_steps.finish(run.as_mut());
            self.flush(run.take(), baseline);
            self.leader(face, ch, span, (baseline, steps));
        }
        edge_steps.finish(run.as_mut());
        self.flush(run.take(), baseline);
        self.tab_marks(face, span, baseline);
    }

    /// Fills a tab's space with leader characters that end where the tab ends. The PDF writer
    /// draws a leader in text objects of [`params::LEADER_OBJECT_GLYPHS`] characters, counted
    /// from its first character. Each object starts at its first character's place, and the
    /// writer steps the characters after it as it steps text. The line's record `steps` gets
    /// each character.
    fn leader(
        &mut self,
        face: FaceIndex,
        ch: char,
        (x, width): (Length, Length),
        (baseline, steps): (Length, &mut Steps),
    ) {
        let Some(glyph) = self.shaper.glyph(face, ch) else {
            return;
        };
        // The grid's step is the character's advance, rounded to the target's leader step.
        let step = self.device.leader_step(glyph.advance);
        if step <= Length::ZERO {
            return;
        }
        // Leader characters sit on a grid of their step from the page's left edge, and only
        // those that fit fully inside the tab are drawn. The grid counts whole steps of the
        // lengths in half-EMUs: up for the first and down for the last.
        let edge = Length::ZERO;
        let first = ((x - edge + step).units() - 1).div_euclid(step.units());
        let last = (x + width - edge).units().div_euclid(step.units());
        let count = (last - first).max(0);
        let start = edge + step * first;
        let (size, em, stand_in) =
            self.shaper
                .faces()
                .get(face)
                .map_or((Length::ZERO, 1, false), |face| {
                    (
                        face.size,
                        i64::from(face.metrics.units_per_em),
                        face.standing.font,
                    )
                });
        // As in text, a face that stands in for the named font keeps its exact places at a
        // size off the grid.
        let exact_places = stand_in && self.device.snap(size) != size;
        let mut builder = RunBuilder::new(face);
        let mut drawn: Option<Drawn> = None;
        let mut edge_steps = EdgeGlyphs::new(&self.device);
        for (index, exact) in (0..count).map(|i| start + step * i).enumerate() {
            let placed = Placed {
                piece: Piece::Glyph(glyph),
                x: Length::ZERO,
                advance: glyph.advance,
                leader: None,
                tab: None,
            };
            let starts = index % params::LEADER_OBJECT_GLYPHS == 0;
            let previous = drawn.filter(|_| !starts && !exact_places);
            let pdf_steps = drawn_x(&self.device, previous, (exact, step), (size, em));
            let at = edge_steps
                .place_leader(
                    &self.device,
                    (exact, step, size),
                    (starts, glyph.written),
                    Some(&mut builder),
                )
                .unwrap_or(pdf_steps.at);
            drawn = Some(Drawn { at, ..pdf_steps });
            steps.leader(exact, at);
            builder.push((ch, glyph.id, None), at, &placed, false);
            builder.shift_last(glyph.offset);
        }
        edge_steps.finish(Some(&mut builder));
        self.flush(Some(builder), baseline);
    }

    fn flush(&mut self, run: Option<RunBuilder>, baseline: Length) {
        let Some(mut run) = run else {
            return;
        };
        let Some(face) = self.shaper.faces().get(run.face).copied() else {
            return;
        };
        // On a centered line whose pieces' middles lie on one line, each run moves to its
        // face's place, in whole dots of the device.
        // quirk: CenteredLine::MiddlesShared (src/quirks.rs)
        let baseline = baseline
            + self
                .centered_middle
                .map_or(Length::ZERO, |middle| self.device.snap(middle.shift(&face)));
        // The highlight or shading of a run fills its text from the ascent to the descent,
        // under its lines and glyphs.
        if let (Some(color), Some((start, end))) = (face.background, run.span()) {
            self.items.push(Item::Rect(Rect {
                x: start,
                y: baseline - face.ascent(),
                width: end - start,
                height: face.ascent() + face.descent(),
                color,
            }));
        }
        let span = run.span().unwrap_or((Length::ZERO, Length::ZERO));
        let lines = rules::run_lines(&self.device, &face, (span, &run.words), baseline);
        self.items.extend(lines.into_iter().map(Item::Rect));
        let needs_outlines = face.shadow.is_some()
            || face.glow.is_some()
            || face.reflection.is_some()
            || face.relief.is_some()
            || matches!(
                face.text_fill,
                DrawnTextFill::White | DrawnTextFill::Gradient(_) | DrawnTextFill::Translucent(_)
            );
        let outline_inputs = needs_outlines.then(|| {
            let places = run.device_places(&self.device, &face, baseline);
            let size = self.device.snap(face.size);
            let turn = (self.device).glyph_turn(
                size,
                &face.metrics,
                face.scale,
                face.standing.synthetic_italic,
            );
            (places, size, turn)
        });
        // Reflection, shadow, glow, and legacy relief lie under the run's text.
        if let Some((places, size, turn)) = outline_inputs.as_ref() {
            self.emit_run_effects(&face, (*size, *turn), baseline, places);
        }
        let (filled, emit_glyphs) =
            self.emit_special_text_fill(&face, span, baseline, outline_inputs.as_ref());
        let pieces = std::mem::take(&mut run.pieces);
        let mut glyphs = run.finish(&self.device, &face, baseline, filled);
        let places = pieces.into_iter().zip(&glyphs.glyphs);
        self.glyph_places
            .extend(places.filter_map(|(piece, glyph)| piece.map(|piece| (piece, glyph.x))));
        apply_relief_shift(&mut glyphs, &face);
        if emit_glyphs {
            match (self.east_asian_axis, self.column.within) {
                (Some(axis), Within::TurnedFrame(_, turn, _)) => self.items.extend(
                    upright_east_asian(glyphs, (face.win_top(), axis), turn)
                        .into_iter()
                        .map(Item::Glyphs),
                ),
                _ => self.items.push(Item::Glyphs(glyphs)),
            }
        }
    }

    /// Emits reflection, shadow, glow, and legacy relief passes that lie behind a run's main text.
    fn emit_run_effects(
        &mut self,
        face: &Face,
        (size, turn): (Length, Option<Turn>),
        baseline: Length,
        places: &[DevicePlace],
    ) {
        let glyphs = (self.shaper.fonts(), face, size, turn);
        if let Some(reflection) = face.reflection {
            let y = baseline - self.device.shift_dots(face.rise);
            self.items
                .extend(shadow_path::reflection_item(glyphs, reflection, y, places));
        }
        match (face.shadow, face.glow) {
            (Some(shadow), Some(glow)) => {
                self.items
                    .extend(shadow_path::shadow_with_glow(glyphs, shadow, glow, places));
                self.items
                    .extend(shadow_path::glow_item(glyphs, glow, places));
            }
            (Some(shadow), None) => {
                self.items.extend(shadow_path::item(glyphs, shadow, places));
            }
            (None, Some(glow)) => {
                self.items
                    .extend(shadow_path::glow_item(glyphs, glow, places));
            }
            (None, None) => {}
        }
        if let Some(relief) = face.relief {
            self.emit_text_relief(glyphs, relief, places);
        }
    }

    /// Emits the two offset filled glyph-outline passes behind embossed (`w:emboss`) or
    /// imprinted (`w:imprint`) text.
    fn emit_text_relief(
        &mut self,
        glyphs: (&dyn crate::Fonts, &Face, Length, Option<Turn>),
        relief: TextRelief,
        places: &[DevicePlace],
    ) {
        let offset = crate::text::legacy_offset(glyphs.1.size);
        let two = offset * 2;
        let gray = params::LEGACY_TEXT_RELIEF_GRAY;
        let relief_gray = f_office_paint::Rgb {
            r: gray,
            g: gray,
            b: gray,
        };
        let passes = match relief {
            TextRelief::Emboss => [
                ((Length::ZERO, Length::ZERO), relief_gray),
                ((-two, -two), f_office_paint::Rgb::BLACK),
            ],
            TextRelief::Imprint => [
                ((two, two), f_office_paint::Rgb::BLACK),
                ((Length::ZERO, Length::ZERO), relief_gray),
            ],
        };
        for (shift, color) in passes {
            let commands = shadow_path::glyph_outlines(glyphs, shift, places);
            if !commands.is_empty() {
                self.items.push(Item::Path(PathItem {
                    commands,
                    color,
                    fill_rule: FillRule::NonZero,
                }));
            }
        }
    }

    /// Emits any vector path or gradient fill required by `face.text_fill` and returns
    /// `(filled, emit_glyphs)` for the run's `GlyphRun`.
    fn emit_special_text_fill(
        &mut self,
        face: &Face,
        span: (Length, Length),
        baseline: Length,
        outline_inputs: Option<&(Vec<DevicePlace>, Length, Option<Turn>)>,
    ) -> (bool, bool) {
        match face.text_fill {
            DrawnTextFill::Solid => (true, true),
            DrawnTextFill::None => {
                let has_stroke = face.outline.is_some() || face.standing.synthetic_bold;
                (false, has_stroke)
            }
            DrawnTextFill::White => {
                if let Some((places, size, turn)) = outline_inputs {
                    let commands = shadow_path::glyph_outlines(
                        (self.shaper.fonts(), face, *size, *turn),
                        (Length::ZERO, Length::ZERO),
                        places,
                    );
                    if !commands.is_empty() {
                        self.items.push(Item::Path(PathItem {
                            commands,
                            color: f_office_paint::Rgb::WHITE,
                            fill_rule: FillRule::NonZero,
                        }));
                    }
                }
                (false, face.outline.is_some())
            }
            DrawnTextFill::Translucent(opacity) => {
                if let Some((places, size, turn)) = outline_inputs {
                    let commands = shadow_path::glyph_outlines(
                        (self.shaper.fonts(), face, *size, *turn),
                        (Length::ZERO, Length::ZERO),
                        places,
                    );
                    if !commands.is_empty() {
                        self.items.push(Item::Path(PathItem {
                            commands,
                            color: on_white(face.color, opacity),
                            fill_rule: FillRule::NonZero,
                        }));
                    }
                }
                (false, face.outline.is_some())
            }
            DrawnTextFill::Gradient(index) => {
                let drawn = outline_inputs.and_then(|(places, size, turn)| {
                    let gradient = self.shaper.text_gradient(index)?;
                    let commands = shadow_path::glyph_outlines(
                        (self.shaper.fonts(), face, *size, *turn),
                        (Length::ZERO, Length::ZERO),
                        places,
                    );
                    if commands.is_empty() {
                        return None;
                    }
                    let corners = (
                        Point {
                            x: span.0,
                            y: baseline - face.ascent(),
                        },
                        Point {
                            x: span.1,
                            y: baseline + face.descent(),
                        },
                    );
                    gradient.fill_path(
                        commands,
                        FillRule::EvenOdd,
                        corners,
                        &self.shaper.theme().shapes.colors,
                    )
                });
                if let Some(item) = drawn {
                    self.items.push(Item::Gradient(item));
                    (false, true)
                } else {
                    (true, true)
                }
            }
        }
    }

    /// The axis of `line` where the turned frame stands the glyphs of the East Asian font side
    /// upright ([`TurnedGlyphs::EastAsianUpright`]): half the largest win ascent less the largest
    /// win descent of its faces above its baseline.
    fn east_asian_axis(&self, line: &Line) -> Option<Length> {
        let Within::TurnedFrame(_, _, TurnedGlyphs::EastAsianUpright) = self.column.within else {
            return None;
        };
        let faces = line.placed.iter().filter_map(|placed| match placed.piece {
            Piece::Glyph(glyph) => self.shaper.faces().get(glyph.face),
            _ => None,
        });
        let (top, bottom) = faces.fold((Length::ZERO, Length::ZERO), |(top, bottom), face| {
            let descent = face.scale(i64::from(face.metrics.descent));
            (top.max(face.win_top()), bottom.max(descent))
        });
        Some((top - bottom).div_toward_zero(2))
    }
}

/// Shifts a run's main glyphs by `(-d, -d)` for `w:emboss` or `(+d, +d)` for `w:imprint`.
fn apply_relief_shift(glyphs: &mut GlyphRun, face: &Face) {
    let Some(relief) = face.relief else {
        return;
    };
    let offset = crate::text::legacy_offset(face.size);
    let delta = match relief {
        TextRelief::Emboss => -offset,
        TextRelief::Imprint => offset,
    };
    for glyph in &mut glyphs.glyphs {
        glyph.x += delta;
        glyph.y += delta;
    }
}

/// The runs that draw `run` in a turned frame whose lines run down the page, turned onto it by
/// `turn`, with each row of
/// its glyphs of the East Asian font side in a run of its own that stands upright on the page
/// ([`TurnedGlyphs::EastAsianUpright`]): each of those glyphs is turned back, its em box starting
/// at its origin along the line, where its face's top `top` above the baseline lies, and centred
/// across the line on the axis `axis` above the baseline.
fn upright_east_asian(run: GlyphRun, (top, axis): (Length, Length), turn: Turn) -> Vec<GlyphRun> {
    let upright = |glyph: &PaintGlyph| {
        run.glyph_text(glyph)
            .and_then(|text| text.chars().next())
            .is_some_and(|ch| CharacterClass::EastAsianFont.contains(ch))
    };
    if !run.glyphs.iter().any(upright) {
        return vec![run];
    }
    // A quarter turn's inverse is its transpose.
    let back = Turn {
        xx: turn.xx,
        yx: turn.xy,
        xy: turn.yx,
        yy: turn.yy,
    };
    // The upright glyph's origin lies `top` along the line from the glyph's origin, and its left
    // edge half an em below the axis, which in a line that runs down the page lies down the frame.
    let shift = (top, run.size.div_toward_zero(2) - axis);
    let stood = Some(run.turn.map_or(back, |own| after(back, own)));
    let template = GlyphRun {
        text: String::new(),
        glyphs: Vec::new(),
        ..run.clone()
    };
    run.glyphs
        .chunk_by(|a, b| upright(a) == upright(b))
        .map(|row| {
            let start = row.iter().map(|g| g.text_start).min().unwrap_or(0);
            let end = row.iter().map(|g| g.text_end).max().unwrap_or(start);
            let text = usize::try_from(start)
                .ok()
                .zip(usize::try_from(end).ok())
                .and_then(|(start, end)| run.text.get(start..end))
                .unwrap_or_default()
                .to_owned();
            let stands = row.first().is_some_and(upright);
            let glyphs = row
                .iter()
                .map(|glyph| PaintGlyph {
                    x: glyph.x + if stands { shift.0 } else { Length::ZERO },
                    y: glyph.y + if stands { shift.1 } else { Length::ZERO },
                    text_start: glyph.text_start - start,
                    text_end: glyph.text_end - start,
                    ..*glyph
                })
                .collect();
            GlyphRun {
                text,
                glyphs,
                turn: if stands { stood } else { run.turn },
                ..template.clone()
            }
        })
        .collect()
}

/// The pieces that can lie between two drawn glyphs, from the weakest to the strongest: the
/// strongest names the step, and of two tabs the later one, which places the glyph. An aligned
/// tab is as strong as a tab.
const GAP_ORDER: &[Step] = &[Step::Space, Step::Stretched, Step::Object, Step::Tab];

/// The left and right edge on the page of each piece of `line`, in the order of drawing: its
/// left edge is the drawn place of its glyph that `drawn` gives by the piece's index, or else
/// its exact place in `exact`. A piece reaches to the next piece's left edge, and the last
/// piece to its exact right edge.
fn piece_edges(
    line: &Line,
    exact: &[(Length, Length)],
    drawn: Vec<(usize, Length)>,
) -> Vec<(Length, Length)> {
    let mut lefts: Vec<Length> = exact.iter().map(|&(x, _)| x).collect();
    for (index, x) in drawn {
        if let Some(left) = lefts.get_mut(index) {
            *left = x;
        }
    }
    let last = line
        .placed
        .last()
        .zip(exact.last())
        .map(|(placed, &(x, stretch))| x + placed.advance + stretch);
    lefts
        .iter()
        .enumerate()
        .map(|(index, &left)| {
            let right = lefts.get(index + 1).copied().or(last).unwrap_or(left);
            (left, right.max(left))
        })
        .collect()
}

/// What lies before each glyph that a line draws, and what the line records of the glyph, in
/// the order of drawing.
#[derive(Clone, Debug, Default)]
pub(in crate::layout) struct DrawnSteps {
    /// One step for each drawn glyph.
    pub(in crate::layout) steps: Vec<Step>,
    /// The character spacing, place and spaces before of each drawn glyph.
    pub(in crate::layout) glyphs: Vec<crate::layout::DrawnGlyph>,
    /// The exact left and right edge on the page of each piece of the line, in the order of
    /// drawing.
    pub(in crate::layout) edges: Vec<(Length, Length)>,
    /// For each piece in the order of drawing, its index in the line's own order; empty when
    /// the two orders are the same.
    pub(in crate::layout) order: Vec<usize>,
}

/// What lies before each glyph that a line draws, gathered while the line is drawn.
#[derive(Clone, Debug, Default)]
struct Steps {
    /// One step and one record for each drawn glyph so far.
    drawn: DrawnSteps,
    /// The spaces placed since the last drawn glyph.
    spaces: u32,
    /// Where the device's steps started again since the last drawn glyph.
    started: crate::layout::StepsStart,
    /// Why the writer started its first text object since the last drawn glyph, if it did.
    object_start: Option<crate::grid::ObjectStart>,
    /// The strongest piece since the last drawn glyph: a tab, then an inline object, then a
    /// space that stretches, then another space.
    gap: Option<Step>,
    /// Whether the last drawn glyph was part of a list label, or `None` before the first.
    previous: Option<bool>,
}

impl Steps {
    /// Adds a placed piece that comes before the next drawn glyph. A space stretches or shrinks
    /// when `stretches` holds.
    fn piece(&mut self, placed: &Placed, stretches: bool) {
        let piece = placed.piece;
        let step = match piece {
            Piece::Tab(_) | Piece::PositionTab(..) => match placed.tab {
                Some(TabKind::Center | TabKind::Right | TabKind::Decimal) => Step::AlignedTab,
                Some(TabKind::Left) | None => Step::Tab,
            },
            Piece::Object { .. } => Step::Object,
            Piece::Glyph(glyph) if glyph.ch.is_whitespace() => {
                self.spaces += 1;
                if stretches && crate::lines::stretches(&piece) {
                    Step::Stretched
                } else {
                    Step::Space
                }
            }
            _ => return,
        };
        let rank = |step: Step| {
            let step = if step == Step::AlignedTab {
                Step::Tab
            } else {
                step
            };
            GAP_ORDER.iter().position(|s| *s == step)
        };
        let tab = rank(step) == rank(Step::Tab);
        if self.gap.is_none_or(|gap| tab || rank(step) > rank(gap)) {
            self.gap = Some(step);
        }
    }

    /// Says that the writer started a text object at `glyph` for the `reason` that its text
    /// objects give, where `glyph_run` says that the glyph starts a run of the line's glyphs. A
    /// start for a run is a text buffer's when the glyph starts one, else the line's glyph
    /// run's, else the document run's when the glyph starts one, else a text piece's. Only the
    /// first since the last drawn glyph counts.
    fn object_started(
        &mut self,
        reason: Option<crate::grid::ObjectStart>,
        glyph_run: bool,
        glyph: &crate::text::Glyph,
    ) {
        use crate::grid::ObjectStart;
        let reason = match reason {
            Some(ObjectStart::Run) if glyph.place.starts_buffer => Some(ObjectStart::Buffer),
            Some(ObjectStart::Run) if glyph_run => Some(ObjectStart::GlyphRun),
            Some(ObjectStart::Run) if !glyph.starts_run => Some(ObjectStart::Piece),
            reason => reason,
        };
        self.object_start = self.object_start.or(reason);
    }

    /// Says that the device's steps placed a glyph, a space when `space` holds, and whether it
    /// `started` the steps again.
    fn placed(&mut self, started: bool, space: bool) {
        if started {
            self.started = if space {
                crate::layout::StepsStart::Space(self.spaces)
            } else {
                crate::layout::StepsStart::Glyph
            };
        }
    }

    /// Adds a character of a tab's leader that the line draws from the place `x` on the leader's
    /// grid at the place `place`. It takes none of the spaces, the restart or the tab that the
    /// line records for the glyph after the tab.
    fn leader(&mut self, x: Length, place: Length) {
        self.drawn.steps.push(Step::Leader);
        self.drawn.glyphs.push(crate::layout::DrawnGlyph {
            spacing: Length::ZERO,
            x,
            place,
            spaces: 0,
            started: crate::layout::StepsStart::Stepped,
            checked: None,
            object_start: None,
            start_place: None,
        });
    }

    /// How the device draws the line's last visible glyph, from `trailing`, its piece's index
    /// and the space after it ([`Layout::trailing_space`]), when `glyph`, the piece `index`, is
    /// that glyph: by the space, when it comes right after the glyph before it, and by its own
    /// exact place, when stretched spaces come right before it.
    fn trailing(
        &self,
        glyph: &crate::text::Glyph,
        index: usize,
        trailing: Option<(usize, TrailingSpace)>,
    ) -> Option<LastGlyph> {
        let (_, space) = trailing.filter(|&(at, _)| at == index)?;
        match self.next_step(glyph) {
            Step::Glyph => Some(LastGlyph::AfterGlyph(space)),
            Step::Stretched => Some(LastGlyph::AfterStretched),
            _ => None,
        }
    }

    /// What lies before `glyph`, a drawn glyph that does not show only white space, if it
    /// comes next.
    fn next_step(&self, glyph: &crate::text::Glyph) -> Step {
        match (self.previous, self.gap) {
            (None, _) if glyph.label => Step::Label,
            (None, Some(tab @ (Step::Tab | Step::AlignedTab))) => tab,
            (None, _) => Step::Start,
            (Some(true), _) if !glyph.label => Step::AfterLabel,
            (Some(_), gap) => gap.unwrap_or(Step::Glyph),
        }
    }

    /// Adds a glyph that the line draws from the unrounded place `x` at the place `place` that
    /// its steps give it, with what their edge check found at it and the place that they
    /// rounded to its dot when they started again at it, unless it shows only white space. The first glyph after a tab that starts the line takes the tab's step, since the
    /// tab's stop places it.
    fn glyph(
        &mut self,
        glyph: &crate::text::Glyph,
        (x, place): (Length, Length),
        (checked, start_place): (Option<crate::grid::EdgeCheck>, Option<Length>),
    ) {
        if glyph.ch.is_whitespace() {
            return;
        }
        let step = self.next_step(glyph);
        self.gap = None;
        self.drawn.steps.push(step);
        self.drawn.glyphs.push(crate::layout::DrawnGlyph {
            spacing: glyph.spacing,
            x,
            place,
            spaces: std::mem::take(&mut self.spaces),
            started: std::mem::take(&mut self.started),
            object_start: self.object_start.take(),
            checked,
            start_place,
        });
        self.previous = Some(glyph.label);
    }
}

/// A glyph that a run has drawn: its exact x, the x where it is drawn, its advance, and the
/// character spacing of its text object in steps of the drawn em (`PDF_ADVANCE_STEPS`), which
/// the object's second glyph sets.
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct Drawn {
    pub(in crate::layout) exact: Length,
    pub(in crate::layout) at: Length,
    pub(in crate::layout) advance: Length,
    pub(in crate::layout) spacing: Option<i64>,
}

/// How a glyph at the exact `x` with `advance` is drawn after the glyph `previous` of its run,
/// at the nominal `size`. The first glyph of a run keeps its exact place.
///
/// Word's PDFs write each advance as the font's width in thousandths of an em plus a
/// correction. At a size on the device grid the correction has one decimal, so the advance
/// rounds to 1/10,000 em, and kerning and the extra space of justified lines are added as they
/// are. A size off the grid is drawn at the size rounded to the grid. There each step counts
/// the glyph's advance and the kerning or character spacing after it, at the drawn size and
/// rounded to 1/10,000 em, less the glyph's width; the first glyph's gives the text object its
/// character spacing (`Tc`). Each step is the glyph's width, the spacing, and a correction in
/// whole thousandths: the spacing less the glyph's own count, rounded half away from zero. The
/// rounding of one step does not carry to the next, so the glyphs drift from their exact
/// places along the object.
pub(in crate::layout) fn drawn_x(
    device: &Device,
    previous: Option<Drawn>,
    (x, advance): (Length, Length),
    (size, units_per_em): (Length, i64),
) -> Drawn {
    let drawn = device.snap(size);
    let steps = params::PDF_ADVANCE_STEPS;
    let per_step = steps / THOUSANDTHS;
    // The advance in font units, which the advance at the nominal size, rounded to a unit of
    // length, still gives exactly, so that the rounding to steps sees the font's own number.
    // The counts in font units and in steps of the em multiply the lengths in half-EMUs.
    let em = units_per_em.max(1);
    let units =
        |advance: Length| f_office_units::div_round(advance.units() * em, size.units().max(1));
    let width =
        |advance: Length| f_office_units::div_round(units(advance) * THOUSANDTHS, em) * per_step;
    let at = |at, spacing| Drawn {
        exact: x,
        at,
        advance,
        spacing,
    };
    // quirk: GridAdvances::RoundToPdfSteps (src/quirks.rs)
    let Some(p) = previous else {
        return at(x, None);
    };
    let kern = x - p.exact - p.advance;
    if drawn == size {
        let tenths = f_office_units::div_round(p.advance.units() * steps, size.units());
        return at(p.at + (size * tenths).div_round(steps) + kern, None);
    }
    // The distance to this glyph at the drawn size, the advance and the kerning or spacing
    // after it, in steps of the drawn em, less the width in steps. The first glyph's sets the
    // object's character spacing.
    let excess = f_office_units::div_round(
        (units(p.advance) * size.units() + kern.units() * em) * steps,
        em * drawn.units().max(1),
    ) - width(p.advance);
    let spacing = p.spacing.unwrap_or(excess);
    let ideal = spacing - excess;
    let correction = ideal.signum() * f_office_units::div_round(ideal.abs(), per_step) * per_step;
    let step = width(p.advance) + spacing - correction;
    at(p.at + (drawn * step).div_round(steps), Some(spacing))
}

/// For each piece of `line`, whether it is the first glyph of a footnote's reference mark: the
/// first of the glyphs right before the footnote's mark without width that share the face of
/// the last of them, the mark's own face at its raised size.
fn note_mark_starts(line: &Line) -> Vec<bool> {
    let glyph_at = |k: usize| match line.placed.get(k) {
        Some(Placed {
            piece: Piece::Glyph(glyph),
            ..
        }) => Some(*glyph),
        _ => None,
    };
    let mut starts = vec![false; line.placed.len()];
    for (index, placed) in line.placed.iter().enumerate() {
        if !matches!(placed.piece, Piece::Note(_)) {
            continue;
        }
        let Some(last) = index.checked_sub(1).filter(|&k| glyph_at(k).is_some()) else {
            continue;
        };
        let face = glyph_at(last).map(|glyph| glyph.face);
        let mut first = last;
        while let Some(before) = first.checked_sub(1) {
            if glyph_at(before).map(|glyph| glyph.face) != face {
                break;
            }
            first = before;
        }
        if let Some(start) = starts.get_mut(first) {
            *start = true;
        }
    }
    starts
}

/// The characters of the parts of a ligature that wait for the ligature's glyph. A part of a
/// ligature draws nothing, and its character joins the ligature's text. In right-to-left text
/// the line draws the ligature after its parts, so their characters wait for it.
#[derive(Default)]
struct LigatureParts(Vec<char>);

impl LigatureParts {
    /// Takes `glyph` when it is a part of a ligature: in right-to-left text, as `right_to_left`
    /// says, its character waits for the ligature; else it joins the text of the last glyph of
    /// `run`. Whether it took the glyph; a part with no glyph drawn before it in left-to-right
    /// text is drawn as a glyph.
    fn take(
        &mut self,
        glyph: &crate::text::Glyph,
        right_to_left: bool,
        run: Option<&mut RunBuilder>,
    ) -> bool {
        if !glyph.part {
            return false;
        }
        if right_to_left {
            self.0.push(glyph.ch);
            return true;
        }
        run.map(|builder| builder.join(glyph.ch)).is_some()
    }

    /// Joins the waiting characters to the text of the glyph that `builder` drew last, the
    /// ligature, after its own character, in the order of the text: the reverse of the order
    /// in which the line drew them.
    fn join_to(&mut self, builder: &mut RunBuilder) {
        for ch in self.0.drain(..).rev() {
            builder.join(ch);
        }
    }
}

struct RunBuilder {
    face: FaceIndex,
    text: String,
    glyphs: Vec<PaintGlyph>,
    /// For each glyph, its place on the device: where it lies when it is pushed, before the
    /// PDF writer moves it to its own place once its text object ends ([`Self::redraw_last`]).
    device_xs: Vec<Length>,
    /// For each glyph, how far the font's layout tables move it to the right of its place in
    /// the line. [`Self::finish`] adds the moves, after the writer's places are final.
    rights: Vec<Length>,
    /// The start of the first and the end of the last of its glyphs that do not trail the
    /// line's last visible one, if it has any.
    extent: Option<(Length, Length)>,
    /// The span of each word of those glyphs: of each row of glyphs without white space.
    words: Vec<(Length, Length)>,
    /// Whether the last glyph was part of a word, so that the next one joins it.
    in_word: bool,
    /// For each glyph, the index of its piece in the line, or none for a glyph of a tab's
    /// leader.
    pieces: Vec<Option<usize>>,
}

impl RunBuilder {
    fn new(face: FaceIndex) -> Self {
        Self {
            face,
            text: String::new(),
            glyphs: Vec::new(),
            device_xs: Vec::new(),
            rights: Vec::new(),
            extent: None,
            words: Vec::new(),
            in_word: false,
            pieces: Vec::new(),
        }
    }

    /// The span of the run's fill and lines: its extent, when it has some width.
    fn span(&self) -> Option<(Length, Length)> {
        self.extent.filter(|(start, end)| end > start)
    }

    /// Adds the glyph `id` of the character `ch` at `x`, of the line's piece `piece` (none for a
    /// glyph of a tab's leader), which trails the line's last visible glyph when `trailing`.
    fn push(
        &mut self,
        (ch, id, piece): (char, u32, Option<usize>),
        x: Length,
        placed: &Placed,
        trailing: bool,
    ) {
        self.pieces.push(piece);
        self.device_xs.push(x);
        let text_start = u32::try_from(self.text.len()).unwrap_or(u32::MAX);
        // A non-breaking hyphen and the hyphen of an automatic point read as a hyphen-minus in
        // Word's PDFs.
        self.text.push(match ch {
            NON_BREAKING_HYPHEN | LINE_END_HYPHEN => '-',
            _ => ch,
        });
        let text_end = u32::try_from(self.text.len()).unwrap_or(u32::MAX);
        self.glyphs.push(PaintGlyph {
            id,
            x,
            y: Length::ZERO,
            text_start,
            text_end,
        });
        self.rights.push(Length::ZERO);
        if !trailing {
            let end = x + placed.advance;
            self.extent = Some(
                self.extent
                    .map_or((x, end), |(first, last)| (first.min(x), last.max(end))),
            );
            match self.words.last_mut() {
                _ if ch.is_whitespace() => {}
                Some((first, last)) if self.in_word => {
                    *first = (*first).min(x);
                    *last = (*last).max(end);
                }
                _ => self.words.push((x, end)),
            }
        }
        self.in_word = !ch.is_whitespace();
    }

    /// Moves the last glyphs to `xs`, one for each.
    fn redraw_last(&mut self, xs: &[Length]) {
        let start = self.glyphs.len().saturating_sub(xs.len());
        for (glyph, &x) in self.glyphs.iter_mut().skip(start).zip(xs) {
            glyph.x = x;
        }
    }

    /// Moves the last glyph from its place in the line by the offset that the font's layout
    /// tables give it, to the right and up. Until [`Self::finish`] a glyph's `y` holds only
    /// the move up, and `rights` holds the move to the right: the end of a text object can
    /// still move the glyph's `x` to where the writer draws it ([`Self::redraw_last`]).
    fn shift_last(&mut self, (right, up): (Length, Length)) {
        if let (Some(last), Some(move_right)) = (self.glyphs.last_mut(), self.rights.last_mut()) {
            *move_right = right;
            last.y = -up;
        }
    }

    /// Adds a character to the text of the last glyph, as the later part of a ligature.
    fn join(&mut self, ch: char) {
        self.text.push(ch);
        let end = u32::try_from(self.text.len()).unwrap_or(u32::MAX);
        if let Some(last) = self.glyphs.last_mut() {
            last.text_end = end;
        }
    }

    /// Puts the glyphs on the baseline `y` and adds the moves of the font's layout tables to
    /// their final places.
    fn settle(&mut self, y: Length) {
        for (glyph, &right) in self.glyphs.iter_mut().zip(&self.rights) {
            glyph.x += right;
            glyph.y = y + glyph.y;
        }
    }

    /// The glyphs of the run on the device, for a shadow drawn as their paths: each glyph's ID
    /// at its place on the device with the moves of the font's layout tables, on the run's
    /// `baseline` with its rise and its own move down, as [`Self::finish`] places the glyphs
    /// but without the PDF writer's moves.
    fn device_places(&self, device: &Device, face: &Face, baseline: Length) -> Vec<DevicePlace> {
        let y = baseline - device.shift_dots(face.rise);
        (self.glyphs.iter().zip(&self.device_xs).zip(&self.rights))
            .map(|((glyph, &x), &right)| DevicePlace {
                glyph: glyph.id,
                x: x + right,
                y: y + glyph.y,
            })
            .collect()
    }

    fn finish(mut self, device: &Device, face: &Face, baseline: Length, filled: bool) -> GlyphRun {
        self.settle(baseline - device.shift_dots(face.rise));
        let size = device.snap(face.size);
        // A bold that Word makes itself strokes the glyphs' outlines in the text color, with
        // pointed corners, unless the run has an outline of its own.
        let bold_stroke = face
            .standing
            .synthetic_bold
            .then(|| device.bold_stroke(size))
            .flatten()
            .map(|width| Outline {
                width,
                color: face.color,
                join: Join::Miter,
            });
        GlyphRun {
            font: face.font,
            size,
            color: face.color,
            text: self.text,
            glyphs: self.glyphs,
            outline: face.outline.or(bold_stroke),
            filled,
            effect: face.effect,
            // The glyphs of a scaled run, which lie at the places of the scale, take the
            // target's factor about their origins, and those of a synthetic italic face lean
            // by the target's slant.
            // quirk: ScaledGlyphs (src/quirks.rs)
            turn: device.glyph_turn(
                size,
                &face.metrics,
                face.scale,
                face.standing.synthetic_italic,
            ),
        }
    }
}

/// Whether a glyph starts a text object of its own, where `starts` says that it starts a run or
/// a piece of the text, `rtl` that it lies in right-to-left text, and `before` gives the same
/// two for the glyph before it on the line, in visual order. Inside right-to-left text, the
/// reading order runs from right to left, so that a glyph that starts a run in the text ends
/// one on the line: the glyph after it, on its right, starts the object. A glyph where the
/// line turns from one direction to the other starts one too.
const fn visual_start(starts: bool, rtl: bool, before: Option<(bool, bool)>) -> bool {
    match before {
        Some((true, before_starts)) if rtl => before_starts,
        Some((before_rtl, _)) if before_rtl != rtl => true,
        _ if rtl => false,
        _ => starts,
    }
}

/// How far the exact place of the glyph after `placed`, a piece of a line that starts `start`
/// past its column's edge (with the first line's own indent in it), moves before it goes to
/// its dot. After a tab to a left stop, the device lands that glyph as
/// it lands a line's start, the stop's distance from the column's edge through
/// `Device::line_start`, and not the line's start plus the distance from it: the halves of the
/// stop's own conversion less those of the line's start. Zero after any other piece or stop.
fn stop_nudge(device: &Device, start: (Length, Length), placed: &Placed) -> Length {
    if !matches!(placed.piece, Piece::Tab(_)) || placed.tab != Some(TabKind::Left) {
        return Length::ZERO;
    }
    device.stop_halves(start, placed.x + placed.advance)
}

/// The exact place where the first `written` pieces of a line end, from their `exact` places
/// ([`exact_places`]): the place of the last one, its advance and what a justified line adds
/// to it, so that the end moves with every space that the line stretches or shrinks before
/// it. `start`, the line's start, for a line of no pieces.
fn written_end(
    line: &Line,
    exact: &[(Length, Length)],
    (start, written): (Length, usize),
) -> Length {
    written
        .checked_sub(1)
        .and_then(|last| line.placed.get(last).zip(exact.get(last)))
        .map_or(start, |(placed, &(x, stretch))| {
            x + placed.advance + stretch
        })
}

/// The exact place of each piece of a line drawn from `origin`, and what a justified line adds
/// to it when it is a space that the line stretches or shrinks: the equal share of its spaces
/// with the piece's departure from it in `departures`.
fn exact_places(
    line: &Line,
    order: VisualOrder<'_>,
    origin: Origin,
    departures: &[Length],
) -> Vec<(Length, Length)> {
    let mut extra = Length::ZERO;
    line.placed
        .iter()
        .enumerate()
        .map(|(index, placed)| {
            extra += inner_mark_shrink_before(line, index, origin.mark_shrink, origin.mark_sides)
                + origin.gap_extra * i64::from(spread_gap(line, index));
            let x = origin.x + placed.x + extra;
            // A space that a justified line stretches or shrinks takes the edge of its
            // justified width in the device's steps, and so does a piece that the line narrows.
            let mut stretch = origin.narrowing.map_or(Length::ZERO, |narrowing| {
                narrowing.at(order.logical_index(index))
            });
            if order.is_stretched(&placed.piece, index) {
                stretch += origin.space_extra + departures.get(index).copied().unwrap_or_default();
            }
            extra += stretch;
            (x, stretch)
        })
        .collect()
}

/// What each piece of `line` takes beyond the equal share `each` of the line's stretched spaces,
/// where they share the free space by their widths first and the spaces stretch or shrink:
/// nothing for another piece, and nothing at all on a line whose spaces keep their widths. Of the free space n × `each` of the n
/// stretched spaces, the part p, the free space or, where it is larger, the part
/// `STRETCH_BY_WIDTH` of the spaces' summed width W with the free space's sign, goes to the
/// spaces in proportion to their widths, and the rest in equal parts; so a space of width w
/// takes p × (n × w − W) / (n × W) beyond `each`. The sum of these up to each space rounds to
/// whole half-EMUs, so that they sum to 0 over the line.
fn width_departures(line: &Line, order: VisualOrder<'_>, each: Length) -> Vec<Length> {
    if each == Length::ZERO {
        return Vec::new();
    }
    let widths: Vec<(usize, i128)> = line
        .placed
        .iter()
        .enumerate()
        .filter(|&(index, placed)| order.is_stretched(&placed.piece, index))
        .map(|(index, placed)| (index, i128::from(placed.advance.units())))
        .collect();
    let count = i128::try_from(widths.len()).unwrap_or(0);
    let total: i128 = widths.iter().map(|&(_, width)| width).sum();
    if count == 0 || total <= 0 {
        return Vec::new();
    }
    let (part, whole) = params::STRETCH_BY_WIDTH;
    // The part p, times `whole`, so that it stays exact.
    let cap = total * i128::from(part);
    let by_width = (count * i128::from(each.units()) * i128::from(whole)).clamp(-cap, cap);
    let denominator = count * total * i128::from(whole);
    let mut departures = vec![Length::ZERO; line.placed.len()];
    let (mut summed, mut before) = (0_i128, 0_i128);
    for (index, width) in widths {
        summed += count * width - total;
        let up_to = f_office_units::div_round_i128(by_width * summed, denominator);
        if let Some(slot) = departures.get_mut(index) {
            *slot = i64::try_from(up_to - before).map_or(Length::ZERO, Length::from_units);
        }
        before = up_to;
    }
    departures
}

/// Whether `piece`, the piece at `index` of its line, is a space that a justified line stretches
/// or shrinks: a space from the line's first stretched piece to its last visible one, as
/// `(first, visible)` give them.
fn stretched_space(piece: &Piece, index: usize, (first, visible): (usize, Option<usize>)) -> bool {
    stretches(piece) && index >= first && visible.is_some_and(|v| index <= v)
}

/// What the edge check of right-edge steps counts beside the share of each stretched space of
/// `line` (`CountedShares::excess`), by piece: nothing for another piece, and nothing at all on
/// a line whose check counts the shares that it spreads.
fn counted_share_excesses(
    line: &Line,
    order: VisualOrder<'_>,
    origin: &Origin,
) -> Vec<Option<(i128, i128)>> {
    let Some(shares) = origin.counted_shares else {
        return Vec::new();
    };
    let mut k = 0;
    line.placed
        .iter()
        .enumerate()
        .map(|(index, placed)| {
            order.is_stretched(&placed.piece, index).then(|| {
                k += 1;
                shares.excess(k)
            })
        })
        .collect()
}

/// A stretch of right-to-left text on a line.
struct Stretch {
    /// Its drawn glyphs, from the left.
    glyphs: Vec<StretchGlyph>,
    /// What follows it in reading order.
    next: After,
}

/// What follows a stretch of right-to-left text in reading order.
#[derive(Clone, Copy)]
enum After {
    /// A drawn glyph with this advance, which the device steps so.
    Glyph(Length, DeviceStep),
    /// The paragraph mark, at the end of the paragraph's last line.
    Mark,
    /// Something else, or nothing.
    Other,
}

/// A drawn glyph of a stretch of right-to-left text.
struct StretchGlyph {
    /// The index of its piece on the line.
    piece: usize,
    /// Its exact place.
    x: Length,
    /// Its advance, with what a justified line adds to it.
    advance: Length,
    /// What a justified line adds to it.
    stretch: Length,
    /// How the device steps it, as it steps a glyph of left-to-right text.
    device: DeviceStep,
}

/// How the device steps one glyph ([`Layout::device_step`]): its size, its measured device
/// width in dots with its advance alone, whether its steps round without the bias, and what
/// rounding took from its advance.
#[derive(Clone, Copy)]
struct DeviceStep {
    /// The glyph's font size.
    size: Length,
    /// Its device width in dots with its advance at the size, where the target's width is not
    /// the advance rounded.
    measured: Option<(i64, Length)>,
    /// Whether its own step and the step after it round without the bias.
    without_bias: bool,
    /// What rounding to whole half-EMUs took from its advance, as a numerator over a
    /// denominator in half-EMUs.
    rounding: Option<(i64, i64)>,
    /// Its character spacing.
    spacing: Length,
    /// What the edge check and the segment rule count beside its advance, as a numerator over
    /// a denominator in half-EMUs.
    counted_extra: Option<(i64, i64)>,
    /// How much nearer than the limit its right edge, when it ends short of its exact edge,
    /// makes the edge check move it one dot right.
    short_ease: Length,
}

impl DeviceStep {
    /// Tells the device's steps `edge` that the next glyph steps so.
    fn tell(self, edge: &mut grid::EdgeSteps) {
        edge.with_device_width(self.measured);
        edge.without_bias(self.without_bias);
        edge.with_advance_rounding(self.rounding);
        edge.with_character_spacing(self.spacing);
        edge.with_counted_extra(self.counted_extra);
        edge.with_short_ease(self.short_ease);
    }

    /// What the glyph's device width adds to its advance rounded with the bias `bias`, as the
    /// edge check counts its right edge.
    fn widens(self, device: &Device, bias: Length) -> Length {
        self.measured.map_or(Length::ZERO, |(width, alone)| {
            device.dots(width) - device.snap(alone + bias)
        })
    }

    /// The place on the device's steps `edge`, with the numbers `numbers` (the bias, the limit
    /// and the segment), of the glyph whose exact place and advance are `(x, advance)`, at its
    /// size.
    fn place(
        self,
        edge: &mut grid::EdgeSteps,
        device: &Device,
        numbers: (Length, Length, Length),
        (x, advance): (Length, Length),
    ) -> Length {
        edge.at_size(self.size, device.snap(self.size));
        self.tell(edge);
        edge.place(device, numbers, x, advance)
    }
}

/// What comes right before the last visible glyph of a filled justified line with a space after
/// it, which says how the device draws the glyph.
#[derive(Clone, Copy)]
enum LastGlyph {
    /// The glyph before it, so that the space after it moves it
    /// (`AlignedEnds::OnDots`).
    AfterGlyph(TrailingSpace),
    /// Stretched spaces, so that its own exact place moves it (`SpacedLastGlyph::EdgeLimit`).
    AfterStretched,
}

/// A space after the last visible glyph of a filled justified line: its exact place, which is
/// the exact right edge of the line's text, the line's own right edge, which lies past it by
/// the part of the free space that the equal shares of the spaces leave, its advance, its
/// character spacing, and how the device steps it.
#[derive(Clone, Copy)]
struct TrailingSpace {
    x: Length,
    end: Length,
    edge: Length,
    advance: Length,
    spacing: Length,
    step: DeviceStep,
}

/// The places on the device of the glyphs of a line's right-to-left stretches, by the index of
/// their pieces, and what the edge check found at each as its stretch's steps placed it.
struct RightToLeftPlaces {
    places: Vec<Option<Length>>,
    checks: Vec<Option<crate::grid::EdgeCheck>>,
}

impl RightToLeftPlaces {
    /// No places yet for a line of `count` pieces.
    fn of(count: usize) -> Self {
        Self {
            places: vec![None; count],
            checks: vec![None; count],
        }
    }

    /// The place of the piece `index`, when its stretch's steps gave one.
    fn place(&self, index: usize) -> Option<Length> {
        self.places.get(index).copied().flatten()
    }

    /// Takes what the edge check found at the piece `index`.
    fn take_check(&mut self, index: usize) -> Option<crate::grid::EdgeCheck> {
        self.checks.get_mut(index).and_then(Option::take)
    }

    /// Gives the piece `index` its place `at`.
    fn place_at(&mut self, index: usize, at: Length) {
        if let Some(place) = self.places.get_mut(index) {
            *place = Some(at);
        }
    }

    /// Keeps what the edge check found at the piece `index`.
    fn check(&mut self, index: usize, check: Option<crate::grid::EdgeCheck>) {
        if let Some(slot) = self.checks.get_mut(index) {
            *slot = check;
        }
    }
}

/// The places of a line's glyphs under `GridAdvances::RightEdgeSteps` and the text objects in
/// which the PDF writer draws them, on every line. Word's places continue across runs, since
/// Word places a line's glyphs before it splits them.
#[derive(Default)]
struct EdgeGlyphs {
    /// The bias, the limit and the segment of the device's steps, or `None` when the target
    /// keeps the PDF writer's steps.
    numbers: Option<(Length, Length, Length)>,
    edge: crate::grid::EdgeSteps,
    objects: crate::grid::TextObjects,
    object: crate::grid::TextObject,
    /// How far right of their steps the line's glyphs lie.
    shift: Length,
    /// The place of the first glyph after the line's written text, a trailing space.
    trails_at: Option<Length>,
    /// How the device draws the glyph that comes next, when it is the last visible glyph of a
    /// filled justified line with a space after it ([`LastGlyph`]).
    last_glyph: Option<LastGlyph>,
    /// Whether the glyph before is a list label's, so that the gap after it is the label's
    /// gap: its tab, or the gap of legacy numbering.
    after_label: bool,
    /// Whether the last piece with a width was a tab or a list label's gap that no glyph has
    /// followed yet.
    after_tab: bool,
    /// The text after the line's tabs to right and center stops.
    tabs: TabTexts,
    /// For each piece of the line, whether it is the first glyph of a footnote's reference
    /// mark.
    note_marks: Vec<bool>,
    /// For each piece of the line, what the edge check counts beside the share of a stretched
    /// space there ([`counted_share_excesses`]).
    share_excesses: Vec<Option<(i128, i128)>>,
    /// Whether the glyph that comes next steps at its nominal size, a glyph of a run with a
    /// character scale on a target that counts those so (`ScaledSteps::NominalSum`).
    nominal_steps: bool,
    /// The steps' place and the exact place of the first glyph of the scaled run that the line
    /// draws now, from which the run's later glyphs take the dots of their exact distance at the
    /// nominal size, rounded down; `None` outside such a run.
    scaled_start: Option<(Length, Length)>,
}

impl EdgeGlyphs {
    /// The state for the line `line` drawn from `origin`, with the text after its tabs to right
    /// and center stops `tabs`.
    fn of_line(
        device: &Device,
        (origin, line, order): (&Origin, &Line, VisualOrder<'_>),
        tabs: TabTexts,
    ) -> Self {
        let mut edge_steps = Self::new(device).right_to_left(origin.right_to_left);
        edge_steps.tabs = tabs;
        edge_steps.note_marks = note_mark_starts(line);
        edge_steps.share_excesses = counted_share_excesses(line, order, origin);
        edge_steps.edge.hands_on_start(origin.starts_at_indent);
        if origin.steps_alone {
            // A limit and a segment as long as the longest length of a file: no glyph of the
            // line ends that far from its exact place.
            let unchecked = Length::from_units(Length::FILE_LIMIT);
            edge_steps.numbers = edge_steps
                .numbers
                .map(|(bias, _, _)| (bias, unchecked, unchecked));
        }
        edge_steps
    }

    /// Tells the right-edge steps that the line's piece `index` steps as `step` says, with what
    /// the edge check counts beside the share of a stretched space there.
    fn tell(&mut self, step: DeviceStep, index: usize) {
        step.tell(&mut self.edge);
        // quirk: EdgeShares (src/quirks.rs)
        self.edge
            .with_counted_share(self.share_excesses.get(index).copied().flatten());
    }

    /// Tells the right-edge steps where `device` puts the line's piece `index` when it is the
    /// first glyph of a footnote's reference mark.
    fn note_mark(&mut self, device: &Device, index: usize) {
        if self.note_marks.get(index) != Some(&true) {
            return;
        }
        self.edge.at_note_mark(device);
    }

    /// Keeps the place `at` of the first glyph that comes `after` the line's written text.
    fn after_written(&mut self, after: bool, at: Length) {
        if after && self.trails_at.is_none() {
            self.trails_at = Some(at);
        }
    }

    /// The place where the written text of a line ends: the place of the first trailing
    /// space, which the steps give as they give each glyph's, or, with none, the dot that the
    /// steps give the written text's exact end `written` ([`written_end`]). `None` for a line
    /// without a glyph, such as a line of one picture, and on a target that keeps the PDF
    /// writer's steps.
    fn end(&self, device: &Device, written: Length) -> Option<Length> {
        self.numbers?;
        self.trails_at.or_else(|| {
            let end = self
                .edge
                .end(device, written)
                .or_else(|| self.tab_end(device, written))?;
            Some(end + self.shift)
        })
    }

    /// The end of a line's written text `written` that ends with a tab or a list label's gap
    /// that no glyph follows: the dot where a glyph after it would lie, under
    /// `AlignedTabEnd::StopDot`; `None` under `Unended`.
    fn tab_end(&self, device: &Device, written: Length) -> Option<Length> {
        if !self.after_tab {
            return None;
        }
        self.edge.tab_end(device, written)
    }

    fn new(device: &Device) -> Self {
        let numbers = match device.advances() {
            crate::grid::Advances::RightEdge {
                bias,
                limit,
                segment,
                ..
            } => Some((bias, limit, segment)),
            crate::grid::Advances::PdfSteps => None,
        };
        Self {
            numbers,
            object: crate::grid::TextObject::of(device),
            ..Self::default()
        }
    }

    /// The glyphs of a line of a right-to-left paragraph lie `shift` right of their steps (see
    /// [`super::Origin`]).
    fn right_to_left(self, shift: Option<Length>) -> Self {
        Self {
            shift: shift.unwrap_or(Length::ZERO),
            ..self
        }
    }

    /// After a `placed` piece that is not a glyph: one with a width ends the text object, and
    /// the next glyph goes to the nearest dot of its exact place. After a tab or the gap after a
    /// list label it starts a segment there; after another piece with a width, such as an inline
    /// object, the device's segment rule says whether it does. A mark without width keeps the
    /// steps of the glyphs around it, except the end of a note's own mark, after which the
    /// device's quirk may start the steps again. Every piece that is not a glyph ends the text after a tab
    /// to a right or a center stop ([`TabTexts`]), and a tab to such a stop starts one.
    fn gap(
        &mut self,
        device: &Device,
        (index, placed, origin): (usize, &Placed, &Origin),
        run: Option<&mut RunBuilder>,
    ) {
        self.tabs.at_piece(placed.piece, device, &self.edge);
        if placed.advance != Length::ZERO {
            let label = std::mem::take(&mut self.after_label);
            self.after_tab =
                label || matches!(placed.piece, Piece::Tab(_) | Piece::PositionTab(..));
            if self.after_tab {
                self.edge.tab();
                self.edge.with_stop_nudge(
                    stop_nudge(device, (origin.start, origin.own), placed) + origin.segment_rest,
                );
            } else {
                self.edge.gap(device);
            }
            self.objects.restart();
            self.finish(run);
            self.tabs.after_gap(index, placed);
        } else if placed.piece == Piece::NoteMarkEnd {
            self.edge.after_note_mark(device);
        }
    }

    /// Ends the text object, whose glyphs are the last of `run`, and moves them to where the
    /// writer draws them.
    fn finish(&mut self, run: Option<&mut RunBuilder>) {
        if self.object.is_empty() {
            return;
        }
        let drawn = self.object.draw();
        if let Some(run) = run {
            run.redraw_last(&drawn);
        }
    }

    /// The place of a glyph whose exact place, advance and font size are `x`, `advance` and
    /// `size`, of the character `ch` with the font side `glyph_side`, where `starts` says that
    /// it starts a run of the document or of the line and `written` is the target's written
    /// width of the glyph, if any; `None`
    /// when the line keeps the PDF writer's steps. `stretch` is what a justified line adds to a
    /// space, which counts in the device's edge check but not in the written width. A glyph of
    /// right-to-left text takes the place `from_right` that its stretch gives it
    /// ([`Self::place_stretch`]). The glyph is the line's piece `index`, which the device may
    /// place as the first glyph of a footnote's reference mark ([`Self::note_mark`]). The glyph
    /// moves to where the writer draws it once its text object ends.
    fn place(
        &mut self,
        device: &Device,
        (x, advance, size, stretch): (Length, Length, Length, Length),
        (ch, glyph_side, starts, written, spacing): (char, FontSide, bool, Option<u16>, Length),
        (index, from_right, per_glyph): (usize, Option<Length>, bool),
        run: Option<&mut RunBuilder>,
    ) -> Option<Length> {
        let last = self.last_glyph.take();
        self.after_tab = false;
        let numbers = self.numbers?;
        self.note_mark(device, index);
        let drawn = device.snap(size);
        self.edge
            .at_size(size, if self.nominal_steps { size } else { drawn });
        let place = if let Some(place) = from_right {
            place
        } else {
            // The character spacing that a glyph carries steps as a justified space's share
            // does: in whole dots on its own. A glyph carries none on a target that keeps the
            // spacing in the advance.
            // quirk: DeviceAdvance (src/quirks.rs)
            let extra = crate::grid::GlyphExtra::of(stretch, spacing);
            self.edge.with_extra(extra);
            if let Some(dot) = self.tabs.take_start() {
                self.edge.with_stop_nudge(dot - x);
            }
            let place = self.edge.place(device, numbers, x, advance + stretch);
            if extra.length() != Length::ZERO {
                self.edge.after_extra(extra);
            }
            let place = self.scaled_place(device, place, x);
            place + self.end_move(device, numbers, last, place - x)
        } + self.shift;
        self.tabs.glyph(place, (x, advance), ch == ' ');
        if self.objects.starts(
            device.writer_char(ch),
            device.writer_side(glyph_side),
            starts,
        ) {
            self.finish(run);
        }
        if per_glyph {
            self.object.set_per_glyph();
        }
        self.object.push_at(place, advance, (size, drawn), written);
        Some(place)
    }

    /// The place of a glyph whose steps' place is `place` and whose exact place is `x`: in a run
    /// with a character scale whose glyphs step at their nominal size, the first glyph keeps
    /// its steps' place and each later glyph lies that many dots further as its exact distance
    /// from the first glyph holds whole dots, rounded down. Every other glyph keeps `place`.
    fn scaled_place(&mut self, device: &Device, place: Length, x: Length) -> Length {
        if !self.nominal_steps {
            self.scaled_start = None;
            return place;
        }
        if let Some((first, first_x)) = self.scaled_start {
            first + device.floor(x - first_x)
        } else {
            self.scaled_start = Some((place, x));
            place
        }
    }

    /// How far the device draws the glyph that the steps placed last from its steps' place,
    /// when `trailing` is the space after it on a filled justified line: the steps place the
    /// space from the glyph as they will, on a copy of them, and the device moves the glyph by
    /// that place and the space's exact place ([`Device::trailing_space_move`],
    /// [`Device::justified_end_move`]). When the glyph
    /// starts a segment and went to the nearest dot of its counted place, the device measures
    /// the space's place from the line's own right edge instead
    /// ([`Device::restarted_end_move`]). When stretched spaces come right before the glyph, the
    /// device moves it by `past`, how far its place lies right of its exact place, and the
    /// steps' limit ([`Device::spaced_end_move`]). Zero without such a space.
    fn end_move(
        &self,
        device: &Device,
        numbers: (Length, Length, Length),
        last: Option<LastGlyph>,
        past: Length,
    ) -> Length {
        let space = match last {
            Some(LastGlyph::AfterGlyph(space)) => space,
            Some(LastGlyph::AfterStretched) => return device.spaced_end_move(past, numbers.1),
            None => return Length::ZERO,
        };
        let at = || {
            let mut ahead = self.edge;
            ahead.with_extra(crate::grid::GlyphExtra::Spacing(space.spacing));
            (space.step).place(&mut ahead, device, numbers, (space.x, space.advance))
        };
        device.trailing_space_move(at, (space.x, space.end, space.edge), self.edge.started())
    }

    /// Places the glyphs of a stretch of right-to-left text, given from the left, into
    /// `places` by the index of their pieces. The line's steps run in reading order: they
    /// take the stretch's glyphs from its right end, each at the exact place that the text
    /// before it in reading order gives it, from the stretch's exact left edge, or, when the
    /// stretch starts the line's steps, from the place that the device gives
    /// ([`Device::right_to_left_origin`]), and go on from the stretch's last glyph to the text
    /// after it at its own exact places. The glyphs are then drawn mirrored
    /// in the span that the steps give the stretch: from its first glyph's place to the place
    /// that the steps give the piece after it, or, with none, to its last glyph's place plus
    /// that glyph's step. Each glyph steps as the device steps right-to-left text
    /// ([`Device::right_to_left_step`]): by its own device step, as a glyph of left-to-right
    /// text does, or by its advance at the nearest dot. Its span on the device is its advance
    /// rounded plus what its device width adds, its device width; a stretched space spans its
    /// advance with the stretch, or its own advance alone, as the quirk
    /// `RightToLeftJustifiedLine` says. What the edge check found at each glyph as the steps
    /// placed it goes to `out` too, for the record of the drawn glyph.
    fn place_stretch(&mut self, device: &Device, stretch: &Stretch, out: &mut RightToLeftPlaces) {
        let glyphs = &stretch.glyphs;
        let (Some(numbers), Some(first)) = (self.numbers, glyphs.first()) else {
            return;
        };
        let step = |advance: Length| device.snap(advance + numbers.0);
        let own_steps = device.ends_right_to_left_at_edge();
        // A stretch that starts the line's steps counts its exact places from where the device
        // says (quirk: RightToLeftCount); the steps go back to its own places after it.
        let moved = self
            .edge
            .when_starting(device.right_to_left_origin(first.x) - first.x);
        let mut read = first.x + moved;
        let mut stepped = Vec::with_capacity(glyphs.len());
        for glyph in glyphs.iter().rev() {
            // A stretched space spans its own step, beside the glyph before it in reading
            // order, or its stretched width.
            let spanned = if own_steps {
                glyph.advance - glyph.stretch
            } else {
                glyph.advance
            };
            let own = step(spanned) + glyph.device.widens(device, numbers.0);
            let mut stepped_device = glyph.device;
            (stepped_device.measured, stepped_device.without_bias) = device.right_to_left_step(
                &mut self.edge,
                (glyph.device.measured, glyph.device.without_bias),
            );
            let at = stepped_device.place(&mut self.edge, device, numbers, (read, glyph.advance));
            out.check(glyph.piece, self.edge.take_checked());
            if glyph.stretch != Length::ZERO {
                self.edge
                    .after_extra(crate::grid::GlyphExtra::Justified(glyph.stretch));
            }
            read += glyph.advance;
            stepped.push((glyph.piece, at, own));
        }
        self.edge.move_exact(Length::ZERO - moved);
        read -= moved;
        let (Some(&(_, start, _)), Some(&(_, last, width))) = (stepped.first(), stepped.last())
        else {
            return;
        };
        let end = match stretch.next {
            After::Glyph(advance, after) => {
                let mut ahead = self.edge;
                after.place(&mut ahead, device, numbers, (read, advance))
            }
            // The paragraph mark goes to the nearest dot of its exact place.
            After::Mark => device.snap(read),
            // A stretched space that ends the reading spans its share too, as the step to a
            // glyph after it would count it.
            After::Other => last + width + self.edge.pending_extra(device),
        };
        for (piece, at, own) in stepped {
            out.place_at(piece, start + end - at - own);
        }
    }

    /// What the edge check found at the glyph that comes next, and where its steps start
    /// (`None` unless the glyph is `stepped`, by the line's steps from the left), or `right`,
    /// what the steps of its right-to-left stretch found, for the record of the drawn glyph.
    fn records(
        &mut self,
        stepped: bool,
        right: Option<crate::grid::EdgeCheck>,
    ) -> (Option<crate::grid::EdgeCheck>, Option<Length>) {
        let checked = self.edge.take_checked().filter(|_| stepped).or(right);
        (checked, self.edge.take_start_place().filter(|_| stepped))
    }

    /// The place of a leader character, as [`Self::place`] gives it, where `starts` alone
    /// says whether the character starts a text object: the writer's rules for the objects of
    /// text, such as a hyphen-minus drawn alone, do not cut a leader.
    fn place_leader(
        &mut self,
        device: &Device,
        (x, advance, size): (Length, Length, Length),
        (starts, written): (bool, Option<u16>),
        run: Option<&mut RunBuilder>,
    ) -> Option<Length> {
        let numbers = self.numbers?;
        let drawn = device.snap(size);
        self.edge.at_size(size, drawn);
        let place = self.edge.place(device, numbers, x, advance) + self.shift;
        if starts {
            self.finish(run);
        }
        self.object.push_at(place, advance, (size, drawn), written);
        Some(place)
    }
}

/// Line-wide marks from reading-order counting of right-to-left stretches
/// (`Layout::right_to_left_object_marks`), one entry per piece of the line.
struct RtlObjectMarks {
    /// Pieces inside a right-to-left stretch counted in reading order.
    reading_order: Vec<bool>,
    /// Pieces where a visual object starts after a full reading-order object.
    full: Vec<bool>,
    /// Pieces where a visual object starts at the leftmost space of a reading-order leading
    /// space-only object.
    after_spaces: Vec<bool>,
}

impl RtlObjectMarks {
    fn of(len: usize) -> Self {
        Self {
            reading_order: vec![false; len],
            full: vec![false; len],
            after_spaces: vec![false; len],
        }
    }

    fn tell(&self, index: usize, objects: &mut grid::TextObjects) {
        if self.reading_order.get(index) == Some(&true) {
            objects.reading_order_spaces();
        }
        if self.full.get(index) == Some(&true) {
            objects.fill();
        }
        if self.after_spaces.get(index) == Some(&true) {
            objects.after_spaces();
        }
    }
}

/// Where the PDF writer starts text objects on a line beside the starts that the line's drawing
/// finds glyph by glyph (`Layout::object_marks`), one mark for each piece of the line.
struct ObjectMarks {
    /// Reading-order object starts for stretches of right-to-left text.
    rtl: RtlObjectMarks,
    /// The glyphs of the objects that the writer writes glyph by glyph.
    off_baseline: Vec<bool>,
}

impl ObjectMarks {
    /// Whether piece `index` lies in an off-baseline right-to-left text object drawn with
    /// relative `TD` moves from its single `Tm` start (`TextObject::set_per_glyph`).
    fn is_off_baseline(&self, index: usize) -> bool {
        self.off_baseline.get(index) == Some(&true)
    }

    /// Tells the trace's object tracker (`trace`) and the line's object tracker (`drawn`) what
    /// the marks say of piece `index`: both learn the reading-order object starts
    /// ([`RtlObjectMarks::tell`]), and `trace` records each glyph of an off-baseline
    /// right-to-left object as its own `TD` start ([`grid::TextObjects::alone_off_baseline`]).
    fn tell(&self, index: usize, trace: &mut grid::TextObjects, drawn: &mut grid::TextObjects) {
        self.rtl.tell(index, trace);
        self.rtl.tell(index, drawn);
        if self.is_off_baseline(index) {
            trace.alone_off_baseline();
        }
    }
}

/// What the count of text objects of [`off_baseline_marks`] takes of a piece of a line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ObjectPiece {
    /// A tab with a face, which ends the line's open run as well as its text object.
    Tab,
    /// Another piece that the line does not draw as a glyph, which ends the text object.
    Gap,
    /// A glyph that the line draws.
    Glyph(ObjectGlyph),
    /// A later part of a ligature, which joins the glyph before it ([`LigatureParts::take`]): in
    /// right-to-left text, as `in_rtl` says, always, and else when a run of the line is open.
    /// A part that joins nothing is drawn as `glyph`.
    Part { in_rtl: bool, glyph: ObjectGlyph },
}

/// What the count of text objects takes of a glyph of a line ([`ObjectPiece::Glyph`] and
/// [`ObjectPiece::Part`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ObjectGlyph {
    /// The glyph's face; a glyph of another face than the one before starts a run of the line.
    face: FaceIndex,
    /// The character and the font side that the writer counts.
    ch: char,
    side: FontSide,
    /// Whether the glyph lies in right-to-left text that the line's steps take so.
    right_to_left: bool,
    /// Whether the glyph starts a run of the document or a text piece.
    text_start: bool,
    /// Whether the writer writes the glyph's object glyph by glyph because of it
    /// ([`Device::object_per_glyph`]).
    off: bool,
}

/// For each of a line's `pieces`, whether it lies in a text object that the writer writes
/// glyph by glyph because one of its glyphs is `off`: the objects that the writer starts
/// otherwise, as the line's drawing starts them ([`grid::TextObjects::starts`]), where
/// `rtl_marks` supplies reading-order full-object and leading-space starts. A glyph starts a
/// run of the document or of the line at the line's start, after a tab, at another face, and
/// where [`visual_start`] says so.
fn off_baseline_marks(pieces: &[ObjectPiece], rtl_marks: &RtlObjectMarks) -> Vec<bool> {
    let mut marks = vec![false; pieces.len()];
    let mut objects = grid::TextObjects::default();
    let mut object: Vec<usize> = Vec::new();
    let mut off = false;
    // The face of the line's open run, which a tab or another face ends.
    let mut face = None;
    let mut before: Option<(bool, bool)> = None;
    for (index, piece) in pieces.iter().enumerate() {
        let glyph = match *piece {
            ObjectPiece::Tab => {
                face = None;
                objects.restart();
                continue;
            }
            ObjectPiece::Gap => {
                objects.restart();
                continue;
            }
            ObjectPiece::Part { in_rtl, glyph } if in_rtl || face.is_some() => {
                off |= glyph.off;
                continue;
            }
            ObjectPiece::Glyph(glyph) | ObjectPiece::Part { glyph, .. } => glyph,
        };
        if face.is_some_and(|open| open != glyph.face) {
            face = None;
        }
        let starts = face.is_none() || visual_start(glyph.text_start, glyph.right_to_left, before);
        before = Some((glyph.right_to_left, glyph.text_start));
        rtl_marks.tell(index, &mut objects);
        if objects.starts(glyph.ch, glyph.side, starts) {
            mark_object(&mut marks, &mut object, std::mem::take(&mut off));
        }
        face = Some(glyph.face);
        object.push(index);
        off |= glyph.off;
    }
    mark_object(&mut marks, &mut object, off);
    marks
}

/// Marks each piece of `object`, the pieces of one text object, in `marks` when `off` says
/// that the writer writes each of its glyphs alone, and empties `object` for the next one.
fn mark_object(marks: &mut [bool], object: &mut Vec<usize>, off: bool) {
    for index in object.drain(..) {
        if let Some(mark) = marks.get_mut(index).filter(|_| off) {
            *mark = true;
        }
    }
}

#[cfg(test)]
mod tests {
    use f_office_units::Length;

    use super::{EdgeGlyphs, RunBuilder, stop_nudge};
    use crate::grid::Device;
    use crate::lines::{Piece, Placed};
    use crate::text::{FaceIndex, SpaceKind};

    /// The glyphs of a run that steps at its nominal size lie as many whole dots after the run's
    /// first glyph as their exact distance from it holds, rounded down, whatever the edge
    /// check gives them; the first glyph of the run and every glyph outside it keep the edge
    /// check's place.
    #[test]
    fn scaled_run_glyphs_lie_on_the_floor_of_their_exact_distance() {
        let device = Device::per_inch(600).unwrap();
        let dot = device.dots(1);
        let mut glyphs = EdgeGlyphs {
            nominal_steps: true,
            ..EdgeGlyphs::default()
        };
        let first = Length::from_units(10 * dot.units());
        let exact = first + Length::from_units(dot.units() / 3);
        assert_eq!(glyphs.scaled_place(&device, first, exact), first);
        // 2.9 dots further, where the edge check gave 4 dots: 2 dots.
        let later = exact + Length::from_units(dot.units() * 29 / 10);
        let steps = first + Length::from_units(4 * dot.units());
        assert_eq!(
            glyphs.scaled_place(&device, steps, later),
            first + Length::from_units(2 * dot.units())
        );
        glyphs.nominal_steps = false;
        assert_eq!(glyphs.scaled_place(&device, steps, later), steps);
        glyphs.nominal_steps = true;
        assert_eq!(glyphs.scaled_place(&device, steps, later), steps);
    }

    /// The letters a to e, a space after each of the widths `widths` in turn (the last one
    /// trailing), each letter 50 wide.
    fn spaced_line(widths: [i64; 5]) -> crate::lines::Line {
        crate::lines::Line {
            placed: "a b c d e "
                .chars()
                .enumerate()
                .map(|(index, ch)| Placed {
                    piece: Piece::Glyph(crate::text::Glyph::plain(FaceIndex::nth(0), ch)),
                    x: Length::ZERO,
                    advance: Length::from_units(if ch == ' ' {
                        widths.get(index / 2).copied().unwrap_or(0)
                    } else {
                        50
                    }),
                    leader: None,
                    tab: None,
                })
                .collect(),
            ..crate::lines::Line::default()
        }
    }

    /// The departures of the spaces of a line of [`spaced_line`] from the equal share `each`.
    fn space_departures(
        line: &crate::lines::Line,
        each: i64,
        share: crate::quirks::StretchedSpaceShare,
    ) -> Vec<i64> {
        let quirks = crate::profile::Profile::base().with_variant(share).quirks();
        let found = crate::layout::decisions::width_first_share(&quirks, || {
            super::width_departures(
                line,
                super::VisualOrder::ltr(line),
                Length::from_units(each),
            )
        })
        .unwrap_or_default();
        (0..line.placed.len())
            .filter(|index| index % 2 == 1)
            .map(|index| found.get(index).map_or(0, |d| d.units()))
            .collect()
    }

    /// Under `StretchedSpaceShare::WidthFirst`, the stretched spaces of a justified line first
    /// take shares in proportion to their widths, up to half of each width, and then equal
    /// parts, whether they stretch or shrink; the departures from the equal share sum to 0 over
    /// the line. Spaces of one width, `Equal` and the trailing space take none.
    #[test]
    fn shares_the_free_space_by_the_widths_of_the_stretched_spaces_up_to_half_of_each() {
        use crate::quirks::StretchedSpaceShare::{Equal, WidthFirst};
        // Spaces of 100 after a and c, of 200 after b and d, and a trailing space of 200.
        let two = spaced_line([100, 200, 100, 200, 200]);
        // A free space of 4 × 30 = 120, below half of the widths' 600: in proportion, 20 and 40.
        assert_eq!(
            space_departures(&two, 30, WidthFirst),
            [-10, 10, -10, 10, 0]
        );
        // A free space of 4 × 300 = 1,200: half of each width, 50 and 100, then 225 each.
        assert_eq!(
            space_departures(&two, 300, WidthFirst),
            [-25, 25, -25, 25, 0]
        );
        // The sums up to each space round to whole half-EMUs: -2.33, -4.67, -2.33 and 0 give
        // -2, -5, -2 and 0.
        let paired = spaced_line([100, 100, 200, 200, 200]);
        assert_eq!(space_departures(&paired, 7, WidthFirst), [-2, -3, 3, 2, 0]);
        assert_eq!(space_departures(&two, 300, Equal), [0; 5]);
        // Spaces that shrink by 4 × 30 = 120 in all: the narrow spaces shrink 20, the wide 40.
        assert_eq!(
            space_departures(&two, -30, WidthFirst),
            [10, -10, 10, -10, 0]
        );
        // A shrink of 4 × 300 = 1,200: half of each width, then the rest in equal parts.
        assert_eq!(
            space_departures(&two, -300, WidthFirst),
            [25, -25, 25, -25, 0]
        );
        let one = spaced_line([150, 150, 150, 150, 150]);
        assert_eq!(space_departures(&one, 300, WidthFirst), [0; 5]);
    }

    #[test]
    fn a_footnote_mark_starts_at_the_first_glyph_of_the_marks_face_before_the_note() {
        use crate::lines::{Line, NoteNumber};
        use crate::text::Glyph;
        // Text in face 0, a two-digit mark in face 1, the note's mark without width, then one
        // glyph in face 0 and a second note: the mark of each note starts at the first of the
        // glyphs right before it that share the face of the last of them, and a piece that is
        // not a glyph ends the run back.
        let pieces = [
            Piece::Glyph(Glyph::plain(FaceIndex::nth(0), 'a')),
            Piece::Glyph(Glyph::plain(FaceIndex::nth(0), 'b')),
            Piece::Glyph(Glyph::plain(FaceIndex::nth(1), '1')),
            Piece::Glyph(Glyph::plain(FaceIndex::nth(1), '2')),
            Piece::Note(NoteNumber::of_index(0)),
            Piece::Glyph(Glyph::plain(FaceIndex::nth(0), 'c')),
            Piece::Note(NoteNumber::of_index(1)),
        ];
        let line = Line {
            placed: pieces
                .iter()
                .map(|&piece| Placed {
                    piece,
                    x: Length::ZERO,
                    advance: Length::ZERO,
                    leader: None,
                    tab: None,
                })
                .collect(),
            ..Line::default()
        };
        let starts = super::note_mark_starts(&line);
        assert_eq!(starts, [false, false, true, false, false, true, false]);
    }

    #[test]
    fn the_text_after_a_left_tab_lands_on_the_dot_of_its_stop_past_the_column_edge() {
        use crate::props::TabKind;
        use crate::quirks::LineStartHalves;
        let plain = Device::per_inch(600).unwrap();
        let device = Device::per_inch_with(600, |p| p.with_variant(LineStartHalves::FixedPoint));
        let twips = |t: i64| Length::from_twips(t).unwrap();
        let size = device.dots(1).units();
        // The dot of the glyph after a tab from `from` to `to` twips past the column's edge,
        // on a line that starts `start` twips past it, as the line's origin and the tab place
        // it.
        let landed = |device: Device, kind, (start, from, to): (i64, i64, i64)| {
            let start = twips(start);
            let tab = Placed {
                piece: Piece::Tab(None),
                x: twips(from - start.units() / 1_270),
                advance: twips(to - from),
                leader: None,
                tab: Some(kind),
            };
            let exact = device.line_start(start) + tab.x + tab.advance;
            device
                .snap(exact + stop_nudge(&device, (start, Length::ZERO), &tab))
                .units()
                / size
        };
        // A left stop at 1,458 twips ends at 607.5 dots, which its own conversion takes down;
        // without the quirk the place goes up.
        assert_eq!(landed(device, TabKind::Left, (0, 300, 1_458)), 607);
        assert_eq!(landed(plain, TabKind::Left, (0, 300, 1_458)), 608);
        // From a line's start of 18 twips, which goes down too, to the same stop and to one
        // on a whole dot.
        assert_eq!(landed(device, TabKind::Left, (18, 300, 1_458)), 607);
        assert_eq!(landed(device, TabKind::Left, (18, 300, 1_464)), 610);
        // Another kind of stop keeps the place of the line's start and the distance from it.
        assert_eq!(landed(device, TabKind::Right, (0, 300, 1_458)), 608);
    }

    /// The device with right-edge advances, its edge numbers (bias, limit and segment) and the
    /// step of a 12-point glyph, for the tests of the move of a justified line's last glyph.
    fn end_move_device() -> (Device, (Length, Length, Length), super::DeviceStep) {
        end_move_device_with(crate::profile::Profile::clone)
    }

    /// The device of [`end_move_device`] with some quirks of another variant (`change`).
    fn end_move_device_with(
        change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
    ) -> (Device, (Length, Length, Length), super::DeviceStep) {
        let u = Length::from_units;
        let numbers = (u(127), u(4_572), u(1_024 * 3_048));
        let advances = crate::grid::Advances::RightEdge {
            bias: numbers.0,
            limit: numbers.1,
            segment: numbers.2,
            point_steps: std::num::NonZeroU32::new(1_024),
            start: f_office_paint::WriterOffset::NONE,
        };
        let device = Device::per_inch_with(600, |p| {
            change(&p.with_variant(crate::quirks::AlignedEnds::OnDots))
        })
        .with_advances(advances);
        let step = super::DeviceStep {
            size: Length::from_points(12).unwrap(),
            measured: None,
            without_bias: false,
            rounding: None,
            spacing: Length::ZERO,
            counted_extra: None,
            short_ease: Length::ZERO,
        };
        (device, numbers, step)
    }

    /// The trailing space of 7,000 half-EMUs at `x` of a line whose right edge is `end`, of a
    /// line that counts its start from the page's left edge.
    fn trailing_space(x: Length, end: Length, step: super::DeviceStep) -> super::TrailingSpace {
        super::TrailingSpace {
            x,
            end,
            edge: Length::ZERO,
            advance: Length::from_units(7_000),
            spacing: Length::ZERO,
            step,
        }
    }

    /// The device draws a justified line's last visible glyph by the place that the steps give
    /// its trailing space from the glyph's own place, which the move leaves to the space.
    #[test]
    fn moves_the_last_glyph_by_the_place_that_the_steps_give_its_trailing_space() {
        let u = Length::from_units;
        let (device, numbers, step) = end_move_device();
        // Lines that start 0.49 dots past dot 328, whose first dot lies below the exact place,
        // and 0.51 dots past it, whose first dot lies above it.
        let dot = device.dots(1);
        let mut found = std::collections::BTreeSet::new();
        for start in [dot * 328 + u(1_494), dot * 328 + u(1_554)] {
            for advance in (20_000..60_000).step_by(97).map(u) {
                let mut glyphs = super::EdgeGlyphs::new(&device);
                for k in 0..6 {
                    glyphs
                        .edge
                        .place(&device, numbers, start + advance * k, advance);
                }
                let x = start + advance * 6;
                let space = trailing_space(x, x, step);
                let last = Some(super::LastGlyph::AfterGlyph(space));
                let moved = glyphs.end_move(&device, numbers, last, Length::ZERO);
                let at = step.place(&mut glyphs.edge, &device, numbers, (space.x, space.advance));
                assert_eq!(moved, device.justified_end_move(at, space.x));
                found.insert(moved);
            }
        }
        assert_eq!(
            found.into_iter().collect::<Vec<_>>(),
            [-dot, Length::ZERO, dot]
        );
        let glyphs = super::EdgeGlyphs::new(&device);
        assert_eq!(
            glyphs.end_move(&device, numbers, None, Length::ZERO),
            Length::ZERO
        );
    }

    /// The device moves a justified line's last visible glyph that stretched spaces come right
    /// before left by whole dots until it lies no more than the steps' limit right of its exact
    /// place, and never right.
    #[test]
    fn moves_the_last_glyph_after_stretched_spaces_within_the_limit_of_its_exact_place() {
        use crate::quirks::SpacedLastGlyph;
        let (limited, numbers, _) =
            end_move_device_with(|p| p.with_variant(SpacedLastGlyph::EdgeLimit));
        let stepped = end_move_device_with(|p| p.with_variant(SpacedLastGlyph::StepsPlace)).0;
        let glyphs = super::EdgeGlyphs::new(&limited);
        let (dot, limit, unit) = (limited.dots(1), numbers.1, Length::from_units(1));
        let last = Some(super::LastGlyph::AfterStretched);
        let moved = |past: Length| glyphs.end_move(&limited, numbers, last, past);
        assert_eq!(moved(limit), Length::ZERO);
        assert_eq!(moved(limit + unit), -dot);
        assert_eq!(moved(limit + dot), -dot);
        assert_eq!(moved(limit + dot + unit), -dot * 2);
        assert_eq!(moved(-limit - dot * 2), Length::ZERO);
        assert_eq!(
            glyphs.end_move(&stepped, numbers, last, limit + dot),
            Length::ZERO
        );
    }

    /// A last glyph at which a segment of the steps starts again moves by its trailing space
    /// too. Each restart goes to the nearest dot of its counted place plus the carry, so over a
    /// few segments of glyphs of varied advances its dot can lie more than a dot right of its
    /// exact place, and the space after it two dots past the line's right edge. The space is
    /// measured from the line's own right edge, the upper dot at an exact half: a line whose
    /// edge lies on a half dot moves its glyph as if the edge lay a dot further right than the
    /// text's exact edge gives.
    #[test]
    fn moves_a_restarted_last_glyph_by_the_line_right_edge() {
        let u = Length::from_units;
        let (device, numbers, step) = end_move_device();
        let dot = device.dots(1);
        let half = dot.div_round(2);
        let mut state: u64 = 1;
        let mut advances = std::iter::repeat_with(move || {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            u(20_000 + i64::try_from((state >> 33) % 60_000).unwrap())
        });
        let mut after_restart = std::collections::BTreeSet::new();
        let mut from_edge = 0;
        for _ in 0..400 {
            let (glyphs, x) = restarted_line(&device, numbers, &mut advances);
            for end in [x, device.snap_half_down(x) + half] {
                let space = trailing_space(x, end, step);
                let last = Some(super::LastGlyph::AfterGlyph(space));
                let moved = glyphs.end_move(&device, numbers, last, Length::ZERO);
                let mut ahead = glyphs.edge;
                let at = step.place(&mut ahead, &device, numbers, (space.x, space.advance));
                assert_eq!(moved, device.restarted_end_move(at, end, Length::ZERO));
                from_edge += i32::from(moved != device.justified_end_move(at, x));
                after_restart.insert((end == x, moved));
            }
        }
        assert!(after_restart.contains(&(true, -dot)));
        assert!(from_edge > 0);
    }

    /// The glyphs of a line that starts 0.49 dots past dot 328, with the steps' start handed
    /// on, and goes on with glyphs of `advances` until its steps have started again 8 times past
    /// dot 400, and the line's exact right edge.
    fn restarted_line(
        device: &Device,
        numbers: (Length, Length, Length),
        advances: &mut impl Iterator<Item = Length>,
    ) -> (super::EdgeGlyphs, Length) {
        let dot = device.dots(1);
        let mut glyphs = super::EdgeGlyphs::new(device);
        glyphs.edge.hands_on_start(true);
        let mut x = dot * 328 + Length::from_units(1_494);
        let mut restarts = 0;
        while restarts < 8 {
            let advance = advances.next().unwrap();
            glyphs.edge.place(device, numbers, x, advance);
            x += advance;
            restarts += i32::from(glyphs.edge.started() && x > dot * 400);
        }
        (glyphs, x)
    }

    /// At a line's right edge on an exact half dot, a space two dots past the lower dot lies
    /// one dot past the upper one, which the move of a restarted glyph takes as the nearest.
    #[test]
    fn a_restarted_last_glyph_takes_the_upper_dot_of_an_edge_on_a_half_dot() {
        let (device, _, _) = end_move_device();
        let dot = device.dots(1);
        let edge = dot * 500 + dot.div_round(2);
        assert_eq!(
            device.restarted_end_move(dot * 502, edge, Length::ZERO),
            Length::ZERO
        );
        assert_eq!(device.justified_end_move(dot * 502, edge), -dot);
        assert_eq!(
            device.restarted_end_move(dot * 503, edge, Length::ZERO),
            -dot
        );
    }

    fn test_glyph(ch: char) -> crate::text::Glyph {
        crate::text::Glyph {
            face: FaceIndex::nth(0),
            ch,
            id: 1,
            advance: Length::from_units(100),
            offset: (Length::ZERO, Length::ZERO),
            spacing: Length::ZERO,
            kerning: Length::ZERO,
            auto_space: Length::ZERO,
            counted: Length::ZERO,
            written: None,
            part: false,
            label: false,
            space: SpaceKind::Free,
            starts_run: false,
            left_out_before: crate::text::LeftOutBefore::Nothing,
            direction: crate::text::RunDirection::default(),
            side: crate::text::FontSide::Open,
            place: crate::text::TextPlace::default(),
            sizing: crate::text::LineSizing::ByFace,
        }
    }

    /// Each drawn glyph records the place that the device's steps start from, the spaces that
    /// the line places between it and the drawn glyph before, and where the steps started again
    /// among them, which a trace prints.
    #[test]
    fn records_the_place_of_each_drawn_glyph_and_the_spaces_before_it() {
        use crate::layout::StepsStart;
        use crate::lines::Step;
        let mut steps = super::Steps::default();
        for (x, ch) in (0..).step_by(100).zip(['a', ' ', ' ', 'b', ' ', 'c']) {
            let glyph = test_glyph(ch);
            let placed = Placed {
                piece: Piece::Glyph(glyph),
                x: Length::ZERO,
                advance: glyph.advance,
                leader: None,
                tab: None,
            };
            steps.piece(&placed, true);
            // The steps start at the line's first glyph and again at the second space.
            steps.placed(x == 0 || x == 200, ch == ' ');
            steps.glyph(
                &glyph,
                (Length::from_units(x), Length::from_units(x + 7)),
                (None, None),
            );
        }
        let records: Vec<(i64, i64, u32, StepsStart)> = (steps.drawn.glyphs.iter())
            .map(|drawn| {
                (
                    drawn.x.units(),
                    drawn.place.units(),
                    drawn.spaces,
                    drawn.started,
                )
            })
            .collect();
        assert_eq!(
            records,
            [
                (0, 7, 0, StepsStart::Glyph),
                (300, 307, 2, StepsStart::Space(2)),
                (500, 507, 1, StepsStart::Stepped)
            ]
        );
        assert_eq!(
            steps.drawn.steps,
            [Step::Start, Step::Stretched, Step::Stretched]
        );
    }

    /// Each character of a tab's leader gets its own record, in the order of drawing, so that
    /// the records stay one for each drawn glyph, and the glyph after the leader keeps the
    /// spaces and the step that lie before it.
    #[test]
    fn records_each_character_of_a_leader_and_leaves_the_glyph_after_it_its_step() {
        use crate::lines::Step;
        let glyph = test_glyph('a');
        let space = test_glyph(' ');
        let mut steps = super::Steps::default();
        steps.piece(
            &Placed {
                piece: Piece::Glyph(space),
                x: Length::ZERO,
                advance: space.advance,
                leader: None,
                tab: None,
            },
            false,
        );
        for x in [300, 400] {
            steps.leader(Length::from_units(x), Length::from_units(x + 5));
        }
        steps.glyph(
            &glyph,
            (Length::from_units(900), Length::from_units(906)),
            (None, None),
        );
        assert_eq!(steps.drawn.steps, [Step::Leader, Step::Leader, Step::Start]);
        let records: Vec<(i64, i64, u32)> = (steps.drawn.glyphs.iter())
            .map(|drawn| (drawn.x.units(), drawn.place.units(), drawn.spaces))
            .collect();
        assert_eq!(records, [(300, 305, 0), (400, 405, 0), (900, 906, 1)]);
    }

    /// A text object of right-to-left text with a glyph off the baseline is written glyph by
    /// glyph, the run before or after it of other properties stays whole, and two runs that
    /// the writer joins in one object go glyph by glyph together.
    #[test]
    fn writes_glyph_by_glyph_only_the_objects_that_hold_a_glyph_off_the_baseline() {
        use super::{ObjectGlyph, ObjectPiece, RtlObjectMarks, off_baseline_marks};
        // A glyph in right-to-left text, off the baseline or not, starting a run or not.
        let glyph = |ch, off, text_start| {
            ObjectPiece::Glyph(ObjectGlyph {
                face: FaceIndex::nth(0),
                ch,
                side: crate::text::FontSide::Open,
                right_to_left: true,
                text_start,
                off,
            })
        };
        let ba = |off, text_start| glyph('\u{0628}', off, text_start);
        // In right-to-left text the glyph after the one that starts a run, the run's first glyph
        // in reading order, which lies at its right end, starts an object: here the fourth
        // glyph, so that the first three pieces are one object and the last two another.
        let line = [
            ba(false, false),
            ba(true, false),
            ba(false, true),
            ba(false, false),
            ba(false, false),
        ];
        assert_eq!(
            off_baseline_marks(&line, &RtlObjectMarks::of(5)),
            [true, true, true, false, false]
        );
        // Without the start of a run, the five glyphs are one object.
        let joined = [line[0], line[1], ba(false, false), line[3], line[4]];
        assert_eq!(
            off_baseline_marks(&joined, &RtlObjectMarks::of(5)),
            [true; 5]
        );
        // A gap ends the object, and the glyphs after it stay whole.
        let gap = [line[0], line[1], ObjectPiece::Gap, line[3], line[4]];
        assert_eq!(
            off_baseline_marks(&gap, &RtlObjectMarks::of(5)),
            [true, true, false, false, false]
        );
        // A later part of a ligature in right-to-left text joins the glyph before it and starts
        // no object of its own, so the object stays the first three glyphs.
        let ObjectPiece::Glyph(facts) = line[3] else {
            unreachable!("the fourth piece is a glyph")
        };
        let part = ObjectPiece::Part {
            in_rtl: true,
            glyph: facts,
        };
        let joined_part = [line[0], line[1], part, line[2], line[3], line[4]];
        assert_eq!(
            off_baseline_marks(&joined_part, &RtlObjectMarks::of(6)),
            [true, true, false, true, false, false]
        );
        // Without a glyph off the baseline nothing goes glyph by glyph.
        let plain = [line[0], line[0], line[2], line[3], line[4]];
        assert_eq!(
            off_baseline_marks(&plain, &RtlObjectMarks::of(5)),
            [false; 5]
        );

        // Under reading-order space marks, a reading-order trailing space (visual left) joins
        // the off-baseline TD object, while a reading-order leading space (visual right) forms
        // its own TJ object and is NOT marked off-baseline.
        let trailing_and_leading = [
            glyph(' ', false, false),
            ba(true, false),
            ba(false, false),
            glyph(' ', false, true),
        ];
        let rtl_marks = RtlObjectMarks {
            reading_order: vec![true; 4],
            full: vec![false; 4],
            after_spaces: vec![false, false, false, true],
        };
        assert_eq!(
            off_baseline_marks(&trailing_and_leading, &rtl_marks),
            [true, true, true, false]
        );
    }

    #[test]
    fn a_glyph_keeps_the_move_of_the_layout_tables_when_its_text_object_is_redrawn() {
        let placed = Placed {
            piece: Piece::Tab(None),
            x: Length::ZERO,
            advance: Length::from_units(100),
            leader: None,
            tab: None,
        };
        let mut run = RunBuilder::new(FaceIndex::nth(0));
        run.push(('a', 1, None), Length::from_units(1000), &placed, false);
        run.push(('b', 2, None), Length::from_units(1100), &placed, false);
        run.shift_last((Length::from_units(-40), Length::from_units(30)));
        // The end of a text object moves its glyphs to where the writer draws them.
        run.redraw_last(&[Length::from_units(1004), Length::from_units(1108)]);
        run.settle(Length::from_units(5000));
        let drawn: Vec<(i64, i64)> = run
            .glyphs
            .iter()
            .map(|glyph| (glyph.x.units(), glyph.y.units()))
            .collect();
        assert_eq!(drawn, [(1004, 5000), (1068, 4970)]);
    }

    #[test]
    fn stretches_logical_post_tab_spaces_on_bidi_reordered_rtl_lines() {
        use super::{Origin, VisualOrder, exact_places};
        use crate::lines::Line;
        use crate::props::TabKind;
        let glyph = |ch| Placed {
            piece: Piece::Glyph(crate::text::Glyph::plain(FaceIndex::nth(0), ch)),
            x: Length::ZERO,
            advance: Length::from_units(100),
            leader: None,
            tab: None,
        };
        let tab = Placed {
            piece: Piece::Tab(None),
            x: Length::ZERO,
            advance: Length::from_units(200),
            leader: None,
            tab: Some(TabKind::Left),
        };
        // Logical order: `[label_a, ' ', label_b, TAB, ' ', w1, ' ', w2]`
        //   indices:          0     1       2       3    4    5   6    7
        // Logical `first_stretched = 5` (after TAB and leading space), `last_visible = Some(7)`.
        // Only logical index 6 (the space between w1 and w2) should stretch.
        // Visual order (RTL): `[w2(7), ' '(6), w1(5), ' '(4), TAB(3), label_b(2), ' '(1), label_a(0)]`
        let visual_line = Line {
            placed: vec![
                glyph('\u{05D1}'),
                glyph(' '),
                glyph('\u{05D0}'),
                glyph(' '),
                tab,
                glyph('\u{05D2}'),
                glyph(' '),
                glyph('\u{05D3}'),
            ],
            ..Line::default()
        };
        let logical = [7, 6, 5, 4, 3, 2, 1, 0];
        let order = VisualOrder {
            rtl: &[true; 8],
            written: 8,
            logical: &logical,
            stretched_bounds: (5, Some(7)),
        };
        let origin = Origin {
            x: Length::ZERO,
            edge: Length::ZERO,
            start: Length::ZERO,
            own: Length::ZERO,
            baseline: Length::ZERO,
            unrounded_baseline: Length::ZERO,
            grid_shift: Length::ZERO,
            space_extra: Length::from_units(50),
            space_rest: Length::ZERO,
            counted_shares: None,
            mark_shrink: Length::ZERO,
            mark_sides: crate::layout::line::MarkSides::BlankHalf,
            gap_extra: Length::ZERO,
            narrowing: None,
            drop: Length::ZERO,
            anchor_bottom: None,
            text_from: 0,
            mark: false,
            right_to_left: Some(Length::ZERO),
            starts_at_indent: false,
            segment_rest: Length::ZERO,
            steps_alone: false,
        };
        let stretches: Vec<i64> = exact_places(&visual_line, order, origin, &[])
            .into_iter()
            .map(|(_, stretch)| stretch.units())
            .collect();
        // Only visual index 1 (logical index 6) stretches by 50; the leading space after the
        // tab (visual 3 / logical 4) and the space inside the label (visual 6 / logical 1) do not.
        assert_eq!(stretches, [0, 50, 0, 0, 0, 0, 0, 0]);
    }

    #[test]
    fn drops_an_inline_vml_shape_on_an_empty_line_of_multiple_spacing() {
        use crate::layout::testing::{NORMAL, lay_out, shape_top};
        let shape = |line: i64, rule: &str| {
            let body = format!(
                r##"<w:p><w:pPr><w:spacing w:line="{line}" w:lineRule="auto" w:after="0"/></w:pPr><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><v:rect style="width:100pt;height:1pt" fillcolor="#000000" stroked="f" {rule}/></w:pict></w:r></w:p>"##
            );
            shape_top(&lay_out(&body, NORMAL, None))
        };
        // With single spacing the shape stands on the baseline, as a horizontal rule does. With
        // spacing of 1.5 lines, the plain shape stands the extra half line of the 10 pt text,
        // 100 twips, lower than the rule.
        assert_eq!(shape(240, ""), shape(240, r#"o:hr="t""#));
        assert_eq!(
            shape(360, "") - shape(360, r#"o:hr="t""#),
            100 * Length::UNITS_PER_TWIP
        );
    }
}