f-office-paint 0.2.3

Display list: the contract between layout and output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
//! Display list.
//!
//! A display list is a sequence of pages, and each page holds positioned glyph runs, filled
//! rectangles, filled paths, paths filled with gradients and images in integer units. It is
//! the only contract between layout and output: the format crates write display lists, and the
//! output crates read them without knowing the format.
//!
//! Positions are measured from the top left corner of the page, with y growing downwards. A
//! glyph's position is the point where its baseline starts.
//!
//! A group holds the items that a picture draws in its own space, such as the records of a
//! metafile. Output draws them in their place, and a target's PDF writer leaves them where the
//! layout puts them.
//!
//! [`Page::painted`] gives the items that paint, in painting order, with a group's items in its
//! place ([`Painted`]), and an output implements [`PageSink`], whose calls [`Page::replay`] makes
//! for them.
//!
//! An image keeps the encoded bytes of its file, and output decodes them when it draws the
//! image. The bytes are shared, so the pages and items that show the same image hold one copy
//! of them. The picture decode, the function `decode` that both outputs call, and its first
//! step `decode_file`, which the writer of pictures again calls too, lie behind the feature
//! `decode`, which only the output stage turns on: a format crate needs no decoder. The JPEG
//! files of four components and the CMYK profiles used by decode tests lie behind the feature `files`.

#![deny(clippy::float_arithmetic)]

use std::num::NonZeroU32;
use std::ops::Range;
use std::sync::Arc;

use f_office_fonts::FontId;
use f_office_units::binary32::Binary32;
use f_office_units::{Length, div_round, div_round_i128};

mod color_effect;
#[cfg(feature = "decode")]
mod decode;
#[cfg(feature = "files")]
pub mod files;
pub mod image_header;
mod image_store;
mod page_sizes;
pub mod paper_forms;
mod sink;
pub mod stroke;
#[cfg(feature = "testing")]
pub mod testing;

pub use color_effect::{ColorEffect, ImageColor};
pub use image_store::{
    DEFAULT_IMAGE_BYTES_CACHE, ImageData, ImageId, ImageKey, ImageLoader, ImageRef, LruBytesCache,
    next_store_id,
};

#[cfg(feature = "decode")]
pub use decode::{converts_inks, decode, decode_file, without_profile};
pub use page_sizes::{GivenSize, PageSizes};
pub use sink::{PageSink, Painted};

/// The pages of one rendered document.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DisplayList {
    /// The pages in order.
    pages: Vec<Page>,
}

/// One page.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Page {
    /// Page width.
    width: Length,
    /// Page height.
    height: Length,
    /// The orientation that the page's section sets, which a writer's page offsets read
    /// ([`WriterOffset::on_page`]).
    orientation: Orientation,
    /// Items in painting order: a later item paints over an earlier one.
    items: Vec<Item>,
}

/// The orientation that a page's section sets for the paper, whatever the page's sides: in
/// DOCX, `w:pgSz/@w:orient` (ECMA-376 Part 1, 17.6.13), portrait when it is missing. A writer
/// whose page offset follows the page's paper form gives a page in a portrait section no rotated
/// form ([`paper_forms::ClassRule`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Orientation {
    /// Portrait (`portrait`), and the orientation of a section that sets none.
    #[default]
    Portrait,
    /// Landscape (`landscape`).
    Landscape,
}

impl DisplayList {
    /// A display list of `pages`, in order. For the format crates, which build display lists;
    /// it carries no promise.
    #[must_use]
    pub const fn new(pages: Vec<Page>) -> Self {
        Self { pages }
    }

    /// The pages in order.
    #[must_use]
    pub const fn pages(&self) -> &[Page] {
        self.pages.as_slice()
    }

    /// The pages in order, out of the list. For the format crates, which build display lists;
    /// it carries no promise.
    #[must_use]
    pub fn into_pages(self) -> Vec<Page> {
        self.pages
    }
}

impl Page {
    /// A page `width` by `height`, in a section of `orientation`, that paints `items` in order:
    /// a later item paints over an earlier one. For the format crates, which build pages; it
    /// carries no promise.
    #[must_use]
    pub const fn new(
        width: Length,
        height: Length,
        orientation: Orientation,
        items: Vec<Item>,
    ) -> Self {
        Self {
            width,
            height,
            orientation,
            items,
        }
    }

    /// The orientation that the page's section sets.
    #[must_use]
    pub const fn orientation(&self) -> Orientation {
        self.orientation
    }

    /// The page's width.
    #[must_use]
    pub const fn width(&self) -> Length {
        self.width
    }

    /// The page's height.
    #[must_use]
    pub const fn height(&self) -> Length {
        self.height
    }

    /// The items in painting order: a later item paints over an earlier one.
    #[must_use]
    pub const fn items(&self) -> &[Item] {
        self.items.as_slice()
    }

    /// The same page with the items that `change` makes of its items, such as the items of a
    /// header put behind them. Every other property of the page stays, so a change of the
    /// items names none of them. For the format crates, which build pages; it carries no
    /// promise.
    #[must_use]
    pub fn map_items(self, change: impl FnOnce(Vec<Item>) -> Vec<Item>) -> Self {
        Self {
            items: change(self.items),
            ..self
        }
    }
}

/// One thing to paint.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Item {
    /// Glyphs from one font at one size and color.
    Glyphs(GlyphRun),
    /// A filled rectangle, such as an underline, a highlight or shading.
    Rect(Rect),
    /// A filled path, such as a shape or a border.
    Path(PathItem),
    /// A path filled with an axial gradient, such as a bar of a chart.
    Gradient(GradientItem),
    /// An image scaled to fill a rectangle, such as a picture.
    Image(ImageItem),
    /// Items in painting order, such as the records of a metafile that a picture draws in its
    /// own space or the text of a text box, with the outline
    /// outside which they show nothing. A target's PDF writer leaves a picture's own items where
    /// the layout puts them, and places the page's as the page's ([`Writer::finish`],
    /// [`GroupPlaces`]).
    Group(Group),
}

/// The items of an [`Item::Group`], in painting order, and the outline outside which they
/// show nothing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Group {
    /// The items, in painting order.
    pub items: Vec<Item>,
    /// The outline outside which the items show nothing, or `None` when they show everywhere.
    /// A clip without area shows nothing.
    pub clip: Option<GroupClip>,
    /// Whose items the group holds, which says whether the writer places them.
    pub places: GroupPlaces,
}

/// Whose items a group holds, which says whether a target's PDF writer places them
/// ([`Writer::finish`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GroupPlaces {
    /// A picture's own items, such as the records of a metafile, which the writer writes
    /// inside the picture: the writer leaves them where
    /// the layout puts them.
    #[default]
    Own,
    /// The page's items under a clip, such as the text of a text box: the writer places them
    /// as it places the page's, and stretches the clip's outline as it stretches a path.
    Page,
    /// A table cell's items under the cell's clip: the writer places them, and stretches the
    /// clip's outline, as for [`Self::Page`], and it also moves the clip's points by its
    /// offsets as it moves a filled rectangle's edges, so that the clip stays on the cell's
    /// lines and its text.
    Cell,
    /// The page's items whose every point the writer places, such as the pictures of an art
    /// border: as for [`Self::Page`], and it also moves the points of the group's clip and of
    /// the paths that the group holds by its offsets, as it moves a filled rectangle's edges,
    /// and writes them with its digits, without holding them on steps.
    Points,
    /// Filled rectangles that the writer fills and strokes with an outline `width` wide, such
    /// as the rectangles of an art border's pictures: the writer places each edge at its own
    /// place, also between two device dots, by the page entry of its offset, holds the edges on
    /// steps as it holds a filled rectangle's, and then draws each rectangle as a PDF fills and
    /// strokes it: the rectangle, and after it the filled outline of its stroke, from half the
    /// width outside its edges, with round corners, to half the width inside them. The group
    /// holds filled rectangles only.
    Stroked {
        /// The width of the outline around each rectangle.
        width: Length,
    },
}

impl Group {
    /// A group of a picture's own `items` that shows them everywhere.
    #[must_use]
    pub fn new(items: Vec<Item>) -> Self {
        Self {
            items,
            clip: None,
            places: GroupPlaces::Own,
        }
    }

    /// A group of the page's `items` that `clip` cuts, which the writer places as the page's.
    #[must_use]
    pub fn of_page(items: Vec<Item>, clip: GroupClip) -> Self {
        Self {
            items,
            clip: Some(clip),
            places: GroupPlaces::Page,
        }
    }

    /// A group of a table cell's `items` that the cell's `clip` cuts, which the writer places
    /// as the page's, with the clip ([`GroupPlaces::Cell`]).
    #[must_use]
    pub fn of_cell(items: Vec<Item>, clip: GroupClip) -> Self {
        Self {
            items,
            clip: Some(clip),
            places: GroupPlaces::Cell,
        }
    }

    /// The items that the writer places as the page's: those of a group of the page's items,
    /// and none of a picture's own.
    fn placed_items(&mut self) -> &mut [Item] {
        match self.places {
            GroupPlaces::Page
            | GroupPlaces::Cell
            | GroupPlaces::Points
            | GroupPlaces::Stroked { .. } => &mut self.items,
            GroupPlaces::Own => &mut [],
        }
    }

    /// The points of the group's clip and of the paths that it holds, not those of the groups
    /// in it.
    fn points_mut(&mut self) -> impl Iterator<Item = &mut Point> {
        let clip = self.clip.iter_mut().flat_map(|clip| &mut clip.commands);
        let items = self.items.iter_mut().flat_map(|item| -> Vec<&mut Point> {
            match item {
                Item::Path(path) => path
                    .commands
                    .iter_mut()
                    .flat_map(PathCommand::points_mut)
                    .collect(),
                Item::Gradient(GradientItem {
                    commands,
                    start,
                    end,
                    ..
                }) => commands
                    .iter_mut()
                    .flat_map(PathCommand::points_mut)
                    .chain([start, end])
                    .collect(),
                _ => Vec::new(),
            }
        });
        clip.flat_map(PathCommand::points_mut).chain(items)
    }

    /// Whether the group shows nothing, because its clip has no area.
    #[must_use]
    pub fn shows_nothing(&self) -> bool {
        self.clip.as_ref().is_some_and(|clip| !clip.has_area())
    }
}

/// The outline outside which the items of a group show nothing: a path, whose outlines close
/// as a fill closes them, and the rule that decides which points lie inside it, as a clip path
/// of a PDF has them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GroupClip {
    /// The outlines of the clip.
    pub commands: Vec<PathCommand>,
    /// The rule that decides which points lie inside the outlines.
    pub fill_rule: FillRule,
}

impl GroupClip {
    /// The clip of the rectangle whose top left corner is at `x` and `y`, with `width` and
    /// `height`.
    #[must_use]
    pub fn rect(x: Length, y: Length, width: Length, height: Length) -> Self {
        let corner = |x, y| PathCommand::LineTo(Point { x, y });
        Self {
            commands: vec![
                PathCommand::MoveTo(Point { x, y }),
                corner(x + width, y),
                corner(x + width, y + height),
                corner(x, y + height),
                PathCommand::Close,
            ],
            fill_rule: FillRule::NonZero,
        }
    }

    /// Whether the clip can enclose area: whether the box around its points has both a width
    /// and a height. A clip without area shows nothing.
    #[must_use]
    pub fn has_area(&self) -> bool {
        let spread = |of: fn(Point) -> Length| {
            let mut values = self.commands.iter().flat_map(PathCommand::points).map(of);
            let first = values.next();
            first.is_some_and(|first| values.any(|value| value != first))
        };
        spread(|point| point.x) && spread(|point| point.y)
    }
}

impl Item {
    /// Maps the places and the lengths of this item, and of each item of a group, as a move
    /// or a scale of the whole item does. `place` maps each glyph's origin, each point of a
    /// path and of a group's clip, and the top left corner of a rectangle, of an image and of
    /// an image's clip. `length` maps the size of a glyph run (the length of one em) and the
    /// width of its outline, and the width and the height of a rectangle, of an image and of
    /// an image's clip. The colors, the turns, the text and the images stay.
    pub fn map_places(
        &mut self,
        mut place: impl FnMut(Point) -> Point,
        mut length: impl FnMut(Length) -> Length,
    ) {
        self.map_places_with(&mut place, &mut length);
    }

    /// The first place that [`Self::map_places`] maps, read without a copy: a glyph run's
    /// first origin, a path's first point, the top left corner of a rectangle or of an image,
    /// and in a group the first place of its items, else of its clip. `None` for an item with
    /// no place, such as an empty group.
    #[must_use]
    pub fn first_place(&self) -> Option<Point> {
        let first_point =
            |commands: &[PathCommand]| commands.iter().flat_map(PathCommand::points).next();
        match self {
            Self::Glyphs(run) => run.glyphs.first().map(|glyph| Point {
                x: glyph.x,
                y: glyph.y,
            }),
            Self::Rect(rect) => Some(Point {
                x: rect.x,
                y: rect.y,
            }),
            Self::Path(path) => first_point(&path.commands),
            Self::Gradient(gradient) => first_point(&gradient.commands),
            Self::Image(image) => Some(Point {
                x: image.x,
                y: image.y,
            }),
            Self::Group(group) => group.items.iter().find_map(Self::first_place).or_else(|| {
                group
                    .clip
                    .as_ref()
                    .and_then(|clip| first_point(&clip.commands))
            }),
        }
    }

    fn map_places_with(
        &mut self,
        place: &mut dyn FnMut(Point) -> Point,
        length: &mut dyn FnMut(Length) -> Length,
    ) {
        match self {
            Self::Glyphs(run) => {
                run.size = length(run.size);
                for glyph in &mut run.glyphs {
                    Point {
                        x: glyph.x,
                        y: glyph.y,
                    } = place(Point {
                        x: glyph.x,
                        y: glyph.y,
                    });
                }
                if let Some(outline) = &mut run.outline {
                    outline.width = length(outline.width);
                }
            }
            Self::Rect(rect) => {
                Point {
                    x: rect.x,
                    y: rect.y,
                } = place(Point {
                    x: rect.x,
                    y: rect.y,
                });
                rect.width = length(rect.width);
                rect.height = length(rect.height);
            }
            Self::Path(path) => map_points(&mut path.commands, place),
            Self::Gradient(gradient) => {
                map_points(&mut gradient.commands, place);
                gradient.start = place(gradient.start);
                gradient.end = place(gradient.end);
            }
            Self::Image(image) => {
                Point {
                    x: image.x,
                    y: image.y,
                } = place(Point {
                    x: image.x,
                    y: image.y,
                });
                image.width = length(image.width);
                image.height = length(image.height);
                if let Some(clip) = &mut image.clip {
                    clip.map_places_with(place, length);
                }
            }
            Self::Group(group) => {
                for item in &mut group.items {
                    item.map_places_with(place, length);
                }
                if let Some(clip) = &mut group.clip {
                    map_points(&mut clip.commands, place);
                }
            }
        }
    }
}

/// Maps each point of the path `commands` by `place`.
fn map_points(commands: &mut [PathCommand], place: &mut dyn FnMut(Point) -> Point) {
    for point in commands.iter_mut().flat_map(PathCommand::points_mut) {
        *point = place(*point);
    }
}

impl Clip {
    fn map_places_with(
        &mut self,
        place: &mut dyn FnMut(Point) -> Point,
        length: &mut dyn FnMut(Length) -> Length,
    ) {
        Point {
            x: self.x,
            y: self.y,
        } = place(Point {
            x: self.x,
            y: self.y,
        });
        self.width = length(self.width);
        self.height = length(self.height);
    }
}

/// Glyphs from one font at one size and color.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GlyphRun {
    /// The font face in the font database.
    pub font: FontId,
    /// The font size, which is the length of one em.
    pub size: Length,
    /// The fill color.
    pub color: Rgb,
    /// The text that the glyphs show, so that output can carry it for search and copy.
    pub text: String,
    /// The glyphs in the order of the text.
    pub glyphs: Vec<Glyph>,
    /// The line drawn along the outline of each glyph, over its fill, if any.
    pub outline: Option<Outline>,
    /// Whether the glyphs' interiors are filled with [`Self::color`]. `false` for unfilled text
    /// such as hollow outlined text or gradient-filled text whose fill is painted as a path
    /// underneath, keeping the run's outline and selectable text.
    pub filled: bool,
    /// Whether the text has an effect that the output does not draw, such as a reflection or
    /// a 3-D format.
    pub effect: bool,
    /// How each glyph is turned, scaled or slanted about its origin, as the text of a table
    /// cell with a text direction turns or a slanted glyph leans: a step along the run goes `xx`
    /// right and `yx` down, and a step down the glyph goes `xy` right and `yy` down. `None`
    /// draws the glyphs upright.
    pub turn: Option<Turn>,
}

impl GlyphRun {
    /// The byte range of [`GlyphRun::text`] that `glyph` shows, or `None` when the range does
    /// not hold whole characters of the text: when it ends before it starts, ends beyond the
    /// text, or starts or ends inside a character.
    #[must_use]
    pub fn glyph_range(&self, glyph: &Glyph) -> Option<Range<usize>> {
        let start = usize::try_from(glyph.text_start).ok()?;
        let end = usize::try_from(glyph.text_end).ok()?;
        self.text.get(start..end).map(|_| start..end)
    }

    /// The text that `glyph` shows, from [`GlyphRun::glyph_range`].
    #[must_use]
    pub fn glyph_text(&self, glyph: &Glyph) -> Option<&str> {
        self.text.get(self.glyph_range(glyph)?)
    }
}

/// A line along the outline of each glyph of a run.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Outline {
    /// The line width.
    pub width: Length,
    /// The line color.
    pub color: Rgb,
    /// How the line turns at the corners of the outline.
    pub join: Join,
}

/// How a line turns at a corner.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Join {
    /// A round corner.
    Round,
    /// A pointed corner, cut off where the miter would be longer than 10 times the line
    /// width, PDF's default miter limit.
    Miter,
}

/// One positioned glyph.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Glyph {
    /// The glyph ID in the font.
    pub id: u32,
    /// The x position of the glyph origin.
    pub x: Length,
    /// The y position of the baseline.
    pub y: Length,
    /// The byte range in [`GlyphRun::text`] that this glyph shows.
    pub text_start: u32,
    /// The end of the byte range in [`GlyphRun::text`] that this glyph shows.
    pub text_end: u32,
}

/// A filled rectangle.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rect {
    /// Left edge.
    pub x: Length,
    /// Top edge.
    pub y: Length,
    /// Width.
    pub width: Length,
    /// Height.
    pub height: Length,
    /// Fill color.
    pub color: Rgb,
}

/// A filled path: one or more outlines in page space, filled with one color.
///
/// Each outline starts with [`PathCommand::MoveTo`]. An outline that does not end with
/// [`PathCommand::Close`] is filled as if a straight line closed it, as in PDF and SVG. Output
/// fills a path with the same anti-aliasing as glyphs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PathItem {
    /// The outlines, as a list of commands.
    pub commands: Vec<PathCommand>,
    /// The fill color.
    pub color: Rgb,
    /// The rule that decides which points lie inside the path.
    pub fill_rule: FillRule,
}

/// A path filled with an axial gradient: each point inside the path takes the color at the
/// place of its projection on the axis from `start` to `end`, between the colors of the stops,
/// and the color of the first stop before the start and of the last stop past the end, as an
/// axial shading of a PDF that extends at both ends paints it (ISO 32000-2, 8.7.4.5.3).
///
/// The path's outlines close and fill as those of a [`PathItem`] do.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct GradientItem {
    /// The outlines, as a list of commands.
    pub commands: Vec<PathCommand>,
    /// The rule that decides which points lie inside the path.
    pub fill_rule: FillRule,
    /// The start of the axis, the place of [`GradientStop::START`].
    pub start: Point,
    /// The end of the axis, the place of [`GradientStop::END`].
    pub end: Point,
    /// The stops, in the order of their places. Two stops at one place change the color there
    /// at once.
    pub stops: Vec<GradientStop>,
}

impl GradientItem {
    /// A path filled with an axial gradient along `axis`, from its start to its end, through
    /// `stops`.
    #[must_use]
    pub fn new(
        commands: Vec<PathCommand>,
        fill_rule: FillRule,
        axis: (Point, Point),
        stops: Vec<GradientStop>,
    ) -> Self {
        Self {
            commands,
            fill_rule,
            start: axis.0,
            end: axis.1,
            stops,
        }
    }

    /// The color at `place` on the axis, in millionths of the axis from its start: the color of
    /// the first stop at or before the start, of the last stop at or past the end, and between
    /// two stops each channel in proportion to the place between theirs, rounded to the nearest
    /// value, a half up. A place where two stops meet takes the later stop's color. Black for a
    /// gradient without stops.
    #[must_use]
    pub fn color_at(&self, place: i64) -> Rgb {
        let (Some(first), Some(last)) = (self.stops.first(), self.stops.last()) else {
            return Rgb::BLACK;
        };
        if place < i64::from(first.place) {
            return first.color;
        }
        let after = self
            .stops
            .partition_point(|stop| i64::from(stop.place) <= place);
        let (Some(before), Some(next)) = (
            after.checked_sub(1).and_then(|at| self.stops.get(at)),
            self.stops.get(after),
        ) else {
            return last.color;
        };
        let span = i64::from(next.place) - i64::from(before.place);
        let along = place - i64::from(before.place);
        let mix = |from: u8, to: u8| {
            let from = i64::from(from);
            let value = from + div_round(along * (i64::from(to) - from), span);
            u8::try_from(value.clamp(0, 255)).unwrap_or(u8::MAX)
        };
        Rgb {
            r: mix(before.color.r, next.color.r),
            g: mix(before.color.g, next.color.g),
            b: mix(before.color.b, next.color.b),
        }
    }
}

