f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
//! Charts in their frames: the plot area, the bars and the axis labels of a clustered column
//! chart, and of the charts that F-Office draws from its rules: line charts, scatter charts and
//! charts of horizontal bars.

use f_office_drawingml::color::{DrawColor, on_white};
use f_office_drawingml::gradient::LinearGradient;
use f_office_drawingml::theme::ShapeTheme;
use f_office_paint::{
    FillRule, Group, GroupClip, Item, PathCommand, PathItem, Point, Rect, Rgb, stroke,
};
use f_office_units::scale::{PERCENT, TENTHS, THOUSANDTHS};
use f_office_units::{Edges, Length};

use super::{Layout, decisions};
use crate::chart::{
    AxisForms, BarStacking, CategoryCrossing, ChartGroup, Columns, Decimal, LabelFormat,
    LabelPiece, LayoutBox, LayoutCorner, LegendPlace, LineDash, LineLook, Marker, MarkerSymbol,
    PlotLayout, PlotPlace, PlotRule, SecondaryValueAxis, SeriesFill, SeriesLabels, SetScale,
    StyleWidth, WrittenLabel,
};
use crate::grid::{Device, Rounding};
use crate::params::{
    CHART_AXIS_HEADROOM, CHART_AXIS_LABEL_ROOM, CHART_AXIS_STEP_LIMIT, CHART_AXIS_STEPS,
    CHART_AXIS_UNITS, CHART_BOTTOM, CHART_BOTTOM_PER_SIZE, CHART_DATA_TABLE_BOTTOM,
    CHART_DATA_TABLE_LEFT, CHART_DATA_TABLE_MANUAL_LEFT, CHART_LINES_BAND_ASCENT_PARTS,
    CHART_LINES_BOTTOM, CHART_LINES_CATEGORY_TOP_PARTS, CHART_LINES_LABEL_GAP_LINE,
    CHART_LINES_LABEL_START, CHART_LINES_LEGEND_PAD, CHART_LINES_LEGEND_ROOM,
    CHART_LINES_OUTER_GAP, CHART_LINES_TITLE_LABEL_TOP, CHART_LINES_UNTITLED_LABEL_TOP,
    CHART_LINES_UNTITLED_TOP, CHART_LINES_VALUE_BASELINE_DESCENTS,
    CHART_LINES_VALUE_BASELINE_PARTS, CHART_PLOT_RIGHT, CHART_STYLE_LINE_STYLES,
    CHART_STYLE_MARKER_BASE, CHART_STYLE_MARKER_LINES, CHART_TITLE_LABEL_TOP, CHART_TITLE_TOP,
    CHART_TURNED_LABEL_LEFT, CHART_VALUE_LABEL_GAP, CHART_VALUE_LABEL_LEFT, MAX_CHART_LINE_DASHES,
};
use crate::props::RunProps;

/// The automatic scale of a value axis that starts at zero: its major unit and the number of
/// units up to its top.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Scale {
    /// The major unit, the distance between two gridlines.
    pub(super) unit: Decimal,
    /// The number of units from zero to the axis' top.
    pub(super) steps: i64,
}

impl Scale {
    /// The scale for values whose largest is `max`, above zero: the smallest major unit of
    /// [`CHART_AXIS_UNITS`] times a power of ten for which the largest value times the
    /// headroom takes at most [`CHART_AXIS_STEPS`] units, and the units that it takes,
    /// rounded up.
    pub(super) fn of(max: Decimal) -> Option<Self> {
        if !max.is_positive() {
            return None;
        }
        // The largest value with the headroom, in thousandths: `need` × 10^`exponent`.
        let need = i128::from(max.digits) * i128::from(CHART_AXIS_HEADROOM);
        let exponent = max.exponent;
        // The unit must reach a tenth of `need` at most steps; start a few powers below it.
        let magnitude = i32::try_from(need.unsigned_abs().checked_ilog10()?).ok()?;
        let first = exponent
            .checked_add(magnitude)?
            .checked_sub(i32::try_from(THOUSANDTHS.ilog10()).ok()?)?
            .checked_sub(TEN_POWERS)?;
        (first..first.checked_add(TEN_POWERS * 2)?).find_map(|power| {
            CHART_AXIS_UNITS.into_iter().find_map(|multiple| {
                let unit = Decimal {
                    digits: multiple,
                    exponent: power,
                };
                let steps = steps_for(need, exponent, unit)?;
                (steps <= CHART_AXIS_STEPS).then_some(Self {
                    unit: unit.normalized(),
                    steps,
                })
            })
        })
    }

    /// The axis' top value.
    pub(super) fn top(self) -> Decimal {
        Decimal {
            digits: self.unit.digits * self.steps,
            exponent: self.unit.exponent,
        }
        .normalized()
    }
}

/// How many powers of ten [`Scale::of`] tries on each side of the largest value's.
const TEN_POWERS: i32 = 2;

/// The units of `unit` that `need` thousandths × 10^`exponent` takes, rounded up.
fn steps_for(need: i128, exponent: i32, unit: Decimal) -> Option<i64> {
    let low = exponent.min(unit.exponent);
    let numerator = need.checked_mul(ten_power(exponent, low)?)?;
    let denominator = i128::from(unit.digits)
        .checked_mul(i128::from(THOUSANDTHS))?
        .checked_mul(ten_power(unit.exponent, low)?)?;
    i64::try_from(numerator.checked_add(denominator - 1)? / denominator).ok()
}

/// 10^(`exponent` − `low`): the factor that brings a decimal of `exponent` to the lower
/// exponent `low` of two, so that both count in the same unit. `None` when `exponent` lies
/// below `low` or the power leaves an `i128`.
fn ten_power(exponent: i32, low: i32) -> Option<i128> {
    i128::from(TENTHS).checked_pow(u32::try_from(exponent - low).ok()?)
}

/// The value axis of a drawn chart: its lowest and highest values, its major unit, the number
/// of units from its lowest value that its labels and gridlines take, and the value at which
/// the category axis crosses it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct ValueAxis {
    /// The lowest value, at the plot area's bottom.
    pub(super) low: Decimal,
    /// The highest value, at the plot area's top.
    pub(super) high: Decimal,
    /// The major unit, the distance between two gridlines.
    pub(super) unit: Decimal,
    /// The number of units from the lowest value to the last label, at or below the highest.
    pub(super) steps: i64,
    /// The value at which the category axis crosses.
    pub(super) crossing: Decimal,
}

/// The digits that [`ValueAxis::of`] adds below the lowest power of ten of the chart's numbers:
/// those of a thousandth, the unit of [`CHART_AXIS_HEADROOM`], so that the headroom counts in
/// whole units.
const HEADROOM_PLACES: u32 = THOUSANDTHS.ilog10();

impl ValueAxis {
    /// The automatic axis of Word's default chart: from zero to the top of [`Scale::of`] for
    /// the largest value, crossed at zero.
    pub(super) fn from_zero(chart: &Columns) -> Option<Self> {
        let scale = Scale::of(values(chart).max()?)?;
        Some(Self {
            low: ZERO,
            high: scale.top(),
            unit: scale.unit,
            steps: scale.steps,
            crossing: ZERO,
        })
    }

    /// The axis of `chart` from the values and what the axis sets: the
    /// highest value is the largest value with the headroom of [`CHART_AXIS_HEADROOM`] over
    /// its distance from the smallest value or zero, and zero when no value is above zero; the
    /// lowest is zero when no value is below zero, else the smallest value less the same
    /// headroom over its distance from the largest value or zero. The major unit is the
    /// smallest of [`CHART_AXIS_UNITS`] times a power of ten at which the axis, rounded out to
    /// whole units, takes at most [`CHART_AXIS_STEPS`] units. A set minimum, maximum or major
    /// unit (`c:min`, `c:max` and `c:majorUnit` of the value axis) takes the place of the
    /// automatic one, and a set minimum is the start of the units. The category axis crosses
    /// at zero, or at the end of the axis nearer to zero when zero is not on it
    /// (`c:crosses val="autoZero"`). `None` when a number leaves an `i128`, when the highest value
    /// does not lie above the lowest, or when the units are more than
    /// [`CHART_AXIS_STEP_LIMIT`].
    pub(super) fn of(chart: &Columns) -> Option<Self> {
        Self::with_most(chart, CHART_AXIS_STEPS)
    }

    /// The axis of [`Self::of`] whose automatic major unit takes at most `most` units in
    /// place of [`CHART_AXIS_STEPS`].
    fn with_most(chart: &Columns, most: i64) -> Option<Self> {
        Self::for_chart(chart, most)
    }

    /// The value axis of `chart` whose automatic major unit takes at most `most` units: for
    /// stacked and 100%-stacked bars or lines, over their cumulative category totals (with
    /// automatic ends capped at `[-1, 1]` for 100%-stacked charts); for other charts, over their
    /// series values.
    pub(super) fn for_chart(chart: &Columns, most: i64) -> Option<Self> {
        let mut axis = Self::unadjusted_for_chart(chart, most)?;
        match chart.category_crossing {
            Some(CategoryCrossing::AutoZero) | None => {}
            Some(CategoryCrossing::Min) => axis.crossing = axis.low,
            Some(CategoryCrossing::At(value)) => axis.crossing = value.clamp(axis.low, axis.high),
        }
        Some(axis)
    }

    /// Computes the value axis bounds of `chart` before applying `chart.category_crossing`.
    fn unadjusted_for_chart(chart: &Columns, most: i64) -> Option<Self> {
        let is_stacked = |s: Option<BarStacking>| {
            matches!(s, Some(BarStacking::Stacked | BarStacking::PercentStacked))
        };
        let stacked_bars = is_stacked(chart.group.stacking());
        if chart.secondary_axis.is_some() {
            let clamp_unit = matches!(chart.group.stacking(), Some(BarStacking::PercentStacked));
            let bar_vals = axis_bar_values(chart, stacked_bars)?;
            return Self::over_with(bar_vals.into_iter(), chart.scale, most, clamp_unit);
        }
        let stacked_lines = is_stacked(chart.group.line_stacking());
        if !stacked_bars && !stacked_lines {
            return Self::over(values(chart), chart.scale, most);
        }
        let clamp_unit = [chart.group.stacking(), chart.group.line_stacking()]
            .contains(&Some(BarStacking::PercentStacked));
        let mut combined = axis_bar_values(chart, stacked_bars)?;
        combined.extend(axis_line_values(chart, stacked_lines)?);
        Self::over_with(combined.into_iter(), chart.scale, most, clamp_unit)
    }

    /// Computes the secondary right value axis over `chart`'s line series.
    fn for_secondary(chart: &Columns, sec: &SecondaryValueAxis, most: i64) -> Option<Self> {
        let stacked = matches!(
            chart.group.line_stacking(),
            Some(BarStacking::Stacked | BarStacking::PercentStacked)
        );
        let clamp_unit = matches!(
            chart.group.line_stacking(),
            Some(BarStacking::PercentStacked)
        );
        let vals = axis_line_values(chart, stacked)?;
        Self::over_with(vals.into_iter(), sec.scale, most, clamp_unit)
    }

    /// The axis of [`Self::with_most`] over `values`, with what the axis sets `set`.
    pub(super) fn over(
        values: impl Iterator<Item = Decimal> + Clone,
        set: SetScale,
        most: i64,
    ) -> Option<Self> {
        Self::over_with(values, set, most, false)
    }

    /// The axis of [`Self::over`], clamping automatic headroom to `[-1, 1]` when `clamp_unit`
    /// is set (100%-stacked charts).
    fn over_with(
        values: impl Iterator<Item = Decimal> + Clone,
        set: SetScale,
        most: i64,
        clamp_unit: bool,
    ) -> Option<Self> {
        let needs = AxisNeeds::of(values, set, clamp_unit)?;
        let (unit, (low, high, units)) = needs.unit_and_ends(most)?;
        if units > i128::from(CHART_AXIS_STEP_LIMIT) {
            return None;
        }
        Some(Self {
            low: needs.decimal(low)?,
            high: needs.decimal(high)?,
            unit: needs.decimal(unit)?,
            steps: i64::try_from(high.checked_sub(low)?.div_euclid(unit)).ok()?,
            crossing: needs.decimal(0_i128.clamp(low, high))?,
        })
    }

    /// The value of the label `step` units above the lowest value.
    pub(super) fn label(&self, step: i64) -> Option<Decimal> {
        let rise = Decimal {
            digits: self.unit.digits.checked_mul(step)?,
            exponent: self.unit.exponent,
        };
        sum(self.low, rise)
    }