/// One stop of a [`GradientItem`]: a place on the axis and its color.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct GradientStop {
    /// The place on the axis, in millionths of the axis from its start
    /// ([`GradientStop::START`]) to its end ([`GradientStop::END`]).
    pub place: u32,
    /// The color at the place.
    pub color: Rgb,
}

impl GradientStop {
    /// The place of the axis's start.
    pub const START: u32 = 0;
    /// The place of the axis's end: one million millionths.
    pub const END: u32 = 1_000_000;

    /// A stop at `place`, in millionths of the axis, with `color`.
    #[must_use]
    pub const fn new(place: u32, color: Rgb) -> Self {
        Self { place, color }
    }
}

/// One command of a [`PathItem`]. A curve or line starts at the end point of the command
/// before it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PathCommand {
    /// Starts a new outline at a point.
    MoveTo(Point),
    /// A straight line to a point.
    LineTo(Point),
    /// A quadratic Bézier curve through a control point to an end point.
    QuadTo(Point, Point),
    /// A cubic Bézier curve through two control points to an end point.
    CubicTo(Point, Point, Point),
    /// A straight line back to the start of the outline, which ends it.
    Close,
}

impl PathCommand {
    /// The points of this command in order: the point of a move or a line, the control points
    /// and the end point of a curve, and none for a close.
    pub fn points_mut(&mut self) -> impl Iterator<Item = &mut Point> {
        let points = match self {
            Self::MoveTo(a) | Self::LineTo(a) => [Some(a), None, None],
            Self::QuadTo(a, b) => [Some(a), Some(b), None],
            Self::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
            Self::Close => [None, None, None],
        };
        points.into_iter().flatten()
    }

    /// The points of this command in order, as [`PathCommand::points_mut`] gives them.
    pub fn points(&self) -> impl Iterator<Item = Point> {
        let points = match *self {
            Self::MoveTo(a) | Self::LineTo(a) => [Some(a), None, None],
            Self::QuadTo(a, b) => [Some(a), Some(b), None],
            Self::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
            Self::Close => [None, None, None],
        };
        points.into_iter().flatten()
    }
}

/// The extent, 1/256 pt rounded up to whole half-EMUs, at or below which a fill paints nothing
/// in the outputs. A reader of a PDF paints a fill that thin as a line of its own width, at
/// least a pixel wide (hayro and pdf.js draw a line along the fill's box), so that a PDF cannot
/// show it as the faint fill that it is; the raster leaves it out, as the PDF writer does.
pub const THINNEST_FILL: Length = Length::from_units(100);

/// Whether a fill whose box is `across` wide and `down` tall paints: whether both exceed
/// [`THINNEST_FILL`]. A negative side counts by its size.
#[must_use]
pub const fn fill_shows(across: Length, down: Length) -> bool {
    across.units().abs() > THINNEST_FILL.units() && down.units().abs() > THINNEST_FILL.units()
}

/// Whether the filled path `commands` paints: whether the box of the points that
/// [`fill_commands`] gives, with the control points of its curves, passes [`fill_shows`].
#[must_use]
pub fn path_shows(commands: &[PathCommand]) -> bool {
    let drawn = fill_commands(commands);
    let mut points = drawn.iter().flat_map(PathCommand::points);
    let Some(first) = points.next() else {
        return false;
    };
    let (low, high) = points.fold((first, first), |(low, high), p| {
        (
            Point {
                x: low.x.min(p.x),
                y: low.y.min(p.y),
            },
            Point {
                x: high.x.max(p.x),
                y: high.y.max(p.y),
            },
        )
    });
    fill_shows(high.x - low.x, high.y - low.y)
}

/// The commands that every output draws for the filled path `commands`, so that a PDF file
/// holds the path that the raster draws. A quadratic curve, which PDF does not have, becomes the
/// cubic curve of [`stroke::quad_as_cubic`], as a stroke of it does; a quadratic curve with no
/// point before it starts at its control point. A straight line to the point where it
/// starts is left out: it adds nothing to a fill, and a reader of a PDF can make it longer so
/// that a stroke of it shows its round cap.
#[must_use]
pub fn fill_commands(commands: &[PathCommand]) -> Vec<PathCommand> {
    let mut current: Option<Point> = None;
    let mut start: Option<Point> = None;
    commands
        .iter()
        .filter_map(|&command| match command {
            PathCommand::MoveTo(p) => {
                (current, start) = (Some(p), Some(p));
                Some(command)
            }
            PathCommand::LineTo(p) => {
                let empty = current == Some(p);
                current = Some(p);
                (!empty).then_some(command)
            }
            PathCommand::CubicTo(_, _, p) => {
                current = Some(p);
                Some(command)
            }
            PathCommand::QuadTo(control, end) => {
                let from = current.unwrap_or(control);
                current = Some(end);
                let [_, first, second, _] = stroke::quad_as_cubic(from, control, end);
                Some(PathCommand::CubicTo(first, second, end))
            }
            PathCommand::Close => {
                current = start;
                Some(command)
            }
        })
        .collect()
}

/// A point on the page.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Point {
    /// The distance from the left edge of the page.
    pub x: Length,
    /// The distance from the top edge of the page.
    pub y: Length,
}

/// The rule that decides which points lie inside a path, as PDF and SVG define them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FillRule {
    /// A point is inside when the outlines wind around it a number of times other than zero,
    /// counting each direction with its own sign.
    #[default]
    NonZero,
    /// A point is inside when a ray from it crosses the outlines an odd number of times.
    EvenOdd,
}

/// An image scaled to fill a rectangle.
///
/// The whole image fills the rectangle at `x` and `y` with `width` and `height`, turned about
/// its centre by `turn`, and only the part inside `clip` shows, so a cropped picture has a
/// rectangle larger than its clip. Output draws the formats that it can decode, and leaves out an image in another format, with data
/// that it cannot decode, or with a side that is not positive.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageItem {
    /// Left edge of the whole image.
    pub x: Length,
    /// Top edge of the whole image.
    pub y: Length,
    /// Width of the whole image.
    pub width: Length,
    /// Height of the whole image.
    pub height: Length,
    /// The rectangle outside which nothing of the image shows, or `None` to show all of it.
    pub clip: Option<Clip>,
    /// How the image is turned about the centre of its rectangle, or `None` for an upright
    /// image.
    pub turn: Option<Turn>,
    /// The encoded image.
    pub image: Image,
}

/// How an image is turned on the page, as a PDF can rotate, flip or skew its images: the
/// linear map from the image's upright rectangle to the page, about the rectangle's centre. A
/// point `u` right of the centre and `v` below it lands `xx u + xy v` right of the centre and
/// `yx u + yy v` below it, with each entry in millionths ([`Turn::SCALE`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Turn {
    /// How far right a step right goes.
    pub xx: i32,
    /// How far down a step right goes.
    pub yx: i32,
    /// How far right a step down goes.
    pub xy: i32,
    /// How far down a step down goes.
    pub yy: i32,
}

impl Turn {
    /// The units of an entry in one: millionths.
    pub const SCALE: i32 = 1_000_000;
}

impl ImageItem {
    /// The part of the item's clip that lies on its upright rectangle, or `None` without a
    /// clip or with one that does not meet the rectangle. Nothing of the image shows outside
    /// either, so the item shows the same with this clip.
    #[must_use]
    pub fn shown(&self) -> Option<Clip> {
        let clip = self.clip?;
        let end = |start: Length, length: Length| start.units().checked_add(length.units());
        let left = clip.x.max(self.x).units();
        let top = clip.y.max(self.y).units();
        let right = end(clip.x, clip.width)?.min(end(self.x, self.width)?);
        let bottom = end(clip.y, clip.height)?.min(end(self.y, self.height)?);
        (left < right && top < bottom).then(|| Clip {
            x: Length::from_units(left),
            y: Length::from_units(top),
            width: Length::from_units(right - left),
            height: Length::from_units(bottom - top),
        })
    }
}

/// A rectangle outside which an item shows nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Clip {
    /// Left edge.
    pub x: Length,
    /// Top edge.
    pub y: Length,
    /// Width.
    pub width: Length,
    /// Height.
    pub height: Length,
}

/// The encoded payload of an image file with its format. A clone shares inline bytes or copies
/// only the lightweight lazy [`ImageRef`] handle.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Image {
    /// The format of the bytes.
    pub format: ImageFormat,
    /// Inline shared bytes or a lazy [`ImageRef`] handle loaded on demand.
    pub data: ImageData,
    /// Multiplier of the file's alpha; [`Opacity::FULL`] preserves the file's alpha.
    pub opacity: Opacity,
    /// Color conversion applied to decoded straight RGB, before alpha compositing.
    pub color: ImageColor,
    /// How the inks of a JPEG file of four components turn into RGB.
    pub inks: InkConversion,
}

/// The opacity of a picture: the multiplier of its file's alpha, a share of
/// [`f_office_units::scale::DRAWING_WHOLE`] from none to a whole.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Opacity(i64);

impl Opacity {
    /// The opacity that preserves the file's alpha.
    pub const FULL: Self = Self(f_office_units::scale::DRAWING_WHOLE);

    /// The opacity of `share` thousandths of a percent, limited to none and a whole, as
    /// DrawingML limits a fixed alpha modifier before it multiplies the alpha.
    #[must_use]
    pub const fn clamped(share: i64) -> Self {
        let whole = f_office_units::scale::DRAWING_WHOLE;
        Self(if share < 0 {
            0
        } else if share > whole {
            whole
        } else {
            share
        })
    }

    /// The product of two opacities, rounded to the nearest thousandth of a percent, a half
    /// up; it lies between none and a whole, as each of them does.
    #[must_use]
    pub const fn times(self, other: Self) -> Self {
        Self(div_round(
            self.0 * other.0,
            f_office_units::scale::DRAWING_WHOLE,
        ))
    }

    /// The share, in thousandths of a percent: from 0 to 100,000.
    #[must_use]
    pub const fn share(self) -> i64 {
        self.0
    }
}

impl Image {
    /// Takes the bytes of an image file and detects their format.
    #[must_use]
    pub fn new(data: impl Into<Arc<[u8]>>) -> Self {
        let data = data.into();
        Self {
            format: ImageFormat::detect(&data),
            data: ImageData::Inline(data),
            opacity: Opacity::FULL,
            color: ImageColor::Original,
            inks: InkConversion::EmbeddedProfile,
        }
    }

    /// Creates an image backed by a lazy [`ImageRef`] handle with detected `format`.
    #[must_use]
    pub const fn from_ref(format: ImageFormat, image_ref: ImageRef) -> Self {
        Self {
            format,
            data: ImageData::Lazy(image_ref),
            opacity: Opacity::FULL,
            color: ImageColor::Original,
            inks: InkConversion::EmbeddedProfile,
        }
    }

    /// Loads the complete encoded bytes of this image (zero-copy `Arc::clone` for inline bytes,
    /// lazy read for [`ImageRef`] handles).
    #[must_use]
    pub fn load_bytes(&self) -> Option<Arc<[u8]>> {
        self.data.bytes()
    }

    /// Loads the complete encoded bytes together with their effective [`ImageFormat`].
    #[must_use]
    pub fn load_bytes_with_format(&self) -> Option<(Arc<[u8]>, ImageFormat)> {
        self.data.bytes_with_format(self.format)
    }

    /// Loads up to `max_bytes` leading bytes for header inspection without inflating the full
    /// image when backed by a lazy loader.
    #[must_use]
    pub fn load_prefix(&self, max_bytes: usize) -> Option<Arc<[u8]>> {
        self.data.prefix(max_bytes)
    }

    /// Returns a cache key uniquely identifying this image's encoded source.
    #[must_use]
    pub fn cache_key(&self) -> ImageKey {
        self.data.key()
    }
}

/// How the picture decode turns the ink amounts of a JPEG file of four components (CMYK or
/// YCCK) into RGB. The format crate chooses it from the target; the output crates apply it
/// without knowing the target.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum InkConversion {
    /// Through the CMYK profile that the file embeds, with the perceptual intent, and by the
    /// plain conversion, R = (255 − C)(255 − K) / 255 and the same for G and B, for a file
    /// without one or whose profile does not read or convert.
    #[default]
    EmbeddedProfile,
    /// Through the ink table, the colors of six amounts of each ink,
    /// interpolated multilinear between them, whatever profile the file embeds.
    InkTable,
}

/// The most bytes of one image's RGBA pixels with 8 bits a channel, which the picture decode
/// keeps, and the most that its decoder may allocate: 256 MiB, the RGBA pixels of an image of
/// 8,192 by 8,192 pixels. The output crates leave a larger image out
/// ([`ImageFault::Limit`]), but for a JPEG file of its own colors, which the PDF output writes
/// as it is, without a decode; and the JPEG decoder refuses a frame whose coefficient blocks
/// need more.
pub const MAX_DECODED_BYTES: u64 = 256 << 20;

/// The most bytes of the RGBA pixels of one PNG picture that a target's PDF writer cuts or
/// resamples before the outputs draw it, and the most that its decoder may allocate: 512 MiB,
/// twice [`MAX_DECODED_BYTES`], the default limit of the `image` crate. The writer reads a larger picture than the outputs can draw
/// because it writes a smaller one, which the outputs then decode within
/// [`MAX_DECODED_BYTES`]. A PNG picture that needs more stays as it is, with a warning.
pub const MAX_DECODED_BYTES_TO_WRITE_AGAIN: u64 = 512 << 20;

/// The format of an image file.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageFormat {
    /// PNG (ISO/IEC 15948).
    Png,
    /// JPEG (ISO/IEC 10918-1), in a JFIF or Exif file.
    Jpeg,
    /// GIF.
    Gif,
    /// Windows bitmap (BMP).
    Bmp,
    /// TIFF.
    Tiff,
    /// Windows Enhanced Metafile (EMF), defined by MS-EMF.
    Emf,
    /// Windows Metafile (WMF), defined by MS-WMF.
    Wmf,
    /// An effect picture that a layout made: what a part of a page that Word draws as one
    /// picture of pixels shows, such as the plot area of a 3-D chart, which the output stage
    /// draws into pixels. No file of a document is in this format: [`ImageFormat::detect`]
    /// never gives it.
    EffectPicture,
    /// A format that none of the others matches.
    Unknown,
}

/// Why an output leaves an image of the display list out.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ImageFault {
    /// The output draws no image of its format.
    Format,
    /// The image's data does not decode in its format.
    Data,
    /// The image is larger than the output's limits: its RGBA pixels, or what its decoder
    /// allocates, need more bytes than the output's limit, or a side is longer than the output
    /// holds.
    Limit,
}

impl std::fmt::Display for ImageFault {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Format => "the output draws no image of this format",
            Self::Data => "its data does not decode",
            Self::Limit => "it is larger than the output's limits",
        })
    }
}

impl std::fmt::Display for ImageFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Png => "PNG",
            Self::Jpeg => "JPEG",
            Self::Gif => "GIF",
            Self::Bmp => "BMP",
            Self::Tiff => "TIFF",
            Self::Emf => "EMF",
            Self::Wmf => "WMF",
            Self::EffectPicture => "effect picture",
            Self::Unknown => "unknown",
        })
    }
}

impl ImageFormat {
    /// Detects the format from the signature at the start of an image file.
    #[must_use]
    pub fn detect(data: &[u8]) -> Self {
        /// The `EMR_HEADER` record type that starts an EMF file, little-endian (MS-EMF 2.3.4.2).
        const EMR_HEADER: [u8; 4] = [1, 0, 0, 0];
        /// The `" EMF"` signature at byte 40 of the EMF header record.
        const EMF_SIGNATURE: &[u8] = b" EMF";
        let starts = |signature: &[u8]| data.starts_with(signature);
        if starts(b"\x89PNG\r\n\x1a\n") {
            Self::Png
        } else if starts(&[0xFF, 0xD8, 0xFF]) {
            Self::Jpeg
        } else if starts(b"GIF87a") || starts(b"GIF89a") {
            Self::Gif
        } else if starts(b"BM") {
            Self::Bmp
        } else if starts(b"II*\0") || starts(b"MM\0*") {
            Self::Tiff
        } else if starts(&EMR_HEADER) && data.get(40..44) == Some(EMF_SIGNATURE) {
            Self::Emf
        } else if is_wmf(data) {
            Self::Wmf
        } else {
            Self::Unknown
        }
    }
}

/// Whether the data starts a WMF file: either the placeable header's key (MS-WMF 2.3.2.3), or a
/// `META_HEADER` record of type 1 or 2 with a header size of 9 words (MS-WMF 2.3.2.2).
fn is_wmf(data: &[u8]) -> bool {
    data.starts_with(&[0xD7, 0xCD, 0xC6, 0x9A])
        || data.starts_with(&[1, 0, 9, 0])
        || data.starts_with(&[2, 0, 9, 0])
}

/// An opaque color.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Rgb {
    /// Red.
    pub r: u8,
    /// Green.
    pub g: u8,
    /// Blue.
    pub b: u8,
}

impl Rgb {
    /// Black.
    pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };

    /// White.
    pub const WHITE: Self = Self {
        r: u8::MAX,
        g: u8::MAX,
        b: u8::MAX,
    };

    /// Reads a color of six hexadecimal digits of either case, such as `FF0080`: the shared
    /// simple type `ST_HexColorRGB` of ECMA-376, `xsd:hexBinary` of three bytes, which
    /// WordprocessingML colors and DrawingML's `a:srgbClr` use. Anything else, a sign
    /// included, gives `None`.
    #[must_use]
    pub fn from_hex(text: &str) -> Option<Self> {
        let digits = text.as_bytes();
        if digits.len() != 6 || !digits.iter().all(u8::is_ascii_hexdigit) {
            return None;
        }
        let value = u32::from_str_radix(text, 16).ok()?;
        let [_, r, g, b] = value.to_be_bytes();
        Some(Self { r, g, b })
    }
}

/// How far a target's PDF writer moves a place that it writes, across or down one page: the
/// offset on a page, which [`WriterOffset::on_page`] gives for the page's size and orientation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Offset {
    /// The writer moves no place.
    #[default]
    None,
    /// The place from the page's left edge divided by `share`, plus `bias`, rounded to the
    /// nearest whole `step`, a half up; `bias` and `step` in half-EMUs.
    Share {
        /// The divisor of the place.
        share: i64,
        /// What is added to the divided place, in half-EMUs.
        bias: i64,
        /// The step to which the offset rounds, in half-EMUs.
        step: i64,
    },
    /// Whole steps of `1/per_inch` inch, as if the page were `steps` steps larger along the
    /// place's side: the place times `steps`, divided by the page's side along it, is rounded
    /// to the nearest whole `parts` of a step first, and that count of parts is then divided
    /// by `parts` and rounded to the nearest step, a half up. `steps` is a fraction of steps.
    /// `product` says how the writer takes the product before it rounds it to parts.
    Page {
        /// The steps that the page's side gains.
        steps: Fraction,
        /// The parts of a step in which the product is rounded before the division.
        parts: i64,
        /// How many steps make an inch.
        per_inch: i64,
        /// How the writer takes the product of the place and the steps.
        product: OffsetProduct,
    },
}

/// How a writer whose offset takes whole steps as if the page were larger ([`Offset::Page`])
/// takes the product of a place and its page's steps before it rounds the product to parts of
/// a step.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OffsetProduct {
    /// The exact product of the place and the steps over the page's side.
    #[default]
    Exact,
    /// The product of the place in whole dots of `1/dots_per_inch` inch, a half up, and the
    /// page entry, held as the nearest binary32 number: the page entry is `parts (per_inch /
    /// dots_per_inch + steps / D)`, D the page's side in whole dots, held as the nearest
    /// binary32 number too, so that the product counts the parts of the whole written place.
    /// Its count of parts, rounded a half up and divided by `parts`, rounded a half up, is the
    /// written place in steps, and the offset is that place less the dot's place.
    Binary32 {
        /// How many dots make an inch.
        dots_per_inch: i64,
    },
}

/// The offset of a target's PDF writer along one axis, as the target's profile gives it (the
/// writer offset): the same offset on every page, or one that each page's size and
/// orientation choose. Only the offset on a page ([`Offset`]) moves a place, so an offset that
/// no page has chosen cannot move one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WriterOffset {
    /// The same offset on every page.
    EveryPage(Offset),
    /// The page form with the steps that a page's size and orientation give ([`PageSizes`]):
    /// given steps for some sizes, and the page entry of the page's paper form for the others.
    Sizes(&'static PageSizes),
}

impl WriterOffset {
    /// The writer moves no place on any page.
    pub const NONE: Self = Self::EveryPage(Offset::None);

    /// The offsets across and down a page `width` by `height` half-EMUs in a section of
    /// `orientation`: those that [`PageSizes`] gives the page for [`Self::Sizes`], and the same
    /// offset on both axes otherwise.
    #[must_use]
    pub fn on_page(self, width: i64, height: i64, orientation: Orientation) -> (Offset, Offset) {
        match self {
            Self::Sizes(sizes) => sizes.offsets(width, height, orientation),
            Self::EveryPage(offset) => (offset, offset),
        }
    }
}

/// The parts of a step in which a profile gives the steps of the page form of a writer's
/// offset ([`Offset::Page`]): hundred-thousandths.
pub const STEP_PARTS: i64 = 100_000;

impl Offset {
    /// The offset of a place at `x` from the page's edge, on a page whose side along `x` is
    /// `side`, all in half-EMUs.
    #[must_use]
    pub fn of(self, x: i64, side: i64) -> i64 {
        self.of_in(x, side, 1)
    }

    /// The place at which the writer writes a filled rectangle's edge at `x` on a page whose
    /// side along `x` is `side`, all in half-EMUs, where the edge need not lie on a device dot.
    /// For a page offset whose product is binary32, it is the edge's own place in dots times
    /// the page entry, held as the nearest binary32 number, rounded to whole parts of a step
    /// and then to whole steps, each a half up, and taken to the nearest half-EMU: an edge
    /// between two dots takes the entry at its own place, not the offset of its nearest dot.
    /// For every other offset it is the edge moved by [`Self::of`].
    #[must_use]
    pub(crate) fn written_place(self, x: i64, side: i64) -> i64 {
        if let Self::Page {
            steps,
            parts,
            per_inch,
            product: OffsetProduct::Binary32 { dots_per_inch },
        } = self
            && let Some(place) =
                binary32_written_place(x, side, (steps, parts, per_inch), dots_per_inch)
        {
            return place;
        }
        x + self.of(x, side)
    }

    /// The offset of [`Self::of`] in `fraction`ths of a half-EMU, the nearest: the place is
    /// whole half-EMUs, and the offset a whole number of the writer's steps, which a
    /// half-EMU need not hold (the step of 1/3000 inch is 609.6 half-EMUs).
    #[must_use]
    pub fn of_in(self, x: i64, side: i64, fraction: i64) -> i64 {
        let fraction = i128::from(fraction.max(1));
        match self {
            Self::None => 0,
            Self::Share { share, bias, step } => {
                if share <= 0 || step <= 0 {
                    return 0;
                }
                let steps = div_round_i128(
                    i128::from(x) + i128::from(bias) * i128::from(share),
                    i128::from(step) * i128::from(share),
                );
                i64::try_from(steps * i128::from(step) * fraction).unwrap_or(0)
            }
            Self::Page {
                steps,
                parts,
                per_inch,
                product,
            } => {
                if side <= 0 || parts <= 0 || per_inch <= 0 || steps.1 <= 0 {
                    return 0;
                }
                if let OffsetProduct::Binary32 { dots_per_inch } = product {
                    return binary32_page_offset(
                        x,
                        side,
                        (steps, parts, per_inch),
                        (dots_per_inch, fraction),
                    )
                    .unwrap_or(0);
                }
                // The product rounds before the division.
                let parts = i128::from(parts);
                let product = div_round_i128(
                    i128::from(x) * i128::from(steps.0) * parts,
                    i128::from(steps.1) * i128::from(side),
                );
                let n = div_round_i128(product, parts);
                let inch = i128::from(Length::UNITS_PER_INCH);
                i64::try_from(div_round_i128(n * inch * fraction, i128::from(per_inch)))
                    .unwrap_or(0)
            }
        }
    }
}

/// The offset of [`OffsetProduct::Binary32`] of a place at `x` on a page whose side along `x` is
/// `side`, both in half-EMUs, with the page form's `steps`, `parts` and `per_inch`: the written
/// place of the place's whole dot less the dot's place, in `fraction`ths of a half-EMU. `None`
/// where a count does not fit or a number is not positive.
fn binary32_page_offset(
    x: i64,
    side: i64,
    (steps, parts, per_inch): (Fraction, i64, i64),
    (dots_per_inch, fraction): (i64, i128),
) -> Option<i64> {
    if dots_per_inch <= 0 {
        return None;
    }
    let inch = i128::from(Length::UNITS_PER_INCH);
    let dpi = i128::from(dots_per_inch);
    let dots = i64::try_from(div_round_i128(i128::from(side) * dpi, inch)).ok()?;
    let place = i64::try_from(div_round_i128(i128::from(x) * dpi, inch)).ok()?;
    let entry = page_entry(dots, (steps, parts, per_inch), dpi)?;
    // The whole parts of the written place, then its whole steps, each a half up.
    let written_parts = i128::from(entry.times(place).whole(false));
    let written = div_round_i128(written_parts, parts.into());
    // The written place less the dot's place, in half-EMUs: (written / per_inch - place / dpi)
    // inches.
    let difference = written
        .checked_mul(dpi)?
        .checked_sub(i128::from(place).checked_mul(per_inch.into())?)?;
    i64::try_from(div_round_i128(
        difference.checked_mul(inch)?.checked_mul(fraction)?,
        i128::from(per_inch).checked_mul(dpi)?,
    ))
    .ok()
}

/// The written place of [`Offset::written_place`] for [`OffsetProduct::Binary32`]: the place at
/// `x` in dots, `x dpi / inch`, times the page entry of the page's side `side`, held as the
/// nearest binary32 number, in whole parts and then whole steps, each a half up, back in
/// half-EMUs, the nearest. `None` where a count does not fit or a number is not positive.
fn binary32_written_place(
    x: i64,
    side: i64,
    (steps, parts, per_inch): (Fraction, i64, i64),
    dots_per_inch: i64,
) -> Option<i64> {
    if dots_per_inch <= 0 || parts <= 0 || per_inch <= 0 {
        return None;
    }
    let inch = i128::from(Length::UNITS_PER_INCH);
    let dpi = i128::from(dots_per_inch);
    let dots = i64::try_from(div_round_i128(i128::from(side) * dpi, inch)).ok()?;
    let entry = page_entry(dots, (steps, parts, per_inch), dpi)?;
    // entry * x dpi / inch, with the entry as its mantissa times a power of two.
    let (mantissa, exponent) = (i128::from(entry.mantissa()), entry.exponent());
    let mut numerator = mantissa.checked_mul(i128::from(x))?.checked_mul(dpi)?;
    let mut denominator = inch;
    let shift = exponent.unsigned_abs();
    if exponent >= 0 {
        numerator = numerator.checked_mul(1_i128.checked_shl(shift)?)?;
    } else {
        denominator = denominator.checked_mul(1_i128.checked_shl(shift)?)?;
    }
    let product = Binary32::nearest(numerator, denominator);
    let written_parts = i128::from(product.whole(false));
    let written = div_round_i128(written_parts, parts.into());
    i64::try_from(div_round_i128(
        written.checked_mul(inch)?,
        i128::from(per_inch),
    ))
    .ok()
}

/// The page entry of a side of `dots` whole dots, `dpi` to the inch, with the page form's
/// `steps`, `parts` and `per_inch`: `parts (per_inch / dpi + steps / dots)`, held as the nearest
/// binary32 number. `None` where the side is not positive or a count does not fit.
fn page_entry(
    dots: i64,
    (steps, parts, per_inch): (Fraction, i64, i64),
    dpi: i128,
) -> Option<Binary32> {
    if dots <= 0 {
        return None;
    }
    // parts (per_inch / dpi + c / D) = parts (per_inch D c.1 + c.0 dpi) / (dpi D c.1).
    let (gain, over) = (i128::from(steps.0), i128::from(steps.1));
    let numerator = i128::from(per_inch)
        .checked_mul(dots.into())?
        .checked_mul(over)?
        .checked_add(gain.checked_mul(dpi)?)?
        .checked_mul(parts.into())?;
    let denominator = dpi.checked_mul(dots.into())?.checked_mul(over)?;
    Some(Binary32::nearest(numerator, denominator))
}

/// Moves a filled rectangle's left and right edges by the writer's horizontal offset `across`
/// of each edge's place, on a page `width` wide.
fn offset_rect(rect: &mut Rect, across: Offset, width: Length) {
    let right = rect.x.units() + rect.width.units();
    let left = rect.x.units() + across.of(rect.x.units(), width.units());
    let right = right + across.of(right, width.units());
    rect.x = Length::from_units(left);
    rect.width = Length::from_units(right - left);
}

/// A number as a fraction: its numerator and its denominator, which is positive.
pub type Fraction = (i64, i64);

/// The most page heights for which a writer holds a factor of its stretch
/// ([`Writer::with_stretch_factors`]).
pub const STRETCH_HEIGHTS: usize = 16;

/// How a target's PDF writer writes the numbers of a page that it decides itself, such as the
/// page size, and the files of its pictures. Layout gives each page its exact size, and the
/// output stage applies the writer to the finished display list. The target's profile says
/// which writer it uses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Writer {
    page_step: i64,
    vertical_stretch: i64,
    glyph_stretch_step: Option<Length>,
    stretch_offset: Fraction,
    stretch_factors: [(i64, Fraction); STRETCH_HEIGHTS],
    stretch_heights: usize,
    digits: Option<NonZeroU32>,
    least_decimals: u32,
    rectangle_steps: Option<NonZeroU32>,
    baseline_steps: Option<NonZeroU32>,
    picture_digits: Option<NonZeroU32>,
    horizontal_offset: WriterOffset,
    vertical_offset: WriterOffset,
    jpeg_quality: Option<JpegQuality>,
    jpeg_share: Option<JpegShare>,
    jpeg_sample: Option<JpegSample>,
    picture_density: Option<PictureDensity>,
    palette_density: Option<PaletteDensity>,
    picture_crop: PictureCrop,
    alpha_mix: AlphaMix,
    linear_limit: LinearLimit,
}

/// How a writer mixes the colors of a picture with an alpha when it resamples the picture
/// ([`Writer::with_alpha_mix`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AlphaMix {
    /// Each color as it is, whatever its alpha.
    Plain,
    /// Each color weighted by its alpha: the writer multiplies each color by its alpha over
    /// 255, rounds it to a whole level, resamples it with the alpha, and divides each new
    /// color by its new alpha. A clear pixel's color then adds nothing, and a color whose new
    /// alpha is 0 is 0.
    Weighted,
}

/// How a writer writes a cropped picture, a picture whose crop shows only its visible part
/// ([`Writer::with_picture_crop`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PictureCrop {
    /// Its whole file, under a clip to the visible part.
    WholeFileUnderClip,
    /// The pixels of its visible part only, at the visible part's place and size and with no
    /// clip. The writer rounds the visible part's left and top edges and its size to the
    /// nearest whole pixels of the file, a half up, and resamples the part as a picture of its
    /// own. A side of the visible part beyond the file ends at the file's edge
    /// ([`ImageItem::shown`]).
    VisiblePart,
    /// The pixels of its visible part only, as [`Self::VisiblePart`], except that a part that
    /// the mean of the area resamples comes from the whole file at the part's scale: on each
    /// axis, the written count over the part's count. The writer resamples the whole file by
    /// the mean of the area to its count times that scale, rounded to the nearest whole pixel,
    /// a half up, and takes written pixel `x` at the place of the part's first pixel times the
    /// scale, plus `x`, by the linear interpolation.
    VisiblePartAtScale,
}

impl PictureCrop {
    /// Whether the writer keeps only the pixels of a cropped picture's visible part.
    #[must_use]
    pub const fn keeps_visible_part(self) -> bool {
        !matches!(self, Self::WholeFileUnderClip)
    }
}

/// The quality of the tables of ITU-T T.81 Annex K at which a writer writes a JPEG picture
/// again: 1 to 100.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JpegQuality(u8);

impl JpegQuality {
    /// The quality `quality`, or `None` outside 1 to 100.
    #[must_use]
    pub const fn new(quality: u8) -> Option<Self> {
        if quality >= 1 && quality <= 100 {
            Some(Self(quality))
        } else {
            None
        }
    }

    /// The quality, from 1 to 100.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

/// The share of a picture's color under Flate below which a writer writes a picture that is not
/// JPEG as a JPEG file ([`Writer::with_jpeg_share`]), in thousandths.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JpegShare(u16);

impl JpegShare {
    /// The share of `thousandths` of a whole, or `None` outside 1 to 1,000.
    #[must_use]
    pub const fn new(thousandths: u16) -> Option<Self> {
        if thousandths >= 1 && thousandths <= 1000 {
            Some(Self(thousandths))
        } else {
            None
        }
    }

    /// The share in thousandths, from 1 to 1,000.
    #[must_use]
    pub const fn thousandths(self) -> u16 {
        self.0
    }

    /// Whether a JPEG file of `jpeg` bytes is smaller than this share of a Flate stream of
    /// `flate` bytes.
    #[must_use]
    pub fn takes(self, jpeg: usize, flate: usize) -> bool {
        let (Ok(jpeg), Ok(flate)) = (u128::try_from(jpeg), u128::try_from(flate)) else {
            return false;
        };
        jpeg * 1000 < u128::from(self.0) * flate
    }
}

/// The second test of a writer that writes a picture that its JPEG share takes as a JPEG file
/// ([`Writer::with_jpeg_sample`]). The picture stays a JPEG file when its color under Flate is
/// at least the whole share of its raw color, or when the estimate from its sample reaches both
/// the sample share of its color under Flate and the floor in bytes; else it stays lossless. The
/// sample is [`Self::STRIPS`] strips of [`Self::ROWS`] rows ([`Self::strips`]), and the estimate
/// is the sum of the strips' colors under Flate, each strip compressed on its own, times the
/// picture's height over the sample's [`Self::STRIPS`] times [`Self::ROWS`] rows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JpegSample {
    share: u16,
    floor: u32,
    whole: u16,
}

impl JpegSample {
    /// The strips of the sample.
    pub const STRIPS: usize = 16;
    /// The rows of each strip of the sample.
    pub const ROWS: usize = 8;

    /// The test with the sample share and the whole share in thousandths, each from 1 to 1,000,
    /// and the floor in bytes, at least 1; `None` outside them.
    #[must_use]
    pub const fn new(share: u16, floor: u32, whole: u16) -> Option<Self> {
        if share >= 1 && share <= 1000 && whole >= 1 && whole <= 1000 && floor >= 1 {
            Some(Self {
                share,
                floor,
                whole,
            })
        } else {
            None
        }
    }

    /// The rows of each strip of the sample of a picture `height` rows high: from the row
    /// `k * height / STRIPS`, rounded down, for `k` from 0 to `STRIPS - 1`, [`Self::ROWS`] rows
    /// or as many as the picture has below it. The strips of a picture below `STRIPS` times
    /// `ROWS` rows overlap.
    pub fn strips(height: usize) -> impl Iterator<Item = std::ops::Range<usize>> {
        (0..Self::STRIPS).map(move |k| {
            let start = k.saturating_mul(height) / Self::STRIPS;
            start..start.saturating_add(Self::ROWS).min(height)
        })
    }

    /// Whether a picture `height` rows high whose sample takes `sample` bytes under Flate and
    /// whose color takes `flate` bytes under Flate of `raw` raw bytes stays a JPEG file.
    #[must_use]
    pub fn takes(self, sample: usize, height: usize, (flate, raw): (usize, usize)) -> bool {
        let (Ok(sample), Ok(height), Ok(flate), Ok(raw), Ok(rows)) = (
            u128::try_from(sample),
            u128::try_from(height),
            u128::try_from(flate),
            u128::try_from(raw),
            u128::try_from(Self::STRIPS * Self::ROWS),
        ) else {
            return false;
        };
        let estimate = sample * height;
        flate * 1000 >= u128::from(self.whole) * raw
            || (estimate * 1000 >= u128::from(self.share) * flate * rows
                && estimate >= u128::from(self.floor) * rows)
    }
}

/// The density to which a writer resamples a dense picture: a direction whose pixels lie at
/// `limit_ppi` per inch of its drawn size or closer gets the most pixels below `ppi` per inch
/// ([`Writer::resampled_size`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PictureDensity {
    /// The density from which a direction is resampled, in pixels per inch.
    pub limit_ppi: NonZeroU32,
    /// The density below which a resampled direction stays, in pixels per inch.
    pub ppi: NonZeroU32,
}

/// The class of a PNG picture file of a palette that a writer with a palette density
/// resamples by limits of its own ([`PaletteDensity`]). Each class has no `tRNS` chunk. A file
/// of another kind, a palette with a `tRNS` chunk, a palette of 2 bits and a palette of more
/// than 1 bit whose entries are all gray have no class.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PaletteClass {
    /// A palette of 1 bit, with gray or color entries.
    OneBit,
    /// A palette of 4 bits with an entry that is not gray.
    FourBitColor,
    /// A palette of 8 bits with an entry that is not gray.
    EightBitColor,
}

/// The limits and the density with which a writer resamples a PNG picture of a palette of a
/// class ([`PaletteClass`]) in place of those of its picture density ([`PictureDensity`]): a
/// direction is dense from its class's limit per inch, a dense direction of a 1-bit palette
/// gets the most pixels below `one_bit_ppi` per inch, each found by the file's pixel under its
/// centre ([`Resampler::CentrePixel`]), and a dense direction of another class gets the most
/// pixels below the picture density's pixels per inch, found by the filter.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaletteDensity {
    /// The density from which a direction of a 1-bit palette is resampled, in pixels per inch.
    pub one_bit_limit_ppi: NonZeroU32,
    /// The density below which a resampled direction of a 1-bit palette stays, in pixels per
    /// inch.
    pub one_bit_ppi: NonZeroU32,
    /// The density from which a direction of a 4-bit color palette is resampled, in pixels per
    /// inch.
    pub four_bits_limit_ppi: NonZeroU32,
    /// The density from which a direction of an 8-bit color palette is resampled, in pixels per
    /// inch.
    pub eight_bits_limit_ppi: NonZeroU32,
}

/// How a writer finds the pixels of a picture that it resamples.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Resampler {
    /// Its filter, which mixes the file's pixels that each new pixel covers: the linear
    /// interpolation for the pictures that the limit names, else the mean of the covered area.
    Filter(LinearLimit),
    /// Each new pixel takes the file's pixel under its centre.
    CentrePixel,
}

/// The pictures that a writer's filter resamples by the linear interpolation; it takes the mean
/// of the covered area for the others ([`Writer::with_linear_limit`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LinearLimit {
    /// The pictures of at most this many source pixels.
    Pixels(NonZeroU32),
    /// The pictures with no side of more than this many source pixels.
    Side(NonZeroU32),
}

impl LinearLimit {
    /// Whether the filter resamples a picture of `pixels` (across, down) by the linear
    /// interpolation.
    #[must_use]
    pub fn takes_linear(self, (width, height): (usize, usize)) -> bool {
        let most = |count: NonZeroU32| usize::try_from(count.get()).unwrap_or(usize::MAX);
        match self {
            Self::Pixels(count) => width.saturating_mul(height) <= most(count),
            Self::Side(count) => width.max(height) <= most(count),
        }
    }
}

/// The limit of a new writer: the linear interpolation up to 2^17 source pixels.
const DEFAULT_LINEAR_LIMIT: LinearLimit = match NonZeroU32::new(1 << 17) {
    Some(count) => LinearLimit::Pixels(count),
    None => LinearLimit::Pixels(NonZeroU32::MIN),
};

impl Writer {
    /// A writer that rounds the page size to whole steps of `page_step`, or `None` when the
    /// step is not positive.
    #[must_use]
    pub const fn new(page_step: Length) -> Option<Self> {
        if page_step.units() > 0 {
            Some(Self {
                page_step: page_step.units(),
                vertical_stretch: 0,
                glyph_stretch_step: None,
                stretch_offset: (0, 1),
                stretch_factors: [(0, (1, 1)); STRETCH_HEIGHTS],
                stretch_heights: 0,
                digits: None,
                least_decimals: 0,
                rectangle_steps: None,
                baseline_steps: None,
                picture_digits: None,
                horizontal_offset: WriterOffset::NONE,
                vertical_offset: WriterOffset::NONE,
                jpeg_quality: None,
                jpeg_share: None,
                jpeg_sample: None,
                picture_density: None,
                palette_density: None,
                picture_crop: PictureCrop::WholeFileUnderClip,
                alpha_mix: AlphaMix::Plain,
                linear_limit: DEFAULT_LINEAR_LIMIT,
            })
        } else {
            None
        }
    }

    /// The same writer, which writes the file of each JPEG picture of a page again as a
    /// baseline JPEG file with the quantization tables of ITU-T T.81 Annex K scaled to
    /// `quality`, its chroma halved across and down, or keeps each file for `None`. This
    /// crate holds no decoder, so the output stage writes the files ([`Self::jpeg_quality`]).
    #[must_use]
    pub const fn with_jpeg_quality(self, quality: Option<JpegQuality>) -> Self {
        Self {
            jpeg_quality: quality,
            ..self
        }
    }

    /// The quality at which the writer writes each JPEG picture of a page again, or `None`
    /// when it keeps each file ([`Self::with_jpeg_quality`]).
    #[must_use]
    pub const fn jpeg_quality(&self) -> Option<JpegQuality> {
        self.jpeg_quality
    }

    /// The same writer, which writes an opaque PNG picture without a palette as a JPEG file at
    /// its JPEG quality ([`Self::with_jpeg_quality`]) when that file is smaller than `share` of
    /// the picture's color under Flate, and keeps it lossless otherwise, or keeps every such
    /// picture lossless for `None`. The output stage writes the files ([`Self::jpeg_share`]).
    #[must_use]
    pub const fn with_jpeg_share(self, share: Option<JpegShare>) -> Self {
        Self {
            jpeg_share: share,
            ..self
        }
    }