    /// The labels' values, from the lowest.
    pub(super) fn labels(&self) -> impl Iterator<Item = Decimal> + '_ {
        (0..=self.steps).map_while(|step| self.label(step))
    }

    /// Where `value` lies on the axis drawn from `from`, the place of its lowest value, to
    /// `to`, the place of its highest, such as from a plot area's bottom up to its top: its
    /// share of the axis from `from`, rounded toward `from`, for a value on the axis or beyond
    /// it at its nearer end.
    pub(super) fn along(&self, (from, to): (Length, Length), value: Decimal) -> Option<Length> {
        self.along_unclamped((from, to), value.clamp(self.low, self.high))
    }

    /// Where `value` lies linearly along `(from, to)` without clamping to `[self.low, self.high]`,
    /// so clipped line and scatter segments keep their true slope across the plot boundary.
    pub(super) fn along_unclamped(
        &self,
        (from, to): (Length, Length),
        value: Decimal,
    ) -> Option<Length> {
        let span = sum(self.high, negated(self.low)?)?;
        Some(from + share(to - from, sum(value, negated(self.low)?)?, span)?)
    }
}

/// What stands across the bottom of a drawn chart's plot area.
#[derive(Clone, Copy)]
pub(super) enum Across<'a> {
    /// The categories, each a band of the plot area's width.
    Bands,
    /// The x axis of a scatter chart, and the x values of each series.
    Values(ValueAxis, &'a [Vec<Decimal>]),
}

/// The direction in which a drawn chart's bars run from the category axis to their values.
/// The categories' bands share the plot area's other side, their **run**, from its start.
#[derive(Clone, Copy)]
enum BarDirection {
    /// Up, as a column chart's bars stand: the value axis from the plot area's bottom up to
    /// its top, and the run from its left edge across to its right edge.
    Up,
    /// Right, as the bars of a horizontal bar chart lie: the value axis from the plot area's
    /// left edge across to its right edge, and the run from its bottom up to its top.
    Right,
}

impl BarDirection {
    /// The places in the plot area `plot` of the value axis' lowest and highest values, as
    /// [`ValueAxis::along`] takes them.
    fn values(self, plot: Edges<Length>) -> (Length, Length) {
        match self {
            Self::Up => (plot.bottom, plot.top),
            Self::Right => (plot.left, plot.right),
        }
    }

    /// The edges of the plot area `plot` at the value axis' two ends, the upper or the left
    /// one first.
    fn value_ends(self, plot: Edges<Length>) -> (Length, Length) {
        match self {
            Self::Up => (plot.top, plot.bottom),
            Self::Right => (plot.left, plot.right),
        }
    }

    /// The length of the run of the plot area `plot`.
    fn run(self, plot: Edges<Length>) -> Length {
        match self {
            Self::Up => plot.right - plot.left,
            Self::Right => plot.bottom - plot.top,
        }
    }

    /// The edges of the plot area `plot` at the run's two ends, the left or the upper one
    /// first.
    fn run_ends(self, plot: Edges<Length>) -> (Length, Length) {
        match self {
            Self::Up => (plot.left, plot.right),
            Self::Right => (plot.top, plot.bottom),
        }
    }

    /// The place `offset` along the run of the plot area `plot` from its start.
    fn at(self, plot: Edges<Length>, offset: Length) -> Length {
        match self {
            Self::Up => plot.left + offset,
            Self::Right => plot.bottom - offset,
        }
    }

    /// The edges of the part of the run of the plot area `plot` that starts `offset` from the
    /// run's start and is `length` long, the left or the upper one first.
    fn part(self, plot: Edges<Length>, offset: Length, length: Length) -> (Length, Length) {
        match self {
            Self::Up => {
                let start = plot.left + offset;
                (start, start + length)
            }
            Self::Right => {
                let start = plot.bottom - offset;
                (start - length, start)
            }
        }
    }

    /// The edges of the part `length` long outside the plot area `plot` before the run's start,
    /// the left or the upper one first.
    fn before_run(self, plot: Edges<Length>, length: Length) -> (Length, Length) {
        match self {
            Self::Up => (plot.left - length, plot.left),
            Self::Right => (plot.bottom, plot.bottom + length),
        }
    }

    /// The edges of the part `length` long from the value axis' place `at` toward its lowest
    /// value, the left or the upper one first.
    fn below(self, at: Length, length: Length) -> (Length, Length) {
        match self {
            Self::Up => (at, at + length),
            Self::Right => (at - length, at),
        }
    }

    /// The rectangle in `color` between the edges `run` along the run and the edges `values`
    /// along the value axis, each pair the left or the upper one first.
    fn rect(self, run: (Length, Length), values: (Length, Length), color: Rgb) -> Rect {
        let (top_left, bottom_right) = self.corners(run, values);
        Rect {
            x: top_left.x,
            y: top_left.y,
            width: bottom_right.x - top_left.x,
            height: bottom_right.y - top_left.y,
            color,
        }
    }

    /// The top left and the bottom right corner of the box between the edges `run` along the
    /// run and the edges `values` along the value axis, each pair the left or the upper one
    /// first.
    fn corners(self, run: (Length, Length), values: (Length, Length)) -> (Point, Point) {
        let ((x0, x1), (y0, y1)) = match self {
            Self::Up => (run, values),
            Self::Right => (values, run),
        };
        (Point { x: x0, y: y0 }, Point { x: x1, y: y1 })
    }
}

/// What paints the bars of a series: a color, or a gradient over each bar's box.
#[derive(Clone, Copy)]
enum BarPaint<'a> {
    /// The color of a series in a color, mixed with white by its opacity.
    Color(Rgb),
    /// The gradient of a series of a gradient fill.
    Gradient(&'a LinearGradient),
}

/// Resolves `fill` for `category` into a [`BarPaint`] against `theme`, or `None` when a solid
/// fill has no color.
fn bar_paint<'a>(fill: &'a SeriesFill, category: i64, theme: &ShapeTheme) -> Option<BarPaint<'a>> {
    let color = match fill {
        SeriesFill::Color(color) => color,
        SeriesFill::Gradient(gradient) => return Some(BarPaint::Gradient(gradient)),
        SeriesFill::None => return None,
        SeriesFill::Points(colors) => colors.get(usize::try_from(category).ok()?)?,
        SeriesFill::BarPoints { points, .. } => {
            points.get(usize::try_from(category).ok()?)?.as_ref()?
        }
    };
    let (rgb, alpha) = color.resolve(&theme.colors)?;
    Some(BarPaint::Color(on_white(rgb, alpha)))
}

/// Paints one bar rectangle or gradient item from its `run` and `values` edges.
fn bar_paint_item(
    direction: BarDirection,
    run: (Length, Length),
    values: (Length, Length),
    (paint, theme): (BarPaint<'_>, &ShapeTheme),
) -> Option<Item> {
    match paint {
        BarPaint::Color(color) => Some(Item::Rect(direction.rect(run, values, color))),
        BarPaint::Gradient(gradient) => gradient
            .item(direction.corners(run, values), &theme.colors)
            .map(Item::Gradient),
    }
}

/// What a chart's numbers ask of its automatic value axis ([`ValueAxis::of`]), each a count of
/// 10^`exponent`.
struct AxisNeeds {
    /// The power of ten that the counts count.
    exponent: i32,
    /// The lowest value that the axis must reach: the smallest value with its headroom.
    low: i128,
    /// The highest value that the axis must reach: the largest value with its headroom.
    high: i128,
    /// What the axis sets: its lowest value, its highest value and its major unit.
    set: [Option<i128>; 3],
}

impl AxisNeeds {
    /// The needs of `values` with what the axis sets `set`, counted [`HEADROOM_PLACES`] below
    /// the lowest power of ten of their numbers; when `clamp_unit` is set, automatic ends stay
    /// within `[-1, 1]`.
    fn of(
        values: impl Iterator<Item = Decimal> + Clone,
        set: SetScale,
        clamp_unit: bool,
    ) -> Option<Self> {
        let min_exp = values
            .clone()
            .chain(set.min)
            .chain(set.max)
            .chain(set.major_unit)
            .map(|d| d.exponent)
            .min()?;
        let base_exp = if clamp_unit { min_exp.min(0) } else { min_exp };
        let exponent = base_exp.checked_sub_unsigned(HEADROOM_PLACES)?;
        let count = |d: Decimal| i128::from(d.digits).checked_mul(ten_power(d.exponent, exponent)?);
        let counts = values.map(count).collect::<Option<Vec<_>>>()?;
        let (low, high) = need_bounds(
            *counts.iter().min()?,
            *counts.iter().max()?,
            (exponent, clamp_unit),
        )?;
        let set_count = |d: Option<Decimal>| d.map_or(Some(None), |d| count(d).map(Some));
        Some(Self {
            exponent,
            low,
            high,
            set: [
                set_count(set.min)?,
                set_count(set.max)?,
                set_count(set.major_unit)?,
            ],
        })
    }

    /// The major unit, and the axis' lowest and highest values and the units between them at
    /// it: the set unit, or the smallest automatic one at which the axis takes at most `most`
    /// units.
    fn unit_and_ends(&self, most: i64) -> Option<(i128, (i128, i128, i128))> {
        if let [_, _, Some(unit)] = self.set {
            return Some((unit, self.ends(unit)?));
        }
        (0_u32..)
            .map_while(|power| i128::from(TENTHS).checked_pow(power))
            .flat_map(|power| {
                CHART_AXIS_UNITS.map(|multiple| power.checked_mul(i128::from(multiple)))
            })
            .map_while(std::convert::identity)
            .find_map(|unit| {
                let ends = self.ends(unit)?;
                (ends.2 <= i128::from(most)).then_some((unit, ends))
            })
    }

    /// The axis' lowest and highest values at `unit`, each the set one or the needed one
    /// rounded out to whole units from the lowest, and the units between them, rounded up;
    /// `None` when the highest does not lie above the lowest.
    fn ends(&self, unit: i128) -> Option<(i128, i128, i128)> {
        let [set_low, set_high, _] = self.set;
        let low = set_low.map_or_else(|| self.low.div_euclid(unit).checked_mul(unit), Some)?;
        let high = set_high.map_or_else(
            || low.checked_add(units_up(self.high.checked_sub(low)?, unit)?.checked_mul(unit)?),
            Some,
        )?;
        let units = units_up(high.checked_sub(low)?, unit)?;
        (high > low).then_some((low, high, units))
    }

    /// A count as a decimal, without the count's trailing zeros: a cache that writes a value
    /// with 17 digits, such as `4.4000000000000004`, counts every value at a power of ten so
    /// low that the axis' ends, as counts, need more digits than a decimal holds, and only
    /// their zeros do.
    fn decimal(&self, digits: i128) -> Option<Decimal> {
        let ten = i128::from(TENTHS);
        let (mut digits, mut exponent) = (digits, self.exponent);
        while digits != 0 && digits % ten == 0 {
            digits /= ten;
            exponent = exponent.checked_add(1)?;
        }
        Some(
            Decimal {
                digits: i64::try_from(digits).ok()?,
                exponent,
            }
            .normalized(),
        )
    }
}

/// The most major units whose labels' single lines, each `line` high, fit a plot area of
/// `height` less [`CHART_AXIS_LABEL_ROOM`]: at least one, and at most [`CHART_AXIS_STEPS`].
fn room_units(height: Length, line: Length) -> i64 {
    if line <= Length::ZERO {
        return CHART_AXIS_STEPS;
    }
    (height - CHART_AXIS_LABEL_ROOM)
        .units()
        .div_euclid(line.units())
        .clamp(1, CHART_AXIS_STEPS)
}

/// The units of `unit` in `span`, rounded up.
fn units_up(span: i128, unit: i128) -> Option<i128> {
    Some(span.checked_add(unit.checked_sub(1)?)?.div_euclid(unit))
}

/// The headroom of [`CHART_AXIS_HEADROOM`] over a distance between values.
fn headroom(span: i128) -> Option<i128> {
    Some(span.checked_mul(i128::from(CHART_AXIS_HEADROOM - THOUSANDTHS))? / i128::from(THOUSANDTHS))
}

/// Automatic `(low, high)` bounds with headroom, optionally clamped to `[-1, 1]` at `exponent`.
fn need_bounds(
    least: i128,
    most: i128,
    (exponent, clamp_unit): (i32, bool),
) -> Option<(i128, i128)> {
    let (low, high) = (low_need(least, most)?, high_need(most, least)?);
    if !clamp_unit {
        return Some((low, high));
    }
    let one = ten_power(0, exponent)?;
    Some((low.max(-one), high.min(one)))
}

/// The highest value that an axis must reach for values up to `most` and down to `least`: the
/// largest value and its headroom over its distance from the smallest value or zero, and zero
/// when no value is above zero.
fn high_need(most: i128, least: i128) -> Option<i128> {
    if most > 0 {
        most.checked_add(headroom(most.checked_sub(least.min(0))?)?)
    } else {
        Some(0)
    }
}

/// The lowest value that an axis must reach for values down to `least` and up to `most`: the
/// smallest value less its headroom over its distance from the largest value or zero, and zero
/// when no value is below zero.
fn low_need(least: i128, most: i128) -> Option<i128> {
    if least < 0 {
        least.checked_sub(headroom(most.max(0).checked_sub(least)?)?)
    } else {
        Some(0)
    }
}

/// Zero as a decimal.
const ZERO: Decimal = Decimal {
    digits: 0,
    exponent: 0,
};

/// The non-blank values of the chart's series, all together.
fn values(chart: &Columns) -> impl Iterator<Item = Decimal> + Clone + '_ {
    chart
        .series
        .iter()
        .flat_map(|s| s.values.iter().copied().flatten())
}