    /// The share of the color under Flate below which the writer writes an opaque PNG picture
    /// as a JPEG file, or `None` when it keeps each one lossless ([`Self::with_jpeg_share`]).
    #[must_use]
    pub const fn jpeg_share(&self) -> Option<JpegShare> {
        self.jpeg_share
    }

    /// The same writer, which keeps a picture that its JPEG share takes ([`Self::jpeg_share`])
    /// a JPEG file only when `sample` takes it too, and writes it lossless otherwise, or which
    /// asks no second test for `None` ([`Self::jpeg_sample`]).
    #[must_use]
    pub const fn with_jpeg_sample(self, sample: Option<JpegSample>) -> Self {
        Self {
            jpeg_sample: sample,
            ..self
        }
    }

    /// The second test of a picture that the JPEG share takes, or `None` when the writer asks
    /// none ([`Self::with_jpeg_sample`]).
    #[must_use]
    pub const fn jpeg_sample(&self) -> Option<JpegSample> {
        self.jpeg_sample
    }

    /// The same writer, which writes a picture whose pixels lie as close as the density's
    /// limit per inch across or down, or closer, with fewer pixels in that direction: the most
    /// that stay below the density's pixels per inch ([`Self::resampled_size`]). `None` keeps
    /// every picture's pixels.
    #[must_use]
    pub const fn with_picture_density(self, density: Option<PictureDensity>) -> Self {
        Self {
            picture_density: density,
            ..self
        }
    }

    /// The same writer, which resamples a PNG picture of a palette of a class by the limits and
    /// the density of `density` ([`PaletteDensity`]). `None` resamples it as any other picture.
    /// A writer without a picture density keeps every picture's pixels, also with a palette
    /// density.
    #[must_use]
    pub const fn with_palette_density(self, density: Option<PaletteDensity>) -> Self {
        Self {
            palette_density: density,
            ..self
        }
    }

    /// The same writer, which writes a cropped picture as `crop` says ([`PictureCrop`]).
    #[must_use]
    pub const fn with_picture_crop(self, crop: PictureCrop) -> Self {
        Self {
            picture_crop: crop,
            ..self
        }
    }

    /// How the writer writes a cropped picture ([`Self::with_picture_crop`]). This crate holds
    /// no decoder, so the output stage cuts the files.
    #[must_use]
    pub const fn picture_crop(&self) -> PictureCrop {
        self.picture_crop
    }

    /// The same writer, which mixes the colors of a picture with an alpha as `mix` says when
    /// it resamples the picture ([`AlphaMix`]).
    #[must_use]
    pub const fn with_alpha_mix(self, mix: AlphaMix) -> Self {
        Self {
            alpha_mix: mix,
            ..self
        }
    }

    /// How the writer mixes the colors of a picture with an alpha when it resamples it
    /// ([`Self::with_alpha_mix`]). This crate holds no decoder, so the output stage resamples
    /// the files.
    #[must_use]
    pub const fn alpha_mix(&self) -> AlphaMix {
        self.alpha_mix
    }

    /// The same writer, whose filter resamples the pictures that `limit` names by the linear
    /// interpolation and the others by the mean of the covered area ([`LinearLimit`]). A new
    /// writer takes the linear interpolation up to 2^17 source pixels.
    #[must_use]
    pub const fn with_linear_limit(self, limit: LinearLimit) -> Self {
        Self {
            linear_limit: limit,
            ..self
        }
    }

    /// The significant digits with which the writer writes a glyph's baseline, and a
    /// rectangle's bottom edge and height ([`Self::with_digits`]); `None` keeps them exact.
    #[must_use]
    pub const fn digits(&self) -> Option<NonZeroU32> {
        self.digits
    }

    /// The least decimals with which the writer prints a glyph's baseline and a rectangle's
    /// numbers ([`Self::with_least_decimals`]).
    #[must_use]
    pub const fn least_decimals(&self) -> u32 {
        self.least_decimals
    }

    /// The steps per inch on which the writer holds a filled rectangle's edges
    /// ([`Self::with_rectangle_steps`]); `None` holds the exact edges.
    #[must_use]
    pub const fn rectangle_steps(&self) -> Option<NonZeroU32> {
        self.rectangle_steps
    }

    /// The steps per inch whose whole count the writer converts to the points of a glyph's
    /// baseline ([`Self::with_baseline_steps`]); `None` holds the baseline's own points.
    #[must_use]
    pub const fn baseline_steps(&self) -> Option<NonZeroU32> {
        self.baseline_steps
    }

    /// The pixel size at which the writer writes a picture of `pixels` that fills `size` on
    /// the page, or `None` when it keeps the picture's pixels: with a limit
    /// ([`Self::with_picture_density`]), a direction whose pixels lie at the limit per inch of
    /// its size or closer gets the largest pixel count below the writer's density on that
    /// size, and a direction that is less dense than the limit keeps its pixels, even when it
    /// is denser than the writer's density. The size is the one at which the picture is drawn,
    /// with no cut to whole twips of its own. A PNG picture of a palette of a `palette` class
    /// takes the limit and the density of the writer's palette density, when it has one
    /// ([`Self::with_palette_density`]). The answer also says how the writer finds the new
    /// pixels, its filter with the writer's limit ([`Self::with_linear_limit`]) for every class
    /// but a 1-bit palette.
    #[must_use]
    pub fn resampled_size(
        &self,
        pixels: (usize, usize),
        size: (Length, Length),
        palette: Option<PaletteClass>,
    ) -> Option<((usize, usize), Resampler)> {
        let density = self.picture_density?;
        let filter = Resampler::Filter(self.linear_limit);
        let (limit_ppi, ppi, resampler) = match (self.palette_density, palette) {
            (Some(palettes), Some(PaletteClass::OneBit)) => (
                palettes.one_bit_limit_ppi,
                palettes.one_bit_ppi,
                Resampler::CentrePixel,
            ),
            (Some(palettes), Some(PaletteClass::FourBitColor)) => {
                (palettes.four_bits_limit_ppi, density.ppi, filter)
            }
            (Some(palettes), Some(PaletteClass::EightBitColor)) => {
                (palettes.eight_bits_limit_ppi, density.ppi, filter)
            }
            _ => (density.limit_ppi, density.ppi, filter),
        };
        let inch = i128::from(Length::UNITS_PER_INCH);
        // A direction is dense when count * inch >= limit * size, and then gets the largest
        // count below the density on its size: count * inch < ppi * size. Another direction
        // keeps its count.
        let written = |count: usize, length: Length| {
            let units = i128::from(length.units());
            let pixels = i128::try_from(count).unwrap_or(i128::MAX);
            if pixels * inch < i128::from(limit_ppi.get()) * units {
                return count;
            }
            let most = (i128::from(ppi.get()) * units - 1) / inch;
            usize::try_from(most).map_or(count, |most| most.min(count))
        };
        let (width, height) = size;
        if width.units() <= 0 || height.units() <= 0 {
            return None;
        }
        let new = (written(pixels.0, width), written(pixels.1, height));
        (new != pixels && new.0 > 0 && new.1 > 0).then_some((new, resampler))
    }

    /// The writer that places every point of a page as if the page were `steps` page steps
    /// taller: a point at `y` from the page's top goes to `y (H + s) / H`, with `H` the page's
    /// height and `s` the steps' length.
    #[must_use]
    pub const fn with_vertical_stretch(self, steps: i64) -> Self {
        Self {
            vertical_stretch: steps,
            ..self
        }
    }

    /// The same writer, which rounds how far its vertical stretch moves a glyph's baseline, and
    /// a filled rectangle's top and bottom edges, to the nearest whole `step`, a half step up,
    /// and places them at their layout place plus that rounded distance. Other items, and all
    /// items for `None`, move by the exact stretch. `None` when the step is not positive.
    #[must_use]
    pub const fn with_glyph_stretch_step(self, step: Option<Length>) -> Option<Self> {
        match step {
            Some(step) if step.units() <= 0 => None,
            Some(step) => Some(Self {
                glyph_stretch_step: Some(step),
                ..self
            }),
            None => Some(Self {
                glyph_stretch_step: None,
                ..self
            }),
        }
    }

    /// The same writer, which counts the steps of a glyph's baseline, and of a filled
    /// rectangle's top and bottom edges, on a page whose written height `factors` names as
    /// `round(s × r + offset)`, a half up, with `s` the exact stretch in steps and `r` the
    /// height's factor, each a fraction. On a page of another height, it rounds `s` itself
    /// ([`Self::with_glyph_stretch_step`]). `None` when `factors` names more than
    /// [`STRETCH_HEIGHTS`] heights, or a fraction has no positive denominator.
    #[must_use]
    pub fn with_stretch_factors(
        self,
        offset: Fraction,
        factors: &[(Length, Fraction)],
    ) -> Option<Self> {
        if factors.len() > STRETCH_HEIGHTS
            || offset.1 <= 0
            || factors.iter().any(|(_, factor)| factor.1 <= 0)
        {
            return None;
        }
        let mut table = [(0, (1, 1)); STRETCH_HEIGHTS];
        for (slot, (height, factor)) in table.iter_mut().zip(factors) {
            *slot = (height.units(), *factor);
        }
        Some(Self {
            stretch_offset: offset,
            stretch_factors: table,
            stretch_heights: factors.len(),
            ..self
        })
    }

    /// The factor and offset with which the writer counts the steps of its stretch on a page
    /// whose written height is `height` ([`Self::with_stretch_factors`]): those of the table,
    /// or a factor of 1 and no offset for a height that it does not name.
    fn stretch_factor(&self, height: Length) -> (Fraction, Fraction) {
        self.stretch_factors
            .iter()
            .take(self.stretch_heights)
            .find(|(written, _)| *written == height.units())
            .map_or(((1, 1), (0, 1)), |(_, factor)| {
                (*factor, self.stretch_offset)
            })
    }

    /// The same writer, which writes a glyph's baseline, and a rectangle's bottom edge and
    /// height, as their distances from the page's bottom edge in points, subtracted in single
    /// precision and printed with `digits` significant digits, a half rounded up, and places
    /// them there. `None` keeps the places exact.
    #[must_use]
    pub const fn with_digits(self, digits: Option<NonZeroU32>) -> Self {
        Self { digits, ..self }
    }

    /// The same writer, which prints each number of a glyph's baseline and of a filled
    /// rectangle with its digits ([`Self::with_digits`]) but with at least `decimals` decimals:
    /// from 1,000 pt, where five significant digits leave one decimal, a writer with 2 prints
    /// a distance of 1,007.88 pt as `1007.88`. Zero leaves the significant digits alone. The
    /// digits of pictures ([`Self::with_picture_digits`]) keep no least decimals.
    #[must_use]
    pub const fn with_least_decimals(self, decimals: u32) -> Self {
        Self {
            least_decimals: decimals,
            ..self
        }
    }

    /// The same writer, which holds each edge of a filled rectangle as the single-precision
    /// product of its whole steps of `1/per_inch` inch and the step in points in single
    /// precision, and writes with its digits the left edge, the bottom edge from the page's
    /// foot, and the width and height as differences of those edges subtracted in single
    /// precision. `None` keeps the single-precision numbers of the exact edge, width and
    /// height.
    #[must_use]
    pub const fn with_rectangle_steps(self, per_inch: Option<NonZeroU32>) -> Self {
        Self {
            rectangle_steps: per_inch,
            ..self
        }
    }

    /// The same writer, which holds a glyph's baseline as its whole count of steps of
    /// `1/per_inch` inch and converts the count to points in single precision, the count
    /// divided by `per_inch` and the quotient multiplied by 72, before it subtracts the
    /// baseline from the page's height and prints it with its digits. `None` holds the
    /// baseline's own points in single precision.
    #[must_use]
    pub const fn with_baseline_steps(self, per_inch: Option<NonZeroU32>) -> Self {
        Self {
            baseline_steps: per_inch,
            ..self
        }
    }

    /// The same writer, which writes an upright image's matrix as it writes a rectangle with
    /// `digits` significant digits ([`Self::with_digits`]): its left edge, width, height and
    /// bottom edge, and places the image there ([`Self::place_pictures`]). `None` keeps the
    /// image's place exact.
    #[must_use]
    pub const fn with_picture_digits(self, digits: Option<NonZeroU32>) -> Self {
        Self {
            picture_digits: digits,
            ..self
        }
    }

    /// Places each upright image of a display list where the writer writes its matrix with its
    /// picture digits ([`Self::with_picture_digits`]) on its page. The output stage calls this
    /// after it has written the pictures' files again, so that a cropped picture drawn at its
    /// clip is placed as it is drawn. The images inside a group keep their places, as in
    /// [`Self::finish`].
    pub fn place_pictures(&self, list: &mut DisplayList) {
        let Some(digits) = self.picture_digits else {
            return;
        };
        for page in &mut list.pages {
            for item in &mut page.items {
                if let Item::Image(image) = item
                    && image.turn.is_none()
                {
                    (image.x, image.y, image.width, image.height) = written_box(
                        page.height,
                        (image.x, image.y, image.width, image.height),
                        (digits.get(), 0),
                    );
                }
            }
        }
    }

    /// The same writer, which moves the left and right edges of a filled rectangle right by
    /// `offset` of each edge's place from the page's left edge, as the writer offsets a text
    /// object's start.
    #[must_use]
    pub const fn with_horizontal_offset(self, offset: WriterOffset) -> Self {
        Self {
            horizontal_offset: offset,
            ..self
        }
    }

    /// The same writer, which moves a glyph's baseline, and a filled rectangle's top and
    /// bottom edges, down by `offset` of each place from the page's top edge, after its
    /// vertical stretch.
    #[must_use]
    pub const fn with_vertical_offset(self, offset: WriterOffset) -> Self {
        Self {
            vertical_offset: offset,
            ..self
        }
    }

    /// The writer's offsets across and down a page `width` by `height` in a section of
    /// `orientation` ([`Self::with_horizontal_offset`], [`Self::with_vertical_offset`],
    /// [`WriterOffset::on_page`]).
    fn page_offsets(
        &self,
        width: Length,
        height: Length,
        orientation: Orientation,
    ) -> (Offset, Offset) {
        let (width, height) = (width.units(), height.units());
        (
            self.horizontal_offset.on_page(width, height, orientation).0,
            self.vertical_offset.on_page(width, height, orientation).1,
        )
    }

    /// The offsets across and down with which the writer places the items of a page `width` by
    /// `height` in a section of `orientation`; unstable helper behind the `development` feature.
    #[cfg(feature = "development")]
    #[must_use]
    pub fn development_page_offsets(
        &self,
        width: Length,
        height: Length,
        orientation: Orientation,
    ) -> (Offset, Offset) {
        self.page_offsets(width, height, orientation)
    }

    /// The page side that the writer writes: `length` rounded to the nearest whole step, a half
    /// step up. A page side lies within [`Length::FILE_LIMIT`], as every page of the DOCX layout
    /// does, since its reader bounds the page size there, so the rounding fits an `i64`.
    #[must_use]
    pub const fn page_side(&self, length: Length) -> Length {
        let step = self.page_step;
        Length::from_units(div_round(length.units(), step) * step)
    }

    /// Gives every page of a display list the size that the writer writes, and places its
    /// points as the writer's vertical stretch, offsets and digits say. The items of a group of
    /// a picture's own items keep their places: the writer writes them inside the picture,
    /// where none of these reach them. The items of a group of the page's items, such as the
    /// text of a text box under its clip, take the page's places.
    pub fn finish(&self, list: &mut DisplayList) {
        for page in &mut list.pages {
            page.width = self.page_side(page.width);
            page.height = self.page_side(page.height);
            let extra = self.vertical_stretch * self.page_step;
            if extra != 0 && page.height.units() > 0 {
                let (factor, offset) = self.stretch_factor(page.height);
                let stretch = Stretch {
                    taller: page.height.units() + extra,
                    height: page.height.units(),
                    glyph_step: self.glyph_stretch_step,
                    factor,
                    offset,
                };
                for item in &mut page.items {
                    stretch.item(item);
                }
            }
            self.offset_items(page);
            if let Some(digits) = self.digits {
                let digits = (digits.get(), self.least_decimals);
                for item in &mut page.items {
                    self.write_digits(page.height, digits, item);
                }
            }
            stroke_items(&mut page.items);
        }
    }

    /// Moves the filled rectangles of a page by the writer's horizontal and vertical offsets,
    /// its glyphs' baselines by the vertical one, and the points of a table cell's clip
    /// ([`GroupPlaces::Cell`]) and of a group whose every point the writer places
    /// ([`GroupPlaces::Points`]) as a rectangle's edges, and each edge of a stroked rectangle
    /// ([`GroupPlaces::Stroked`]) at its own place.
    fn offset_items(&self, page: &mut Page) {
        let (width, height) = (page.width, page.height);
        let (across, down_offset) = self.page_offsets(width, height, page.orientation);
        let down =
            |y: Length| Length::from_units(y.units() + down_offset.of(y.units(), height.units()));
        let place = |point: &mut Point| {
            let x = point.x.units();
            point.x = Length::from_units(x + across.of(x, width.units()));
            point.y = down(point.y);
        };
        offset_all(&mut page.items, &|item| match item {
            Item::Rect(rect) => {
                offset_rect(rect, across, width);
                let bottom = Length::from_units(rect.y.units() + rect.height.units());
                let top = down(rect.y);
                let bottom = down(bottom);
                rect.y = top;
                rect.height = Length::from_units(bottom.units() - top.units());
            }
            Item::Glyphs(run) => {
                for glyph in &mut run.glyphs {
                    glyph.y = down(glyph.y);
                }
            }
            Item::Group(group) if group.places == GroupPlaces::Cell => {
                let clip = group.clip.iter_mut().flat_map(|clip| &mut clip.commands);
                clip.flat_map(PathCommand::points_mut).for_each(place);
            }
            Item::Group(group) if group.places == GroupPlaces::Points => {
                group.points_mut().for_each(place);
            }
            Item::Group(group) if matches!(group.places, GroupPlaces::Stroked { .. }) => {
                place_edges(&mut group.items, (across, down_offset), (width, height));
            }
            Item::Path(_) | Item::Gradient(_) | Item::Image(_) | Item::Group(_) => {}
        });
    }

    /// Places a glyph run's baselines, or a filled rectangle's edges, where the writer writes
    /// them with `digits`, its significant digits and least decimals, on a page of `height`.
    fn write_digits(&self, height: Length, digits: (u32, u32), item: &mut Item) {
        match item {
            Item::Glyphs(run) => {
                for glyph in &mut run.glyphs {
                    glyph.y = match self.baseline_steps {
                        Some(per_inch) => {
                            counted_y(height, glyph.y, digits, i64::from(per_inch.get()))
                        }
                        None => written_y(height, glyph.y, digits),
                    };
                }
            }
            Item::Rect(rect) => {
                let exact = (rect.x, rect.y, rect.width, rect.height);
                (rect.x, rect.y, rect.width, rect.height) = self
                    .rectangle_steps
                    .and_then(|steps| held_box(height, exact, (digits, i64::from(steps.get()))))
                    .unwrap_or_else(|| written_box(height, exact, digits));
            }
            Item::Group(group) => {
                if group.places == GroupPlaces::Points {
                    for point in group.points_mut() {
                        *point = written_point(height, *point, digits);
                    }
                }
                for item in group.placed_items() {
                    self.write_digits(height, digits, item);
                }
            }
            Item::Path(_) | Item::Gradient(_) | Item::Image(_) => {}
        }
    }
}

/// Runs `place` on each of `items` and on each item of a group of the page's items in them,
/// but for the rectangles of a stroked group ([`GroupPlaces::Stroked`]), which `place` places
/// with their group.
fn offset_all(items: &mut [Item], place: &dyn Fn(&mut Item)) {
    for item in items {
        if let Item::Group(group) = item
            && !matches!(group.places, GroupPlaces::Stroked { .. })
        {
            offset_all(group.placed_items(), place);
        }
        place(item);
    }
}

/// Places the edges of each rectangle of a stroked group's `items` ([`GroupPlaces::Stroked`])
/// where the writer writes them with its offsets across and down ([`Offset::written_place`]),
/// on a page `width` by `height`.
fn place_edges(
    items: &mut [Item],
    (across, down): (Offset, Offset),
    (width, height): (Length, Length),
) {
    for item in items {
        let Item::Rect(rect) = item else {
            continue;
        };
        let (left, top) = (rect.x.units(), rect.y.units());
        let (right, bottom) = (left + rect.width.units(), top + rect.height.units());
        let (left, right) = (
            across.written_place(left, width.units()),
            across.written_place(right, width.units()),
        );
        let (top, bottom) = (
            down.written_place(top, height.units()),
            down.written_place(bottom, height.units()),
        );
        rect.x = Length::from_units(left);
        rect.y = Length::from_units(top);
        rect.width = Length::from_units(right - left);
        rect.height = Length::from_units(bottom - top);
    }
}

/// Draws each rectangle of a stroked group in `items` ([`GroupPlaces::Stroked`]), at any depth,
/// as a PDF fills and then strokes it: the rectangle, then the filled outline of its stroke
/// ([`stroke_outline`]) in its color.
fn stroke_items(items: &mut [Item]) {
    for item in items {
        let Item::Group(group) = item else {
            continue;
        };
        if let GroupPlaces::Stroked { width } = group.places {
            let half = Length::from_units(div_round(width.units(), 2));
            group.items = std::mem::take(&mut group.items)
                .into_iter()
                .flat_map(|item| match item {
                    Item::Rect(rect) => {
                        let outline = stroke_outline(&rect, half);
                        vec![Item::Rect(rect), Item::Path(outline)]
                    }
                    other => vec![other],
                })
                .collect();
        }
        stroke_items(&mut group.items);
    }
}

/// The part of a circle's radius at which a cubic Bézier curve that draws a quarter of the
/// circle has its control points, `4/3 tan(Ï€/8)`, in billionths.
const QUARTER_ARC_ARM: i64 = 552_284_750;

/// The filled outline of the stroke of `rect` with a round join, `half` its width on each side
/// of the edges: the outer outline, the rectangle grown by `half` with a quarter circle at each
/// corner, and the inner one through the ends of the edges moved `half` inward, which the
/// nonzero rule leaves empty inside them. A rectangle no wider or taller than the stroke has the
/// outer outline alone. The outlines run as the reader of a PDF expands a filled and stroked
/// rectangle's stroke, from the left end of the bottom edge.
fn stroke_outline(rect: &Rect, half: Length) -> PathItem {
    let (left, top) = (rect.x, rect.y);
    let (right, bottom) = (rect.x + rect.width, rect.y + rect.height);
    let (outer_left, outer_top) = (left - half, top - half);
    let (outer_right, outer_bottom) = (right + half, bottom + half);
    let start = Point {
        x: left,
        y: outer_bottom,
    };
    // Each side of the outer outline as its end, the corner of the grown box after it and the
    // start of the next side, between which a quarter circle turns.
    let sides = [
        [
            (right, outer_bottom),
            (outer_right, outer_bottom),
            (outer_right, bottom),
        ],
        [
            (outer_right, top),
            (outer_right, outer_top),
            (right, outer_top),
        ],
        [
            (left, outer_top),
            (outer_left, outer_top),
            (outer_left, top),
        ],
        [
            (outer_left, bottom),
            (outer_left, outer_bottom),
            (left, outer_bottom),
        ],
    ];
    let mut commands = vec![PathCommand::MoveTo(start)];
    for [(end_x, end_y), (corner_x, corner_y), (next_x, next_y)] in sides {
        let end = Point { x: end_x, y: end_y };
        commands.push(PathCommand::LineTo(end));
        commands.push(quarter_arc(
            end,
            Point {
                x: corner_x,
                y: corner_y,
            },
            Point {
                x: next_x,
                y: next_y,
            },
        ));
    }
    commands.push(PathCommand::Close);
    if rect.width > half + half && rect.height > half + half {
        let inner = [
            (left, bottom - half),
            (left + half, bottom),
            (left + half, top),
            (left, top + half),
            (right, top + half),
            (right - half, top),
            (right - half, bottom),
            (right, bottom - half),
            (left, bottom - half),
        ];
        for (index, (x, y)) in inner.into_iter().enumerate() {
            let point = Point { x, y };
            commands.push(if index == 0 {
                PathCommand::MoveTo(point)
            } else {
                PathCommand::LineTo(point)
            });
        }
        commands.push(PathCommand::Close);
    }
    PathItem {
        commands,
        color: rect.color,
        fill_rule: FillRule::NonZero,
    }
}

/// The cubic Bézier curve of a quarter circle from `from` to `to`, whose tangents meet at
/// `corner`: each control point lies on its end's tangent, `QUARTER_ARC_ARM` of the way to the
/// corner.
fn quarter_arc(from: Point, corner: Point, to: Point) -> PathCommand {
    let arm = |distance: Length| {
        Length::from_units(div_round(
            distance.units().saturating_mul(QUARTER_ARC_ARM),
            1_000_000_000,
        ))
    };
    let toward = |point: Point| Point {
        x: point.x + arm(corner.x - point.x),
        y: point.y + arm(corner.y - point.y),
    };
    PathCommand::CubicTo(toward(from), toward(to), to)
}

/// A single-precision number of the page coordinates as its significand and the power of two
/// that divides it, `significand * 2^-shift`, which the writer's printing reads.
fn fraction(number: Binary32) -> (i128, u32) {
    let (mantissa, exponent) = (i128::from(number.mantissa()), number.exponent());
    match u32::try_from(exponent) {
        Ok(up) => (mantissa << up, 0),
        Err(_) => (mantissa, exponent.unsigned_abs()),
    }
}

/// `a` less `b`, both single-precision numbers, subtracted in single precision, or `None` when
/// the difference is not positive.
fn single_less(a: Binary32, b: Binary32) -> Option<Binary32> {
    let ((a, a_shift), (b, b_shift)) = (fraction(a), fraction(b));
    let shift = a_shift.max(b_shift);
    let exact = (a << (shift - a_shift)) - (b << (shift - b_shift));
    single(exact, 1_i128 << shift)
}

/// A place `units` from the page's left or top edge as a writer holds it on steps of
/// `1/per_inch` inch: the single-precision product of its whole number of steps, the nearest,
/// and the step in points as a single-precision number. A place at the edge is zero.
fn held(units: i64, per_inch: i64) -> Option<Binary32> {
    let inch = i128::from(Length::UNITS_PER_INCH);
    let per_inch = i128::from(per_inch);
    let steps = div_round_i128(i128::from(units) * per_inch, inch);
    if steps == 0 {
        return Some(Binary32::ZERO);
    }
    let (step, shift) = fraction(single(72, per_inch)?);
    single(steps * step, 1_i128 << shift)
}

/// A rectangle's left edge, top edge, width and height as a writer that holds its edges on
/// steps of `1/per_inch` inch writes them on a page of `height` ([`held`]): its left edge, its
/// bottom edge from the page's foot (the page's height, a single-precision number, less the
/// bottom edge), its width (the right edge less the left edge) and its height (the bottom edge
/// less the top edge), each subtracted in single precision and printed with `digits`
/// ([`Digits`]), a half rounded up. It places the edges where a reader of the PDF puts them,
/// the written corner plus the written width and height, each rounded to the nearest half-EMU.
/// `None` when a number is not positive.
fn held_box(
    height: Length,
    (x, y, width, tall): (Length, Length, Length, Length),
    (digits, per_inch): (Digits, i64),
) -> Option<(Length, Length, Length, Length)> {
    let point = i128::from(Length::UNITS_PER_POINT);
    let written = |number: Binary32| {
        let (significand, shift) = fraction(number);
        decimal(
            significand,
            shift,
            significant_decimals(significand, shift, digits),
        )
    };
    let edge = |units: i64| held(units, per_inch);
    let (left, right) = (edge(x.units())?, edge(x.units() + width.units())?);
    let (top, bottom) = (edge(y.units())?, edge(y.units() + tall.units())?);
    let foot = written(single_less(
        single(i128::from(height.units()), point)?,
        bottom,
    )?);
    let (left, across) = (written(left), written(single_less(right, left)?));
    let down = written(single_less(bottom, top)?);
    let (left_units, right_units) = (
        decimal_units(left)?,
        decimal_units(decimal_sum(left, across))?,
    );
    let bottom_units = height.units() - decimal_units(foot)?;
    let top_units = height.units() - decimal_units(decimal_sum(foot, down))?;
    Some((
        Length::from_units(left_units),
        Length::from_units(top_units),
        Length::from_units(right_units - left_units),
        Length::from_units(bottom_units - top_units),
    ))
}

/// A point of a path or a clip, from the top left corner of a page of `height`, as the writer
/// writes it with `digits` ([`Digits`]): its distance from the left edge as a single-precision
/// number, and its height as [`written_y`] writes a baseline, each printed with `digits`. The
/// writer holds no point on steps, also when it holds a rectangle's edges so: a point between
/// two steps stays between them. A point at or below the bottom edge keeps its height.
fn written_point(height: Length, point: Point, digits: Digits) -> Point {
    let unit = i128::from(Length::UNITS_PER_POINT);
    let x = single(i128::from(point.x.units()), unit)
        .map(fraction)
        .and_then(|(significand, shift)| printed(significand, shift, digits))
        .map_or(point.x, Length::from_units);
    Point {
        x,
        y: written_y(height, point.y, digits),
    }
}

/// How a writer prints a number of points: with a count of significant digits, but with at
/// least a count of decimals ([`Writer::with_digits`], [`Writer::with_least_decimals`]).
type Digits = (u32, u32);

/// The baseline `y` from the top of a page of `height` as the writer writes it: its distance
/// from the bottom edge in points, which the writer subtracts in single precision (the height
/// less the baseline, each a single-precision number, and the difference rounded to one),
/// printed with `digits` ([`Digits`]) and a half rounded up. A baseline at or below the bottom
/// edge, or one too far for the page sizes that the writer meets, stays.
fn written_y(height: Length, y: Length, digits: Digits) -> Length {
    let point = i128::from(Length::UNITS_PER_POINT);
    // A single-precision number is `significand * 2^-shift`, with a significand of 24 bits,
    // rounded to the nearest, a half to the even significand, as the processor rounds it.
    let difference = match (
        single(i128::from(height.units()), point),
        single(i128::from(y.units()), point),
    ) {
        (Some(top), Some(low)) => single_less(top, low),
        _ => single(i128::from(height.units() - y.units()), point),
    };
    let Some((significand, shift)) = difference.map(fraction) else {
        return y;
    };
    printed(significand, shift, digits)
        .map_or(y, |units| Length::from_units(height.units() - units))
}

/// The baseline `y` from the top of a page of `height` as a writer writes it that holds the
/// baseline as its whole count `n` of steps of `1/per_inch` inch, the nearest: the points
/// `(n / per_inch) × 72`, each step in single precision, subtracted from the page's height in
/// single precision and printed with `digits` ([`Digits`]), a half up. Where the distance from
/// the foot lies on a half of its last printed decimal, the single-precision numbers of the
/// quotient and the product decide its side: on a page of 792 pt, the baseline 582.925 pt
/// (23,317 steps of 1/2880 inch) is written 209.07 pt, where [`written_y`] writes 209.08 pt.
/// A baseline between two steps, which only an error of the layout gives, and a baseline at
/// the top edge or at or below the bottom edge are written as [`written_y`] writes them: a
/// nearest count would move a baseline between two steps by up to half a step.
fn counted_y(height: Length, y: Length, digits: Digits, per_inch: i64) -> Length {
    let point = i128::from(Length::UNITS_PER_POINT);
    let inch = i128::from(Length::UNITS_PER_INCH);
    let per_inch = i128::from(per_inch);
    let scaled = i128::from(y.units()) * per_inch;
    if scaled % inch != 0 {
        return written_y(height, y, digits);
    }
    let count = scaled / inch;
    let points = single(count, per_inch)
        .map(fraction)
        .and_then(|(significand, shift)| single(significand * 72, 1_i128 << shift));
    let difference = single(i128::from(height.units()), point)
        .zip(points)
        .and_then(|(top, low)| single_less(top, low));
    let Some((significand, shift)) = difference.map(fraction) else {
        return written_y(height, y, digits);
    };
    printed(significand, shift, digits)
        .map_or(y, |units| Length::from_units(height.units() - units))
}

/// A rectangle's left edge, top edge, width and height as the writer writes them on a page of
/// `height`: its left edge and width, held as single-precision numbers, and its height, and
/// its bottom edge as [`written_y`] writes a baseline, each printed with `digits`
/// ([`Digits`]), a half rounded up.
fn written_box(
    height: Length,
    (x, y, width, tall): (Length, Length, Length, Length),
    digits: Digits,
) -> (Length, Length, Length, Length) {
    let point = i128::from(Length::UNITS_PER_POINT);
    let written = |length: Length| {
        single(i128::from(length.units()), point)
            .map(fraction)
            .and_then(|(significand, shift)| printed(significand, shift, digits))
            .map_or(length, Length::from_units)
    };
    let written_tall = written(tall);
    let bottom = written_y(height, Length::from_units(y.units() + tall.units()), digits);
    (
        written(x),
        Length::from_units(bottom.units() - written_tall.units()),
        written(width),
        written_tall,
    )
}

/// The single-precision number `significand * 2^-shift` points printed with `digits`
/// significant digits, but with at least `least` decimals, a half up on its exact value, in
/// half-EMUs. A number below one point gets the decimals of a number of one digit before the
/// point.
fn printed(significand: i128, shift: u32, (digits, least): Digits) -> Option<i64> {
    let whole = (significand >> shift).max(1);
    let decimals = digits.saturating_sub(whole.ilog10() + 1).max(least);
    decimal_units(decimal(significand, shift, decimals))
}

/// The decimals with which a writer prints the single-precision number `significand *
/// 2^-shift` points with `digits` significant digits, counted from its first digit that is
/// not zero, also below one point: 0.47998 has five. A number of one point or more gets at
/// least `least` decimals.
fn significant_decimals(significand: i128, shift: u32, (digits, least): Digits) -> u32 {
    let whole = significand >> shift;
    if whole > 0 {
        return digits.saturating_sub(whole.ilog10() + 1).max(least);
    }
    let mut decimals = digits;
    let mut scaled = significand * 10;
    while significand > 0 && scaled < 1 << shift {
        decimals += 1;
        scaled *= 10;
    }
    decimals
}

/// A number as a writer prints it: a whole number of `scale`ths of a point, and `scale`.
type Decimal = (i128, i128);

/// The single-precision number `significand * 2^-shift` points printed with `decimals`
/// decimals, a half up on its exact value.
fn decimal(significand: i128, shift: u32, decimals: u32) -> Decimal {
    let scale = i128::from(f_office_units::scale::TENTHS).pow(decimals);
    (
        (significand * scale * 2 + (1 << shift)) >> (shift + 1),
        scale,
    )
}

/// The sum of two printed numbers, exact.
fn decimal_sum((a, a_scale): Decimal, (b, b_scale): Decimal) -> Decimal {
    let scale = a_scale.max(b_scale);
    (a * (scale / a_scale) + b * (scale / b_scale), scale)
}

/// A printed number of points in half-EMUs, the nearest, a half up.
fn decimal_units((value, scale): Decimal) -> Option<i64> {
    let point = i128::from(Length::UNITS_PER_POINT);
    i64::try_from(div_round_i128(value * point, scale)).ok()
}

/// The single-precision number nearest to `numerator / denominator`, both positive, or `None`
/// outside the range that the page coordinates use, from 2^-41 up to 2^24. Writers that hold a
/// number in single precision compute with it, without float arithmetic.
#[must_use]
pub fn single(numerator: i128, denominator: i128) -> Option<Binary32> {
    if numerator <= 0 || denominator <= 0 {
        return None;
    }
    // The power of two below the quotient, so that the significand gets its 24 bits.
    let mut exponent =
        i32::try_from(numerator.ilog2()).ok()? - i32::try_from(denominator.ilog2()).ok()?;
    let below = if exponent >= 0 {
        numerator < denominator << exponent
    } else {
        numerator << -exponent < denominator
    };
    if below {
        exponent -= 1;
    }
    let shift = u32::try_from(i32::try_from(Binary32::BITS).ok()? - 1 - exponent).ok()?;
    if shift > u32::BITS * 2 {
        return None;
    }
    Some(Binary32::nearest(numerator, denominator))
}

/// How a writer moves the points of one page down: each `y` times `taller / height`, and a
/// glyph's baseline by that distance in whole `glyph_step`s when it has a step, counted
/// with the page's stretch factor and offset ([`Writer::with_stretch_factors`]).
struct Stretch {
    taller: i64,
    height: i64,
    glyph_step: Option<Length>,
    factor: Fraction,
    offset: Fraction,
}

impl Stretch {
    /// A glyph's baseline `y` plus the distance that the stretch moves it in whole glyph steps:
    /// the exact distance in steps times the factor, plus the offset, rounded to the nearest
    /// whole step, a half step up; the exact stretch without a step.
    fn glyph_y(&self, y: Length) -> Length {
        let Some(glyph_step) = self.glyph_step else {
            return self.y(y);
        };
        let distance = i128::from(y.units()) * i128::from(self.taller - self.height);
        let per_step = i128::from(self.height) * i128::from(glyph_step.units());
        let (factor, of) = (i128::from(self.factor.0), i128::from(self.factor.1));
        let (offset, by) = (i128::from(self.offset.0), i128::from(self.offset.1));
        // round(distance / per_step × factor / of + offset / by), with a half up: the floor of
        // (2 distance factor by + 2 offset of per_step + of by per_step) / (2 of by per_step).
        let whole = of * by * per_step;
        let steps = div_round_i128(distance * factor * by + offset * of * per_step, whole);
        let moved = i64::try_from(steps * i128::from(glyph_step.units())).unwrap_or(i64::MAX);
        Length::from_units(y.units().saturating_add(moved))
    }

    /// `y` times `taller / height`, to the nearest unit.
    fn y(&self, y: Length) -> Length {
        let product = i128::from(y.units()) * i128::from(self.taller);
        let height = i128::from(self.height);
        let rounded = div_round_i128(product, height);
        Length::from_units(i64::try_from(rounded).unwrap_or(i64::MAX))
    }

    /// The new top and height of a filled rectangle, whose top and bottom edges move as a
    /// glyph's baseline does ([`Self::glyph_y`]).
    fn stepped_span(&self, (top, height): (Length, Length)) -> (Length, Length) {
        let new_top = self.glyph_y(top);
        let bottom = self.glyph_y(Length::from_units(top.units() + height.units()));
        (
            new_top,
            Length::from_units(bottom.units() - new_top.units()),
        )
    }

    fn point(&self, point: &mut Point) {
        point.y = self.y(point.y);
    }