/// The value-axis inputs from `chart`'s bar series: stacked outer ends when `stacked` is set,
/// else raw non-blank bar values.
fn axis_bar_values(chart: &Columns, stacked: bool) -> Option<Vec<Decimal>> {
    if stacked {
        return Some(bars::stacked_segments(chart)?.outer_ends().collect());
    }
    Some(
        chart
            .bar_series()
            .iter()
            .flat_map(|s| s.values.iter().copied().flatten())
            .collect(),
    )
}

/// The value-axis inputs from `chart`'s line series: cumulative stacked values when `stacked` is
/// set, else raw non-blank line values.
fn axis_line_values(chart: &Columns, stacked: bool) -> Option<Vec<Decimal>> {
    if stacked {
        return Some(
            bars::stacked_line_values(chart)?
                .into_iter()
                .flatten()
                .flatten()
                .collect(),
        );
    }
    Some(
        chart
            .line_series()
            .iter()
            .flat_map(|s| s.values.iter().copied().flatten())
            .collect(),
    )
}

/// `a` + `b`, with as many of its highest digits as a decimal holds ([`within_digits`]).
pub(super) fn sum(a: Decimal, b: Decimal) -> Option<Decimal> {
    let low = a.exponent.min(b.exponent);
    let wide = |d: Decimal| i128::from(d.digits).checked_mul(ten_power(d.exponent, low)?);
    let total = wide(a)?.checked_add(wide(b)?)?;
    let (digits, exponent) = within_digits(total, low)?;
    Some(Decimal { digits, exponent }.normalized())
}

/// `digits` × 10^`exponent` with as many of its highest digits as 64 bits hold, the rest
/// rounded half away from zero: a cache's 17 digits of a value and a value of other powers of
/// ten can sum to more.
fn within_digits(digits: i128, exponent: i32) -> Option<(i64, i32)> {
    let fits = |drop: u32| {
        i128::from(TENTHS)
            .checked_pow(drop)
            .and_then(|power| digits.checked_div(power))
            .is_some_and(|kept| i64::try_from(kept).is_ok())
    };
    let drop = (0..=u32::MAX).find(|&drop| fits(drop))?;
    let power = i128::from(TENTHS).checked_pow(drop)?;
    let rest = digits.checked_rem(power)?.checked_abs()?;
    let away = if rest.checked_mul(2)? >= power {
        digits.signum()
    } else {
        0
    };
    let kept = digits.checked_div(power)?.checked_add(away)?;
    Some((
        i64::try_from(kept).ok()?,
        exponent.checked_add(i32::try_from(drop).ok()?)?,
    ))
}

/// −`value`, or `None` for the lowest digits, which have no opposite.
fn negated(value: Decimal) -> Option<Decimal> {
    Some(Decimal {
        digits: value.digits.checked_neg()?,
        exponent: value.exponent,
    })
}

/// `value` × `length` / `whole` for two decimals, rounded toward zero. The product of the
/// decimals counts in `i128`, beyond the range of a length.
pub(super) fn share(length: Length, value: Decimal, whole: Decimal) -> Option<Length> {
    let low = value.exponent.min(whole.exponent);
    let numerator = i128::from(length.units())
        .checked_mul(i128::from(value.digits))?
        .checked_mul(ten_power(value.exponent, low)?)?;
    let denominator = i128::from(whole.digits).checked_mul(ten_power(whole.exponent, low)?)?;
    i64::try_from(numerator.checked_div(denominator)?)
        .ok()
        .map(Length::from_units)
}

/// A path item filled under the nonzero rule.
fn path(commands: Vec<PathCommand>, color: Rgb) -> Item {
    Item::Path(PathItem {
        commands,
        color,
        fill_rule: FillRule::NonZero,
    })
}

/// The width that `width` gives: its own, or `styles` times the width of the theme's first line
/// style for the chart style's. `None` when the theme has no first line style.
fn line_width(width: StyleWidth, theme: &ShapeTheme, styles: i64) -> Option<Length> {
    match width {
        StyleWidth::Set(width) => Some(width),
        StyleWidth::Automatic => theme.line_width(1)?.checked_mul(styles),
    }
}

/// The items of each contiguous run of two or more non-blank points of a series line in `look`,
/// `width` wide, in `color` and inside `clip` when there is one. An isolated point between blanks
/// draws no line stroke. `None` when a run's outlines have none ([`line_commands`]).
fn line_runs_items(
    look: &LineLook,
    points: &[Option<(Point, Point)>],
    width: Option<Length>,
    (color, clip): (Rgb, Option<&GroupClip>),
) -> Option<Vec<Item>> {
    let mut items = Vec::new();
    for run in points.split(Option::is_none) {
        let drawn: Vec<Point> = run
            .iter()
            .filter_map(|point| point.map(|(drawn, _)| drawn))
            .collect();
        if drawn.len() >= 2 {
            items.extend(line_item(look, drawn, width, (color, clip))?);
        }
    }
    Some(items)
}

/// The items of the series line of `look` through `points`, `width` wide, in `color` and
/// inside `clip` when there is one: none for a series without a line, and `None` when its
/// outlines have none ([`line_commands`]).
fn line_item(
    look: &LineLook,
    points: Vec<Point>,
    width: Option<Length>,
    (color, clip): (Rgb, Option<&GroupClip>),
) -> Option<Vec<Item>> {
    let Some(width) = width else {
        return Some(Vec::new());
    };
    let points = smooth::form_points(look.form, points);
    let line = path(line_commands(&points, width, look.dash)?, color);
    Some(vec![match clip {
        Some(clip) => Item::Group(Group::of_page(vec![line], clip.clone())),
        None => line,
    }])
}

/// The outlines of a series line through `points`, `width` wide, with round caps and round
/// joins: one line, or the dashes of `dash`. `None` when the dashes would be more than
/// [`MAX_CHART_LINE_DASHES`].
fn line_commands(
    points: &[Point],
    width: Length,
    dash: Option<LineDash>,
) -> Option<Vec<PathCommand>> {
    let half = width.div_toward_zero(2);
    match dash {
        None => Some(stroke::round_line(points, half)),
        Some(dash) => stroke::round_dashes(
            points,
            half,
            &dash_lengths(dash, width)?,
            MAX_CHART_LINE_DASHES,
        ),
    }
}

/// The lengths along a series line of the preset dash `dash` that are on and off in turn, for a
/// line `width` wide: the preset's dashes and gaps in widths of the line, each dash one width
/// shorter and each gap one width longer, so that a dash with its round caps covers its length
/// and a dot is a dash of length 0. `None` when a length leaves `Length`.
// quirk: ChartLineStrokes::StyleRound (src/quirks.rs)
fn dash_lengths(dash: LineDash, width: Length) -> Option<Vec<Length>> {
    (0..)
        .zip(dash.pattern())
        .map(|(index, &widths)| {
            let length = width.checked_mul(widths)?;
            if index % 2 == 0 {
                length.checked_sub(width)
            } else {
                length.checked_add(width)
            }
        })
        .collect()
}

/// The size of a marker: its own, or the chart style's, [`CHART_STYLE_MARKER_BASE`] points and
/// [`CHART_STYLE_MARKER_LINES`] times the width of the theme's first line style, cut to a whole
/// point.
fn marker_size(marker: &Marker, theme: &ShapeTheme) -> Option<Length> {
    if let Some(size) = marker.size {
        return Some(size);
    }
    let size = Length::from_points(CHART_STYLE_MARKER_BASE)?
        + theme.line_width(1)?.checked_mul(CHART_STYLE_MARKER_LINES)?;
    Length::from_points(size.units() / Length::UNITS_PER_POINT)
}

/// The kinds of a marker's parts, which take their size and their place on the layout device's
/// dots each in their own way ([`marker_span`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MarkerPart {
    /// A square or a circle.
    Whole,
    /// A diamond, a triangle, or the box of an x or a star.
    Even,
    /// The lines of an x or a star.
    Lines,
}

/// The start and the length of a marker's part on one axis of `device`, for a marker `size`
/// across whose outline is an odd number of dots wide (`odd_outline`) or not, around the series
/// point's exact place `point` on that axis. The marker's middle is the dot nearest to the
/// point; under an odd outline, the middle of the dot that holds the point, and for a point on
/// a dot the dot after it (`after`, across) or before it (down). With the size in whole dots, a
/// half up: a square or a circle is that size, one dot less under an odd outline, and starts
/// half the size in dots, a half up, before the middle; a diamond, a triangle and a box are the
/// size made even downward, around the middle; the lines of an x or a star are as long as the
/// box, one dot longer under an odd outline, around the middle.
fn marker_span(
    device: &Device,
    part: MarkerPart,
    size: Length,
    odd_outline: bool,
    (point, after): (Length, bool),
) -> (Length, Length) {
    let whole = device.count(size, Rounding::HalfUp);
    let half_dot = device.dots(1).div_toward_zero(2);
    let middle = match (odd_outline, after) {
        (false, _) => device.snap(point),
        (true, true) => device.dots(device.count(point, Rounding::Down)) + half_dot,
        (true, false) => device.dots(device.count(point, Rounding::Up)) - half_dot,
    };
    let odd = i64::from(odd_outline);
    let even = whole.div_euclid(2);
    let (reach, length) = match part {
        MarkerPart::Whole => (
            device.dots(device.count(size.div_toward_zero(2), Rounding::HalfUp)),
            device.dots(whole - odd),
        ),
        MarkerPart::Even => (device.dots(even), device.dots(even * 2)),
        MarkerPart::Lines => (
            device.dots(even) + if odd_outline { half_dot } else { Length::ZERO },
            device.dots(even * 2 + odd),
        ),
    };
    (middle - reach, length)
}