    /// Moves the points of an item down; glyphs keep their size.
    fn item(&self, item: &mut Item) {
        match item {
            Item::Glyphs(run) => {
                for glyph in &mut run.glyphs {
                    glyph.y = self.glyph_y(glyph.y);
                }
            }
            Item::Rect(rect) => (rect.y, rect.height) = self.stepped_span((rect.y, rect.height)),
            Item::Path(path) => {
                for point in path.commands.iter_mut().flat_map(PathCommand::points_mut) {
                    self.point(point);
                }
            }
            Item::Gradient(gradient) => {
                let axis = [&mut gradient.start, &mut gradient.end];
                let outline = gradient
                    .commands
                    .iter_mut()
                    .flat_map(PathCommand::points_mut);
                for point in outline.chain(axis) {
                    self.point(point);
                }
            }
            // The writer draws a picture, with its clip, at its layout place and size; the
            // page's items under a clip stretch as the page's, with the clip.
            Item::Group(group) => {
                if group.places != GroupPlaces::Own {
                    let clip = group.clip.iter_mut().flat_map(|clip| &mut clip.commands);
                    for point in clip.flat_map(PathCommand::points_mut) {
                        self.point(point);
                    }
                }
                for item in group.placed_items() {
                    self.item(item);
                }
            }
            Item::Image(_) => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use f_office_units::Length;

    use super::{
        DEFAULT_LINEAR_LIMIT, DisplayList, Glyph, GlyphRun, Image, ImageFormat, JpegQuality,
        LinearLimit, Offset, OffsetProduct, Orientation, Page, PaletteClass, PaletteDensity,
        PictureDensity, Resampler, Rgb, Writer, WriterOffset,
    };

    #[test]
    fn takes_the_linear_interpolation_up_to_a_count_or_up_to_a_side() {
        let count = |n| std::num::NonZeroU32::new(n).unwrap();
        let (pixels, side) = (
            LinearLimit::Pixels(count(1 << 17)),
            LinearLimit::Side(count(419)),
        );
        let cases = [
            (pixels, (400, 327), true),
            (pixels, (400, 328), false),
            (pixels, (480, 270), true),
            (side, (419, 419), true),
            (side, (420, 100), false),
            (side, (100, 420), false),
            (side, (480, 270), false),
        ];
        for (limit, size, linear) in cases {
            assert_eq!(limit.takes_linear(size), linear, "{limit:?} {size:?}");
        }
        assert_eq!(DEFAULT_LINEAR_LIMIT, pixels);
    }

    #[test]
    fn answers_with_the_filter_of_its_own_limit() {
        let side = LinearLimit::Side(std::num::NonZeroU32::new(419).unwrap());
        let density = PictureDensity {
            limit_ppi: std::num::NonZeroU32::new(275).unwrap(),
            ppi: std::num::NonZeroU32::new(200).unwrap(),
        };
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_picture_density(Some(density))
            .with_linear_limit(side);
        let inch = Length::from_units(Length::UNITS_PER_INCH);
        let answer = writer.resampled_size((600, 600), (inch, inch), None);
        assert_eq!(answer, Some(((199, 199), Resampler::Filter(side))));
    }

    #[test]
    fn a_filled_path_draws_quadratic_curves_as_cubic_curves_of_whole_units() {
        use super::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
        let at = |x, y| super::Point {
            x: Length::from_units(x),
            y: Length::from_units(y),
        };
        let commands = [
            MoveTo(at(0, 0)),
            QuadTo(at(30, 10), at(31, 0)),
            Close,
            QuadTo(at(3, 3), at(6, 0)),
            LineTo(at(9, 9)),
        ];
        // Two thirds of 30 and 10 are 20 and 6.67; of -1 and 10, -0.67 and 6.67. After the
        // close, the curve starts at the start of the outline.
        let expected = vec![
            MoveTo(at(0, 0)),
            CubicTo(at(20, 7), at(30, 7), at(31, 0)),
            Close,
            CubicTo(at(2, 2), at(4, 2), at(6, 0)),
            LineTo(at(9, 9)),
        ];
        assert_eq!(super::fill_commands(&commands), expected);
        assert_eq!(
            super::fill_commands(&[QuadTo(at(3, 3), at(6, 0))]),
            vec![CubicTo(at(3, 3), at(4, 2), at(6, 0))]
        );
    }

    #[test]
    fn a_filled_path_leaves_out_lines_to_their_own_start() {
        use super::PathCommand::{Close, LineTo, MoveTo};
        let at = |x, y| super::Point {
            x: Length::from_units(x),
            y: Length::from_units(y),
        };
        let commands = [
            MoveTo(at(5, 5)),
            LineTo(at(5, 5)),
            LineTo(at(9, 5)),
            LineTo(at(9, 5)),
            LineTo(at(9, 9)),
            Close,
            LineTo(at(5, 5)),
            LineTo(at(7, 7)),
        ];
        // After the close, the outline starts again at its first point.
        let expected = vec![
            MoveTo(at(5, 5)),
            LineTo(at(9, 5)),
            LineTo(at(9, 9)),
            Close,
            LineTo(at(7, 7)),
        ];
        assert_eq!(super::fill_commands(&commands), expected);
    }

    #[test]
    fn a_fill_at_most_the_thinnest_fill_across_paints_nothing() {
        use super::PathCommand::{Close, CubicTo, LineTo, MoveTo};
        let at = |x, y| super::Point {
            x: Length::from_units(x),
            y: Length::from_units(y),
        };
        let bar = |across| {
            [
                MoveTo(at(0, 0)),
                LineTo(at(across, 0)),
                LineTo(at(across, 5000)),
                LineTo(at(0, 5000)),
                Close,
            ]
        };
        assert!(!super::path_shows(&bar(100)));
        assert!(super::path_shows(&bar(101)));
        assert!(!super::fill_shows(
            Length::from_units(5000),
            Length::from_units(-100)
        ));
        assert!(super::fill_shows(
            Length::from_units(5000),
            Length::from_units(-101)
        ));
        // The control points of a curve widen the box, as a reader of a PDF measures it.
        let bowed = [
            MoveTo(at(0, 0)),
            CubicTo(at(150, 1000), at(150, 4000), at(0, 5000)),
            Close,
        ];
        assert!(super::path_shows(&bowed));
        assert!(!super::path_shows(&[]));
    }

    /// Places `item` where `writer`, which has digits, writes it with its digits and least
    /// decimals on a page of `height`.
    fn write_digits(writer: &Writer, height: Length, item: &mut super::Item) {
        let digits = (writer.digits().unwrap().get(), writer.least_decimals());
        writer.write_digits(height, digits, item);
    }

    #[test]
    fn gives_the_text_of_a_glyph_only_on_whole_characters() {
        let run = GlyphRun {
            font: f_office_fonts::FontId::from_index(0),
            size: Length::ZERO,
            color: Rgb::BLACK,
            text: "a\u{e9}".to_owned(),
            glyphs: Vec::new(),
            outline: None,
            filled: true,
            effect: false,
            turn: None,
        };
        let glyph = |text_start, text_end| Glyph {
            id: 0,
            x: Length::ZERO,
            y: Length::ZERO,
            text_start,
            text_end,
        };
        assert_eq!(run.glyph_text(&glyph(0, 1)), Some("a"));
        assert_eq!(run.glyph_range(&glyph(1, 3)), Some(1..3));
        assert_eq!(run.glyph_text(&glyph(1, 3)), Some("\u{e9}"));
        assert_eq!(run.glyph_text(&glyph(1, 1)), Some(""));
        // Inside the two bytes of the second character, backwards, and beyond the text.
        for (start, end) in [(1, 2), (2, 3), (1, 0), (0, 4)] {
            assert_eq!(run.glyph_range(&glyph(start, end)), None, "{start}..{end}");
            assert_eq!(run.glyph_text(&glyph(start, end)), None, "{start}..{end}");
        }
    }

    /// `count` as a count that is not zero.
    fn non_zero(count: u32) -> std::num::NonZeroU32 {
        std::num::NonZeroU32::new(count).unwrap()
    }

    /// The picture density with the limit `limit_ppi` and `ppi` pixels per inch.
    fn density(limit_ppi: u32, ppi: u32) -> PictureDensity {
        PictureDensity {
            limit_ppi: non_zero(limit_ppi),
            ppi: non_zero(ppi),
        }
    }

    #[test]
    fn reads_six_hexadecimal_digits_only() {
        let rgb = |r, g, b| Some(Rgb { r, g, b });
        assert_eq!(Rgb::from_hex("FF0080"), rgb(255, 0, 128));
        assert_eq!(Rgb::from_hex("1f3864"), rgb(31, 56, 100));
        for wrong in [
            "+FFFFF", "+F+F+F", "-FFFFF", "FFFFF", "FFFFFFF", "GGGGGG", " FFFFF", "auto",
        ] {
            assert_eq!(Rgb::from_hex(wrong), None, "{wrong}");
        }
    }

    /// A glyph run, a rectangle, a path of each command and a clipped image, each with the
    /// places `(1, 2)`, `(3, 4)`, ... and the lengths 10, 20, ..., in a group: the places are
    /// `at(n)` and the lengths `by(n)`.
    fn every_kind(at: impl Fn(i64) -> super::Point, by: impl Fn(i64) -> Length) -> super::Item {
        use super::{
            Clip, FillRule, Glyph, GlyphRun, Group, GroupClip, GroupPlaces, ImageItem, Item, Join,
            Outline, PathCommand, PathItem, Rect,
        };
        let glyph = |n: i64| Glyph {
            id: 1,
            x: at(n).x,
            y: at(n).y,
            text_start: 0,
            text_end: 1,
        };
        let run = GlyphRun {
            font: f_office_fonts::FontId::from_index(0),
            size: by(1),
            color: Rgb::BLACK,
            text: "a".to_owned(),
            glyphs: vec![glyph(1), glyph(2)],
            outline: Some(Outline {
                width: by(2),
                color: Rgb::BLACK,
                join: Join::Round,
            }),
            filled: true,
            effect: false,
            turn: None,
        };
        let rect = Rect {
            x: at(3).x,
            y: at(3).y,
            width: by(3),
            height: by(4),
            color: Rgb::BLACK,
        };
        let path = PathItem {
            commands: vec![
                PathCommand::MoveTo(at(4)),
                PathCommand::LineTo(at(5)),
                PathCommand::QuadTo(at(6), at(7)),
                PathCommand::CubicTo(at(8), at(9), at(10)),
                PathCommand::Close,
            ],
            color: Rgb::BLACK,
            fill_rule: FillRule::NonZero,
        };
        let image = ImageItem {
            x: at(11).x,
            y: at(11).y,
            width: by(5),
            height: by(6),
            clip: Some(Clip {
                x: at(12).x,
                y: at(12).y,
                width: by(7),
                height: by(8),
            }),
            turn: None,
            image: Image::new(vec![0]),
        };
        Item::Group(Group::new(vec![
            Item::Glyphs(run),
            Item::Group(Group {
                items: vec![Item::Rect(rect), Item::Path(path)],
                clip: Some(GroupClip {
                    commands: vec![
                        PathCommand::MoveTo(at(13)),
                        PathCommand::LineTo(at(14)),
                        PathCommand::QuadTo(at(15), at(16)),
                        PathCommand::Close,
                    ],
                    fill_rule: FillRule::EvenOdd,
                }),
                places: GroupPlaces::Own,
            }),
            Item::Image(image),
        ]))
    }

    #[test]
    fn maps_every_place_and_length_of_an_item_and_of_the_items_of_its_groups() {
        use super::Point;
        let u = Length::from_units;
        let at = |n: i64| Point {
            x: u(2 * n - 1),
            y: u(2 * n),
        };
        let mut item = every_kind(at, |n| u(10 * n));
        // Each place moves one unit right and doubles down; each length triples.
        item.map_places(
            |p| Point {
                x: p.x + u(1),
                y: p.y * 2,
            },
            |v| v * 3,
        );
        let mapped = |n: i64| Point {
            x: u(2 * n),
            y: u(4 * n),
        };
        assert_eq!(item, every_kind(mapped, |n| u(30 * n)));
    }

    #[test]
    fn gives_the_pages_and_the_parts_that_it_was_built_from() {
        use super::Point;
        let u = Length::from_units;
        let at = |n: i64| Point { x: u(n), y: u(n) };
        let items = vec![every_kind(at, u), every_kind(at, |n| u(2 * n))];
        let landscape = Orientation::Landscape;
        let page = Page::new(u(300), u(400), landscape, items.clone());
        assert_eq!((page.width(), page.height()), (u(300), u(400)));
        assert_eq!(page.orientation(), landscape);
        assert_eq!(page.items(), items.as_slice());
        let empty = Page::new(u(5), u(6), Orientation::Portrait, Vec::new());
        let list = DisplayList::new(vec![page.clone(), empty.clone()]);
        assert_eq!(list.pages(), [page.clone(), empty.clone()].as_slice());
        assert_eq!(list.into_pages(), vec![page.clone(), empty]);
        let fewer = page.map_items(|mut kept| {
            kept.truncate(1);
            kept
        });
        assert_eq!(
            fewer,
            Page::new(u(300), u(400), landscape, items[..1].to_vec())
        );
    }

    #[test]
    fn writes_the_page_size_in_whole_steps() {
        assert_eq!(Writer::new(Length::ZERO), None);
        let step = Length::from_units(Length::UNITS_PER_DOT);
        let writer = Writer::new(step).unwrap();
        // An A4 page, 15,120,000 units wide, is 2,480.3 dots; half a dot rounds up.
        let page = |width, height| Page {
            width: Length::from_units(width),
            height: Length::from_units(height),
            orientation: Orientation::Portrait,
            items: Vec::new(),
        };
        let mut list = DisplayList {
            pages: vec![page(15_120_000, 3048 + 6096 * 3)],
        };
        writer.finish(&mut list);
        assert_eq!(list.pages[0].width.units(), 2480 * 6096);
        assert_eq!(list.pages[0].height.units(), 4 * 6096);
    }

    #[test]
    fn keeps_the_picture_files_unless_it_has_a_jpeg_quality() {
        let writer = Writer::new(Length::from_units(10)).unwrap();
        assert_eq!(writer.jpeg_quality(), None);
        let quality = JpegQuality::new(75);
        assert_eq!(writer.with_jpeg_quality(quality).jpeg_quality(), quality);
        assert_eq!(writer.with_jpeg_quality(None), writer);
    }

    #[test]
    fn keeps_an_opacity_between_none_and_a_whole() {
        use super::Opacity;
        assert_eq!(Opacity::clamped(-5).share(), 0);
        assert_eq!(Opacity::clamped(150_000), Opacity::FULL);
        assert_eq!(Opacity::FULL.share(), 100_000);
        // 50% of 50.001% is 25.0005%, which rounds a half up.
        let half = Opacity::clamped(50_000);
        assert_eq!(half.times(Opacity::clamped(50_001)).share(), 25_001);
        assert_eq!(Opacity::FULL.times(half), half);
    }

    #[test]
    fn takes_a_jpeg_quality_of_1_to_100_only() {
        assert_eq!(JpegQuality::new(1).map(JpegQuality::get), Some(1));
        assert_eq!(JpegQuality::new(100).map(JpegQuality::get), Some(100));
        assert_eq!(JpegQuality::new(0), None);
        assert_eq!(JpegQuality::new(101), None);
        assert_eq!(JpegQuality::new(255), None);
    }

    #[test]
    fn resamples_pictures_denser_than_the_limit_below_its_density() {
        let inches =
            |hundredths: i64| Length::from_units(Length::UNITS_PER_INCH * hundredths / 100);
        let size = (
            inches(150),
            Length::from_units(Length::UNITS_PER_POINT * 81),
        );
        let writer = Writer::new(Length::from_units(10)).unwrap();
        assert_eq!(writer.resampled_size((600, 450), size, None), None);
        let writer = writer.with_picture_density(Some(density(275, 200)));
        let filter = |pixels| Some((pixels, Resampler::Filter(DEFAULT_LINEAR_LIMIT)));
        // 275 ppi stays, 276 ppi becomes 299 by 224 pixels for 1.5 by 1.125 inches.
        assert_eq!(writer.resampled_size((412, 309), size, None), None);
        assert_eq!(
            writer.resampled_size((414, 311), size, None),
            filter((299, 224))
        );
        assert_eq!(
            writer.resampled_size((600, 450), size, None),
            filter((299, 224))
        );
        // 1.25 by 0.9375 inches: 249 by 187 pixels, the most below 200 ppi.
        let size = (
            inches(125),
            Length::from_units(Length::UNITS_PER_POINT * 135 / 2),
        );
        assert_eq!(
            writer.resampled_size((500, 375), size, None),
            filter((249, 187))
        );
        // Never more pixels than the picture has.
        assert_eq!(
            writer.resampled_size((600, 100), size, None),
            filter((249, 100))
        );
        assert_eq!(
            writer.resampled_size((600, 450), (Length::from_units(0), size.1), None),
            None
        );
    }

    #[test]
    fn resamples_a_palette_of_a_class_by_the_limits_of_its_class() {
        // One inch across and 0.3 inch down; the pixels give each class's density on both.
        let size = (
            Length::from_units(Length::UNITS_PER_INCH),
            Length::from_units(Length::UNITS_PER_INCH * 3 / 10),
        );
        let palettes = PaletteDensity {
            one_bit_limit_ppi: non_zero(750),
            one_bit_ppi: non_zero(600),
            four_bits_limit_ppi: non_zero(562),
            eight_bits_limit_ppi: non_zero(395),
        };
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_picture_density(Some(density(275, 200)));
        let (centre, filter) = (
            Resampler::CentrePixel,
            Resampler::Filter(DEFAULT_LINEAR_LIMIT),
        );
        let classes = [
            (
                Some(PaletteClass::OneBit),
                749_usize,
                750_usize,
                (599, 179),
                centre,
            ),
            (
                Some(PaletteClass::FourBitColor),
                561,
                562,
                (199, 59),
                filter,
            ),
            (
                Some(PaletteClass::EightBitColor),
                394,
                395,
                (199, 59),
                filter,
            ),
            (None, 274, 275, (199, 59), filter),
        ];
        let with = writer.with_palette_density(Some(palettes));
        for (class, kept, dense, new, resampler) in classes {
            // The pixels down at a density below `kept` and at `dense` or above.
            let (kept, dense) = ((kept, kept * 3 / 10), (dense, (dense * 3).div_ceil(10)));
            assert_eq!(with.resampled_size(kept, size, class), None);
            let written = with.resampled_size(dense, size, class);
            assert_eq!(written, Some((new, resampler)));
            // Without a palette density, every class takes the picture density.
            let general = writer.resampled_size(dense, size, class);
            assert_eq!(general, Some(((199, 59), filter)));
        }
        // Without a picture density, the palette density resamples nothing.
        let none = Writer::new(Length::from_units(10))
            .unwrap()
            .with_palette_density(Some(palettes));
        let one_bit = Some(PaletteClass::OneBit);
        assert_eq!(none.resampled_size((900, 270), size, one_bit), None);
    }

    /// The written sizes of a half-inch square of each of `pixels` with the density
    /// `limit_ppi` and `ppi`.
    fn half_inch_sizes(
        limit_ppi: u32,
        ppi: u32,
        pixels: &[(usize, usize)],
    ) -> Vec<Option<(usize, usize)>> {
        let half = Length::from_units(Length::UNITS_PER_POINT * 36);
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_picture_density(Some(density(limit_ppi, ppi)));
        pixels
            .iter()
            .map(|&pixels| writer.resampled_size(pixels, (half, half), None))
            .map(|written| written.map(|(pixels, _)| pixels))
            .collect()
    }

    #[test]
    fn resamples_only_the_directions_denser_than_a_limit_of_275_ppi() {
        // Half-inch squares: a writer with this limit writes
        // 290 by 260 ppi as 99 by 130 pixels and 290 by 276 ppi as 99 by 99.
        assert_eq!(
            half_inch_sizes(275, 200, &[(145, 130), (130, 145), (145, 138), (145, 137)]),
            [
                Some((99, 130)),
                Some((130, 99)),
                Some((99, 99)),
                Some((99, 137))
            ]
        );
    }

    #[test]
    fn resamples_only_the_directions_at_a_limit_of_450_ppi_or_denser() {
        // The writer with this limit and 300 ppi keeps 446 ppi and writes 450 by 350 ppi as
        // 149 by 175 pixels.
        assert_eq!(
            half_inch_sizes(
                450,
                300,
                &[(223, 223), (225, 225), (225, 175), (200, 225), (225, 150)]
            ),
            [
                None,
                Some((149, 149)),
                Some((149, 175)),
                Some((200, 149)),
                Some((149, 150))
            ]
        );
    }

    /// The written pixels across of `pixels` drawn across `units`, and 30 pixels down 0.15
    /// inch, with the density `limit_ppi` and `ppi`, or the pixels when the writer keeps them.
    fn across(limit_ppi: u32, ppi: u32, pixels: usize, units: i64) -> usize {
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_picture_density(Some(density(limit_ppi, ppi)));
        let size = (
            Length::from_units(units),
            Length::from_emus(137_160).unwrap(),
        );
        writer
            .resampled_size((pixels, 30), size, None)
            .map_or(pixels, |(written, _)| written.0)
    }

    #[test]
    fn tests_and_resamples_the_drawn_size_itself() {
        // Each case: limit and density in ppi, pixels across, drawn size in length units
        // (1,270 to a twip), written pixels.
        let cases = [
            // 225 pixels drawn on 720 twips are
            // 450 ppi and get 149 pixels at 300 ppi and 99 at 200 ppi; on 721 twips they stay
            // at 450 ppi and get 100 at 200 ppi.
            (450, 300, 225, 914_400, 149),
            (450, 300, 225, 915_670, 225),
            (275, 200, 225, 914_400, 99),
            (275, 200, 225, 915_670, 100),
            // A direction exactly at the limit is resampled, and one unit more keeps it: 275
            // pixels on an inch.
            (275, 200, 275, 1_828_800, 199),
            (275, 200, 275, 1_828_801, 275),
            // 211 pixels step up from 93 to 94 pixels past 573,024 units
            // at 300 ppi, and from 101 to 102 past 932,688 units at 200 ppi, before the next
            // whole twip; they are at 450 ppi on 857,504 units, and below it past them.
            (450, 300, 211, 573_024, 93),
            (450, 300, 211, 573_025, 94),
            (275, 200, 211, 932_688, 101),
            (275, 200, 211, 932_689, 102),
            (450, 300, 211, 857_504, 140),
            (450, 300, 211, 857_505, 211),
        ];
        for (limit, ppi, pixels, units, written) in cases {
            assert_eq!(
                across(limit, ppi, pixels, units),
                written,
                "{pixels} on {units}"
            );
        }
    }

    #[test]
    fn stretches_glyphs_and_rectangles_down_by_the_steps_of_the_page() {
        use super::Item;
        let page = stretched();
        let Item::Glyphs(run) = &page.items[0] else {
            panic!("no glyphs")
        };
        assert_eq!(
            (run.glyphs[0].x.units(), run.glyphs[0].y.units()),
            (500, 402)
        );
        assert_eq!(run.size.units(), 120);
        let Item::Rect(rect) = &page.items[1] else {
            panic!("no rect")
        };
        let units = [rect.x, rect.y, rect.width, rect.height].map(Length::units);
        assert_eq!(units, [100, 201, 300, 402]);
        // The page keeps its size.
        assert_eq!((page.width.units(), page.height.units()), (1000, 2000));
    }

    #[test]
    fn stretches_paths_down_and_leaves_pictures_and_everything_without_a_stretch() {
        use super::{Item, PathCommand, Point};
        let page = stretched();
        let Item::Path(path) = &page.items[2] else {
            panic!("no path")
        };
        let corner = Point {
            x: Length::from_units(1000),
            y: Length::from_units(2010),
        };
        assert_eq!(path.commands[0], PathCommand::MoveTo(corner));
        // A picture and its clip keep their layout place and size.
        assert_eq!(page.items[3], sample_page().items[3]);
        let mut plain = DisplayList {
            pages: vec![sample_page()],
        };
        Writer::new(Length::from_units(10))
            .unwrap()
            .finish(&mut plain);
        assert_eq!(plain.pages[0], sample_page());
    }

    #[test]
    fn holds_a_quotient_as_the_nearest_single_precision_number() {
        use super::{fraction, single};
        // Significands and powers of two as single-precision numbers hold the quotients:
        // 744.975 is 744.9749755859375, 434.125 is exact, 1/3 and 2/3 round up, and half of
        // 2^24 + 1 is a tie that goes to the even significand.
        let cases = [
            ((744_975, 1000), Some((12_205_670, 14))),
            ((434_125, 1000), Some((14_225_408, 15))),
            ((1, 3), Some((11_184_811, 25))),
            ((2, 3), Some((11_184_811, 24))),
            ((123_456_789, 25_400), Some((9_954_311, 11))),
            ((16_777_217, 2), Some((8_388_608, 0))),
            ((16_777_217, 1), None),
            ((0, 1), None),
            // 2^24 - 1/2 rounds up to 2^24 and stays in the range.
            (((1 << 25) - 1, 2), Some((1 << 24, 0))),
        ];
        for ((numerator, denominator), expected) in cases {
            assert_eq!(
                single(numerator, denominator).map(fraction),
                expected,
                "{numerator}/{denominator}"
            );
        }
    }

    #[test]
    fn writes_a_baseline_from_the_bottom_with_significant_digits() {
        use super::written_y;
        // Baselines on a page of 792 pt, written with five digits: the
        // distance 434.125 pt is a half and rounds up to 434.13 pt; 744.975 pt is held as
        // 744.97498 and goes down to 744.97 pt; 709.725 pt likewise goes to 709.72 pt; a
        // distance below 100 pt keeps three decimals. The baseline 586.425 pt is held as
        // 586.424988, so the distance, subtracted in single precision, is 205.575012 and rounds
        // up to 205.58 pt, where the exact 205.575 pt held as 205.574997 would go down.
        let point =
            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
        let page = point(792_000);
        assert_eq!(written_y(page, point(357_875), (5, 0)), point(357_870));
        assert_eq!(written_y(page, point(47_025), (5, 0)), point(47_030));
        assert_eq!(written_y(page, point(82_275), (5, 0)), point(82_280));
        assert_eq!(written_y(page, point(741_025), (5, 0)), point(741_025));
        assert_eq!(written_y(page, point(800_000), (5, 0)), point(800_000));
        assert_eq!(written_y(page, point(586_425), (5, 0)), point(586_420));
    }

    #[test]
    fn writes_a_baseline_from_its_count_of_steps() {
        use super::{counted_y, written_y};
        // On a page of 792 pt, a baseline whose distance from the foot lies on a half of its
        // last decimal takes the side of the single-precision points of its count of steps of
        // 1/2880 inch: 582.925 pt is 23,317 steps, whose points lie just above the half, so
        // the distance 209.075 pt is written 209.07 pt; 273.825 pt gives 518.18 pt. Both go
        // the other way from the baseline's own points. 587.925 pt and 586.425 pt
        // (205.58 pt) go the same way, and so does a half that binary numbers hold exactly.
        let point =
            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
        let page = point(792_000);
        let counted = |y: i64| counted_y(page, point(y), (5, 2), 2_880);
        let written = |y: i64| written_y(page, point(y), (5, 2));
        let pairs = [582_925, 273_825].map(|y| (counted(y), written(y)));
        assert_eq!(pairs[0], (point(582_930), point(582_920)));
        assert_eq!(pairs[1], (point(273_820), point(273_830)));
        for same in [587_925, 586_425, 357_875, 744_975, 300_000] {
            assert_eq!(counted(same), written(same), "{same}");
        }
    }

    #[test]
    fn writes_a_baseline_off_the_steps_from_its_own_points() {
        use super::{counted_y, written_y};
        // A baseline at the top, below the foot or between two steps is written as the
        // baseline's own points: 582.938 pt keeps 209.06 pt, where the nearest count, 23,318
        // steps (582.95 pt), would give 209.05 pt.
        let point =
            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
        let page = point(792_000);
        let counted = |y: i64| counted_y(page, point(y), (5, 2), 2_880);
        let written = |y: i64| written_y(page, point(y), (5, 2));
        for y in [0, 800_000, 582_938] {
            assert_eq!(counted(y), written(y), "{y}");
        }
        assert_eq!(counted(582_938), point(582_940));
    }

    #[test]
    fn writes_glyph_baselines_from_their_counts_where_the_writer_holds_steps() {
        use super::{Glyph, GlyphRun, Item};
        let point =
            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
        let glyphs = || {
            Item::Glyphs(GlyphRun {
                font: f_office_fonts::FontId::from_index(0),
                size: point(11_000),
                color: Rgb::BLACK,
                text: "a".to_owned(),
                glyphs: vec![Glyph {
                    id: 1,
                    x: point(72_000),
                    y: point(582_925),
                    text_start: 0,
                    text_end: 1,
                }],
                outline: None,
                filled: true,
                effect: false,
                turn: None,
            })
        };
        let baseline = |writer: &Writer| {
            let mut item = glyphs();
            write_digits(writer, point(792_000), &mut item);
            let Item::Glyphs(run) = item else {
                unreachable!()
            };
            run.glyphs[0].y
        };
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_digits(Some(non_zero(5)))
            .with_least_decimals(2);
        let counting = writer.with_baseline_steps(Some(non_zero(2_880)));
        assert_eq!(counting.baseline_steps(), Some(non_zero(2_880)));
        assert_eq!(writer.baseline_steps(), None);
        assert_eq!(baseline(&counting), point(582_930));
        assert_eq!(baseline(&writer), point(582_920));
    }

    #[test]
    fn writes_a_baseline_from_1000_pt_with_the_least_decimals() {
        use super::written_y;
        // A baseline 576.12 pt below the top of a page of 1,584 pt lies 1,007.88 pt above its
        // foot. Five significant digits print it as 1007.9, and two least decimals as 1007.88.
        let point =
            |thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
        let page = point(1_584_000);
        assert_eq!(written_y(page, point(576_120), (5, 0)), point(576_100));
        assert_eq!(written_y(page, point(576_120), (5, 2)), point(576_120));
        // A distance whose second decimal is a 0 is the same with one or two.
        assert_eq!(written_y(page, point(576_400), (5, 2)), point(576_400));
        // Two least decimals change no number below 1,000 pt: on a Letter page, 434.125 pt
        // above the foot still rounds up to 434.13 pt, and 50.975 pt keeps three decimals.
        let letter = point(792_000);
        assert_eq!(written_y(letter, point(357_875), (5, 2)), point(357_870));
        assert_eq!(written_y(letter, point(741_025), (5, 2)), point(741_025));
    }

    #[test]
    fn offsets_a_rectangles_edges_as_a_text_objects_start() {
        // With a target's offset (1/2400 of the place plus 18 half-EMUs, on 635 half-EMUs), a
        // left edge at 66.5 pt moves by 0.025 pt to 66.525 pt, and a right edge at 186.75 pt by
        // 0.075 pt.
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
                share: 2_400,
                bias: 18,
                step: 635,
            }));
        let point = |thousandths: i64| Length::from_units(thousandths * 254 / 10);
        let (width, height) = (point(612_000), point(792_000));
        let across = |writer: Writer, x: Length| {
            Length::from_units(
                writer
                    .page_offsets(width, height, Orientation::Portrait)
                    .0
                    .of(x.units(), width.units()),
            )
        };
        assert_eq!(across(writer, point(66_500)), point(25));
        assert_eq!(across(writer, point(186_750)), point(75));
        assert_eq!(
            across(Writer::new(Length::from_units(10)).unwrap(), point(66_500)),
            point(0)
        );
    }

    /// The page form of Word for Windows's writer with the steps `c` hundred-thousandths and
    /// the product rounded in `parts` of a step first.
    const fn page_form(c: i64, parts: i64) -> Offset {
        Offset::Page {
            steps: (c, 100_000),
            parts,
            per_inch: 3_000,
            product: OffsetProduct::Exact,
        }
    }

    /// The page form of [`page_form`] with the product of the dot and the page entry held in
    /// binary32, for dots of 1/600 inch.
    const fn binary32_page_form(c: i64) -> Offset {
        Offset::Page {
            steps: (c, 100_000),
            parts: 16,
            per_inch: 3_000,
            product: OffsetProduct::Binary32 { dots_per_inch: 600 },
        }
    }

    #[test]
    fn rounds_the_product_of_the_dot_and_the_page_entry_in_binary32() {
        // Across a Letter page 5,100 dots wide with c = 4.72515, the page entry is the binary32
        // number nearest 16 (5 + c / 5,100), 80.0148239. The exact rule changes from 3 to 4
        // steps at the dot 3,744; with the product of the dot 3,743 and the entry held in
        // binary32 it already gives 4 steps there, 0.096 pt, as Word does.
        let offset = |c, k: i64| binary32_page_form(c).of(k * DOT, LETTER);
        assert_eq!(page_form(472_515, 16).of(3_743 * DOT, LETTER), 1_829);
        assert_eq!(offset(472_515, 3_743), 2_438);
        assert_eq!(offset(472_515, 3_742), 1_829);
        // Elsewhere both take the same steps: the dots 1,585 and 1,586 change from 1 to 2.
        for k in [600, 1_585, 1_586, 2_664, 2_665, 3_744] {
            assert_eq!(
                offset(472_515, k),
                page_form(472_515, 16).of(k * DOT, LETTER)
            );
        }
        // A place inside a dot takes its dot's offset, and no page gives none.
        assert_eq!(
            binary32_page_form(472_515).of(3_743 * DOT + 1_000, LETTER),
            2_438
        );
        assert_eq!(binary32_page_form(472_515).of(3_743 * DOT, 0), 0);
    }

    /// A dot of 1/600 inch in half-EMUs; a step of 1/3000 inch is 609.6 half-EMUs, so that one
    /// step rounds to 610 half-EMUs and two to 1,219.
    const DOT: i64 = 3_048;

    /// The width of a Letter page, 12,240 twips, in half-EMUs.
    const LETTER: i64 = 12_240 * 1_270;

    #[test]
    fn offsets_a_place_by_whole_steps_as_if_the_page_were_larger() {
        // The page form writes a dot k of 1/600 inch as 5 k + round(round(16 k c / D) / 16)
        // in 1/3000 inch, D the page's side in dots: on a Letter page 5,100 dots wide, with
        // c = 4.72515, that gives the dots 600, 646 and 692 one step and the dot 0 none.
        for k in [600, 646, 692] {
            assert_eq!(page_form(472_515, 16).of(k * DOT, LETTER), 610);
        }
        assert_eq!(page_form(472_515, 16).of(0, LETTER), 0);
        assert_eq!(Offset::None.of(1_585 * DOT, LETTER), 0);
    }

    #[test]
    fn rounds_the_product_of_the_page_form_before_the_division() {
        // With c = 4.73073 the dot 1,585 gives 23.52 sixteenths, 24 rounded, which is 1.5
        // steps and rounds up to two, where the quotient 1.470 would round to one; the dot
        // 1,583 gives 23.49 sixteenths, 23 rounded.
        assert_eq!(page_form(473_073, 16).of(1_585 * DOT, LETTER), 1_219);
        assert_eq!(page_form(473_073, 16).of(1_583 * DOT, LETTER), 610);
        assert_eq!(page_form(473_073, 1).of(1_585 * DOT, LETTER), 610);
        assert_eq!(page_form(473_073, 0).of(1_585 * DOT, LETTER), 0);
    }

    #[test]
    fn writes_a_rectangle_with_significant_digits() {
        // A rule 0.5 pt high on a page of 842 pt, 646.7032 pt from the top: its bottom edge
        // lies 194.7968 pt above the page's foot and is written as 194.8 pt, so the rule moves
        // to 646.7 pt; its width of
        // 357.652 pt is written as 357.65 pt.
        use super::Item;
        let u = Length::from_units;
        let writer = Writer::new(u(10)).unwrap().with_digits(Some(non_zero(5)));
        let mut rect = Item::Rect(super::Rect {
            x: u(3_023_870),
            y: u(16_426_262),
            width: u(9_084_361),
            height: u(12_700),
            color: super::Rgb::BLACK,
        });
        write_digits(&writer, u(842 * 25_400), &mut rect);
        let Item::Rect(rect) = rect else {
            unreachable!()
        };
        assert_eq!(
            (
                rect.x.units(),
                rect.y.units(),
                rect.width.units(),
                rect.height.units()
            ),
            (3_023_870, 16_426_180, 9_084_310, 12_700)
        );
    }

    #[test]
    fn writes_a_rectangle_from_its_edges_on_the_steps() {
        // A rule 0.48 pt high and wide, at 13,172 and 21,198 steps of 1/3000 inch from the left
        // and top edges of a Letter page (316.128 and 508.752 pt). Its height and width are
        // written as 0.47998 and 0.48001 pt: the differences of the single-precision products of
        // its edges' steps and 0.024. A reader puts its top 508.75002 pt from the
        // page's top, at the nearest half-EMU.
        use super::Item;
        let u = Length::from_units;
        let writer = Writer::new(u(10))
            .unwrap()
            .with_digits(Some(non_zero(5)))
            .with_rectangle_steps(Some(non_zero(3_000)));
        let rect = |x, y, width, height| {
            Item::Rect(super::Rect {
                x: u(x),
                y: u(y),
                width: u(width),
                height: u(height),
                color: super::Rgb::BLACK,
            })
        };
        let mut rule = rect(8_029_651, 12_922_301, 12_192, 12_192);
        write_digits(&writer, u(792 * 25_400), &mut rule);
        let Item::Rect(rule) = rule else {
            unreachable!()
        };
        let edges = |r: &super::Rect| (r.x.units(), r.y.units(), r.width.units(), r.height.units());
        assert_eq!(edges(&rule), (8_029_702, 12_922_251, 12_192, 12_191));
        // A rectangle with an edge before the page's left edge keeps the single-precision
        // numbers of its exact size.
        let mut wide = rect(-25_400, 12_922_301, 50_800, 12_192);
        write_digits(&writer, u(792 * 25_400), &mut wide);
        let Item::Rect(wide) = wide else {
            unreachable!()
        };
        assert_eq!(edges(&wide).2, 50_800);
        assert_eq!(writer.rectangle_steps(), Some(non_zero(3_000)));
        // The same rule 42,609 steps from the left edge of a wide page (1,022.616 pt): five
        // significant digits print its left edge as 1022.6, and two least decimals as 1022.62.
        // Its other numbers lie below 1,000 pt and stay.
        let far = || rect(25_974_446, 12_922_301, 12_192, 12_192);
        let written = |writer: Writer| {
            let mut item = far();
            write_digits(&writer, u(792 * 25_400), &mut item);
            let Item::Rect(written) = item else {
                unreachable!()
            };
            edges(&written)
        };
        let (left, top, _, tall) = written(writer);
        assert_eq!((left, top, tall), (25_974_040, 12_922_251, 12_191));
        let (left, top, _, tall) = written(writer.with_least_decimals(2));
        assert_eq!((left, top, tall), (25_974_548, 12_922_251, 12_191));
    }

    #[test]
    fn writes_an_upright_image_with_significant_digits() {
        // A picture of 36 by 48 pt on a page of 792 pt, 66.25193 pt from the top: its bottom
        // edge lies 677.74807 pt above the page's foot and is written as 677.75 pt, so the
        // picture moves up to 66.25 pt.
        use super::{ImageItem, Item, Turn};
        let u = Length::from_units;
        let image = |turn| {
            Item::Image(ImageItem {
                x: u(1_143_000),
                y: u(1_682_799),
                width: u(914_400),
                height: u(1_219_200),
                clip: None,
                turn,
                image: Image::new(vec![0]),
            })
        };
        // A turned image keeps its place: its matrix is not a rectangle's numbers.
        let turn = Turn {
            xx: 0,
            xy: -Turn::SCALE,
            yx: Turn::SCALE,
            yy: 0,
        };
        let placed = |writer: Writer| {
            let mut list = DisplayList {
                pages: vec![Page {
                    width: u(612 * 25_400),
                    height: u(792 * 25_400),
                    orientation: Orientation::Portrait,
                    items: vec![image(None), image(Some(turn))],
                }],
            };
            writer.finish(&mut list);
            writer.place_pictures(&mut list);
            list.pages[0]
                .items
                .iter()
                .map(|item| match item {
                    Item::Image(image) => (image.x, image.y, image.width, image.height),
                    _ => unreachable!(),
                })
                .collect::<Vec<_>>()
        };
        let exact = (u(1_143_000), u(1_682_799), u(914_400), u(1_219_200));
        let writer = Writer::new(u(10)).unwrap();
        assert_eq!(
            placed(writer.with_picture_digits(Some(non_zero(5)))),
            [
                (u(1_143_000), u(1_682_750), u(914_400), u(1_219_200)),
                exact
            ]
        );
        // The digits of glyphs and rectangles leave images where they are.
        assert_eq!(
            placed(writer.with_digits(Some(non_zero(5)))),
            [exact, exact]
        );
    }

    #[test]
    fn rounds_the_stretch_of_a_glyph_to_whole_steps() {
        use super::Item;
        // The glyph's baseline and the rectangle's top after a stretch of one step of 10 units
        // on a page 2,000 units high, with glyph steps of `step` units.
        let moved = |step: Option<i64>| {
            let writer = Writer::new(Length::from_units(10))
                .unwrap()
                .with_vertical_stretch(1)
                .with_glyph_stretch_step(step.map(Length::from_units))
                .unwrap();
            let mut list = DisplayList {
                pages: vec![sample_page()],
            };
            writer.finish(&mut list);
            let (Item::Glyphs(run), Item::Rect(rect)) =
                (&list.pages[0].items[0], &list.pages[0].items[1])
            else {
                panic!("no glyphs or rect")
            };
            (run.glyphs[0].y.units(), rect.y.units())
        };
        // The exact stretch moves the baseline at 400 units by 2 units: 2/3 of a step of 3
        // rounds to one step, 2/5 of a step of 5 to none, and half a step of 4 up. The
        // rectangle's top at 200 units moves by 1 unit, which rounds to no step of 3, 4 or 5.
        assert_eq!(moved(None), (402, 201));
        assert_eq!(moved(Some(3)), (403, 200));
        assert_eq!(moved(Some(5)), (400, 200));
        assert_eq!(moved(Some(4)), (404, 200));
    }

    #[test]
    fn refuses_a_glyph_stretch_step_that_is_not_positive() {
        let writer = Writer::new(Length::from_units(10)).unwrap();
        assert_eq!(writer.with_glyph_stretch_step(Some(Length::ZERO)), None);
        assert_eq!(
            writer.with_glyph_stretch_step(Some(Length::from_units(-4))),
            None
        );
        assert_eq!(writer.with_glyph_stretch_step(None), Some(writer));
    }

    /// A writer with a stretch of one step of 10 units and glyph steps of 4 units.
    fn stepping_writer() -> Writer {
        Writer::new(Length::from_units(10))
            .unwrap()
            .with_vertical_stretch(1)
            .with_glyph_stretch_step(Some(Length::from_units(4)))
            .unwrap()
    }

    /// The glyph's baseline at 400 units and the rectangle's top at 200 units of
    /// [`sample_page`], 2,000 units high, after [`stepping_writer`] with a stretch offset and
    /// stretch factors: half a step and a quarter of one before the factor and the offset.
    fn moved(offset: super::Fraction, factors: &[(Length, super::Fraction)]) -> (i64, i64) {
        use super::Item;
        let mut list = DisplayList {
            pages: vec![sample_page()],
        };
        stepping_writer()
            .with_stretch_factors(offset, factors)
            .unwrap()
            .finish(&mut list);
        let (Item::Glyphs(run), Item::Rect(rect)) =
            (&list.pages[0].items[0], &list.pages[0].items[1])
        else {
            panic!("no glyphs or rect")
        };
        (run.glyphs[0].y.units(), rect.y.units())
    }

    #[test]
    fn counts_the_steps_of_the_stretch_with_the_factor_and_offset_of_the_page_height() {
        let u = Length::from_units;
        let page = u(2000);
        assert_eq!(moved((0, 1), &[]), (404, 200));
        // A factor below 1 takes the half step below a half, and an offset up again.
        assert_eq!(moved((0, 1), &[(page, (99, 100))]), (400, 200));
        assert_eq!(moved((1, 100), &[(page, (99, 100))]), (404, 200));
        assert_eq!(moved((-1, 100), &[(page, (1, 1))]), (400, 200));
        // A factor of 2 doubles both: a whole step, and half a step rounded up.
        assert_eq!(moved((0, 1), &[(page, (2, 1))]), (404, 204));
        // The factor of another page height leaves the page on the rounding of the exact
        // stretch, without the offset.
        assert_eq!(moved((-1, 100), &[(u(3000), (2, 1))]), (404, 200));
    }

    #[test]
    fn holds_no_stretch_factors_without_denominators_or_beyond_its_heights() {
        use super::STRETCH_HEIGHTS;
        let writer = stepping_writer();
        let page = Length::from_units(2000);
        assert_eq!(writer.with_stretch_factors((0, 0), &[]), None);
        assert_eq!(writer.with_stretch_factors((0, 1), &[(page, (1, 0))]), None);
        let many = [(page, (1, 1)); STRETCH_HEIGHTS + 1];
        assert_eq!(writer.with_stretch_factors((0, 1), &many), None);
    }

    #[test]
    fn leaves_the_items_of_a_group_where_the_layout_puts_them() {
        use super::Item;
        // The sample page's items in a group, after a writer with a stretch, glyph steps, an
        // offset of rectangles' edges and five digits: they keep every place, and output
        // paints them in their order.
        let grouped = || {
            let mut page = sample_page();
            page.items = vec![Item::Group(super::Group::new(page.items))];
            page
        };
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_vertical_stretch(1)
            .with_glyph_stretch_step(Some(Length::from_units(3)))
            .unwrap()
            .with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
                share: 2,
                bias: 0,
                step: 10,
            }))
            .with_digits(Some(non_zero(5)));
        let mut list = DisplayList {
            pages: vec![grouped()],
        };
        writer.finish(&mut list);
        assert_eq!(list.pages[0], grouped());
        let sample = sample_page();
        assert_eq!(list.pages[0].painted(), sample.painted());
    }

    #[test]
    fn places_the_items_of_a_group_of_the_page_as_the_pages_items() {
        use super::{Group, GroupClip, Item};
        // The sample page's items in a group of the page's items under a clip, after a writer
        // with a stretch, glyph steps, an offset of rectangles' edges and five digits: they
        // take the places that they take outside a group, and the clip stretches as a path.
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_vertical_stretch(1)
            .with_glyph_stretch_step(Some(Length::from_units(3)))
            .unwrap()
            .with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
                share: 2,
                bias: 0,
                step: 10,
            }))
            .with_digits(Some(non_zero(5)));
        let u = Length::from_units;
        let mut plain = DisplayList {
            pages: vec![sample_page()],
        };
        writer.finish(&mut plain);
        let mut page = sample_page();
        let clip = GroupClip::rect(u(0), u(1000), u(500), u(1000));
        page.items = vec![Item::Group(Group::of_page(page.items, clip))];
        let mut grouped = DisplayList { pages: vec![page] };
        writer.finish(&mut grouped);
        let placed = DisplayList {
            pages: vec![Page {
                items: vec![Item::Group(Group::of_page(
                    plain.pages[0].items.clone(),
                    GroupClip::rect(u(0), u(1005), u(500), u(1005)),
                ))],
                ..plain.pages.remove(0)
            }],
        };
        assert_eq!(grouped, placed);
    }

    #[test]
    fn moves_the_clip_of_a_table_cell_with_the_offsets_of_the_cells_items() {
        use super::{Group, GroupClip, Item, Rect, Rgb};
        // A cell's clip over a filled rectangle with the same edges, after a writer with an
        // offset across and down: the clip's edges stay on the rectangle's. A text box's clip
        // keeps its place.
        let offset = WriterOffset::EveryPage(Offset::Share {
            share: 2,
            bias: 0,
            step: 10,
        });
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_horizontal_offset(offset)
            .with_vertical_offset(offset);
        let u = Length::from_units;
        let (x, y, width, height) = (u(300), u(900), u(200), u(400));
        let fill = Item::Rect(Rect {
            x,
            y,
            width,
            height,
            color: Rgb::BLACK,
        });
        let clip = GroupClip::rect(x, y, width, height);
        let page = |group: fn(Vec<Item>, GroupClip) -> Group| Page {
            width: u(1000),
            height: u(2000),
            items: vec![Item::Group(group(vec![fill.clone()], clip.clone()))],
            ..sample_page()
        };
        let mut list = DisplayList {
            pages: vec![page(Group::of_cell), page(Group::of_page)],
        };
        writer.finish(&mut list);
        let group = |page: &Page| match &page.items[0] {
            Item::Group(group) => group.clone(),
            _ => unreachable!("the page holds one group"),
        };
        let cell = group(&list.pages[0]);
        let Item::Rect(moved) = &cell.items[0] else {
            unreachable!("the group holds one rectangle")
        };
        assert_ne!((moved.x, moved.y), (x, y));
        assert_eq!(
            cell.clip,
            Some(GroupClip::rect(moved.x, moved.y, moved.width, moved.height))
        );
        assert_eq!(group(&list.pages[1]).clip, Some(clip));
    }

    #[test]
    fn moves_every_point_of_a_group_of_points_as_a_rectangles_edges() {
        use super::{Group, GroupClip, GroupPlaces, Item, PathItem, Rect, Rgb};
        // A path and a clip with the edges of a filled rectangle, in a group whose every point
        // the writer places, after a writer with an offset across and down: their points stay
        // on the rectangle's edges. In a group of the page's items, the path keeps its place.
        let offset = WriterOffset::EveryPage(Offset::Share {
            share: 2,
            bias: 0,
            step: 10,
        });
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_horizontal_offset(offset)
            .with_vertical_offset(offset);
        let u = Length::from_units;
        let (x, y, width, height) = (u(300), u(900), u(200), u(400));
        let fill = Item::Rect(Rect {
            x,
            y,
            width,
            height,
            color: Rgb::BLACK,
        });
        let outline = |x, y, width, height| GroupClip::rect(x, y, width, height).commands;
        let path = Item::Path(PathItem {
            commands: outline(x, y, width, height),
            color: Rgb::BLACK,
            fill_rule: super::FillRule::NonZero,
        });
        let page = |places| Page {
            width: u(1000),
            height: u(2000),
            items: vec![Item::Group(Group {
                items: vec![fill.clone(), path.clone()],
                clip: Some(GroupClip::rect(x, y, width, height)),
                places,
            })],
            ..sample_page()
        };
        let mut list = DisplayList {
            pages: vec![page(GroupPlaces::Points), page(GroupPlaces::Page)],
        };
        writer.finish(&mut list);
        let items = |page: &Page| match &page.items[0] {
            Item::Group(group) => (group.items.clone(), group.clip.clone()),
            _ => unreachable!("the page holds one group"),
        };
        let (moved, clip) = items(&list.pages[0]);
        let [Item::Rect(rect), Item::Path(drawn)] = moved.as_slice() else {
            unreachable!("the group holds a rectangle and a path")
        };
        assert_ne!((rect.x, rect.y), (x, y));
        let edges = outline(rect.x, rect.y, rect.width, rect.height);
        assert_eq!(drawn.commands, edges);
        assert_eq!(clip.map(|clip| clip.commands), Some(edges));
        let (kept, _) = items(&list.pages[1]);
        assert_eq!(kept[1], path);
    }

    /// The writer offset of a Letter page of Word for Windows across: 4.72515 steps over the
    /// page, in sixteenths of a step, with a binary32 product of dots of 1/600 inch.
    const LETTER_ACROSS: Offset = Offset::Page {
        steps: (472_515, 100_000),
        parts: 16,
        per_inch: 3_000,
        product: super::OffsetProduct::Binary32 { dots_per_inch: 600 },
    };

    #[test]
    fn writes_an_edge_between_two_dots_by_the_entry_at_its_own_place() {
        // On a Letter page 612 pt wide, an edge 0.04 dot past dot 4,700 is written at step
        // 23,505 by the entry at its own place, where the offset of its nearest dot moves it to
        // 0.2 step past step 23,504; on a whole dot both give the same place.
        let side = 612 * 25_400;
        let between = 4_700 * 3_048 + 122;
        assert_eq!(LETTER_ACROSS.written_place(between, side), 14_328_648);
        assert_eq!(between + LETTER_ACROSS.of(between, side), 14_328_160);
        let dot = 4_800 * 3_048;
        assert_eq!(LETTER_ACROSS.written_place(dot, side), 14_632_838);
        assert_eq!(dot + LETTER_ACROSS.of(dot, side), 14_632_838);
        // Every other offset moves the edge as it moves a whole dot.
        let share = Offset::Share {
            share: 2,
            bias: 0,
            step: 10,
        };
        assert_eq!(
            share.written_place(between, side),
            between + share.of(between, side)
        );
    }

    /// The items that the writer draws from a group of `places` on a Letter page of Word for
    /// Windows that holds two rectangles whose left edges lie 0.04 dot past dot 4,700: one dot
    /// wide, and four dots wide.
    fn drawn_rectangles(places: super::GroupPlaces) -> Vec<super::Item> {
        use super::{Group, Item, Rect};
        let u = Length::from_units;
        let writer = Writer::new(u(1))
            .unwrap()
            .with_horizontal_offset(WriterOffset::EveryPage(LETTER_ACROSS));
        let rect = Rect {
            x: u(4_700 * 3_048 + 122),
            y: u(9_000_000),
            width: u(3_048),
            height: u(50_000),
            color: Rgb::BLACK,
        };
        let wide = Rect {
            width: u(4 * 3_048),
            ..rect.clone()
        };
        let mut list = DisplayList {
            pages: vec![Page {
                width: u(612 * 25_400),
                height: u(792 * 25_400),
                items: vec![Item::Group(Group {
                    items: vec![Item::Rect(rect), Item::Rect(wide)],
                    clip: None,
                    places,
                })],
                ..sample_page()
            }],
        };
        writer.finish(&mut list);
        match &list.pages[0].items[0] {
            Item::Group(group) => group.items.clone(),
            _ => unreachable!("the page holds one group"),
        }
    }

    #[test]
    fn draws_a_stroked_rectangle_and_then_its_stroke_after_placing_its_edges() {
        use super::{FillRule, GroupPlaces, Item, PathCommand, Point};
        // A rectangle one dot wide whose edges lie 0.04 dot past dots 4,700 and 4,701 of a
        // Letter page, stroked 0.14 pt wide: its edges go to steps 23,505 and 23,510, and its
        // stroke's outline follows it, 0.07 pt outside the edges; it is narrower than the stroke,
        // so the outline has no inner part. In a group of points, the left edge takes the offset
        // of its nearest dot instead.
        let u = Length::from_units;
        let stroked = drawn_rectangles(GroupPlaces::Stroked { width: u(3_556) });
        let [Item::Rect(placed), Item::Path(outline), ..] = stroked.as_slice() else {
            unreachable!("each rectangle and then its stroke's outline")
        };
        assert_eq!(placed.x, u(14_328_648));
        assert_eq!(placed.width, u(14_331_696 - 14_328_648));
        assert_eq!((placed.y, placed.height), (u(9_000_000), u(50_000)));
        assert_eq!(
            (outline.color, outline.fill_rule),
            (Rgb::BLACK, FillRule::NonZero)
        );
        let (right, below) = (u(14_331_696), u(9_050_000) + u(1_778));
        let at = |x, y| Point { x, y };
        // The outer outline starts at the left end of the bottom edge, 0.07 pt below it, and its
        // corner's quarter circle has its arms 982 units long.
        assert_eq!(
            outline.commands[..3],
            [
                PathCommand::MoveTo(at(u(14_328_648), below)),
                PathCommand::LineTo(at(right, below)),
                PathCommand::CubicTo(
                    at(right + u(982), below),
                    at(right + u(1_778), u(9_050_000) + u(982)),
                    at(right + u(1_778), u(9_050_000)),
                ),
            ]
        );
        assert_eq!(outline.commands.len(), 10);
        let points = drawn_rectangles(GroupPlaces::Points);
        let [Item::Rect(nearest), Item::Rect(_)] = points.as_slice() else {
            unreachable!("a group of points draws the rectangles alone")
        };
        assert_eq!(nearest.x, u(14_328_160));
    }

    #[test]
    fn draws_the_inner_outline_of_the_stroke_of_a_rectangle_wider_than_the_stroke() {
        use super::{GroupPlaces, Item, PathCommand, Point};
        // A rectangle four dots wide, stroked 0.14 pt wide: the inner outline of its stroke
        // starts 0.07 pt above the left end of its bottom edge and goes through the ends of its
        // edges moved 0.07 pt inward.
        let u = Length::from_units;
        let stroked = drawn_rectangles(GroupPlaces::Stroked { width: u(3_556) });
        let [_, _, Item::Rect(wide), Item::Path(outline)] = stroked.as_slice() else {
            unreachable!("each rectangle and then its stroke's outline")
        };
        let (left, right, bottom) = (wide.x, wide.x + wide.width, u(9_050_000));
        assert_eq!(left, u(14_328_648));
        let at = |x, y| Point { x, y };
        assert_eq!(
            outline.commands[10..13],
            [
                PathCommand::MoveTo(at(left, bottom - u(1_778))),
                PathCommand::LineTo(at(left + u(1_778), bottom)),
                PathCommand::LineTo(at(left + u(1_778), u(9_000_000))),
            ]
        );
        assert_eq!(
            outline.commands[17],
            PathCommand::LineTo(at(right, bottom - u(1_778)))
        );
        assert_eq!(outline.commands.len(), 20);
    }

    #[test]
    fn writes_every_point_of_a_group_of_points_with_the_writers_digits() {
        use super::{Group, GroupPlaces, Item, PathCommand, PathItem, Point, Rgb};
        // A point at 123.4567 pt across and 700.1234 pt down a page of 792 pt, written with
        // five digits: 123.46 pt across, and its height as a baseline.
        let u = Length::from_units;
        let point = Point {
            x: u(3_135_800),
            y: u(17_783_134),
        };
        let height = u(792 * 25_400);
        let page = Page {
            width: u(612 * 25_400),
            height,
            items: vec![Item::Group(Group {
                items: vec![Item::Path(PathItem {
                    commands: vec![PathCommand::MoveTo(point), PathCommand::Close],
                    color: Rgb::BLACK,
                    fill_rule: super::FillRule::NonZero,
                })],
                clip: None,
                places: GroupPlaces::Points,
            })],
            ..sample_page()
        };
        let written = |steps: Option<u32>| {
            let writer = Writer::new(Length::from_units(1))
                .unwrap()
                .with_digits(Some(non_zero(5)))
                .with_rectangle_steps(steps.map(non_zero));
            let mut list = DisplayList {
                pages: vec![page.clone()],
            };
            writer.finish(&mut list);
            match &list.pages[0].items[0] {
                Item::Group(group) => match &group.items[0] {
                    Item::Path(path) => path.commands[0].points().next(),
                    _ => None,
                },
                _ => None,
            }
        };
        let plain = written(None).unwrap();
        assert_eq!(plain.x, u(3_135_884));
        assert_eq!(plain.y, super::written_y(height, point.y, (5, 0)));
        // A writer that holds a rectangle's edges on steps of 1/3000 inch holds no point: on
        // steps, the point would lie at 29,172 steps down, 700.128 pt.
        assert_eq!(written(Some(3_000)), Some(plain));
    }

    /// [`sample_page`] after a writer with a step of 10 units and a vertical stretch of one
    /// step: y grows by 1/200, and x stays.
    fn stretched() -> Page {
        let writer = Writer::new(Length::from_units(10))
            .unwrap()
            .with_vertical_stretch(1);
        let mut list = DisplayList {
            pages: vec![sample_page()],
        };
        writer.finish(&mut list);
        list.pages.remove(0)
    }

    /// A page of 1,000 by 2,000 units with a glyph, a rectangle, a path and a clipped image.
    fn sample_page() -> Page {
        use super::{Clip, Glyph, GlyphRun, ImageItem, Item, PathCommand, PathItem, Point, Rect};
        let u = Length::from_units;
        let glyph = Glyph {
            id: 1,
            x: u(500),
            y: u(400),
            text_start: 0,
            text_end: 1,
        };
        let items = vec![
            Item::Glyphs(GlyphRun {
                font: f_office_fonts::FontId::from_index(0),
                size: u(120),
                color: super::Rgb::default(),
                text: "a".to_owned(),
                glyphs: vec![glyph],
                outline: None,
                filled: true,
                effect: false,
                turn: None,
            }),
            Item::Rect(Rect {
                x: u(100),
                y: u(200),
                width: u(300),
                height: u(400),
                color: super::Rgb::default(),
            }),
            Item::Path(PathItem {
                commands: vec![PathCommand::MoveTo(Point {
                    x: u(1000),
                    y: u(2000),
                })],
                color: super::Rgb::default(),
                fill_rule: super::FillRule::NonZero,
            }),
            Item::Image(ImageItem {
                x: u(0),
                y: u(0),
                width: u(1000),
                height: u(2000),
                clip: Some(Clip {
                    x: u(100),
                    y: u(200),
                    width: u(100),
                    height: u(200),
                }),
                turn: None,
                image: Image::new(vec![0]),
            }),
        ];
        Page {
            width: u(1000),
            height: u(2000),
            orientation: Orientation::Portrait,
            items,
        }
    }

    #[test]
    fn detects_formats_from_their_signatures() {
        let mut emf = vec![1, 0, 0, 0];
        emf.resize(40, 0);
        emf.extend_from_slice(b" EMF");
        let cases: [(&[u8], ImageFormat); 12] = [
            (b"\x89PNG\r\n\x1a\nrest", ImageFormat::Png),
            (&[0xFF, 0xD8, 0xFF, 0xE0], ImageFormat::Jpeg),
            (b"GIF89a", ImageFormat::Gif),
            (b"GIF87a", ImageFormat::Gif),
            (b"BM", ImageFormat::Bmp),
            (b"II*\0", ImageFormat::Tiff),
            (b"MM\0*", ImageFormat::Tiff),
            (&emf, ImageFormat::Emf),
            (&[0xD7, 0xCD, 0xC6, 0x9A], ImageFormat::Wmf),
            (&[1, 0, 9, 0], ImageFormat::Wmf),
            (&[2, 0, 9, 0], ImageFormat::Wmf),
            (&[1, 0, 0, 0], ImageFormat::Unknown),
        ];
        for (data, format) in cases {
            assert_eq!(ImageFormat::detect(data), format, "{data:?}");
        }
        assert_eq!(ImageFormat::detect(&emf[..43]), ImageFormat::Unknown);
        assert_eq!(ImageFormat::detect(b""), ImageFormat::Unknown);
    }

    #[test]
    fn shares_the_bytes_of_an_image() {
        let image = Image::new(vec![0xFF, 0xD8, 0xFF]);
        assert_eq!(image.format, ImageFormat::Jpeg);
        let copy = image.clone();
        assert!(Arc::ptr_eq(
            image.data.inline_bytes().unwrap(),
            copy.data.inline_bytes().unwrap()
        ));
    }

    #[test]
    fn shows_the_part_of_a_clip_that_lies_on_the_image() {
        let length = Length::from_units;
        let clip = |x, y, width, height| super::Clip {
            x: length(x),
            y: length(y),
            width: length(width),
            height: length(height),
        };
        let item = |clip| super::ImageItem {
            x: length(100),
            y: length(200),
            width: length(80),
            height: length(40),
            clip,
            turn: None,
            image: Image::new(vec![0xFF, 0xD8, 0xFF]),
        };
        // A clip beyond the image's right edge, from a crop below zero, and inside its bottom.
        assert_eq!(
            item(Some(clip(100, 200, 100, 30))).shown(),
            Some(clip(100, 200, 80, 30))
        );
        // A clip around the whole image shows all of it.
        assert_eq!(
            item(Some(clip(90, 190, 100, 60))).shown(),
            Some(clip(100, 200, 80, 40))
        );
        assert_eq!(item(Some(clip(180, 200, 10, 40))).shown(), None);
        assert_eq!(item(None).shown(), None);
    }

    #[test]
    fn first_place_is_the_first_place_that_map_places_maps() {
        use super::{Group, GroupPlaces, Item, Rect};
        let rect = |y| {
            Item::Rect(Rect {
                x: Length::from_units(1),
                y: Length::from_units(y),
                width: Length::from_units(2),
                height: Length::from_units(3),
                color: Rgb::BLACK,
            })
        };
        let group = |items| {
            Item::Group(Group {
                items,
                clip: None,
                places: GroupPlaces::Own,
            })
        };
        let empty = group(Vec::new());
        let nested = group(vec![empty.clone(), rect(5), rect(7)]);
        for item in [rect(4), empty, nested] {
            let mut mapped = None;
            item.clone().map_places(
                |place| {
                    mapped.get_or_insert(place);
                    place
                },
                |length| length,
            );
            assert_eq!(item.first_place(), mapped);
        }
    }

    /// A gradient from black at 100,000 millionths through a red of 201, 10, 0 and, at the same
    /// place 500,000, blue, to white at the end.
    fn four_stops() -> super::GradientItem {
        use super::{FillRule, GradientItem, GradientStop, Point};
        let origin = Point {
            x: Length::ZERO,
            y: Length::ZERO,
        };
        let stops = vec![
            GradientStop::new(100_000, Rgb::BLACK),
            GradientStop::new(
                500_000,
                Rgb {
                    r: 201,
                    g: 10,
                    b: 0,
                },
            ),
            GradientStop::new(500_000, Rgb { r: 0, g: 0, b: 255 }),
            GradientStop::new(GradientStop::END, Rgb::WHITE),
        ];
        GradientItem::new(Vec::new(), FillRule::NonZero, (origin, origin), stops)
    }

    #[test]
    fn gives_the_color_of_a_gradient_between_its_stops_and_beyond_its_ends() {
        let gradient = four_stops();
        assert_eq!(gradient.color_at(-5), Rgb::BLACK);
        assert_eq!(gradient.color_at(50_000), Rgb::BLACK);
        assert_eq!(gradient.color_at(2_000_000), Rgb::WHITE);
        // A half of 201 rounds up and a half of 10 is 5.
        assert_eq!(gradient.color_at(300_000), Rgb { r: 101, g: 5, b: 0 });
        assert_eq!(
            gradient.color_at(750_000),
            Rgb {
                r: 128,
                g: 128,
                b: 255
            }
        );
    }

    #[test]
    fn gives_the_later_color_where_two_stops_meet_and_black_without_stops() {
        let gradient = four_stops();
        assert_eq!(
            gradient.color_at(499_999),
            Rgb {
                r: 201,
                g: 10,
                b: 0
            }
        );
        assert_eq!(gradient.color_at(500_000), Rgb { r: 0, g: 0, b: 255 });
        let mut empty = gradient;
        empty.stops.clear();
        assert_eq!(empty.color_at(0), Rgb::BLACK);
    }

    #[test]
    fn moves_the_axis_of_a_gradient_with_its_outline() {
        use super::{FillRule, GradientItem, Item, PathCommand, Point};
        let at = |x, y| Point {
            x: Length::from_units(x),
            y: Length::from_units(y),
        };
        let mut item = Item::Gradient(GradientItem::new(
            vec![PathCommand::MoveTo(at(1, 2)), PathCommand::LineTo(at(3, 4))],
            FillRule::NonZero,
            (at(0, 0), at(10, 0)),
            Vec::new(),
        ));
        item.map_places(
            |p| Point {
                x: p.x + Length::from_units(100),
                y: p.y,
            },
            |length| length,
        );
        let Item::Gradient(moved) = &item else {
            panic!("not a gradient");
        };
        assert_eq!(moved.commands[0], PathCommand::MoveTo(at(101, 2)));
        assert_eq!((moved.start, moved.end), (at(100, 0), at(110, 0)));
        assert_eq!(item.first_place(), Some(at(101, 2)));
    }
}