/// The items of `marker` at a series point whose exact place is `point`: its fill, then its
/// outline with flat ends and round joins when it has one, each in its own color or the
/// series' (`series`, as the file gives it and as drawn), on the dots of `device` as
/// [`marker_span`] places each part. The x and the star are strokes of the outline without a
/// fill, over a filled and outlined square box when the marker has a fill of its own.
fn marker_items(
    marker: &Marker,
    point: Point,
    series: (&DrawColor, Rgb),
    theme: &ShapeTheme,
    device: &Device,
) -> Vec<Item> {
    let resolved = |color: &Option<DrawColor>| match color {
        Some(color) => color
            .resolve(&theme.colors)
            .map(|(rgb, alpha)| on_white(rgb, alpha)),
        None => Some(series.1),
    };
    // The outline's color and width, or none for a marker without an outline.
    let outline = match &marker.outline {
        Some(outline) => match (
            resolved(&outline.color),
            line_width(outline.width, theme, 1),
        ) {
            (Some(color), Some(width)) => Some((color, width)),
            _ => return Vec::new(),
        },
        None => None,
    };
    let (Some(size), Some(fill)) = (marker_size(marker, theme), resolved(&marker.fill)) else {
        return Vec::new();
    };
    let width = outline.map_or(Length::ZERO, |(_, width)| width);
    let w = width.div_toward_zero(2);
    // The outline's color and its half width on each side of the edge.
    let edge = outline.map(|(color, _)| (color, w));
    let odd_outline = device.count(width, Rounding::HalfUp).rem_euclid(2) == 1;
    // The corners of a part's box, its top left and its bottom right.
    let span = |part: MarkerPart| {
        let (left, across) = marker_span(device, part, size, odd_outline, (point.x, true));
        let (top, down) = marker_span(device, part, size, odd_outline, (point.y, false));
        (
            Point { x: left, y: top },
            Point {
                x: left + across,
                y: top + down,
            },
        )
    };
    let middle = |(a, b): (Point, Point)| Point {
        x: a.x + (b.x - a.x).div_toward_zero(2),
        y: a.y + (b.y - a.y).div_toward_zero(2),
    };
    let square =
        |(a, b): (Point, Point)| vec![a, Point { x: b.x, y: a.y }, b, Point { x: a.x, y: b.y }];
    let corners = match marker.symbol {
        MarkerSymbol::Circle => {
            let (a, b) = span(MarkerPart::Whole);
            let (center, r) = (middle((a, b)), (b.x - a.x).div_toward_zero(2));
            return circle_items(center, r, fill, edge);
        }
        MarkerSymbol::X | MarkerSymbol::Star => {
            let mut items = if marker.fill.is_some() {
                outlined(&square(span(MarkerPart::Even)), fill, edge)
            } else {
                Vec::new()
            };
            let Some((color, _)) = outline else {
                return items;
            };
            let (a, b) = span(MarkerPart::Lines);
            let mut strokes = vec![(a, b), (Point { x: a.x, y: b.y }, Point { x: b.x, y: a.y })];
            if marker.symbol == MarkerSymbol::Star {
                let x = middle((a, b)).x;
                strokes.push((Point { x, y: a.y }, Point { x, y: b.y }));
            }
            let commands = strokes
                .into_iter()
                .filter_map(|(from, to)| stroke::band(from, to, w))
                .flatten()
                .collect();
            items.push(path(commands, color));
            return items;
        }
        MarkerSymbol::Square => square(span(MarkerPart::Whole)),
        MarkerSymbol::Diamond => {
            let (a, b) = span(MarkerPart::Even);
            let m = middle((a, b));
            vec![
                Point { x: m.x, y: a.y },
                Point { x: b.x, y: m.y },
                Point { x: m.x, y: b.y },
                Point { x: a.x, y: m.y },
            ]
        }
        MarkerSymbol::Triangle => {
            let (a, b) = span(MarkerPart::Even);
            vec![
                Point {
                    x: middle((a, b)).x,
                    y: a.y,
                },
                b,
                Point { x: a.x, y: b.y },
            ]
        }
    };
    outlined(&corners, fill, edge)
}

/// The items of a circle marker around `center` with the radius `r`: a disc filled in `fill`,
/// then, when `edge` gives its color and half width, a ring that wide on each side of its edge
/// in that color, or one wider disc when that color is the fill's.
fn circle_items(center: Point, r: Length, fill: Rgb, edge: Option<(Rgb, Length)>) -> Vec<Item> {
    let Some((color, w)) = edge else {
        return vec![path(stroke::disc(center, r).to_vec(), fill)];
    };
    if fill == color {
        return vec![path(stroke::disc(center, r + w).to_vec(), fill)];
    }
    let mut ring = stroke::disc(center, r + w).to_vec();
    ring.extend(stroke::disc(center, r - w));
    vec![
        path(stroke::disc(center, r).to_vec(), fill),
        Item::Path(PathItem {
            commands: ring,
            color,
            fill_rule: FillRule::EvenOdd,
        }),
    ]
}

/// The shape of `corners` filled in `fill`, then, when `edge` gives its color and half width,
/// its outline that wide on each side of its edge, with round joins, in that color.
fn outlined(corners: &[Point], fill: Rgb, edge: Option<(Rgb, Length)>) -> Vec<Item> {
    let mut shape: Vec<PathCommand> = corners
        .iter()
        .enumerate()
        .map(|(index, &corner)| {
            if index == 0 {
                PathCommand::MoveTo(corner)
            } else {
                PathCommand::LineTo(corner)
            }
        })
        .collect();
    shape.push(PathCommand::Close);
    let mut items = vec![path(shape, fill)];
    if let Some((color, half)) = edge {
        items.push(path(stroke::round_outline(corners, half), color));
    }
    items
}

/// Where the bars of a clustered chart lie along a run `span` long ([`BarDirection`]): one
/// band for each category, and in a band the bars of the series side by side with the overlap
/// between them and the gap shared on both sides of them. The run counts `parts`: in each
/// band, a hundred for each series, less the overlap between two neighbours, plus the gap, all
/// as percentages of a bar's thickness (ECMA-376 Part 1, 21.2.2.75 and 21.2.2.131).
struct Clusters {
    /// The file's gap between the bands, a percentage of a bar's thickness.
    gap: i64,
    /// The file's overlap of two neighbouring bars, a percentage of a bar's thickness.
    overlap: i64,
    /// The count of categories, each a band.
    categories: i64,
    /// The run's length.
    span: Length,
    /// The run's parts.
    parts: i64,
    /// A bar's thickness, a hundred parts.
    thickness: Length,
}

impl Clusters {
    /// The bars of `chart` with the file's gap and overlap `(gap, overlap)` along a run `span`
    /// long. `None` when the file's overlap or gap makes the count of parts leave an `i64`,
    /// when the run has no parts, or when a bar's thickness does not fit in a length.
    fn of(chart: &Columns, (gap, overlap): (i64, i64), span: Length) -> Option<Self> {
        let series = i64::try_from(chart.bar_series().len()).ok()?;
        let categories = i64::try_from(chart.categories).ok()?;
        let overlaps = (series - 1).checked_mul(overlap)?;
        let band = (PERCENT * series).checked_sub(overlaps)?.checked_add(gap)?;
        let parts = categories.checked_mul(band).filter(|&parts| parts > 0)?;
        let thickness = span.checked_mul(PERCENT)?.div_toward_zero(parts);
        Some(Self {
            gap,
            overlap,
            categories,
            span,
            parts,
            thickness,
        })
    }

    /// How far the bar of the series `index` in the category `category` starts from the run's
    /// start. `None` when a product with the file's gap, overlap or counts does not fit in a
    /// length.
    fn start(&self, (category, index): (i64, i64)) -> Option<Length> {
        let band = self
            .span
            .checked_mul(category)?
            .div_toward_zero(self.categories);
        let gap = self
            .span
            .checked_mul(self.gap)?
            .div_toward_zero(self.parts.checked_mul(2)?);
        let beside = self
            .span
            .checked_mul(index)?
            .checked_mul(PERCENT.checked_sub(self.overlap)?)?
            .div_toward_zero(self.parts);
        Some(band + gap + beside)
    }
}

/// Whether a bar chart's items hold all of its data labels ([`DrawnText::data_labels`]): it has
/// no labels of other kinds, and the labels of its values are drawn (`drawn`) or no series
/// shows them.
fn holds_all_data_labels(chart: &Columns, drawn: bool) -> bool {
    let shows_values = chart
        .series
        .iter()
        .any(|series| matches!(series.labels, SeriesLabels::Values(_)));
    !chart.other_labels && (drawn || !shows_values)
}

/// The lengths of a font's text that place a plot area and its labels: the win line of the
/// labels and the top of their font without a line gap, at their size.
#[derive(Clone, Copy)]
struct LabelLines {
    /// The labels' size, the length of their em.
    size: Length,
    /// The labels' win line.
    line: Length,
    /// The top of the labels' font without a line gap.
    top: Length,
    /// The part of the face's single line above the baseline, which holds the line gap of a
    /// taller hhea line above the top.
    single_top: Length,
    /// The face's single line.
    single_line: Length,
}

impl LabelLines {
    /// The part of the top in a band ([`CHART_LINES_BAND_ASCENT_PARTS`]).
    fn top_part(self) -> Length {
        self.top.div_toward_zero(CHART_LINES_BAND_ASCENT_PARTS)
    }

    /// A band of chart text: a line and a part of the top.
    fn band(self) -> Length {
        self.line + self.top_part()
    }

    /// `per_thousand` thousandths of the line.
    fn of_line(self, per_thousand: i64) -> Option<Length> {
        Some(
            self.line
                .checked_mul(per_thousand)?
                .div_toward_zero(THOUSANDTHS),
        )
    }

    /// The room of a legend at the bottom or the top:
    /// [`CHART_LINES_LEGEND_PAD`] and [`CHART_LINES_LEGEND_ROOM`] of the line.
    fn legend_room(self) -> Option<Length> {
        Some(CHART_LINES_LEGEND_PAD + self.of_line(CHART_LINES_LEGEND_ROOM)?)
    }

    /// The distance of the plot area's edge from the frame's top without a title, or
    /// from the legend's room at the bottom when the category labels stand inside the plot
    /// area: [`CHART_LINES_UNTITLED_TOP`], or
    /// [`CHART_LINES_UNTITLED_LABEL_TOP`] and half a line when that is more.
    fn untitled_edge(self) -> Length {
        CHART_LINES_UNTITLED_TOP.max(CHART_LINES_UNTITLED_LABEL_TOP + self.line.div_toward_zero(2))
    }

    /// The gap from the end of each value label to the plot area: half a line
    /// ([`CHART_LINES_LABEL_GAP_LINE`]) and a part of the top.
    fn label_gap(self) -> Option<Length> {
        Some(self.of_line(CHART_LINES_LABEL_GAP_LINE)? + self.top_part())
    }

    /// How far a value label's baseline lies below the place of its value: the em and
    /// the win top less [`CHART_LINES_VALUE_BASELINE_DESCENTS`] win descents, over
    /// [`CHART_LINES_VALUE_BASELINE_PARTS`].
    fn value_baseline(self) -> Option<Length> {
        let descents = (self.line - self.top).checked_mul(CHART_LINES_VALUE_BASELINE_DESCENTS)?;
        Some((self.size + self.top - descents).div_toward_zero(CHART_LINES_VALUE_BASELINE_PARTS))
    }

    /// How far a category label's baseline lies below the plot area: the win top and
    /// [`CHART_LINES_CATEGORY_TOP_PARTS`] parts of it.
    fn category_baseline(self) -> Option<Length> {
        Some(
            self.top
                + self
                    .top_part()
                    .checked_mul(CHART_LINES_CATEGORY_TOP_PARTS)?,
        )
    }
}

/// The lines of the labels on two sides of a plot area, each at its own size.
#[derive(Clone, Copy)]
struct SideLines {
    /// The lines of the labels at the left.
    left: LabelLines,
    /// The lines of the labels below.
    below: LabelLines,
}

/// Which of a drawn chart's text its items hold.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct DrawnText {
    /// Whether they hold the axis labels, the title and the legend.
    pub(super) axes_and_legend: bool,
    /// Whether they hold the data labels of every series that shows them.
    pub(super) data_labels: bool,
}

/// Whether the chart reserves room for secondary right value-axis labels at `plot.right`.
enum RightLabels {
    /// No shown secondary right value-axis labels.
    Absent,
    /// Secondary right value-axis labels reserving `widest_label + label_gap`.
    Shown(Length),
}

/// Dispatch result of [`Layout::special_chart_group`].
enum SpecialLayout {
    /// Chart group laid out by its own handler (`Pie`, `Doughnut`, or `Bars`).
    Handled(Option<(Vec<Item>, DrawnText)>),
    /// Standard vertical column, line, or scatter chart.
    Standard,
}

impl Layout<'_> {
    /// The items of a clustered column chart in its box on the page, `frame`: the value
    /// axis' gridlines, the bars and the category axis' line in the plot area, which the rule
    /// that the target's quirk `ChartPlotArea` gives the chart places
    /// ([`crate::reader::settings::PlotRules::rule`]); `None` when a step gives no place, such
    /// as an axis whose numbers leave the digits of a decimal or a plot area without room in the
    /// frame, which the caller leaves out with a warning. Says too which of the chart's text the
    /// items hold ([`DrawnText`]): F-Office draws the axis labels, the title and the legend only
    /// where the rule `FontLines` places them, and each only where its rules hold, and the data
    /// labels of the bars only where the target's quirk `ChartDataLabels` draws them.
    pub(super) fn columns(
        &mut self,
        chart: &Columns,
        frame: Edges<Length>,
    ) -> Option<(Vec<Item>, DrawnText)> {
        let rule = decisions::chart_plot_rule(&self.context.quirks, chart)?;
        if let SpecialLayout::Handled(result) = self.special_chart_group(chart, rule, frame) {
            return result;
        }
        let (axis, secondary, mut plot) = match rule {
            // quirk: ChartPlotArea::DefaultChart (src/quirks.rs)
            PlotRule::DefaultChart => {
                let axis = ValueAxis::from_zero(chart)?;
                (axis, None, self.default_plot(chart, &axis, frame)?)
            }
            // quirk: ChartPlotArea::FontLines (src/quirks.rs)
            PlotRule::FontLines => self.font_line_axes_and_plot(chart, frame)?,
        };
        let legend_plot = self.legend_plot_for(chart, secondary.as_ref(), plot)?;
        let across = self.axis_across(chart, frame, &mut plot)?;
        if plot.right <= plot.left
            || plot.bottom <= plot.top
            || Self::flips_top_labels(chart, &axis)
        {
            return None;
        }
        let up = BarDirection::Up;
        let mut items = self.gridlines(chart, (&axis, up), plot);
        let crossing = self.place(&axis, up.values(plot), axis.crossing)?;
        let (group, data_labels) = self.group_and_axes(
            chart,
            (&axis, secondary.as_ref(), across),
            (plot, frame),
            crossing,
        )?;
        items.extend(group);
        items.extend(self.ticks_across(chart, across, plot, crossing));
        let all_data_labels = holds_all_data_labels(chart, data_labels.is_some());
        items.extend(data_labels.into_iter().flatten());
        // Only the plot area of the font's lines draws the axis labels, the title and the
        // legend.
        // quirk: ChartPlotArea::FontLines (src/quirks.rs)
        let axes_and_legend = rule == PlotRule::FontLines
            && self.chart_texts(
                chart,
                (&axis, secondary.as_ref(), across, plot, crossing),
                (legend_plot, frame),
                &mut items,
            );
        Some((
            items,
            DrawnText {
                axes_and_legend,
                data_labels: all_data_labels,
            },
        ))
    }

    /// Whether `chart`'s `nextTo` category labels would flip above the plot top because the category
    /// axis crosses at the value axis' highest value.
    fn flips_top_labels(chart: &Columns, axis: &ValueAxis) -> bool {
        chart.data_table.is_none()
            && axis.crossing == axis.high
            && !chart.axis_forms.low_labels
            && !matches!(chart.group, ChartGroup::Scatter { .. })
    }

    /// Dispatches chart groups that have their own plot layout (`Pie`, `Doughnut`, `Bars`), all
    /// of which require `PlotRule::FontLines`, returning [`SpecialLayout::Standard`] for vertical
    /// column/line/scatter charts.
    fn special_chart_group(
        &mut self,
        chart: &Columns,
        rule: PlotRule,
        frame: Edges<Length>,
    ) -> SpecialLayout {
        // quirk: ChartPlotArea::FontLines (src/quirks.rs)
        let allowed = rule == PlotRule::FontLines;
        match &chart.group {
            ChartGroup::Pie {
                first_angle,
                view,
                fills,
                labels,
                explosion,
            } => SpecialLayout::Handled(
                allowed
                    .then(|| {
                        self.pie(
                            chart,
                            (*first_angle, *view, fills, *labels),
                            explosion,
                            frame,
                        )
                    })
                    .flatten(),
            ),
            ChartGroup::Doughnut {
                first_angle,
                hole_size,
            } => SpecialLayout::Handled(
                allowed
                    .then(|| self.doughnut(chart, (*first_angle, *hole_size), frame))
                    .flatten(),
            ),
            ChartGroup::Bars { gap, overlap, .. } => SpecialLayout::Handled(
                allowed
                    .then(|| self.horizontal_bars(chart, (*gap, *overlap), frame))
                    .flatten(),
            ),
            ChartGroup::Columns { .. }
            | ChartGroup::Lines { .. }
            | ChartGroup::Scatter { .. }
            | ChartGroup::Combo { .. } => SpecialLayout::Standard,
        }
    }

    /// The items of the chart group of `chart` in its plot area `plot` and of its axes' lines,
    /// the axis across at `crossing`, in painting order, and the data labels of a column chart
    /// on a target that draws them. A column chart paints its bars, the value axis and the axis
    /// across; a chart of lines or of scatter points paints its series' lines and markers in
    /// the place of the bars, or after the axis across on a target that paints it first
    /// ([`decisions::chart_axis_before_lines`]); a combination chart paints its columns before
    /// its lines.
    fn group_and_axes(
        &mut self,
        chart: &Columns,
        (axis, secondary, across): (&ValueAxis, Option<&ValueAxis>, Across<'_>),
        (plot, frame): (Edges<Length>, Edges<Length>),
        crossing: Length,
    ) -> Option<(Vec<Item>, Option<Vec<Item>>)> {
        let axis_line = self.chart_rule(&chart.axis, (plot.left, plot.right), crossing);
        let mut items = Vec::new();
        match &chart.group {
            ChartGroup::Columns { gap, overlap, .. } => {
                let up = (axis, BarDirection::Up);
                items.extend(self.bars(chart, (*gap, *overlap), up, (plot, crossing)));
                let context = self.context;
                let data_labels = decisions::chart_data_labels(&context.quirks, || {
                    self.data_labels(chart, (*gap, *overlap), up, (plot, frame))
                });
                items.extend(self.value_axis(chart, (axis, BarDirection::Up), plot));
                items.extend(axis_line);
                Some((items, data_labels))
            }
            // Horizontal bars, pies, and doughnuts have their own layouts.
            ChartGroup::Bars { .. } | ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. } => {
                Some((Vec::new(), None))
            }
            ChartGroup::Lines { looks, .. } => {
                let lines = self.series_lines(chart, looks, (axis, across), plot)?;
                self.append_lines_and_axes(chart, axis, plot, (lines, axis_line), &mut items);
                let context = self.context;
                let data_labels = decisions::chart_data_labels(&context.quirks, || {
                    self.line_data_labels(chart, looks, axis, (plot, frame))
                });
                Some((items, data_labels))
            }
            ChartGroup::Scatter { looks, .. } => {
                let lines = self.series_lines(chart, looks, (axis, across), plot)?;
                self.append_lines_and_axes(chart, axis, plot, (lines, axis_line), &mut items);
                Some((items, None))
            }
            ChartGroup::Combo {
                gap,
                overlap,
                looks,
                ..
            } => {
                let up = (axis, BarDirection::Up);
                let line_axis = secondary.unwrap_or(axis);
                items.extend(self.bars(chart, (*gap, *overlap), up, (plot, crossing)));
                let context = self.context;
                let data_labels = decisions::chart_data_labels(&context.quirks, || {
                    let mut all = self.data_labels(chart, (*gap, *overlap), up, (plot, frame))?;
                    all.extend(self.line_data_labels(chart, looks, line_axis, (plot, frame))?);
                    Some(all)
                });
                let lines = self.series_lines(chart, looks, (line_axis, across), plot)?;
                self.append_lines_and_axes(chart, axis, plot, (lines, axis_line), &mut items);
                if let (Some(sec), Some(sec_axis)) = (chart.secondary_axis.as_deref(), secondary) {
                    items.extend(self.secondary_value_axis(chart, sec, sec_axis, plot));
                }
                Some((items, data_labels))
            }
        }
    }

    /// Appends `lines` and `axis_line` in target order, followed by the value axis.
    fn append_lines_and_axes(
        &mut self,
        chart: &Columns,
        axis: &ValueAxis,
        plot: Edges<Length>,
        (lines, axis_line): (Vec<Item>, Vec<Item>),
        items: &mut Vec<Item>,
    ) {
        // quirk: ChartAxisOrder::BeforeLines (src/quirks.rs)
        if decisions::chart_axis_before_lines(&self.context.quirks) {
            items.extend(axis_line);
            items.extend(lines);
            items.extend(self.value_axis(chart, (axis, BarDirection::Up), plot));
        } else {
            items.extend(lines);
            items.extend(self.value_axis(chart, (axis, BarDirection::Up), plot));
            items.extend(axis_line);
        }
    }

    /// What stands across the bottom of the plot area `plot` of a chart in its frame `frame`:
    /// the bands of its categories, or a scatter chart's x axis ([`Self::x_axis`]), whose last
    /// label moves the plot area's right edge. `None` when the x axis has no place.
    fn axis_across<'a>(
        &mut self,
        chart: &'a Columns,
        frame: Edges<Length>,
        plot: &mut Edges<Length>,
    ) -> Option<Across<'a>> {
        match &chart.group {
            ChartGroup::Scatter {
                x_values, x_scale, ..
            } => {
                let (x_axis, right) = self.x_axis(chart, (x_values, *x_scale), (frame, *plot))?;
                plot.right = right;
                Some(Across::Values(x_axis, x_values))
            }
            ChartGroup::Columns { .. } | ChartGroup::Lines { .. } | ChartGroup::Combo { .. } => {
                Some(Across::Bands)
            }
            // Horizontal bars, pies, and doughnuts have their own layouts.
            ChartGroup::Bars { .. } | ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. } => None,
        }
    }

    /// The plot area of Word's default chart in Calibri: it ends [`CHART_PLOT_RIGHT`] left of
    /// the frame's right edge, starts after the widest value label, below the title, and
    /// above the category labels and the legend. `None` for a deleted value axis or low
    /// category labels, which only the plot area of the font's lines places.
    fn default_plot(
        &mut self,
        chart: &Columns,
        axis: &ValueAxis,
        frame: Edges<Length>,
    ) -> Option<Edges<Length>> {
        if chart.axis_forms != AxisForms::default() {
            return None;
        }
        let title = chart.title.as_ref()?;
        let size = Length::from_half_points(chart.label_size)?;
        let value_size = Length::from_half_points(chart.value_label_size)?;
        let widest = self.widest_label(chart, axis)?;
        let left = frame.left
            + CHART_VALUE_LABEL_LEFT
            + widest
            + value_size
                .checked_mul(CHART_VALUE_LABEL_GAP)?
                .div_toward_zero(THOUSANDTHS);
        let right = frame.right - CHART_PLOT_RIGHT;
        let title_lines = self.title_line_count(title, frame)?;
        let below_title = CHART_TITLE_TOP
            + self
                .chart_line(chart, title.size)?
                .checked_mul(title_lines)?;
        let below_label = CHART_TITLE_LABEL_TOP
            + self
                .chart_line(chart, chart.value_label_size)?
                .div_toward_zero(2);
        let top = frame.top + below_title.max(below_label);
        let bottom = frame.bottom
            - (CHART_BOTTOM
                + size
                    .checked_mul(CHART_BOTTOM_PER_SIZE)?
                    .div_toward_zero(THOUSANDTHS));
        Some(Edges {
            left,
            top,
            right,
            bottom,
        })
    }

    /// The axis and the plot area of a chart whose plot area comes from its labels' lines,
    /// from `fitted`, the axis of at most [`CHART_AXIS_STEPS`] units and its plot area. On a
    /// target whose variant is `ChartAxisRoom::LabelLines`, an automatic axis takes at most as
    /// many units as [`room_units`] gives for the plot area's height and the labels' single
    /// Computes primary (and optional secondary right) value axes and the `FontLines` plot area,
    /// narrowing axis unit counts when the plot height cannot hold them (`roomed_axis`).
    fn font_line_axes_and_plot(
        &mut self,
        chart: &Columns,
        frame: Edges<Length>,
    ) -> Option<(ValueAxis, Option<ValueAxis>, Edges<Length>)> {
        let axis = ValueAxis::of(chart)?;
        let secondary = match chart.secondary_axis.as_deref() {
            Some(sec) => Some(ValueAxis::for_secondary(chart, sec, CHART_AXIS_STEPS)?),
            None => None,
        };
        let plot = self.font_line_plot_with(chart, (&axis, secondary.as_ref()), frame)?;
        self.roomed_axis(chart, (axis, secondary, plot), frame)
    }

    /// Shrinks primary and secondary axis unit counts when the plot area's height does not hold
    /// all tick labels, then recomputes the plot area for the updated label widths.
    fn roomed_axis(
        &mut self,
        chart: &Columns,
        fitted: (ValueAxis, Option<ValueAxis>, Edges<Length>),
        frame: Edges<Length>,
    ) -> Option<(ValueAxis, Option<ValueAxis>, Edges<Length>)> {
        let context = self.context;
        decisions::chart_axis_room(&context.quirks, fitted, |fitted| {
            let (mut axis, mut secondary, mut plot) = fitted;
            let height = plot.bottom - plot.top;
            let mut changed = false;
            let line = self.chart_line(chart, chart.value_label_size)?;
            let most = room_units(height, line);
            if axis.steps > most {
                axis = ValueAxis::with_most(chart, most)?;
                changed = true;
            }
            if let (Some(sec), Some(sec_axis)) =
                (chart.secondary_axis.as_deref(), secondary.as_ref())
            {
                let sec_line = self.chart_line(chart, sec.label_size)?;
                let sec_most = room_units(height, sec_line);
                if sec_axis.steps > sec_most {
                    secondary = Some(ValueAxis::for_secondary(chart, sec, sec_most)?);
                    changed = true;
                }
            }
            if changed {
                plot = self.font_line_plot_with(chart, (&axis, secondary.as_ref()), frame)?;
            }
            Some((axis, secondary, plot))
        })
    }

    /// The anchor plot box passed to `chart_legend`: `plot`, with `right` restored past any
    /// secondary right value-axis label room so a right legend stands to the right of the
    /// secondary labels at its normal non-secondary anchor.
    fn legend_plot_for(
        &mut self,
        chart: &Columns,
        secondary: Option<&ValueAxis>,
        mut plot: Edges<Length>,
    ) -> Option<Edges<Length>> {
        if let RightLabels::Shown(right_room) = self.right_labels_room(chart, secondary)? {
            plot.right = plot.right + right_room + CHART_LINES_LABEL_START - CHART_PLOT_RIGHT;
        }
        Some(plot)
    }

    /// The width of the secondary right value axis' widest label plus its gap, or
    /// [`RightLabels::Absent`] when `chart` has no shown secondary right value labels.
    fn right_labels_room(
        &mut self,
        chart: &Columns,
        secondary: Option<&ValueAxis>,
    ) -> Option<RightLabels> {
        let (Some(sec), Some(sec_axis)) = (chart.secondary_axis.as_deref(), secondary) else {
            return Some(RightLabels::Absent);
        };
        if sec.labels_hidden {
            return Some(RightLabels::Absent);
        }
        let sec_lines = self.lines_of(&chart_props(chart, sec.label_size))?;
        let widest = self.widest_formatted_label(chart, sec_axis, (&sec.format, sec.label_size))?;
        Some(RightLabels::Shown(widest + sec_lines.label_gap()?))
    }

    #[cfg(test)]
    fn font_line_plot(
        &mut self,
        chart: &Columns,
        axis: &ValueAxis,
        frame: Edges<Length>,
    ) -> Option<Edges<Length>> {
        self.font_line_plot_with(chart, (axis, None), frame)
    }

    fn font_line_plot_with(
        &mut self,
        chart: &Columns,
        (axis, secondary): (&ValueAxis, Option<&ValueAxis>),
        frame: Edges<Length>,
    ) -> Option<Edges<Length>> {
        let widest = if chart.axis_forms.value_deleted {
            None
        } else {
            Some(self.widest_label(chart, axis)?)
        };
        let right_room = match self.right_labels_room(chart, secondary)? {
            RightLabels::Absent => None,
            RightLabels::Shown(room) => Some(room),
        };
        let labels_below = !chart.axis_forms.category_hidden
            && (axis.crossing == axis.low || chart.axis_forms.low_labels);
        self.label_plot(chart, (widest, right_room), labels_below, frame)
    }

    /// The plot area of [`Self::font_line_axes_and_plot`] whose labels at the left are `widest` wide at
    /// most, or that has no labels at the left when `widest` is `None`, with a band of labels
    /// below it when `labels_below`. Each side's labels take their own lines
    /// ([`Self::plot_side_lines`]): the gap, the half line at the top and the untitled edges
    /// come from the labels at the left, the band and the part of the top at the bottom from
    /// the labels below, and the legend's line and room from the category labels', the
    /// legend's size. `None` for
    /// a plot area without labels at the left in the outer box of a manual layout, which these
    /// rules do not place.
    fn label_plot(
        &mut self,
        chart: &Columns,
        (widest, right_room): (Option<Length>, Option<Length>),
        labels_below: bool,
        frame: Edges<Length>,
    ) -> Option<Edges<Length>> {
        let lines = self.label_lines(chart)?;
        let sides = self.plot_side_lines(chart, lines)?;
        let labels = match widest {
            Some(widest) => Some(widest + sides.left.label_gap()?),
            None => None,
        };
        if let PlotPlace::Manual(layout) = chart.plot_place {
            let labels = labels.or_else(|| layout.inner.then_some(Length::ZERO))?;
            let plot = manual_plot(layout, frame, labels, sides)?;
            return self.clamp_manual_data_table(chart, layout.inner, plot, frame);
        }
        let title_room = self.title_room(chart, sides.left, frame)?;
        let (value_title, category_title) = self.axis_title_rooms(chart)?;
        let left = labels.map_or(frame.left + CHART_PLOT_RIGHT, |labels| {
            frame.left + CHART_LINES_LABEL_START + labels
        }) + value_title;
        let right = right_room.map_or(frame.right - CHART_PLOT_RIGHT, |room| {
            frame.right - CHART_LINES_LABEL_START - room
        });
        let (left, bottom_room) =
            self.plot_below_room(chart, (left, right), (lines, sides), labels_below, frame)?;
        let plot = Edges {
            left,
            top: frame.top + title_room,
            right,
            bottom: frame.bottom - bottom_room - category_title,
        };
        self.with_legend(chart, lines, plot, frame)
    }

    /// Shifts a manual `inner` plot box rightward (preserving its width) when a data table's stub
    /// would otherwise cross inside `frame.left + CHART_DATA_TABLE_MANUAL_LEFT`.
    fn clamp_manual_data_table(
        &mut self,
        chart: &Columns,
        inner: bool,
        mut plot: Edges<Length>,
        frame: Edges<Length>,
    ) -> Option<Edges<Length>> {
        if inner && let Some(table) = chart.data_table.as_deref() {
            let metrics = self.data_table_metrics(chart, table)?;
            let min_left = frame.left + CHART_DATA_TABLE_MANUAL_LEFT + metrics.stub_width;
            if plot.left < min_left {
                let shift = min_left - plot.left;
                plot.left += shift;
                plot.right += shift;
            }
        }
        Some(plot)
    }

    /// Computes `(plot_left, bottom_room)` below the plot area for a data table, category labels,
    /// or bare bottom edge.
    fn plot_below_room(
        &mut self,
        chart: &Columns,
        (left, right): (Length, Length),
        (lines, sides): (LabelLines, SideLines),
        labels_below: bool,
        frame: Edges<Length>,
    ) -> Option<(Length, Length)> {
        if let Some(table) = chart.data_table.as_deref() {
            let metrics = self.data_table_metrics(chart, table)?;
            return Some((
                left.max(frame.left + CHART_DATA_TABLE_LEFT + metrics.stub_width),
                lines.legend_room()? + metrics.total_height + CHART_DATA_TABLE_BOTTOM,
            ));
        }
        if labels_below {
            self.below_room(chart, (left, right), frame, sides.below)
        } else {
            Some((left, lines.legend_room()? + sides.left.untitled_edge()))
        }
    }

    /// The plot area's left edge and its distance from the frame's bottom with category labels
    /// below it in `frame`, from the edges `left` and `right` of [`Self::label_plot`] and the
    /// lines of the labels below (`below`): the left edge moves right to
    /// [`CHART_TURNED_LABEL_LEFT`] beyond the reach of labels turned 45 degrees
    /// ([`categories::CategoryForm::left_reach`] with the span from the frame's left edge) when
    /// that lies further right, and the distance is [`Self::below_base`] and the labels' room
    /// beyond one line ([`categories::CategoryForm::room`] of [`Self::below_form`]).
    fn below_room(
        &mut self,
        chart: &Columns,
        (left, right): (Length, Length),
        frame: Edges<Length>,
        below: LabelLines,
    ) -> Option<(Length, Length)> {
        let form = self.below_form(chart, right - left, frame);
        let room = form
            .as_ref()
            .map_or(Some(Length::ZERO), |form| form.room(below))?;
        let reach = form.and_then(|form| form.left_reach(right - frame.left));
        let left = reach.map_or(left, |reach| {
            left.max(frame.left + CHART_TURNED_LABEL_LEFT + reach)
        });
        Some((left, self.below_base(chart)? + room))
    }

    /// The distance from the plot area's bottom to the frame's bottom with one upright line of
    /// category labels and the legend below it: [`CHART_LINES_BOTTOM`], a band and a part of
    /// the top of the labels below, and a line of the legend.
    fn below_base(&mut self, chart: &Columns) -> Option<Length> {
        let lines = self.label_lines(chart)?;
        let sides = self.plot_side_lines(chart, lines)?;
        Some(CHART_LINES_BOTTOM + sides.below.band() + sides.below.top_part() + lines.line)
    }

    /// The distance of the plot area's top from the frame's top, from the lines `left` of the
    /// labels at the left: below the title's lines and [`CHART_TITLE_TOP`], or
    /// [`CHART_LINES_TITLE_LABEL_TOP`] and half a line when that is more, or without a title
    /// [`LabelLines::untitled_edge`].
    fn title_room(
        &mut self,
        chart: &Columns,
        left: LabelLines,
        frame: Edges<Length>,
    ) -> Option<Length> {
        let Some(title) = &chart.title else {
            return Some(left.untitled_edge());
        };
        let half_line = left.line.div_toward_zero(2);
        Some(
            self.chart_line(chart, title.size)?
                .checked_mul(self.title_line_count(title, frame)?)?
                + CHART_TITLE_TOP.max(CHART_LINES_TITLE_LABEL_TOP + half_line),
        )
    }

    /// The plot area of a chart whose legend stands at its place, from `plot`, the plot area
    /// with the legend at the bottom, whose room comes from the labels' lines `lines`. The
    /// legend's own lines ([`Self::legend_lines`]) give the room on its side: a legend at the
    /// bottom moves the bottom by the difference of their [`LabelLines::legend_room`], and a
    /// chart without a legend at the bottom moves the bottom down by the labels' room
    /// ([`Self::legend_bottom`]); a legend at the top moves the top down by its room, and a
    /// legend at the left or the right takes [`Self::side_legend`] from that side.
    fn with_legend(
        &mut self,
        chart: &Columns,
        lines: LabelLines,
        mut plot: Edges<Length>,
        frame: Edges<Length>,
    ) -> Option<Edges<Length>> {
        plot.bottom -= self.legend_bottom(chart, lines, frame)?;
        let legend = match chart.legend {
            Some(_) => self.legend_lines(chart)?,
            None => lines,
        };
        match chart.legend {
            Some(LegendPlace::Top) => {
                plot.top += self.horizontal_legend_room(chart, legend, frame)?;
            }
            Some(LegendPlace::Left) => plot.left += self.side_legend(chart, legend)?,
            Some(LegendPlace::Right) => plot.right -= self.side_legend(chart, legend)?,
            Some(LegendPlace::Bottom) | None => {}
        }
        Some(plot)
    }

    /// How much farther the plot area's bottom lies from the frame's bottom than the room
    /// that [`Self::label_plot`] gives it, whose legend's room is that of the labels' lines
    /// `lines`: a legend at the bottom's own room less that room, or less that room for a
    /// legend at another place or no legend.
    fn legend_bottom(
        &mut self,
        chart: &Columns,
        lines: LabelLines,
        frame: Edges<Length>,
    ) -> Option<Length> {
        let room = lines.legend_room()?;
        if chart.legend == Some(LegendPlace::Bottom) {
            let legend = self.legend_lines(chart)?;
            Some(self.horizontal_legend_room(chart, legend, frame)? - room)
        } else {
            Some(Length::ZERO - room)
        }
    }

    /// The vertical room taken from the plot area by a bottom or top legend in `frame`: one
    /// [`LabelLines::legend_room`] when all entries fit on one row (or under a manual legend box),
    /// or `legend_room + (rows - 1) * row_step - CHART_LEGEND_MULTI_ROW_TRIM` when automatic
    /// wrapping puts the entries onto `rows >= 2` rows.
    fn horizontal_legend_room(
        &mut self,
        chart: &Columns,
        lines: LabelLines,
        frame: Edges<Length>,
    ) -> Option<Length> {
        let single = lines.legend_room()?;
        if chart.legend_box != crate::chart::LegendBox::Automatic
            || chart.legend_text.own_entries
            || !matches!(chart.legend, Some(LegendPlace::Bottom | LegendPlace::Top))
        {
            return Some(single);
        }
        let Some(rows) = self.horizontal_legend_row_count(chart, lines, frame) else {
            return Some(single);
        };
        if rows <= 1 {
            return Some(single);
        }
        let step = legend::row_step(lines)?;
        let extra = step.checked_mul(i64::try_from(rows - 1).ok()?)?;
        Some(single + extra - crate::params::CHART_LEGEND_MULTI_ROW_TRIM)
    }

    /// The width that a legend at the left or the right takes from the plot area: its widest
    /// entry's name ([`legend::legend_entries`]) in the legend's face ([`legend_props`]),
    /// [`CHART_LINES_LEGEND_PAD`] and what its keys add ([`legend::Keys::side_room`]:
    /// [`crate::params::CHART_LINES_SIDE_LEGEND`] of the legend's line `lines`, or a line
    /// key's area).
    fn side_legend(&mut self, chart: &Columns, lines: LabelLines) -> Option<Length> {
        let names: Vec<&str> = legend::legend_entries(chart)
            .into_iter()
            .map(|(name, _)| name)
            .collect::<Option<_>>()?;
        let props = legend_props(chart);
        let widest = names
            .into_iter()
            .map(|name| self.text_width(&props, name))
            .max()?;
        Some(widest + CHART_LINES_LEGEND_PAD + legend::Keys::of(chart).side_room(lines)?)
    }

    /// The width of the left tick labels and their gap, or zero when the left axis draws no
    /// labels.
    pub(super) fn left_labels_room(&mut self, chart: &Columns, axis: &ValueAxis) -> Option<Length> {
        let lines = self.label_lines(chart)?;
        let sides = self.plot_side_lines(chart, lines)?;
        let widest = match chart.group {
            ChartGroup::Bars { .. } if chart.axis_forms.category_hidden => None,
            ChartGroup::Bars { .. } => self.widest_category(chart),
            _ if chart.axis_forms.value_deleted => None,
            _ => self.widest_label(chart, axis),
        };
        match widest {
            Some(widest) => Some(widest + sides.left.label_gap()?),
            None => Some(Length::ZERO),
        }
    }

    /// The vertical room below `plot.bottom` occupied by the bottom tick labels without any
    /// bottom legend.
    pub(super) fn below_labels_room(
        &mut self,
        chart: &Columns,
        axis: &ValueAxis,
        plot: Edges<Length>,
        frame: Edges<Length>,
    ) -> Option<Length> {
        if let Some(table) = chart.data_table.as_deref() {
            let metrics = self.data_table_metrics(chart, table)?;
            return Some(metrics.total_height + CHART_DATA_TABLE_BOTTOM);
        }
        let lines = self.label_lines(chart)?;
        let sides = self.plot_side_lines(chart, lines)?;
        let labels_below = match chart.group {
            ChartGroup::Bars { .. } => !chart.axis_forms.value_deleted,
            _ => {
                !chart.axis_forms.category_hidden
                    && (axis.crossing == axis.low || chart.axis_forms.low_labels)
            }
        };
        if labels_below {
            let (_, room) = self.below_room(chart, (plot.left, plot.right), frame, sides.below)?;
            Some(room - lines.legend_room()?)
        } else {
            Some(sides.left.untitled_edge())
        }
    }

    /// The width of the widest value label in the chart's label format, or `None` when the
    /// target does not write a label in it.
    fn widest_label(&mut self, chart: &Columns, axis: &ValueAxis) -> Option<Length> {
        let format = chart.value_format.as_ref()?;
        self.widest_formatted_label(chart, axis, (format, chart.value_label_size))
    }

    /// The width of the widest label of `axis` in `format` at `size` half-points.
    fn widest_formatted_label(
        &mut self,
        chart: &Columns,
        axis: &ValueAxis,
        (format, size): (&LabelFormat, i64),
    ) -> Option<Length> {
        let props = chart_props(chart, size);
        let widths = axis
            .labels()
            .map(|value| Some(self.written_width(&props, &format.write(value)?)))
            .collect::<Option<Vec<_>>>()?;
        widths.into_iter().max()
    }

    /// The room of the written label `written` in the look `props`: its text pieces together
    /// as [`Self::text_width`] measures them, and each blank as wide as a space.
    fn written_width(&mut self, props: &RunProps, written: &WrittenLabel) -> Length {
        let mut text = String::new();
        let mut blanks = Length::ZERO;
        for piece in &written.pieces {
            match piece {
                LabelPiece::Text(own) => text.push_str(own),
                LabelPiece::Blank(_) => blanks += self.text_width(props, " "),
            }
        }
        self.text_width(props, &text) + blanks
    }

    /// Where `value` lies on the value axis `axis` drawn from `from` to `to`
    /// ([`ValueAxis::along`]), as the axis' gridlines and its crossing and a scatter chart's
    /// points lie: at the axis' end for its lowest and highest values, and centered on the
    /// layout device between them.
    fn place(
        &self,
        axis: &ValueAxis,
        (from, to): (Length, Length),
        value: Decimal,
    ) -> Option<Length> {
        let exact = axis.along((from, to), value)?;
        Some(if value == axis.low || value == axis.high {
            exact
        } else {
            self.device.snap(exact)
        })
    }

    /// Where `value` lies along `(from, to)` on `axis` on the layout device, without clamping to
    /// `[axis.low, axis.high]`.
    fn place_unclamped(
        &self,
        axis: &ValueAxis,
        (from, to): (Length, Length),
        value: Decimal,
    ) -> Option<Length> {
        let exact = axis.along_unclamped((from, to), value)?;
        Some(if value == axis.low || value == axis.high {
            exact
        } else {
            self.device.snap(exact)
        })
    }

    /// The bars of the chart in its plot area `plot`, which run in the direction `direction`
    /// ([`BarDirection`]) and lie along its run as [`Clusters`] places them. A clustered bar runs
    /// from the category axis at `crossing` to its value; a stacked or 100%-stacked bar runs
    /// between its cumulative endpoints ([`bars::stacked_segments`]). A bar in a color has its
    /// value endpoints and its edges along the run on the layout device; a bar of a gradient has
    /// them at their exact places, with the gradient over its own box.
    fn bars(
        &self,
        chart: &Columns,
        (gap, overlap): (i64, i64),
        (axis, direction): (&ValueAxis, BarDirection),
        (plot, crossing): (Edges<Length>, Length),
    ) -> Vec<Item> {
        let theme = &self.shaper.theme().shapes;
        let (Some(clusters), Some(spans)) = (
            Clusters::of(chart, (gap, overlap), direction.run(plot)),
            bars::BarSpans::of(chart),
        ) else {
            return Vec::new();
        };
        let mut items = Vec::new();
        for (index, one) in (0_i64..).zip(chart.bar_series()) {
            for (category, value) in (0_i64..).zip(&one.values) {
                let (Some(value), Some(paint)) = (*value, bar_paint(&one.fill, category, theme))
                else {
                    continue;
                };
                if let Some(item) = self.bar_item(
                    (&clusters, &spans),
                    (axis, direction, plot, crossing),
                    (index, category, value),
                    (paint, theme),
                ) {
                    items.push(item);
                }
            }
        }
        items
    }

    /// One bar item of series `index` at `category`, or `None` when empty or out of bounds.
    fn bar_item(
        &self,
        (clusters, spans): (&Clusters, &bars::BarSpans),
        (axis, direction, plot, crossing): (&ValueAxis, BarDirection, Edges<Length>, Length),
        (index, category, value): (i64, i64, Decimal),
        (paint, theme): (BarPaint<'_>, &ShapeTheme),
    ) -> Option<Item> {
        let start = clusters.start((category, index))?;
        let (from_val, to_val) = spans.endpoints((index, category), (axis.crossing, value))?;
        let span = direction.values(plot);
        let snap = |at: Length| match paint {
            BarPaint::Color(_) => self.device.snap(at),
            BarPaint::Gradient(_) => at,
        };
        let from_px = if from_val == axis.crossing {
            crossing
        } else {
            snap(axis.along(span, from_val)?)
        };
        let to_px = snap(axis.along(span, to_val)?);
        let (first, last) = direction.part(plot, start, clusters.thickness);
        let (run, values) = (
            (snap(first), snap(last)),
            (from_px.min(to_px), from_px.max(to_px)),
        );
        (run.1 > run.0 && values.1 > values.0)
            .then(|| bar_paint_item(direction, run, values, (paint, theme)))
            .flatten()
    }

    /// The line of each series in the plot area, in the width of its look with round caps and
    /// round joins, through its points at their values' heights and across at
    /// [`Self::point_across`], each placed on the layout device as [`Self::place`] places the
    /// gridlines, in straight pieces or in a smooth line's curves ([`smooth::curves`]) as its
    /// look's form says, and after it the series' markers on the device's dots around its points'
    /// exact places ([`marker_items`]). A series without a line draws its markers alone. A
    /// scatter chart's lines, and not its markers, show only inside [`Self::lines_clip`], and a
    /// line chart's too on a target that clips them ([`decisions::chart_line_clip`]). A line of
    /// a preset dash is its dashes ([`dash_lengths`]); `None` when one would take more than
    /// [`MAX_CHART_LINE_DASHES`].
    fn series_lines(
        &self,
        chart: &Columns,
        looks: &[LineLook],
        (axis, across): (&ValueAxis, Across<'_>),
        plot: Edges<Length>,
    ) -> Option<Vec<Item>> {
        let theme = &self.shaper.theme().shapes;
        let clip = match across {
            Across::Bands => {
                decisions::chart_line_clip(&self.context.quirks).then(|| self.lines_clip(plot))
            }
            Across::Values(..) => Some(self.lines_clip(plot)),
        };
        let stacked = bars::stacked_line_values(chart)?;
        let offset = chart.bar_series().len();
        let mut items = Vec::new();
        for (index, (one, look)) in chart.line_series().iter().zip(looks).enumerate() {
            // A line takes no gradient ([`SeriesFill`]).
            let Some(fill) = one.fill.color() else {
                continue;
            };
            let Some((rgb, alpha)) = fill.resolve(&theme.colors) else {
                continue;
            };
            let width = look
                .width
                .map(|width| line_width(width, theme, CHART_STYLE_LINE_STYLES));
            if width == Some(None) {
                continue;
            }
            let values = stacked
                .get(index)
                .map_or(one.values.as_slice(), Vec::as_slice);
            let Some(points) = self.series_points(
                chart,
                (axis, across),
                plot,
                (offset + index, values, clip.is_some()),
            ) else {
                continue;
            };
            let color = on_white(rgb, alpha);
            items.extend(line_runs_items(
                look,
                &points,
                width.flatten(),
                (color, clip.as_ref()),
            )?);
            if let Some(marker) = &look.marker {
                for (_, place) in points.into_iter().flatten() {
                    if clip.is_some()
                        && (place.x < plot.left
                            || place.x > plot.right
                            || place.y < plot.top
                            || place.y > plot.bottom)
                    {
                        continue;
                    }
                    items.extend(marker_items(
                        marker,
                        place,
                        (fill, color),
                        theme,
                        &self.device,
                    ));
                }
            }
        }
        Some(items)
    }

    /// Each point of the series `index` as drawn on its line, and its exact place, in the plot
    /// area `plot`, `None` at a blank point; outer `None` when a non-blank point has no place.
    fn series_points(
        &self,
        chart: &Columns,
        (axis, across): (&ValueAxis, Across<'_>),
        plot: Edges<Length>,
        (index, values, unclamped): (usize, &[Option<Decimal>], bool),
    ) -> Option<Vec<Option<(Point, Point)>>> {
        (0_i64..)
            .zip(values)
            .map(|(point, value)| {
                let Some(value) = *value else {
                    return Some(None);
                };
                let (x, exact_x) = self.point_across(chart, across, plot, (index, point))?;
                let (y, exact_y) = if unclamped {
                    (
                        self.place_unclamped(axis, (plot.bottom, plot.top), value)?,
                        axis.along_unclamped((plot.bottom, plot.top), value)?,
                    )
                } else {
                    (
                        self.place(axis, (plot.bottom, plot.top), value)?,
                        axis.along((plot.bottom, plot.top), value)?,
                    )
                };
                Some(Some((
                    Point { x, y },
                    Point {
                        x: exact_x,
                        y: exact_y,
                    },
                )))
            })
            .collect()
    }

    /// Where the point `point` of the series `index` lies across the plot area `plot`, as drawn
    /// on the layout device and exactly: in the middle of its category's band, the drawn place
    /// on the device; or at its x value's place on a scatter chart's x axis
    /// ([`Self::place`]). `None` for a chart without categories or a point without an x
    /// value.
    fn point_across(
        &self,
        chart: &Columns,
        across: Across<'_>,
        plot: Edges<Length>,
        (index, point): (usize, i64),
    ) -> Option<(Length, Length)> {
        match across {
            Across::Bands => {
                let bands = i64::try_from(chart.categories)
                    .ok()?
                    .checked_mul(2)
                    .filter(|&bands| bands > 0)?;
                let middle = (plot.right - plot.left)
                    .checked_mul(point.checked_mul(2)?.checked_add(1)?)?
                    .div_toward_zero(bands);
                Some((self.device.snap(plot.left + middle), plot.left + middle))
            }
            Across::Values(x_axis, x_values) => {
                let x = *x_values.get(index)?.get(usize::try_from(point).ok()?)?;
                let span = (plot.left, plot.right);
                Some((
                    self.place_unclamped(&x_axis, span, x)?,
                    x_axis.along_unclamped(span, x)?,
                ))
            }
        }
    }

    /// The value axis' major gridlines in the plot area `plot` across its run, one at each
    /// label but the crossing, before the bars, placed as [`Self::place`] places them on the
    /// value axis that runs in the direction `direction`.
    fn gridlines(
        &self,
        chart: &Columns,
        (axis, direction): (&ValueAxis, BarDirection),
        plot: Edges<Length>,
    ) -> Vec<Item> {
        let Some(look) = &chart.gridlines else {
            return Vec::new();
        };
        let axis_drawn = chart.axis.line(&self.shaper.theme().shapes).is_some();
        axis.labels()
            .filter(|&value| !axis_drawn || value != axis.crossing)
            .filter_map(|value| self.place(axis, direction.values(plot), value))
            .flat_map(|at| self.value_line(look, direction, direction.run_ends(plot), at))
            .collect()
    }

    /// The value axis' line along the plot area's edge at the start of its run, the left edge
    /// for bars that run up and the bottom for bars that run right ([`BarDirection`]), then its
    /// tick marks outside the plot area when it draws them ([`Columns::ticks`]): one at each
    /// label, the crossing too, placed as [`Self::place`] places them,
    /// [`LabelLines::top_part`] of the labels long, in the axis line's look.
    fn value_axis(
        &mut self,
        chart: &Columns,
        (axis, direction): (&ValueAxis, BarDirection),
        plot: Edges<Length>,
    ) -> Vec<Item> {
        let mut items = self.run_line(
            &chart.value_axis,
            direction,
            direction.value_ends(plot),
            direction.at(plot, Length::ZERO),
        );
        if !chart.ticks.value {
            return items;
        }
        let Some(length) = self.value_lines(chart).map(LabelLines::top_part) else {
            return items;
        };
        for value in axis.labels() {
            if let Some(at) = self.place(axis, direction.values(plot), value) {
                let outside = direction.before_run(plot, length);
                items.extend(self.value_line(&chart.value_axis, direction, outside, at));
            }
        }
        items
    }

    /// The axis line and outside tick marks of a combination chart's secondary right value axis
    /// along `plot.right`.
    fn secondary_value_axis(
        &mut self,
        chart: &Columns,
        sec: &SecondaryValueAxis,
        axis: &ValueAxis,
        plot: Edges<Length>,
    ) -> Vec<Item> {
        let mut items = self.chart_upright(&sec.line, (plot.top, plot.bottom), plot.right);
        if !sec.ticks {
            return items;
        }
        let Some(length) = self
            .lines_of(&chart_props(chart, sec.label_size))
            .map(LabelLines::top_part)
        else {
            return items;
        };
        for value in axis.labels() {
            if let Some(y) = self.place(axis, (plot.bottom, plot.top), value) {
                items.extend(self.chart_rule(&sec.line, (plot.right, plot.right + length), y));
            }
        }
        items
    }

    /// The tick marks of the axis across below the axis at `crossing`: the category axis' at
    /// the edges of the bands ([`Self::category_ticks`]), or a scatter chart's x axis' at its
    /// labels ([`Self::x_ticks`]).
    fn ticks_across(
        &mut self,
        chart: &Columns,
        across: Across<'_>,
        plot: Edges<Length>,
        crossing: Length,
    ) -> Vec<Item> {
        match across {
            Across::Bands => self.category_ticks(chart, (plot, BarDirection::Up), crossing),
            Across::Values(x_axis, _) => self.x_ticks(chart, &x_axis, plot, crossing),
        }
    }

    /// The category axis' tick marks outside the plot area, from its line at `crossing` toward
    /// the value axis' lowest value, when it draws them ([`Columns::ticks`]): one at each edge
    /// of a category's band along the run of the plot area `plot` in the direction
    /// `direction`, [`LabelLines::top_part`] of the labels long, in the axis line's look.
    fn category_ticks(
        &mut self,
        chart: &Columns,
        (plot, direction): (Edges<Length>, BarDirection),
        crossing: Length,
    ) -> Vec<Item> {
        if !chart.ticks.category || chart.data_table.is_some() {
            return Vec::new();
        }
        let Some(length) = self.label_lines(chart).map(LabelLines::top_part) else {
            return Vec::new();
        };
        let Ok(count) = i64::try_from(chart.categories) else {
            return Vec::new();
        };
        if count == 0 {
            return Vec::new();
        }
        let run = direction.run(plot);
        let ticks = direction.below(crossing, length);
        (0..=count)
            .filter_map(|edge| {
                Some(direction.at(plot, run.checked_mul(edge)?.div_toward_zero(count)))
            })
            .flat_map(|at| self.run_line(&chart.axis, direction, ticks, at))
            .collect()
    }

    /// A line of a chart in `look` at the value axis' place `at`, from `from` to `to` along the
    /// run ([`BarDirection`]): across a plot area whose bars run up, up one whose bars run
    /// right.
    fn value_line(
        &self,
        look: &f_office_drawingml::shape::ShapeLook,
        direction: BarDirection,
        (from, to): (Length, Length),
        at: Length,
    ) -> Vec<Item> {
        match direction {
            BarDirection::Up => self.chart_rule(look, (from, to), at),
            BarDirection::Right => self.chart_upright(look, (from, to), at),
        }
    }

    /// A line of a chart in `look` at the run's place `at`, from `from` to `to` along the value
    /// axis ([`BarDirection`]): up a plot area whose bars run up, across one whose bars run
    /// right.
    fn run_line(
        &self,
        look: &f_office_drawingml::shape::ShapeLook,
        direction: BarDirection,
        (from, to): (Length, Length),
        at: Length,
    ) -> Vec<Item> {
        match direction {
            BarDirection::Up => self.chart_upright(look, (from, to), at),
            BarDirection::Right => self.chart_rule(look, (from, to), at),
        }
    }

    /// A line of a chart from `top` to `bottom` down, centered on `x`, in the color and the
    /// width of `look`'s line, or nothing for a look without a line.
    fn chart_upright(
        &self,
        look: &f_office_drawingml::shape::ShapeLook,
        (top, bottom): (Length, Length),
        x: Length,
    ) -> Vec<Item> {
        let theme = &self.shaper.theme().shapes;
        let Some((rgb, alpha, width)) = look.line(theme) else {
            return Vec::new();
        };
        vec![Item::Rect(Rect {
            x: x - width.div_toward_zero(2),
            y: top,
            width,
            height: bottom - top,
            color: on_white(rgb, alpha),
        })]
    }

    /// A line of a chart from `left` to `right` across, centered on `y`, in the color and the
    /// width of `look`'s line, or nothing for a look without a line.
    fn chart_rule(
        &self,
        look: &f_office_drawingml::shape::ShapeLook,
        (left, right): (Length, Length),
        y: Length,
    ) -> Vec<Item> {
        let theme = &self.shaper.theme().shapes;
        let Some((rgb, alpha, width)) = look.line(theme) else {
            return Vec::new();
        };
        vec![Item::Rect(Rect {
            x: left,
            y: y - width.div_toward_zero(2),
            width: right - left,
            height: width,
            color: on_white(rgb, alpha),
        })]
    }

    /// The width of a chart's text in the run properties `props`, the sum of its advances.
    fn text_width(&mut self, props: &RunProps, text: &str) -> Length {
        let mut glyphs = Vec::new();
        self.shaper.measure(props, text, &mut glyphs);
        glyphs.iter().map(|g| g.advance).sum()
    }

    /// The single line height of the chart's font at `size` half-points.
    fn chart_line(&mut self, chart: &Columns, size: i64) -> Option<Length> {
        self.line_of(&chart_props(chart, size))
    }

    /// The line height of the face that `props` choose.
    fn line_of(&mut self, props: &RunProps) -> Option<Length> {
        let face = self.shaper.face(props, true)?;
        Some(self.shaper.faces().get(face)?.line_height())
    }

    /// The win line and the top of the chart's font at the label size, the category labels'.
    fn label_lines(&mut self, chart: &Columns) -> Option<LabelLines> {
        self.lines_of(&chart_props(chart, chart.label_size))
    }

    /// The win line and the top of the chart's font at the value labels' size.
    fn value_lines(&mut self, chart: &Columns) -> Option<LabelLines> {
        self.lines_of(&chart_props(chart, chart.value_label_size))
    }

    /// The lines of the labels at the left of the plot area and below it, from the category
    /// labels' lines `category`: the value labels stand at the left and the category labels
    /// below, but for horizontal bars, whose category labels stand at the left.
    fn plot_side_lines(&mut self, chart: &Columns, category: LabelLines) -> Option<SideLines> {
        let value = self.value_lines(chart)?;
        Some(match chart.group {
            ChartGroup::Bars { .. } => SideLines {
                left: category,
                below: value,
            },
            _ => SideLines {
                left: value,
                below: category,
            },
        })
    }

    /// The win line and the top of the legend's face at the legend's size: the chart's font,
    /// bold or italic as the legend's names are ([`legend_props`]).
    fn legend_lines(&mut self, chart: &Columns) -> Option<LabelLines> {
        self.lines_of(&legend_props(chart))
    }

    /// The win line and the top of the face that `props` choose.
    fn lines_of(&mut self, props: &RunProps) -> Option<LabelLines> {
        let face = self.shaper.face(props, true)?;
        let face = self.shaper.faces().get(face)?;
        Some(LabelLines {
            size: face.size,
            line: face.win_line(),
            top: face.win_top(),
            single_top: face.ascent(),
            single_line: face.line_height(),
        })
    }
}

/// The plot area of a manual layout in the edge mode: its box as parts of the frame's width
/// and height from its top left corner (ECMA-376 Part 1, 21.2.2.95), which is the plot area
/// itself when the layout is `inner`. When it is `outer`, the box holds the plot area
/// and its labels: [`CHART_LINES_OUTER_GAP`] and the value labels' region
/// (`labels`) at its left, half a line for the highest value label at its top, and
/// [`CHART_LINES_OUTER_GAP`], a band of category labels and a part of the top at its bottom.
fn manual_plot(
    layout: PlotLayout,
    frame: Edges<Length>,
    labels: Length,
    sides: SideLines,
) -> Option<Edges<Length>> {
    let layout_box = layout_edges(frame, layout.edges)?;
    if layout.inner {
        return Some(layout_box);
    }
    let below = sides.below;
    Some(Edges {
        left: layout_box.left + CHART_LINES_OUTER_GAP + labels,
        top: layout_box.top + sides.left.line.div_toward_zero(2),
        right: layout_box.right,
        bottom: layout_box.bottom - (CHART_LINES_OUTER_GAP + below.band() + below.top_part()),
    })
}

/// One, the whole of a frame's width or height in a manual layout.
pub(super) const ONE: Decimal = Decimal {
    digits: 1,
    exponent: 0,
};

/// The box of a manual layout in the edge mode in the frame `frame`: its left edge, top edge,
/// width and height are `x`, `y`, `w` and `h` parts of the frame's width and height from its
/// top left corner (ECMA-376 Part 1, 21.2.2.95).
fn layout_edges(frame: Edges<Length>, layout: LayoutBox) -> Option<Edges<Length>> {
    let LayoutBox { x, y, w, h } = layout;
    let (left, top) = layout_corner(frame, LayoutCorner { x, y })?;
    Some(Edges {
        left,
        top,
        right: left + share(frame.right - frame.left, w, ONE)?,
        bottom: top + share(frame.bottom - frame.top, h, ONE)?,
    })
}

/// The corner of a manual layout in the edge mode in the frame `frame`: its left and its top
/// are `x` and `y` parts of the frame's width and height from its top left corner.
fn layout_corner(frame: Edges<Length>, corner: LayoutCorner) -> Option<(Length, Length)> {
    Some((
        frame.left + share(frame.right - frame.left, corner.x, ONE)?,
        frame.top + share(frame.bottom - frame.top, corner.y, ONE)?,
    ))
}

/// The run properties of the legend's names: the chart's text at the legend's size, bold or
/// italic as the legend's text properties say ([`crate::chart::LegendText`]).
fn legend_props(chart: &Columns) -> RunProps {
    RunProps {
        font_ascii: Some(chart.legend_font.clone()),
        font_hansi: Some(chart.legend_font.clone()),
        bold: chart.legend_text.bold.then_some(true),
        italic: chart.legend_text.italic.then_some(true),
        ..chart_props(chart, chart.legend_size)
    }
}

/// The run properties of the chart's text at `size` half-points.
fn chart_props(chart: &Columns, size: i64) -> RunProps {
    RunProps {
        font_ascii: Some(chart.font.clone()),
        font_hansi: Some(chart.font.clone()),
        size: Some(size),
        ..RunProps::default()
    }
}

mod bars;
mod categories;
mod data_table;
mod labels;
mod legend;
mod pie;
mod scatter;
mod smooth;
#[cfg(test)]
mod tests;
mod title;