f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
//! Charts (`c:chart`). Word saves a chart in a chart part (`c:chartSpace`), with the values of
//! its series in caches (`c:numCache`). F-Office reads each chart part whose plot area holds
//! only bar, line, scatter and pie groups into its chart model ([`ChartModel`]), draws the
//! charts of the model's drawn cases ([`Part::of`]), and keeps every other chart as its empty
//! frame.

use f_office_drawingml::color::{DrawColor, SchemeSlot};
use f_office_drawingml::gradient::LinearGradient;
use f_office_drawingml::shape::{Geometry, ShapeLook};
use f_office_units::scale::{HALF_POINTS_PER_POINT, PERCENT, QUARTER_TURN, TENTHS, THOUSANDTHS};
use f_office_units::{Edges, Length};
use f_office_warnings::{Warned, Warnings};
use f_office_xml::enumeration::{Values, own};
use f_office_xml::{Document, NodeId};

use crate::body::{Block, DrawingMut, visit_drawings};
use crate::floating::{Floating, body_insets};
use crate::ns::{A, C, R};
use crate::params::{
    CHART_DATA_LABEL_INSETS, CHART_EXPONENT_LIMIT, CHART_GAP_WIDTH, CHART_OVERLAP,
    CHART_STYLE_C14_OFFSET, CHART_STYLE_COLUMNS, CHART_STYLE_DARK_TINTS, CHART_STYLE_FLAT_ROWS,
    CHART_STYLE_LINE_TINT, CHART_STYLE_MAX, CHART_STYLE_SHADE_FLOOR, CHART_STYLED_TITLE_SIZE,
    CHART_TEXT_SIZE, MAX_CHART_POINTS,
};
use crate::props::FontRef;
use crate::reader::settings::PlotRules;
use crate::reader::{PartReader, picture_fill_warning};
use crate::warnings::{ChartReason, DrawingMlFeature, DrawingMlWarning};

/// The chart of a drawing: the relationship ID of its part (`r:id` of `c:chart`) and, once the
/// part is read, the chart when F-Office draws its kind.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Chart {
    /// The relationship ID of the chart part.
    pub id: String,
    /// The clustered column chart of the part.
    pub columns: Option<Box<Columns>>,
}

/// A clustered column chart (`c:barChart` with `c:barDir val="col"`) with both axes shown, or
/// with the forms of the axes that the target draws ([`AxisForms`]): the drawn case of the
/// chart model, which each target's quirk `ChartPlotArea` draws in its own
/// part (`chart::Part::of`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Columns {
    /// The series in their order, each with its fill and its values.
    pub series: Vec<Series>,
    /// The number of categories.
    pub categories: usize,
    /// What the plot area draws of the series: clustered columns or lines.
    pub group: ChartGroup,
    /// The title, or `None` for a chart whose automatic title is deleted
    /// (`c:autoTitleDeleted`) and that has no title of its own.
    pub title: Option<Title>,
    /// Where the legend stands, or `None` for a chart without a legend.
    pub legend: Option<LegendPlace>,
    /// The box that the legend's entries stand in.
    pub legend_box: LegendBox,
    /// The size of the category axis' labels, in half-points: the size that their own text
    /// sets, else the chart text's ([`ChartText`]).
    pub label_size: i64,
    /// The size of the legend's entries, in half-points: the size that the legend's own text
    /// sets, else the chart text's.
    pub legend_size: i64,
    /// The size of the value axis' labels, in half-points: the size that their own text sets,
    /// else the chart text's; [`Self::label_size`] when the value axis is deleted.
    pub value_label_size: i64,
    /// The font of the labels (`a:latin` of their `a:defRPr`), the theme's body font when
    /// they name none.
    pub font: FontRef,
    /// The line of the value axis' major gridlines (`c:majorGridlines/c:spPr`), or `None`
    /// without them.
    pub gridlines: Option<ShapeLook>,
    /// The line of the category axis (`c:spPr` of `c:catAx`).
    pub axis: ShapeLook,
    /// The line of the value axis (`c:spPr` of `c:valAx`), which only a target that draws the
    /// style look draws (`PlotRules::draws_style_look`); without a line on the others.
    pub value_axis: ShapeLook,
    /// The axes that draw their major tick marks outside the plot area, on a target that
    /// draws the style look.
    pub ticks: OutsideTicks,
    /// Where the plot area stands: the automatic place or a manual layout.
    pub plot_place: PlotPlace,
    /// What the value axis sets of its scale.
    pub scale: SetScale,
    /// Where the category axis crosses the value axis (`None` when the target does not draw the
    /// chart's axis crossings, giving `ChartReason::SetCrossing` on `FontLines`).
    pub category_crossing: Option<CategoryCrossing>,
    /// The titles of the axes (`c:title` of `c:catAx` or `c:valAx`).
    pub axis_titles: AxisTitles,
    /// The label format of the value axis' labels: the axis' own, else that of the series'
    /// caches when every series' gives the same, or `None` for a format that the target does
    /// not write.
    pub value_format: Option<LabelFormat>,
    /// The text of each category's label, from the first series' categories as
    /// [`category_texts`] reads them, or `None` when they give no text for each category.
    pub category_names: Option<Vec<String>>,
    /// The fill of the value axis' labels (`a:solidFill` of their `a:defRPr`), or `None` for
    /// the automatic color.
    pub value_label_fill: Option<DrawColor>,
    /// The fill of the category axis' labels, as for [`Columns::value_label_fill`].
    pub category_label_fill: Option<DrawColor>,
    /// The font of the legend's names (`a:latin` of the legend's `a:defRPr`), the theme's
    /// body font when it names none.
    pub legend_font: FontRef,
    /// The fill of the legend's names, as for [`Columns::value_label_fill`].
    pub legend_fill: Option<DrawColor>,
    /// What else the legend's text sets.
    pub legend_text: LegendText,
    /// Whether a series shows data labels in a form that F-Office does not draw
    /// ([`SeriesLabels::Other`]), or data labels of a line chart.
    pub other_labels: bool,
    /// Whether the value axis is deleted and where the category labels stand.
    pub axis_forms: AxisForms,
    /// Secondary right value axis of a combination chart (`valAx` at `axPos="r"`), when its line
    /// group plots on an independent right scale.
    pub secondary_axis: Option<Box<SecondaryValueAxis>>,
    /// Data table (`c:dTable`) drawn beneath the plot area on a target that draws the style look.
    pub data_table: Option<Box<DataTable>>,
}

/// Which border grid lines a chart data table (`c:dTable`) draws.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DataTableBorders {
    /// Whether interior horizontal gridlines between series rows are drawn (`c:showHorzBorder`).
    pub horz: bool,
    /// Whether interior vertical gridlines between category columns are drawn (`c:showVertBorder`).
    pub vert: bool,
    /// Whether the outer frame and header/stub dividers are drawn (`c:showOutline`).
    pub outline: bool,
}

/// A chart's data table (`c:dTable`, ECMA-376 Part 1, 21.2.2.54) drawn directly beneath the plot
/// area of a column, line, or combination chart on a target that draws the style look.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTable {
    /// Which border grid lines (`c:showHorzBorder`, `c:showVertBorder`, `c:showOutline`) are drawn.
    pub borders: DataTableBorders,
    /// Whether each series row shows its legend key swatch before the series name (`c:showKeys`).
    pub keys: bool,
    /// Border line look (`c:spPr`, defaulting to the chart style's line look).
    pub border: ShapeLook,
    /// Text size in half-points (`c:txPr`, defaulting to the chart text size).
    pub text_size: i64,
    /// Text font (`c:txPr`, defaulting to the chart text font).
    pub text_font: FontRef,
    /// Text fill color (`c:txPr`), or `None` for automatic black.
    pub text_fill: Option<DrawColor>,
    /// Whether table text is bold (`b` of `c:txPr`'s `a:defRPr`).
    pub bold: bool,
    /// Whether table text is italic (`i` of `c:txPr`'s `a:defRPr`).
    pub italic: bool,
}

/// Secondary right value axis of a combination chart (`c:valAx` at `axPos="r"`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SecondaryValueAxis {
    /// Explicit scale (`c:min`, `c:max`, `c:majorUnit`).
    pub scale: SetScale,
    /// Label format of the secondary right value axis.
    pub format: LabelFormat,
    /// Label size in half-points.
    pub label_size: i64,
    /// Label fill color, or `None` for automatic black.
    pub label_fill: Option<DrawColor>,
    /// Axis line look (`c:spPr`).
    pub line: ShapeLook,
    /// Whether outside major tick marks are drawn on the secondary right value axis.
    pub ticks: bool,
    /// Whether secondary axis labels are hidden (`c:delete val="1"` or `c:tickLblPos val="none"`).
    pub labels_hidden: bool,
}

/// The forms of a drawn chart's axes besides both axes shown with their labels next to them,
/// each on a target that draws it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AxisForms {
    /// Whether the value axis draws no labels (`c:delete val="1"` or `c:tickLblPos val="none"`
    /// on `c:valAx`), on a target that draws it (`PlotRules::draws_deleted_axis`): the plot area
    /// takes the room of its labels. When `c:delete val="1"` is set, its line and tick marks are
    /// omitted too.
    pub value_deleted: bool,
    /// Whether the category (or scatter x) axis draws no labels (`c:delete val="1"` or
    /// `c:tickLblPos val="none"`), on a target that draws it (`PlotRules::draws_deleted_axis`):
    /// the plot area takes the room of its labels. When `c:delete val="1"` is set, its line and
    /// tick marks are omitted too.
    pub category_hidden: bool,
    /// Whether the category labels stand at the value axis' lowest value
    /// (`c:tickLblPos val="low"` of `c:catAx`), on a target that draws them
    /// (`PlotRules::draws_low_labels`): below/left of the plot area wherever the category axis
    /// crosses.
    pub low_labels: bool,
}

/// Where the category axis crosses the value axis on a target that draws explicit crossings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CategoryCrossing {
    /// At zero, clamped to `[low, high]` (`c:crosses val="autoZero"`).
    AutoZero,
    /// At the value axis' lowest value (`c:crosses val="min"`).
    Min,
    /// At an explicit value (`c:crossesAt`), clamped to `[low, high]`.
    At(Decimal),
}

/// The titles of a drawn chart's axes (`c:title` of `c:catAx` or `c:valAx`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AxisTitles {
    /// The titles that the target draws ([`PlotRules::draws_axis_titles`]), each `None` for an
    /// axis without a title: the value axis' title reads upward at the plot area's left, and
    /// the category axis' title stands upright below it.
    Drawn {
        /// The value axis' title.
        value: Option<Box<AxisTitle>>,
        /// The category axis' title.
        category: Option<Box<AxisTitle>>,
    },
    /// An axis shows a title that F-Office does not draw on this target.
    Other,
}

impl AxisTitles {
    /// No axis shows a title.
    pub const NONE: Self = Self::Drawn {
        value: None,
        category: None,
    };

    /// The `(left, bottom)` axis titles for `group`, or `None` when the target leaves out the
    /// chart's axis titles. On horizontal bars, the category axis stands at the left and the
    /// value axis across the bottom; on every other group, the value axis stands at the left and
    /// the category (or x) axis across the bottom.
    pub fn sides(&self, group: &ChartGroup) -> Option<(Option<&AxisTitle>, Option<&AxisTitle>)> {
        let Self::Drawn { value, category } = self else {
            return None;
        };
        if matches!(group, ChartGroup::Bars { .. }) {
            Some((category.as_deref(), value.as_deref()))
        } else {
            Some((value.as_deref(), category.as_deref()))
        }
    }
}

/// An axis title that the target draws: one line of text at its size, at the automatic place or
/// at the corner of a manual layout.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AxisTitle {
    /// The size, in half-points.
    pub size: i64,
    /// The text: its one line ([`TitleText::lines`]), font, bold, italic and fill.
    pub text: TitleText,
    /// The top-left corner of a manual layout in the edge mode (`c:manualLayout`), or `None` for
    /// the automatic place.
    pub corner: Option<LayoutCorner>,
}

/// How the bars of a drawn bar or column chart share a category (`c:grouping`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BarStacking {
    /// Side by side (`clustered`).
    Clustered,
    /// Stacked cumulatively (`stacked`).
    Stacked,
    /// Stacked as shares of each category's sum of magnitudes (`percentStacked`).
    PercentStacked,
}

/// How a bar or column group assigns style colors to bare series ([`PlotRules::bar_color_mode`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BarColorMode {
    /// Do not assign style colors when `c:varyColors` is not explicitly off.
    None,
    /// Assign each bare series the style color of its series index (`0..series_count`).
    BySeries,
    /// Single-series bar chart with varied colors: color each bar by its point fill or category
    /// style color (`0..category_count`) and list categories in the legend.
    ByCategory,
}

/// How far a pie's slices are pulled out (`c:explosion`), in percent of slice radius.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PieExplosion {
    /// Series-level `c:ser/c:explosion` (`0` when absent), which shrinks a 2-D pie's radius.
    pub series: u32,
    /// Per-slice resolved explosion in the order of the points (point override or series value).
    pub slices: Vec<u32>,
}

/// What a drawn chart draws of its series in the plot area.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ChartGroup {
    /// Columns (`c:barChart` with `c:barDir val="col"`): each series' bars in its fill, side by
    /// side or stacked as `stacking` says.
    Columns {
        /// The gap between the clusters, as a percentage of a bar's width (`c:gapWidth`).
        gap: i64,
        /// How far the bars of a cluster overlap, as a percentage of a bar's width
        /// (`c:overlap`); below zero, they keep apart.
        overlap: i64,
        /// Whether the series' bars stand side by side, stacked, or 100%-stacked.
        stacking: BarStacking,
    },
    /// Horizontal bars (`c:barChart` with `c:barDir val="bar"`), on a target that draws
    /// them (`PlotRules::draws_horizontal_bars`): the bars of [`ChartGroup::Columns`] turned,
    /// with the categories up the plot area's left side and the values across its bottom.
    Bars {
        /// The gap between the clusters, as a percentage of a bar's thickness (`c:gapWidth`).
        gap: i64,
        /// How far the bars of a cluster overlap, as a percentage of a bar's thickness
        /// (`c:overlap`); below zero, they keep apart.
        overlap: i64,
        /// Whether the series' bars stand side by side, stacked, or 100%-stacked.
        stacking: BarStacking,
    },
    /// Lines (`c:lineChart` with `standard`, `stacked`, or `percentStacked` grouping): each series
    /// one line through its values in its line's color ([`Series::fill`]), with round caps and
    /// round joins, in the form of its look ([`LineForm`]), and markers at its points when its
    /// look has them.
    Lines {
        /// The look of each series, in the order of the series.
        looks: Vec<LineLook>,
        /// How the line series stack (`Clustered` for standard unstacked, `Stacked`, or
        /// `PercentStacked`).
        stacking: BarStacking,
    },
    /// Scatter points of lines and markers (`c:scatterChart` with
    /// `c:scatterStyle val="lineMarker"`, or `smoothMarker` on a target that draws smooth lines):
    /// each series' points at their x values across and
    /// their values up ([`Series::values`]), joined in their order by a line as
    /// [`ChartGroup::Lines`] draws it, and with markers at them when its look has them.
    Scatter {
        /// The look of each series, in the order of the series.
        looks: Vec<LineLook>,
        /// The x values of each series (`c:xVal`), one for each of its values, in the order of
        /// the series.
        x_values: Vec<Vec<Decimal>>,
        /// What the x value axis sets of its scale (`c:min`, `c:max` and `c:majorUnit`).
        x_scale: SetScale,
    },
    /// A pie (`c:pieChart`), on a target that draws it (`PlotRules::draws_pies`), or a 3-D pie
    /// (`c:pie3DChart`, `PlotRules::draws_pies_3d`): the first series' points as slices of one
    /// circle, clockwise in their order.
    Pie {
        /// Where the first slice starts, in degrees clockwise from the top
        /// (`c:firstSliceAng`, or the turn of a 3-D pie's view).
        first_angle: i64,
        /// The view of a 3-D pie, `None` for a 2-D pie.
        view: Option<pie::PieView>,
        /// The fill of each point's slice, in the order of the points.
        fills: Vec<DrawColor>,
        /// Where the first series' data labels stand.
        labels: PieLabelPlace,
        /// How far the series and each point's slice are pulled out (`c:explosion`).
        explosion: PieExplosion,
    },
    /// A doughnut (`c:doughnutChart`), on a target that draws it (`PlotRules::doughnut_group`):
    /// one concentric annular ring per series from inside (`hole_size` percent of the outer
    /// radius) out to the outer circle, each ring's slices colored by its `SeriesFill::Points`.
    Doughnut {
        /// Where the first slice starts, in degrees clockwise from the top (`c:firstSliceAng`).
        first_angle: i64,
        /// The inner hole diameter as a percentage (`0..=99`) of the outer diameter (`c:holeSize`),
        /// `0` when the part omits `c:holeSize`.
        hole_size: u32,
    },
    /// A shared-axis combination chart (`c:barChart` vertical columns + `c:lineChart` standard
    /// lines sharing one category axis and one value axis), on a target that draws it
    /// (`PlotRules::combo_group`): the first `bar_count` entries of `Columns::series` are columns
    /// and the remaining entries are lines with `looks`.
    Combo {
        /// The column group's gap width (`c:gapWidth`), in percent of one bar's width.
        gap: i64,
        /// The column group's overlap (`c:overlap`), in percent of one bar's width.
        overlap: i64,
        /// How the column group stacks its series (`Clustered` or `Stacked`).
        stacking: BarStacking,
        /// How many leading entries of `Columns::series` belong to the column group.
        bar_count: usize,
        /// The line look of each trailing line series (`Columns::series[bar_count..]`).
        looks: Vec<LineLook>,
        /// How the line group stacks its trailing line series (`Clustered` for standard or
        /// `Stacked`).
        line_stacking: BarStacking,
    },
}

impl ChartGroup {
    /// Whether a chart of this group draws a blank point of a series, as its `c:dispBlanksAs`
    /// says, where the target draws blank points: a chart of columns, horizontal bars, lines,
    /// a pie (flat or 3-D), a doughnut, or a combination chart, and not a scatter chart.
    const fn has_blank_points(&self) -> bool {
        match self {
            Self::Columns { .. }
            | Self::Bars { .. }
            | Self::Lines { .. }
            | Self::Pie { .. }
            | Self::Doughnut { .. }
            | Self::Combo { .. } => true,
            Self::Scatter { .. } => false,
        }
    }

    /// How a bar, column, or combination group stacks its bar series, or `None` for another chart
    /// group.
    pub(crate) const fn stacking(&self) -> Option<BarStacking> {
        match *self {
            Self::Columns { stacking, .. }
            | Self::Bars { stacking, .. }
            | Self::Combo { stacking, .. } => Some(stacking),
            Self::Lines { .. }
            | Self::Scatter { .. }
            | Self::Pie { .. }
            | Self::Doughnut { .. } => None,
        }
    }

    /// How a line or combination group stacks its line series (`Clustered` for standard unstacked,
    /// `Stacked`, or `PercentStacked`), or `None` for another chart group.
    pub(crate) const fn line_stacking(&self) -> Option<BarStacking> {
        match *self {
            Self::Lines { stacking, .. } => Some(stacking),
            Self::Combo { line_stacking, .. } => Some(line_stacking),
            Self::Columns { .. }
            | Self::Bars { .. }
            | Self::Scatter { .. }
            | Self::Pie { .. }
            | Self::Doughnut { .. } => None,
        }
    }
}

/// Where a drawn pie's data labels stand, which also decides the room of its circle.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PieLabelPlace {
    /// No labels, or labels at the center of their slices: the largest circle.
    Center,
    /// Labels at the inner end of their slices: the largest circle.
    InnerEnd,
    /// Labels at the outer end of their slices: a smaller circle.
    OuterEnd,
    /// Labels at the best fit, which is also a pie's default position: a smaller circle.
    BestFit,
}

impl PieLabelPlace {
    /// Whether the labels may stand outside the circle, which makes it smaller.
    #[must_use]
    pub const fn outside(self) -> bool {
        matches!(self, Self::OuterEnd | Self::BestFit)
    }
}

/// How a series of a drawn line or scatter chart draws its line and its markers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LineLook {
    /// The width of its line, or `None` for a series of a scatter group whose line has no fill
    /// (`a:noFill`), which draws its markers alone.
    pub width: Option<StyleWidth>,
    /// The marker at each of its points, or `None` for none.
    pub marker: Option<Marker>,
    /// The form of its line between its points.
    pub form: LineForm,
    /// The preset dash of its line, or `None` for a solid line.
    pub dash: Option<LineDash>,
}

/// A preset dash of a series line (`a:prstDash`) other than `solid`, which a target draws
/// when [`PlotRules::fills_line_strokes`] holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineDash {
    /// `dot`.
    Dot,
    /// `dash`.
    Dash,
    /// `lgDash`.
    LongDash,
    /// `dashDot`.
    DashDot,
    /// `lgDashDot`.
    LongDashDot,
    /// `lgDashDotDot`.
    LongDashDotDot,
    /// `sysDash`.
    SystemDash,
    /// `sysDot`.
    SystemDot,
    /// `sysDashDot`.
    SystemDashDot,
    /// `sysDashDotDot`.
    SystemDashDotDot,
}

impl LineDash {
    /// The dashes and the gaps of the preset in turn, from its first dash, in widths of the
    /// line (ECMA-376 Part 1, 20.1.10.48).
    #[must_use]
    pub const fn pattern(self) -> &'static [i64] {
        use crate::params::{
            PRESET_DASH_WIDTHS as DASH, PRESET_DOT_WIDTHS as DOT, PRESET_GAP_WIDTHS as GAP,
            PRESET_LONG_DASH_WIDTHS as LONG, PRESET_SYSTEM_DASH_WIDTHS as SYSTEM,
            PRESET_SYSTEM_GAP_WIDTHS as SYSTEM_GAP,
        };
        match self {
            Self::Dot => &[DOT, GAP],
            Self::Dash => &[DASH, GAP],
            Self::LongDash => &[LONG, GAP],
            Self::DashDot => &[DASH, GAP, DOT, GAP],
            Self::LongDashDot => &[LONG, GAP, DOT, GAP],
            Self::LongDashDotDot => &[LONG, GAP, DOT, GAP, DOT, GAP],
            Self::SystemDash => &[SYSTEM, SYSTEM_GAP],
            Self::SystemDot => &[DOT, SYSTEM_GAP],
            Self::SystemDashDot => &[SYSTEM, SYSTEM_GAP, DOT, SYSTEM_GAP],
            Self::SystemDashDotDot => &[SYSTEM, SYSTEM_GAP, DOT, SYSTEM_GAP, DOT, SYSTEM_GAP],
        }
    }
}

/// The form of a series' line between its points (`c:smooth`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineForm {
    /// Straight pieces from each point to the next.
    Straight,
    /// A smooth curve through the points (`c:smooth` true), on a target that draws one
    /// ([`PlotRules::draws_smooth_lines`]).
    Smooth,
}

/// A width that a series sets (`w` of an `a:ln`), or that the chart's style gives it from the
/// theme's first line style.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StyleWidth {
    /// Set in the chart part.
    Set(Length),
    /// The chart style's: a series line [`CHART_STYLE_LINE_STYLES`] times the theme's first
    /// line style, and a marker's outline that line style itself.
    ///
    /// [`CHART_STYLE_LINE_STYLES`]: crate::params::CHART_STYLE_LINE_STYLES
    Automatic,
}

/// A marker at each point of a line chart's series (`c:marker`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Marker {
    /// Its shape.
    pub symbol: MarkerSymbol,
    /// Its size across (`c:size`, in points), or `None` for the chart style's size:
    /// [`CHART_STYLE_MARKER_BASE`] and [`CHART_STYLE_MARKER_LINES`] times the theme's first
    /// line style, cut to a whole point.
    ///
    /// [`CHART_STYLE_MARKER_BASE`]: crate::params::CHART_STYLE_MARKER_BASE
    /// [`CHART_STYLE_MARKER_LINES`]: crate::params::CHART_STYLE_MARKER_LINES
    pub size: Option<Length>,
    /// Its fill (`a:solidFill` of its `c:spPr`), or `None` for the series' color.
    pub fill: Option<DrawColor>,
    /// Its outline, or `None` for a marker without one (an `a:ln` of `a:noFill`).
    pub outline: Option<MarkerOutline>,
}

/// The outline of a [`Marker`], with flat ends and round joins.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MarkerOutline {
    /// Its color (`a:solidFill` of the `a:ln` of the marker's `c:spPr`), or `None` for the
    /// series' color.
    pub color: Option<DrawColor>,
    /// Its width.
    pub width: StyleWidth,
}

impl MarkerOutline {
    /// The chart style's outline: the series' color, as wide as the theme's first line style.
    pub const STYLE: Self = Self {
        color: None,
        width: StyleWidth::Automatic,
    };
}

/// `ST_MarkerStyle`, the shapes of a marker that F-Office draws, each in the box of the
/// marker's size around its point.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MarkerSymbol {
    /// A circle (`circle`).
    Circle,
    /// A square standing on a corner, its corners on the box's middle lines (`diamond`).
    Diamond,
    /// A square (`square`).
    Square,
    /// A triangle with its apex at the middle of the box's top and its base on the box's
    /// bottom (`triangle`).
    Triangle,
    /// The box's two diagonals, without a fill (`x`).
    X,
    /// The box's two diagonals and its vertical middle line, without a fill (`star`).
    Star,
}

/// The symbols of the chart style's automatic markers, for the series in turn.
const AUTOMATIC_SYMBOLS: [MarkerSymbol; 6] = [
    MarkerSymbol::Diamond,
    MarkerSymbol::Square,
    MarkerSymbol::Triangle,
    MarkerSymbol::X,
    MarkerSymbol::Star,
    MarkerSymbol::Circle,
];

/// A marker's symbol (`c:symbol`) as F-Office reads it.
#[derive(Clone, Copy)]
enum SymbolCase {
    /// A symbol that F-Office draws.
    Drawn(MarkerSymbol),
    /// No marker (`none`).
    Hidden,
    /// A symbol that F-Office does not draw.
    Other,
}

/// `ST_MarkerStyle` (ECMA-376 Part 1, 21.2.3.27).
const MARKER_SYMBOLS: &Values<SymbolCase> = &Values::new(&[
    own("circle", SymbolCase::Drawn(MarkerSymbol::Circle)),
    own("diamond", SymbolCase::Drawn(MarkerSymbol::Diamond)),
    own("square", SymbolCase::Drawn(MarkerSymbol::Square)),
    own("triangle", SymbolCase::Drawn(MarkerSymbol::Triangle)),
    own("x", SymbolCase::Drawn(MarkerSymbol::X)),
    own("star", SymbolCase::Drawn(MarkerSymbol::Star)),
    own("none", SymbolCase::Hidden),
    own("auto", SymbolCase::Other),
    own("dash", SymbolCase::Other),
    own("dot", SymbolCase::Other),
    own("picture", SymbolCase::Other),
    own("plus", SymbolCase::Other),
]);

/// What a chart's legend sets of its names beyond their font, size and fill.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LegendText {
    /// Whether its names are bold (`b` of the legend's `a:defRPr`).
    pub bold: bool,
    /// Whether its names are italic (`i` of the legend's `a:defRPr`).
    pub italic: bool,
    /// Whether it has entries of its own (`c:legendEntry`), which change the text of a series'
    /// entry or delete it.
    pub own_entries: bool,
}

impl LegendText {
    /// What the `c:legend` element `legend` sets of its names.
    fn read(doc: &Document, legend: NodeId) -> Self {
        let run = default_run(doc, legend);
        let on = |name| {
            run.and_then(|run| doc.attribute(run, None, name))
                .is_some_and(f_office_drawingml::boolean)
        };
        Self {
            bold: on("b"),
            italic: on("i"),
            own_entries: doc.child(legend, C, "legendEntry").is_some(),
        }
    }
}

/// The rule that places the plot area of a drawn chart ([`Columns::default_chart_rule`],
/// [`Columns::font_lines_rule`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlotRule {
    /// The plot area of Word's default chart in Calibri, from that chart's numbers.
    DefaultChart,
    /// The plot area from the lines and the ascent of the labels' font, with the axis labels,
    /// the title and the legend.
    FontLines,
}

impl Columns {
    /// The bar/column series of this chart: all series for `Columns`/`Bars`, the leading
    /// `bar_count` series for `Combo`, and empty otherwise.
    #[must_use]
    pub(crate) fn bar_series(&self) -> &[Series] {
        match self.group {
            ChartGroup::Columns { .. } | ChartGroup::Bars { .. } => &self.series,
            ChartGroup::Combo { bar_count, .. } => self.series.get(..bar_count).unwrap_or_default(),
            ChartGroup::Lines { .. }
            | ChartGroup::Scatter { .. }
            | ChartGroup::Pie { .. }
            | ChartGroup::Doughnut { .. } => &[],
        }
    }

    /// The line series of this chart: all series for `Lines`/`Scatter`, the trailing series
    /// after `bar_count` for `Combo`, and empty otherwise.
    #[must_use]
    pub(crate) fn line_series(&self) -> &[Series] {
        match self.group {
            ChartGroup::Lines { .. } | ChartGroup::Scatter { .. } => &self.series,
            ChartGroup::Combo { bar_count, .. } => self.series.get(bar_count..).unwrap_or_default(),
            ChartGroup::Columns { .. }
            | ChartGroup::Bars { .. }
            | ChartGroup::Pie { .. }
            | ChartGroup::Doughnut { .. } => &[],
        }
    }

    /// The rule of Word's default chart for the chart's plot area, or why it does not draw the
    /// chart: the first condition that the chart does not meet. It draws only Word's default
    /// chart with a title, the legend at the bottom, the automatic scale and no value below
    /// zero, at the automatic place whatever manual layout the part gives.
    pub fn default_chart_rule(&self) -> Result<PlotRule, ChartReason> {
        let other_group = match self.group {
            ChartGroup::Scatter { .. } => ChartReason::Scatter,
            ChartGroup::Bars { .. } => ChartReason::HorizontalBars,
            ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. } => ChartReason::OtherGroup,
            ChartGroup::Combo { .. } => ChartReason::NotOneGroup,
            ChartGroup::Columns {
                stacking: BarStacking::Stacked | BarStacking::PercentStacked,
                ..
            } => ChartReason::NotClustered,
            ChartGroup::Columns { .. } | ChartGroup::Lines { .. } => ChartReason::Lines,
        };
        meets([
            (
                matches!(
                    self.group,
                    ChartGroup::Columns {
                        stacking: BarStacking::Clustered,
                        ..
                    }
                ),
                other_group,
            ),
            (self.title.is_some(), ChartReason::Untitled),
            (
                self.legend == Some(LegendPlace::Bottom),
                ChartReason::LegendNotAtBottom,
            ),
            (self.scale == SetScale::default(), ChartReason::SetScale),
            (
                self.series
                    .iter()
                    .flat_map(|s| s.values.iter().flatten())
                    .all(|v| !v.digits.is_negative()),
                ChartReason::NegativeValue,
            ),
            (self.data_table.is_none(), ChartReason::DataTable),
        ])
        .map(|()| PlotRule::DefaultChart)
    }

    /// Whether the rule of the labels' font lines draws the chart's axis titles: a chart without
    /// one, or one whose titles the target draws ([`AxisTitles::Drawn`]) without a legend at the
    /// left and without an unknown plot area layout.
    fn draws_axis_titles(&self) -> bool {
        match self.axis_titles {
            AxisTitles::Drawn { .. } if self.axis_titles == AxisTitles::NONE => true,
            AxisTitles::Drawn { .. } => {
                self.plot_place != PlotPlace::Other && self.legend != Some(LegendPlace::Left)
            }
            AxisTitles::Other => false,
        }
    }

    /// The rule of the labels' font lines for the chart's plot area, or why it does not draw
    /// the chart. It places each chart whose axes cross at the automatic zero, with the
    /// automatic place or a manual layout in the edge mode, with a name for each series when
    /// the legend stands at the left or the right, without an axis title that the target does
    /// not draw ([`AxisTitles::Other`]) and with value labels in a label format that the target
    /// writes, the scope of the rule; any other chart that the default chart's rule draws
    /// keeps that rule ([`Columns::default_chart_rule`]), so that the narrower scope leaves no
    /// chart out.
    pub fn font_lines_rule(&self) -> Result<PlotRule, ChartReason> {
        let side = matches!(self.legend, Some(LegendPlace::Left | LegendPlace::Right));
        // A pie's or doughnut's legend names its points, and neither has value labels.
        if matches!(
            self.group,
            ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. }
        ) {
            return meets([
                (
                    self.plot_place != PlotPlace::Other,
                    ChartReason::OtherPlotPlace,
                ),
                (
                    !(side && self.category_names.is_none()),
                    ChartReason::UnnamedSeriesBesideLegend,
                ),
            ])
            .map(|()| PlotRule::FontLines);
        }
        let missing_legend_name = match self.series.as_slice() {
            [one] if matches!(one.fill, SeriesFill::Points(_)) => self.category_names.is_none(),
            _ => self.series.iter().any(|s| s.name.is_none()),
        };
        meets([
            (self.category_crossing.is_some(), ChartReason::SetCrossing),
            (
                self.plot_place != PlotPlace::Other,
                ChartReason::OtherPlotPlace,
            ),
            (
                !(side && missing_legend_name),
                ChartReason::UnnamedSeriesBesideLegend,
            ),
            (self.draws_axis_titles(), ChartReason::AxisTitle),
            (self.value_format.is_some(), ChartReason::OtherNumberFormat),
        ])
        .map(|()| PlotRule::FontLines)
        .or_else(|reason| self.default_chart_rule().map_err(|_| reason))
    }
}

/// The data label properties that show a label's text (ECMA-376 Part 1, 21.2.2.49): a value,
/// a percentage, a category name, a series name or a bubble size.
const SHOWN_LABEL_PARTS: [&str; 5] = [
    "showVal",
    "showPercent",
    "showCatName",
    "showSerName",
    "showBubbleSize",
];

/// A boolean element of a chart part (the schema's `CT_Boolean`, ECMA-376 Part 1, 21.2.2), such
/// as `c:delete`, `c:showVal`, `c:smooth` or `c:varyColors`, as the part writes it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Flag {
    /// Written without a `val`, or with `1` or `true`.
    On,
    /// Written with another `val`, such as `0` or `false`.
    Off,
    /// Not written.
    Missing,
}

impl Flag {
    /// The boolean child `name` of `node`.
    fn of(doc: &Document, node: NodeId, name: &str) -> Self {
        match doc.child(node, C, name) {
            None => Self::Missing,
            Some(flag) => {
                if doc
                    .attribute(flag, None, "val")
                    .is_none_or(f_office_drawingml::boolean)
                {
                    Self::On
                } else {
                    Self::Off
                }
            }
        }
    }

    /// Whether the element is on: written on; a missing element reads as off.
    const fn is_on(self) -> bool {
        matches!(self, Self::On)
    }
}

/// Whether the data labels `labels` (`c:dLbls`, or `c:dLbl` of one point) show a part of a
/// label's text and are not deleted (`c:delete`).
fn shows_labels(doc: &Document, labels: NodeId) -> bool {
    !Flag::of(doc, labels, "delete").is_on()
        && SHOWN_LABEL_PARTS
            .iter()
            .any(|name| Flag::of(doc, labels, name).is_on())
}

/// Where a series' data labels stand (`c:dLblPos`, ECMA-376 Part 1, 21.2.2.48), as the part
/// writes it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DataLabelPosition {
    /// Not written: where the chart's type puts them.
    Default,
    /// `bestFit`.
    BestFit,
    /// `ctr`.
    Center,
    /// `inBase`.
    InsideBase,
    /// `inEnd`.
    InsideEnd,
    /// `outEnd`.
    OutsideEnd,
    /// `t` (above a line point).
    Top,
    /// `b` (below a line point).
    Bottom,
    /// `l` (left of a line point).
    Left,
    /// `r` (right of a line point).
    Right,
    /// A value that does not read, or a label of one point (`c:dLbl`) at a position of its own.
    Other,
}

/// The positions of `c:dLblPos` that F-Office reads by their values.
const DATA_LABEL_POSITIONS: [(&str, DataLabelPosition); 9] = [
    ("bestFit", DataLabelPosition::BestFit),
    ("ctr", DataLabelPosition::Center),
    ("inBase", DataLabelPosition::InsideBase),
    ("inEnd", DataLabelPosition::InsideEnd),
    ("outEnd", DataLabelPosition::OutsideEnd),
    ("t", DataLabelPosition::Top),
    ("b", DataLabelPosition::Bottom),
    ("l", DataLabelPosition::Left),
    ("r", DataLabelPosition::Right),
];

/// The positions at which a clustered bar or column chart draws its data labels.
const COLUMN_LABEL_POSITIONS: [DataLabelPosition; 5] = [
    DataLabelPosition::Default,
    DataLabelPosition::OutsideEnd,
    DataLabelPosition::Center,
    DataLabelPosition::InsideEnd,
    DataLabelPosition::InsideBase,
];

/// The positions at which a stacked or 100%-stacked bar or column chart draws its data labels.
const STACKED_LABEL_POSITIONS: [DataLabelPosition; 4] = [
    DataLabelPosition::Default,
    DataLabelPosition::Center,
    DataLabelPosition::InsideEnd,
    DataLabelPosition::InsideBase,
];

/// The positions at which a line chart (or the line series of a combo chart) draws its data
/// labels.
const LINE_LABEL_POSITIONS: [DataLabelPosition; 6] = [
    DataLabelPosition::Default,
    DataLabelPosition::Center,
    DataLabelPosition::Top,
    DataLabelPosition::Bottom,
    DataLabelPosition::Left,
    DataLabelPosition::Right,
];

impl DataLabelPosition {
    /// The position written on `node` itself (`c:dLbls` or `c:dLbl`), or `Default` when omitted.
    fn own(doc: &Document, node: NodeId) -> Self {
        value(doc, node, "dLblPos").map_or(Self::Default, |written| {
            DATA_LABEL_POSITIONS
                .iter()
                .find(|(name, _)| *name == written)
                .map_or(Self::Other, |&(_, position)| position)
        })
    }

    /// The position of the data labels `labels` (`c:dLbls`): their own, or
    /// [`DataLabelPosition::Other`] when a label of one point writes another.
    fn of(doc: &Document, labels: NodeId) -> Self {
        let position = Self::own(doc, labels);
        let agreed = doc
            .child_elements(labels)
            .filter(|&node| doc.is(node, C, "dLbl") && doc.child(node, C, "dLblPos").is_some())
            .all(|point| Self::own(doc, point) == position);
        if agreed { position } else { Self::Other }
    }

    /// The pie-room position of a pie's data labels (`c:dLbls` and every non-deleted `c:dLbl`
    /// override): preserves the shared position when all agree or when any `c:dLbl` is deleted
    /// (`delete="1"`, in which case Word decides the circle shrink from `c:dLbls/c:dLblPos`
    /// alone); otherwise, when known pie positions are mixed, returns `BestFit` (shrunk) if every
    /// position is outside-capable (`Default`, `BestFit`, or `OutsideEnd`) and `Center` (full
    /// radius) if any position is inside (`Center` or `InsideEnd`). Returns `Other` if any
    /// position is outside the pie positions.
    fn for_pie(doc: &Document, labels: NodeId) -> Self {
        let series = Self::own(doc, labels);
        let has_deleted = doc
            .child_elements(labels)
            .any(|node| doc.is(node, C, "dLbl") && Flag::of(doc, node, "delete") == Flag::On);
        let points = doc.child_elements(labels).filter(|&node| {
            doc.is(node, C, "dLbl")
                && Flag::of(doc, node, "delete") != Flag::On
                && doc.child(node, C, "dLblPos").is_some()
        });
        let positions: Vec<Self> = std::iter::once(series)
            .chain(points.map(|point| Self::own(doc, point)))
            .collect();
        if positions.iter().any(|pos| {
            !matches!(
                pos,
                Self::Default | Self::BestFit | Self::Center | Self::InsideEnd | Self::OutsideEnd
            )
        }) {
            Self::Other
        } else if has_deleted || positions.iter().all(|&pos| pos == series) {
            series
        } else if positions
            .iter()
            .any(|pos| matches!(pos, Self::Center | Self::InsideEnd))
        {
            Self::Center
        } else {
            Self::BestFit
        }
    }
}

/// Whether `<c:showPercent>` is requested before format resolution.
#[derive(Clone, Copy, PartialEq, Eq)]
enum MarkupPercent {
    Hidden,
    Shown,
}

/// Which text parts and separator a series' `<c:dLbls>` asks for before format resolution.
struct MarkupLabelParts {
    show_ser_name: bool,
    show_cat_name: bool,
    show_val: bool,
    percent: MarkupPercent,
    separator: Option<String>,
    own_format: Option<FormatCode>,
}

/// Per-point `<c:dLbl>` markup before format/font resolution.
enum MarkupPointLabel {
    Deleted,
    Custom(Box<MarkupPointSpec>),
}

/// Unresolved per-point `<c:dLbl>` properties.
struct MarkupPointSpec {
    position: DataLabelPosition,
    size: Option<i64>,
    font: Option<FontRef>,
    fill: Box<Look<Option<DrawColor>>>,
    insets: Edges<Length>,
    format: FormatCode,
    parts: MarkupLabelParts,
    rich_lines: Option<Vec<String>>,
    layout: PointLabelLayout,
}

/// What a series' data labels are, as the part writes them: before the chart text gives the
/// size and the font that they leave open.
enum LabelMarkup {
    /// No data labels.
    Hidden,
    /// One or more supported label parts at a position that F-Office reads ([`SeriesLabels::Values`]
    /// where the chart draws them there), optionally with per-point `<c:dLbl>` overrides.
    Values {
        /// Whether points without a `<c:dLbl>` override show the series-level label.
        show_default: bool,
        /// Where they stand.
        position: DataLabelPosition,
        /// The size that their text sets, in half-points.
        size: Option<i64>,
        /// The font that their text sets.
        font: Option<FontRef>,
        /// The fill of their text, kept apart as the largest part.
        fill: Box<Look<Option<DrawColor>>>,
        /// The insets of their text box.
        insets: Edges<Length>,
        /// Their number format code (own `c:numFmt`, else cached source format).
        format: FormatCode,
        /// Which text parts and separator to show, plus own non-source-linked format code.
        parts: Box<MarkupLabelParts>,
        /// Sparse per-point overrides (`(point_index, override)`).
        point_overrides: Vec<(usize, MarkupPointLabel)>,
    },
    /// Another form ([`SeriesLabels::Other`]).
    Other,
}

impl LabelMarkup {
    /// The series' labels in a drawn chart, with the size and the font that `text` gives
    /// where their own text leaves them open, the label format that `rules` give their format
    /// code, and the warnings of their fill in `warnings`. F-Office draws the labels only at
    /// the positions `drawn_at` that its chart's rules place, percentages only where
    /// `allow_percent` holds (pies and doughnuts), and no labels in a format that the target
    /// does not write.
    fn drawn(
        self,
        (drawn_at, allow_percent, rules): (&[DataLabelPosition], bool, PlotRules),
        text: &ChartText,
        warnings: &mut Warnings<DrawingMlWarning>,
    ) -> SeriesLabels {
        match self {
            Self::Hidden => SeriesLabels::Hidden,
            Self::Other => SeriesLabels::Other,
            Self::Values {
                show_default,
                position,
                size,
                font,
                fill,
                insets,
                format,
                parts,
                point_overrides,
            } => {
                if show_default && !drawn_at.contains(&position) {
                    return SeriesLabels::Other;
                }
                let Some((val_format, percent, parts_sep, show_ser, show_cat, show_val)) =
                    resolve_series_parts(show_default, *parts, &format, (allow_percent, rules))
                else {
                    return SeriesLabels::Other;
                };
                let Some(resolved_points) = resolve_point_overrides(
                    point_overrides,
                    position,
                    (drawn_at, allow_percent, rules),
                    text,
                    warnings,
                ) else {
                    return SeriesLabels::Other;
                };
                let fill = *fill;
                warnings.extend(fill.warnings, std::convert::identity);
                SeriesLabels::Values(DataLabelText {
                    position,
                    size: text.size(size),
                    font: text.font(font),
                    fill: fill.value,
                    insets,
                    format: val_format,
                    parts: DataLabelParts {
                        show_ser_name: show_ser,
                        show_cat_name: show_cat,
                        show_val,
                        percent,
                        separator: parts_sep,
                    },
                    show_default,
                    point_overrides: resolved_points,
                })
            }
        }
    }
}

/// Resolves value and percentage formats for series-level `parts` (when `active` is false, returns
/// benign placeholders because only per-point overrides are displayed).
fn resolve_series_parts(
    active: bool,
    parts: MarkupLabelParts,
    format: &FormatCode,
    (allow_percent, rules): (bool, PlotRules),
) -> Option<(LabelFormat, PercentMode, Option<String>, bool, bool, bool)> {
    if !active {
        return Some((
            LabelFormat::all_digits(),
            PercentMode::Hidden,
            parts.separator,
            false,
            false,
            false,
        ));
    }
    if parts.percent == MarkupPercent::Shown && !allow_percent {
        return None;
    }
    let val_format = if parts.show_val {
        format.decided(rules, LabelPlace::Data)?
    } else {
        LabelFormat::all_digits()
    };
    let percent = resolved_percent_mode(parts.percent, parts.own_format.as_ref(), rules)?;
    Some((
        val_format,
        percent,
        parts.separator,
        parts.show_ser_name,
        parts.show_cat_name,
        parts.show_val,
    ))
}

/// Resolves every parsed `<c:dLbl>` override into [`PointLabelOverride`], returning `None` if any
/// point uses an unsupported position, format, or percentage mode.
fn resolve_point_overrides(
    overrides: Vec<(usize, MarkupPointLabel)>,
    series_position: DataLabelPosition,
    (drawn_at, allow_percent, rules): (&[DataLabelPosition], bool, PlotRules),
    text: &ChartText,
    warnings: &mut Warnings<DrawingMlWarning>,
) -> Option<Vec<(usize, PointLabelOverride)>> {
    let mut out = Vec::with_capacity(overrides.len());
    for (idx, item) in overrides {
        match item {
            MarkupPointLabel::Deleted => out.push((idx, PointLabelOverride::Deleted)),
            MarkupPointLabel::Custom(spec) => {
                let spec = *spec;
                let effective_pos = if spec.position == DataLabelPosition::Default
                    && !drawn_at.contains(&DataLabelPosition::Default)
                {
                    series_position
                } else {
                    spec.position
                };
                if !drawn_at.contains(&effective_pos) {
                    return None;
                }
                let has_rich = spec.rich_lines.is_some();
                let (val_format, percent, sep, show_ser, show_cat, show_val) =
                    resolve_series_parts(
                        !has_rich,
                        spec.parts,
                        &spec.format,
                        (allow_percent, rules),
                    )?;
                let fill = *spec.fill;
                warnings.extend(fill.warnings, std::convert::identity);
                out.push((
                    idx,
                    PointLabelOverride::Custom(Box::new(PointLabelSpec {
                        label: DataLabelText {
                            position: effective_pos,
                            size: text.size(spec.size),
                            font: text.font(spec.font),
                            fill: fill.value,
                            insets: spec.insets,
                            format: val_format,
                            parts: DataLabelParts {
                                show_ser_name: show_ser,
                                show_cat_name: show_cat,
                                show_val,
                                percent,
                                separator: sep,
                            },
                            show_default: true,
                            point_overrides: Vec::new(),
                        },
                        rich_lines: spec.rich_lines,
                        layout: spec.layout,
                    })),
                ));
            }
        }
    }
    Some(out)
}

/// Resolves how `c:showPercent` formats slice shares: `PercentMode::Hidden` when off,
/// `PercentMode::Integer` when Word uses integer `0%` with largest-remainder rounding (omitted,
/// source-linked, `"0%"`, or a non-percentage format), `PercentMode::Format(fmt)` for an explicit
/// decimal percentage format such as `"0.0%"`, or `None` when an explicit percentage format is
/// unsupported by `rules`.
fn resolved_percent_mode(
    percent: MarkupPercent,
    own_format: Option<&FormatCode>,
    rules: PlotRules,
) -> Option<PercentMode> {
    if percent == MarkupPercent::Hidden {
        return Some(PercentMode::Hidden);
    }
    let Some(own) = own_format else {
        return Some(PercentMode::Integer);
    };
    let trimmed = own.0.trim();
    if !trimmed.contains('%') || trimmed == "0%" {
        return Some(PercentMode::Integer);
    }
    own.decided(rules, LabelPlace::Data)
        .map(PercentMode::Format)
}

/// Reads non-source-linked `<c:numFmt formatCode="..."/>` on `node`, if present.
fn own_num_fmt(doc: &Document, node: NodeId) -> Option<FormatCode> {
    doc.child(node, C, "numFmt")
        .filter(|&own| {
            !doc.attribute(own, None, "sourceLinked")
                .is_some_and(f_office_drawingml::boolean)
        })
        .map(|own| {
            FormatCode(
                doc.attribute(own, None, "formatCode")
                    .unwrap_or_default()
                    .to_owned(),
            )
        })
}

/// On `<c:dLbl>`, an omitted `c:show*` flag defaults to ON in Word for Windows (unlike `<c:dLbls>`
/// where omitted flags are OFF). Returns `false` only when the flag is explicitly written off.
fn flag_default_on(doc: &Document, node: NodeId, name: &str) -> bool {
    Flag::of(doc, node, name) != Flag::Off
}

/// Reads `<c:layout>` on a per-point `<c:dLbl>` into [`PointLabelLayout`], or `None` if an
/// unsupported manual-layout mode is written.
fn read_point_layout(reader: &mut PartReader, point: NodeId) -> Option<PointLabelLayout> {
    let doc = reader.doc;
    let Some(layout) = doc.child(point, C, "layout") else {
        return Some(PointLabelLayout::Automatic);
    };
    let Some(manual) = doc.child(layout, C, "manualLayout") else {
        return Some(PointLabelLayout::Automatic);
    };
    let parsed = ManualLayout::read(reader, manual);
    let [x, y, _, _] = parsed.edges;
    match parsed.modes {
        [LayoutMode::Edge, LayoutMode::Edge] => Some(PointLabelLayout::Edge { x: x?, y: y? }),
        [LayoutMode::Factor, LayoutMode::Factor] => Some(PointLabelLayout::Offset {
            dx: x.unwrap_or(Decimal::ZERO),
            dy: y.unwrap_or(Decimal::ZERO),
        }),
        _ => None,
    }
}

/// Outcome of reading `<c:tx>` on a per-point `<c:dLbl>`.
enum RichTextRead {
    Absent,
    Lines(Vec<String>),
    Unsupported,
}

/// Reads `<c:tx>` on a per-point `<c:dLbl>`: `Absent` when missing, `Lines` for `<c:tx><c:rich>`
/// with one line per `<a:p>`, and `Unsupported` for any other `<c:tx>` form.
fn read_point_rich_lines(doc: &Document, point: NodeId) -> RichTextRead {
    let Some(tx) = doc.child(point, C, "tx") else {
        return RichTextRead::Absent;
    };
    let Some(rich) = doc.child(tx, C, "rich") else {
        return RichTextRead::Unsupported;
    };
    let mut lines = Vec::new();
    for para in doc.child_elements(rich).filter(|&n| doc.is(n, A, "p")) {
        let mut line = String::new();
        for child in doc.child_elements(para) {
            if (doc.is(child, A, "r") || doc.is(child, A, "fld"))
                && let Some(t) = doc.child(child, A, "t")
            {
                line.push_str(&doc.text_content(t));
            }
        }
        lines.push(line);
    }
    if lines.is_empty() {
        RichTextRead::Unsupported
    } else {
        RichTextRead::Lines(lines)
    }
}

/// Series-level `<c:dLbls>` defaults inherited by `<c:dLbl>` overrides when omitted.
struct SeriesLabelDefaults<'a> {
    format: &'a FormatCode,
    separator: Option<&'a str>,
    size: Option<i64>,
    font: Option<&'a FontRef>,
    insets: Edges<Length>,
    node: NodeId,
}

/// Reads one `<c:dLbl>` child of `<c:dLbls>`, inheriting text properties and format from the
/// series-level `dLbls` where omitted. Returns `None` if the `<c:dLbl>` uses an unsupported
/// feature (legend key, bubble size, unknown position, unsupported layout, or non-rich `c:tx`).
fn read_point_label(
    reader: &mut PartReader,
    point: NodeId,
    series: &SeriesLabelDefaults<'_>,
) -> Option<(usize, MarkupPointLabel)> {
    let doc = reader.doc;
    let idx = read_value(reader, point, "idx", |v| v.parse::<usize>().ok())?;
    if Flag::of(doc, point, "delete").is_on() {
        return Some((idx, MarkupPointLabel::Deleted));
    }
    if flag_default_on(doc, point, "showLegendKey") || flag_default_on(doc, point, "showBubbleSize")
    {
        return None;
    }
    let position = DataLabelPosition::own(doc, point);
    if position == DataLabelPosition::Other {
        return None;
    }
    let layout = read_point_layout(reader, point)?;
    let rich_lines = match read_point_rich_lines(doc, point) {
        RichTextRead::Absent => None,
        RichTextRead::Lines(lines) => Some(lines),
        RichTextRead::Unsupported => return None,
    };
    let show_val = flag_default_on(doc, point, "showVal");
    let show_cat_name = flag_default_on(doc, point, "showCatName");
    let show_ser_name = flag_default_on(doc, point, "showSerName");
    let show_percent = flag_default_on(doc, point, "showPercent");
    let any_part = show_val || show_cat_name || show_ser_name || show_percent;
    if rich_lines.is_none() && !any_part {
        return Some((idx, MarkupPointLabel::Deleted));
    }
    let own_format = own_num_fmt(doc, point);
    let format = own_format.clone().unwrap_or_else(|| series.format.clone());
    let separator = doc
        .child(point, C, "separator")
        .map(|sep| doc.text_content(sep))
        .or_else(|| series.separator.map(str::to_owned))
        .or_else(|| Some(", ".to_owned()));
    let body = doc
        .child(point, C, "txPr")
        .and_then(|text| doc.child(text, A, "bodyPr"));
    let insets = if body.is_some() {
        body_insets(reader, body, CHART_DATA_LABEL_INSETS)
    } else {
        series.insets
    };
    let own_fill = text_fill(doc, point);
    let fill = if own_fill.value.is_some() {
        own_fill
    } else {
        text_fill(doc, series.node)
    };
    Some((
        idx,
        MarkupPointLabel::Custom(Box::new(MarkupPointSpec {
            position,
            size: text_size(reader, point).or(series.size),
            font: text_font(doc, point).or_else(|| series.font.cloned()),
            fill: Box::new(fill),
            insets,
            format,
            parts: MarkupLabelParts {
                show_ser_name,
                show_cat_name,
                show_val,
                percent: if show_percent {
                    MarkupPercent::Shown
                } else {
                    MarkupPercent::Hidden
                },
                separator,
                own_format,
            },
            rich_lines,
            layout,
        })),
    ))
}

/// The data labels `labels` of a series (its own `c:dLbls`, else its group's) whose cached
/// values have the format code `source`. Supports any non-empty combination of `c:showSerName`,
/// `c:showCatName`, `c:showVal`, and `c:showPercent` with optional `<c:separator>` and per-point
/// `<c:dLbl>` overrides when no legend key or bubble size is shown and F-Office reads the
/// position ([`DataLabelPosition`]); their number format code is their `c:numFmt`'s, else
/// `source` when it is linked to the source or missing. Labels that are deleted and show no
/// point are hidden.
fn label_markup(
    reader: &mut PartReader,
    labels: Option<NodeId>,
    source: &FormatCode,
) -> LabelMarkup {
    let doc = reader.doc;
    let Some(labels) = labels else {
        return LabelMarkup::Hidden;
    };
    let points: Vec<NodeId> = doc
        .child_elements(labels)
        .filter(|&node| doc.is(node, C, "dLbl"))
        .collect();
    let show_default = shows_labels(doc, labels);
    if !show_default && !points.iter().any(|&point| shows_labels(doc, point)) {
        return LabelMarkup::Hidden;
    }
    let own_format = own_num_fmt(doc, labels);
    let format = own_format.clone().unwrap_or_else(|| source.clone());
    let show_val = Flag::of(doc, labels, "showVal").is_on();
    let show_cat_name = Flag::of(doc, labels, "showCatName").is_on();
    let show_ser_name = Flag::of(doc, labels, "showSerName").is_on();
    let show_percent = Flag::of(doc, labels, "showPercent").is_on();
    let show_bubble = Flag::of(doc, labels, "showBubbleSize").is_on();
    let any_part = show_val || show_cat_name || show_ser_name || show_percent;
    let position = DataLabelPosition::own(doc, labels);
    if show_default
        && (!any_part
            || show_bubble
            || Flag::of(doc, labels, "showLegendKey").is_on()
            || position == DataLabelPosition::Other)
    {
        return LabelMarkup::Other;
    }
    let separator = doc
        .child(labels, C, "separator")
        .map(|sep| doc.text_content(sep));
    let body = doc
        .child(labels, C, "txPr")
        .and_then(|text| doc.child(text, A, "bodyPr"));
    let size = text_size(reader, labels);
    let font = text_font(doc, labels);
    let insets = body_insets(reader, body, CHART_DATA_LABEL_INSETS);
    let defaults = SeriesLabelDefaults {
        format: &format,
        separator: separator.as_deref(),
        size,
        font: font.as_ref(),
        insets,
        node: labels,
    };
    let mut point_overrides = Vec::with_capacity(points.len());
    for point in points {
        let Some(entry) = read_point_label(reader, point, &defaults) else {
            return LabelMarkup::Other;
        };
        point_overrides.push(entry);
    }
    LabelMarkup::Values {
        show_default,
        position,
        size,
        font,
        fill: Box::new(text_fill(doc, labels)),
        insets,
        format,
        parts: Box::new(MarkupLabelParts {
            show_ser_name,
            show_cat_name,
            show_val,
            percent: if show_percent {
                MarkupPercent::Shown
            } else {
                MarkupPercent::Hidden
            },
            separator,
            own_format,
        }),
        point_overrides,
    }
}

/// `Ok` when each condition holds, else the reason of the first that does not.
fn meets<const N: usize>(conditions: [(bool, ChartReason); N]) -> Result<(), ChartReason> {
    conditions
        .into_iter()
        .find(|&(holds, _)| !holds)
        .map_or(Ok(()), |(_, reason)| Err(reason))
}

/// Where the plot area of a drawn chart stands (`c:layout` of `c:plotArea`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlotPlace {
    /// Where the application puts it: the part gives no manual layout.
    Automatic,
    /// The box of a manual layout in the edge mode.
    Manual(PlotLayout),
    /// A manual layout in another mode, or one without its whole box.
    Other,
}

/// A number format code as a chart part writes it: the `formatCode` of a `c:numFmt`, or the
/// `c:formatCode` of a series' cache (`c:numCache`), which a format linked to the source takes.
/// The reader's plot rules decide the label format that it gives ([`PlotRules::label_format`]).
#[derive(Clone, Debug, PartialEq, Eq)]
struct FormatCode(String);

impl FormatCode {
    /// The code `General`, of a cache that writes none.
    fn general() -> Self {
        Self("General".to_owned())
    }

    /// Whether the code is `General`, whose case does not count.
    fn is_general(&self) -> bool {
        self.0.trim().eq_ignore_ascii_case("General")
    }

    /// The label format that the code gives under `rules` to a label at `place`, or `None`
    /// for a format that the target does not write.
    fn decided(&self, rules: PlotRules, place: LabelPlace) -> Option<LabelFormat> {
        rules.label_format(&self.0, place)
    }
}

/// Where the legend of a drawn chart stands (`c:legendPos`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LegendPlace {
    /// Below the plot area (`b`).
    Bottom,
    /// Above the plot area (`t`).
    Top,
    /// At the left (`l`).
    Left,
    /// At the right (`r`).
    Right,
}

/// The manual layout of a plot area in the edge mode (ECMA-376 Part 1, 21.2.2.95).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlotLayout {
    /// Whether the box is the plot area itself (`inner`), or the plot area with its tick
    /// labels (`outer`, the default).
    pub inner: bool,
    /// The box.
    pub edges: LayoutBox,
}

/// The box of a manual layout in the edge mode (ECMA-376 Part 1, 21.2.2.95), as parts of the
/// chart's width and height from the chart's top left corner.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LayoutBox {
    /// The box's left edge, as a part of the chart's width (`c:x`).
    pub x: Decimal,
    /// The box's top edge, as a part of the chart's height (`c:y`).
    pub y: Decimal,
    /// The box's width, as a part of the chart's width (`c:w`).
    pub w: Decimal,
    /// The box's height, as a part of the chart's height (`c:h`).
    pub h: Decimal,
}

/// The box that a drawn chart's legend stands in (`c:layout` of `c:legend`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LegendBox {
    /// The application's box at the legend's place: the part gives no manual layout.
    Automatic,
    /// The box of a manual layout in the edge mode.
    Manual(LayoutBox),
    /// A manual layout in another mode, or one without its whole box.
    Other,
}

/// What a value axis sets of its scale (`c:scaling` and `c:majorUnit`), each `None` when the
/// application chooses it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SetScale {
    /// The lowest value (`c:min`).
    pub min: Option<Decimal>,
    /// The highest value (`c:max`).
    pub max: Option<Decimal>,
    /// The step between two gridlines (`c:majorUnit`), above zero.
    pub major_unit: Option<Decimal>,
}

/// The title of a chart (`c:title`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Title {
    /// The number of its lines: of its paragraphs, or one for an automatic title.
    pub lines: usize,
    /// Its size, in half-points.
    pub size: i64,
    /// The font of its face: the first that its places name, or else the chart text's.
    pub font: FontRef,
    /// Its text, where the target draws it ([`PlotRules::draws_title_text`]).
    pub text: Option<TitleText>,
    /// The top left corner of its manual layout, or `None` at the automatic place.
    pub corner: Option<LayoutCorner>,
}

/// The top left corner that a manual layout in the edge mode gives without a size (ECMA-376
/// Part 1, 21.2.2.95), as parts of the chart's width and height from the chart's top left
/// corner.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LayoutCorner {
    /// The left, as a part of the chart's width (`c:x`).
    pub x: Decimal,
    /// The top, as a part of the chart's height (`c:y`).
    pub y: Decimal,
}

/// The text of a chart's own title that F-Office draws, with the properties of all its runs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TitleText {
    /// The text of each line: of each paragraph, or the cached text of a reference.
    pub lines: Vec<String>,
    /// The font of its face.
    pub font: FontRef,
    /// Whether it is bold.
    pub bold: bool,
    /// Whether it is italic.
    pub italic: bool,
    /// Its fill, or `None` when it sets none.
    pub fill: Option<DrawColor>,
}

/// A series of a column or line chart (`c:ser`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Series {
    /// The fill of its bars and of its legend key, or the color of its line.
    pub fill: SeriesFill,
    /// Its values, one for each category, `None` at a blank point that draws nothing.
    pub values: Vec<Option<Decimal>>,
    /// Its name (`c:tx`), which the legend shows, when the part caches one.
    pub name: Option<String>,
    /// What its data labels show.
    pub labels: SeriesLabels,
}

/// The paint of a drawn series ([`Series`]): the fill of its bars and of its legend key, or the
/// color of its line.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SeriesFill {
    /// A color: the solid fill of its bars (`a:solidFill` of its `c:spPr`) or of its line
    /// (`a:solidFill` of the `a:ln` of its `c:spPr`), or its chart style's color.
    Color(DrawColor),
    /// A gradient fill of its bars (`a:gradFill` of its `c:spPr`) that F-Office paints.
    Gradient(LinearGradient),
    /// No fill (`a:noFill`): bars/lines draw no filled shape while keeping stack/cluster slots
    /// and legend text without a swatch.
    None,
    /// Per-category solid fills of a single-series bar/column or doughnut ring whose colors vary
    /// by point (listing category names in a single-series bar chart's legend).
    Points(Vec<DrawColor>),
    /// Per-point solid/noFill overrides on a bar/column series, keeping the series `base` fill
    /// for its legend swatch.
    BarPoints {
        /// The series' base solid fill for its legend swatch, or `None` when transparent.
        base: Option<DrawColor>,
        /// The resolved fill of each category's bar (`None` omits that bar's rectangle).
        points: Vec<Option<DrawColor>>,
    },
}

impl SeriesFill {
    /// Its color, or `None` for a gradient, no fill, or per-point fills.
    #[must_use]
    pub fn color(&self) -> Option<&DrawColor> {
        match self {
            Self::Color(color) => Some(color),
            Self::Gradient(_) | Self::None | Self::Points(_) | Self::BarPoints { .. } => None,
        }
    }
}

/// The data labels of a series of a drawn chart: its own `c:dLbls`, else its chart group's.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SeriesLabels {
    /// No data labels.
    Hidden,
    /// Its values alone, at the default position or the outer end of its bars
    /// (`c:dLblPos val="outEnd"`), in General: the form that F-Office draws where the target's
    /// quirk `ChartDataLabels` says so.
    Values(DataLabelText),
    /// Data labels in another form, which F-Office does not draw: other parts of a label's text,
    /// a label of one point (`c:dLbl`), another position or number format, or a legend key.
    Other,
}

/// How a pie or doughnut data label formats its share percentage (`c:showPercent`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum PercentMode {
    /// Percentage is not displayed.
    #[default]
    Hidden,
    /// Integer `0%` with largest-remainder (Hamilton) rounding so non-blank slices sum to 100%.
    Integer,
    /// Explicit decimal percentage format (such as `0.0%`), rounded independently per slice.
    Format(LabelFormat),
}

impl PercentMode {
    /// Whether the label includes a percentage part.
    #[must_use]
    pub const fn is_shown(&self) -> bool {
        !matches!(self, Self::Hidden)
    }
}

/// Which text parts and separator a series' drawn data labels display.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataLabelParts {
    /// Whether to include the series name (`c:showSerName`).
    pub show_ser_name: bool,
    /// Whether to include the category name (`c:showCatName`).
    pub show_cat_name: bool,
    /// Whether to include the formatted point value (`c:showVal`).
    pub show_val: bool,
    /// Whether and how to include the point's share percentage (`c:showPercent`, pies/doughnuts).
    pub percent: PercentMode,
    /// Explicit `<c:separator>` text, or `None` when omitted (Word defaults to `"\n"` when
    /// `percent` is shown, else `", "`).
    pub separator: Option<String>,
}

impl Default for DataLabelParts {
    fn default() -> Self {
        Self {
            show_ser_name: false,
            show_cat_name: false,
            show_val: true,
            percent: PercentMode::Hidden,
            separator: None,
        }
    }
}

impl DataLabelParts {
    /// Whether the label shows only the formatted value (`c:showVal` alone).
    #[must_use]
    pub const fn is_value_only(&self) -> bool {
        self.show_val && !self.show_ser_name && !self.show_cat_name && !self.percent.is_shown()
    }

    /// The separator placed between consecutive displayed parts.
    #[must_use]
    pub fn effective_separator(&self) -> &str {
        self.separator
            .as_deref()
            .unwrap_or(if self.percent.is_shown() { "\n" } else { ", " })
    }
}

/// Manual placement of one point's data label (`c:dLbl/c:layout/c:manualLayout`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PointLabelLayout {
    /// Automatic placement from the label's position.
    #[default]
    Automatic,
    /// Relative shift `(dx, dy)` in fractions of the chart frame's width and height
    /// (`xMode`/`yMode` omitted or `factor`).
    Offset {
        /// Horizontal shift fraction of the chart frame's width (`c:x`).
        dx: Decimal,
        /// Vertical shift fraction of the chart frame's height (`c:y`).
        dy: Decimal,
    },
    /// Absolute top-left `(x, y)` in fractions of the chart frame's width and height
    /// (`xMode="edge"` and `yMode="edge"`).
    Edge {
        /// Left edge fraction of the chart frame's width (`c:x`).
        x: Decimal,
        /// Top edge fraction of the chart frame's height (`c:y`).
        y: Decimal,
    },
}

/// Per-point override of a series' data labels (`c:dLbl` inside `c:dLbls`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PointLabelOverride {
    /// `<c:delete val="1"/>` — hides this point's label.
    Deleted,
    /// Custom settings for this point.
    Custom(Box<PointLabelSpec>),
}

/// Resolved settings for one point's `<c:dLbl>` override.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PointLabelSpec {
    /// Text look, position, format, and parts for this point.
    pub label: DataLabelText,
    /// Optional custom rich-text paragraphs (`c:tx/c:rich`), one line per `<a:p>`.
    pub rich_lines: Option<Vec<String>>,
    /// Manual offset or edge placement from `c:layout/c:manualLayout`.
    pub layout: PointLabelLayout,
}

/// What the data labels that show a series' values set of their text: their own `a:defRPr`, else
/// the chart text's ([`ChartText`]), and the insets of their text box.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataLabelText {
    /// Where the labels stand (`c:dLblPos`).
    pub position: DataLabelPosition,
    /// The size, in half-points.
    pub size: i64,
    /// The font.
    pub font: FontRef,
    /// The fill of their text, or `None` for the automatic color.
    pub fill: Option<DrawColor>,
    /// The insets of each label's text box (`a:bodyPr` of their `c:txPr`), each missing one
    /// Word's own (`params::CHART_DATA_LABEL_INSETS`).
    pub insets: Edges<Length>,
    /// The label format in which they write their values: their own `c:numFmt`, else that of
    /// the series' cache.
    pub format: LabelFormat,
    /// Which text parts and separator to display.
    pub parts: DataLabelParts,
    /// Whether points without an entry in `point_overrides` draw the series-level label.
    pub show_default: bool,
    /// Sparse per-point `<c:dLbl>` overrides indexed by point index (`c:idx`).
    pub point_overrides: Vec<(usize, PointLabelOverride)>,
}

/// A number as Word writes it in a cache (`c:v`): `digits` × 10^`exponent`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Decimal {
    /// The digits, with the sign.
    pub digits: i64,
    /// The power of ten that they are multiplied by.
    pub exponent: i32,
}

impl Decimal {
    /// The number zero.
    pub(crate) const ZERO: Self = Self {
        digits: 0,
        exponent: 0,
    };

    /// Reads a number such as `4.3`, `-12` or `1.5E-3`. Digits that do not fit in 64 bits
    /// are left out, so very long numbers lose their last digits. A number whose digits carry
    /// a power of ten beyond [`CHART_EXPONENT_LIMIT`] gives `None`.
    #[must_use]
    pub fn parse(text: &str) -> Option<Self> {
        let text = text.trim();
        let (mantissa, exponent) = match text.split_once(['E', 'e']) {
            Some((mantissa, exponent)) => (mantissa, exponent.parse::<i32>().ok()?),
            None => (text, 0),
        };
        let negative = mantissa.starts_with('-');
        let mantissa = mantissa.trim_start_matches(['-', '+']);
        let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
        if whole.is_empty() && fraction.is_empty() {
            return None;
        }
        let exponent = exponent.checked_sub(i32::try_from(fraction.len()).ok()?)?;
        let (digits, exponent) = digits_of(whole.chars().chain(fraction.chars()), exponent)?;
        if !(-CHART_EXPONENT_LIMIT..=CHART_EXPONENT_LIMIT).contains(&i64::from(exponent)) {
            return None;
        }
        let digits = if negative { -digits } else { digits };
        Some(Self { digits, exponent }.normalized())
    }

    /// The same number without trailing zeros in its digits.
    #[must_use]
    pub fn normalized(self) -> Self {
        let mut out = self;
        while out.digits != 0 && out.digits % TENTHS == 0 {
            out.digits /= TENTHS;
            out.exponent += 1;
        }
        if out.digits == 0 {
            out.exponent = 0;
        }
        out
    }

    /// Whether the number is above zero.
    #[must_use]
    pub const fn is_positive(self) -> bool {
        self.digits > 0
    }
}

/// The decimal digits `chars` as a number, with `exponent` raised by one for each digit that
/// does not fit in 64 bits, or `None` for a character that is not a digit.
fn digits_of(chars: impl Iterator<Item = char>, mut exponent: i32) -> Option<(i64, i32)> {
    let radix = u32::try_from(TENTHS).ok()?;
    let mut digits: i64 = 0;
    for ch in chars {
        let digit = i64::from(ch.to_digit(radix)?);
        match digits
            .checked_mul(TENTHS)
            .and_then(|d| d.checked_add(digit))
        {
            Some(next) => digits = next,
            None => exponent = exponent.checked_add(1)?,
        }
    }
    Some((digits, exponent))
}

impl PartialOrd for Decimal {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Decimal {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let low = self.exponent.min(other.exponent);
        let wide = |d: Self| {
            let shift = u32::try_from(d.exponent - low).unwrap_or(u32::MAX);
            i128::from(d.digits).saturating_mul(i128::from(TENTHS).saturating_pow(shift))
        };
        wide(*self).cmp(&wide(*other))
    }
}

/// The chart that a drawing's `a:graphicData` holds (`c:chart`), before its part is read.
#[must_use]
pub fn reference(doc: &Document, graphic_data: NodeId) -> Option<Chart> {
    let chart = doc.child(graphic_data, C, "chart")?;
    Some(Chart {
        id: doc.attribute(chart, Some(R), "id")?.to_owned(),
        columns: None,
    })
}

/// Gives each chart of the blocks, also inside tables, text boxes and groups, its part, from
/// `find`, which reads the chart part that a relationship ID names. A chart that F-Office does
/// not draw keeps no columns.
pub fn attach_charts(blocks: &mut [Block], find: &mut dyn FnMut(&str) -> Option<Part>) {
    visit_drawings(blocks, &mut |drawing| {
        if let DrawingMut::Floating(floating) = drawing {
            attach(floating, find);
        }
    });
}

fn attach(floating: &mut Floating, find: &mut dyn FnMut(&str) -> Option<Part>) {
    let Some(chart) = floating.chart.as_mut() else {
        return;
    };
    let Some(columns) = find(&chart.id) else {
        return;
    };
    // The chart area's fill and line frame the chart.
    floating.look = Some(columns_area(columns.area.clone()));
    chart.columns = Some(Box::new(columns.columns));
}

/// A chart part's clustered column chart with the fill and line of its chart area.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Part {
    /// The chart area's fill and line (`c:spPr` of `c:chartSpace`).
    pub area: ShapeLook,
    /// The chart.
    pub columns: Columns,
}

/// The chart area as a rectangle.
fn columns_area(mut look: ShapeLook) -> ShapeLook {
    look.geometry = Geometry::Rect;
    look
}

/// Reads a chart part (`c:chartSpace`) into its [`ChartModel`], and gives the part that
/// F-Office draws of it ([`Part::of`], or [`pie::part`] for a pie) when the target's plot rules `rules` draw its columns
/// ([`PlotRules::rule`]), or why F-Office does not draw the chart. The looks of a chart that
/// F-Office draws warn, and a value that does not read warns in every chart that has a model.
pub(crate) fn read(
    reader: &mut PartReader,
    space: NodeId,
    rules: PlotRules,
) -> Result<Part, ChartReason> {
    let mut model = ChartModel::read(reader, space)?;
    model.title = model.title.decided(rules);
    let drawn = match model.groups.as_slice() {
        [Group::Pie(_)] => pie::part(model, rules)?,
        [Group::Doughnut(_)] => pie::doughnut_part(model, rules)?,
        _ => Part::of(model, rules)?,
    };
    rules.rule(&drawn.value.columns)?;
    reader
        .drawing_warnings()
        .extend(drawn.warnings, std::convert::identity);
    Ok(drawn.value)
}

/// A look of a chart, such as a fill or a line, with the warnings of its reading, which count
/// only when F-Office draws the look.
type Look<T> = Warned<T, DrawingMlWarning>;

/// The model of a chart part (`c:chartSpace`, ECMA-376 Part 1, 21.2) whose plot area holds
/// only bar and line groups, as the part writes it, before F-Office decides what it draws:
/// its groups, axes, legend, title and chart area.
struct ChartModel {
    /// The chart groups of the plot area, in their order.
    groups: Vec<Group>,
    /// The axes of the plot area, in their order.
    axes: Vec<Axis>,
    /// The legend (`c:legend`).
    legend: Option<Legend>,
    /// The title, as [`title`] reads it.
    title: TitleState,
    /// The manual layout of the plot area (`c:manualLayout` of its `c:layout`).
    plot_layout: Option<ManualLayout>,
    /// Data table (`c:dTable`), when present in the plot area.
    data_table: Option<DataTableMarkup>,
    /// How the chart shows the blank points of its series.
    blanks: BlankPoints,
    /// The chart area's fill and line (`c:spPr` of `c:chartSpace`).
    area: ElementLook,
    /// Normalized Office chart style (`1..=48`, with omitted style defaulting to `2` and
    /// Office 2010 `c14:style` `101..=148` mapped by subtracting 100) plus whether the part
    /// writes only a non-2 Office 2007 `c:style` without `c14:style` (`legacy_lines`), in which
    /// case Word draws bare axes and gridlines in untinted `dk1` (`#000000`) rather than tinted
    /// `CHART_STYLE_LINE_TINT` (`#868686`). `None` if malformed or conflicting.
    style: Option<ChartStyleInfo>,
    /// The chart text: the size and font that the chart space's text sets for every element.
    text: ChartText,
}

/// The text properties that a chart part sets for all of its elements (`c:txPr` of
/// `c:chartSpace`, ECMA-376 Part 1, 21.2.2.216): an element whose own text sets no size or font
/// takes these, and without them the size [`CHART_TEXT_SIZE`] and the theme's body font
/// (ECMA-376 Part 1, 21.2.3.46).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct ChartText {
    /// The size, in half-points, as [`text_size`] reads it.
    size: Option<i64>,
    /// The font, as [`text_font`] reads it.
    font: Option<FontRef>,
    /// Whether it is bold (`b` of its `a:defRPr`), when it says so.
    bold: Option<bool>,
    /// Whether the part names its chart style in Word's form: `c14:style` in its
    /// `mc:AlternateContent`, whatever the number.
    styled: bool,
}

impl ChartText {
    /// The size of an element whose own text sets `own`, in half-points.
    fn size(&self, own: Option<i64>) -> i64 {
        own.or(self.size).unwrap_or(CHART_TEXT_SIZE)
    }

    /// The size of a title that writes none in a chart whose text writes none either, in
    /// half-points, where the target draws a title's text: [`CHART_STYLED_TITLE_SIZE`] when the
    /// part names its chart style in Word's form, else the size of an element that writes none.
    fn title_size(&self) -> i64 {
        if self.styled {
            CHART_STYLED_TITLE_SIZE
        } else {
            self.size(None)
        }
    }

    /// The font of an element whose own text names `own`.
    fn font(&self, own: Option<FontRef>) -> FontRef {
        own.or_else(|| self.font.clone())
            .unwrap_or(FontRef::MinorLatin)
    }
}

impl TitleState {
    /// The state on a target whose plot rules are `rules`: an automatic title that the target
    /// is known to hide is none ([`PlotRules::hides_automatic_title`]), and another automatic
    /// title is unknown.
    fn decided(self, rules: PlotRules) -> Self {
        match self {
            Self::Automatic(title) if rules.hides_automatic_title(title) => Self::Deleted,
            Self::Automatic(_) => Self::Unknown,
            other => other,
        }
    }

    /// The state, or `None` for an unknown title, which F-Office does not draw.
    fn known(self) -> Option<Self> {
        match self {
            Self::Unknown | Self::Automatic(_) => None,
            known => Some(known),
        }
    }

    /// The own title that the chart shows, if any.
    fn shown(self) -> Option<OwnTitle> {
        match self {
            Self::Shown(title) => Some(*title),
            Self::Deleted | Self::Automatic(_) | Self::Unknown => None,
        }
    }
}

/// Whether a chart shows a title, as `c:title` and `c:autoTitleDeleted` give it.
enum TitleState {
    /// The chart's own title (`c:title`), shown.
    Shown(Box<OwnTitle>),
    /// No title: the automatic title is deleted and the chart has no title of its own, or the
    /// target hides the automatic title ([`TitleState::decided`]).
    Deleted,
    /// The automatic title: the chart has no title of its own and does not delete its automatic
    /// title (`c:autoTitleDeleted` missing or `0`); the target decides whether it shows.
    Automatic(AutomaticTitle),
    /// A title that F-Office does not know: a title of its own whose automatic title is
    /// deleted, or an automatic title that the target does not hide.
    Unknown,
}

/// A chart's own title (`c:title`), as its part writes it.
struct OwnTitle {
    /// The number of its lines: of the paragraphs of its rich text, or one.
    lines: usize,
    /// What its first run with run properties, the default run properties of its rich text's
    /// first paragraph and its own text properties (`c:txPr`) write, in this order.
    places: [TitleProps; 3],
    /// Its text, as [`shown_title`] reads it.
    text: OwnText,
    /// The top left corner of its manual layout ([`ManualLayout::corner`]).
    corner: Option<LayoutCorner>,
    /// How its rich text turns ([`TitleTurn::of`]).
    turn: TitleTurn,
    /// The warnings of the fills of its places.
    warnings: Warnings<DrawingMlWarning>,
}

/// How a title's rich text turns its text (`rot` and `vert` of the `a:bodyPr` of its
/// `c:rich`), as its part writes it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TitleTurn {
    /// No turn: neither `rot` nor `vert`, or `vert="horz"` alone, whose element's default turn
    /// applies.
    Default,
    /// A quarter turn to read upward (`rot="-5400000"`), with `vert="horz"` or none.
    Upward,
    /// No turn (`rot="0"`), with `vert="horz"` or none.
    Upright,
    /// Any other turn, vertical text, or a title without rich text.
    Other,
}

impl TitleTurn {
    /// How the rich text of the title `node` turns its text.
    fn of(doc: &Document, node: NodeId) -> Self {
        let Some(rich) = doc
            .child(node, C, "tx")
            .and_then(|tx| doc.child(tx, C, "rich"))
        else {
            return Self::Other;
        };
        let body = doc.child(rich, A, "bodyPr");
        let attribute = |name| body.and_then(|body| doc.attribute(body, None, name));
        if attribute("vert").is_some_and(|vert| vert != "horz") {
            return Self::Other;
        }
        match attribute("rot").map(f_office_drawingml::integer) {
            None => Self::Default,
            Some(Some(TITLE_UPWARD_TURN)) => Self::Upward,
            Some(Some(0)) => Self::Upright,
            Some(_) => Self::Other,
        }
    }
}

/// The turn of a title's rich text that reads upward, in 60,000ths of a degree (`rot` of
/// `a:bodyPr`, ECMA-376 Part 1, 21.1.2.1.1): a quarter turn counterclockwise.
const TITLE_UPWARD_TURN: i64 = -QUARTER_TURN;

/// The text of a chart's own title, as its part writes it.
enum OwnText {
    /// The text of each line ([`title_lines`]).
    Lines(Vec<String>),
    /// No text of its own (`c:tx`): the target's placeholder for the chart's series
    /// ([`PlotRules::title_placeholder`]).
    Placeholder(TitleSeries),
    /// Text that F-Office does not draw.
    Undrawn,
}

impl OwnText {
    /// The text of each line on a target whose plot rules are `rules`, or `None` when F-Office
    /// does not draw it.
    fn lines(self, rules: PlotRules) -> Option<Vec<String>> {
        match self {
            Self::Lines(lines) => Some(lines),
            Self::Placeholder(series) => rules
                .title_placeholder(series.automatic, series.first_name.as_deref())
                .map(|text| vec![text]),
            Self::Undrawn => None,
        }
    }
}

/// The series of a chart that a placeholder title depends on.
struct TitleSeries {
    /// The number of series in all of its groups and whether the first has a name.
    automatic: AutomaticTitle,
    /// The cached name of the first series ([`series_name`]).
    first_name: Option<String>,
}

/// What one place of a title's text properties (`a:rPr` or `a:defRPr`) writes.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct TitleProps {
    /// The size (`sz`), in half-points.
    size: Option<i64>,
    /// Whether it is bold (`b`).
    bold: Option<bool>,
    /// Whether it is italic (`i`).
    italic: Option<bool>,
    /// The font (`a:latin`).
    font: Option<FontRef>,
    /// The fill (`a:solidFill`).
    fill: Option<DrawColor>,
}

impl TitleProps {
    /// What the run properties `props` write, with the warnings of their fill in `warnings`.
    fn read(
        reader: &mut PartReader,
        props: NodeId,
        warnings: &mut Warnings<DrawingMlWarning>,
    ) -> Self {
        let doc = reader.doc;
        let flag = |name| {
            doc.attribute(props, None, name)
                .map(f_office_drawingml::boolean)
        };
        Self {
            size: reader
                .or_missing_in(props, (None, "sz"), f_office_drawingml::integer)
                .map(|hundredths| hundredths * HALF_POINTS_PER_POINT / PERCENT),
            bold: flag("b"),
            italic: flag("i"),
            font: doc
                .child(props, A, "latin")
                .and_then(|latin| doc.attribute(latin, None, "typeface"))
                .map(FontRef::of_typeface),
            fill: doc
                .child(props, A, "solidFill")
                .and_then(|solid| DrawColor::read(doc, solid, warnings)),
        }
    }
}

impl OwnTitle {
    /// The title on a target whose plot rules are `rules`, in a chart whose text is `text`, or
    /// [`ChartReason::UnknownTitle`] when its size is not known.
    ///
    /// Where the target does not draw a title's text, its size is that of its first run, else
    /// of its own text properties. Where it does ([`PlotRules::draws_title_text`]), its size,
    /// bold, italic, font and fill are those of the first of its places that writes them, and
    /// a title that writes no size has [`ChartText::title_size`] when the chart's text writes
    /// none either; when it does, the size is not known. A title that writes no bold is bold, and
    /// its text is not drawn when the chart's text writes a bold. Its font is the chart text's
    /// font when no place names one.
    fn decided(self, rules: PlotRules, text: &ChartText) -> Result<Look<Title>, ChartReason> {
        let Self {
            lines,
            places,
            text: shown,
            corner,
            turn: _,
            warnings,
        } = self;
        let [run, _, own] = &places;
        let font = text.font(places.iter().find_map(|place| place.font.clone()));
        if !rules.draws_title_text() {
            let size = run.size.or(own.size).ok_or(ChartReason::UnknownTitle)?;
            let title = Title {
                lines,
                size,
                font,
                text: None,
                corner,
            };
            return Ok(Warned::new(title, Warnings::new()));
        }
        // quirk: ChartTitleText::Drawn (src/quirks.rs)
        let size = places.iter().find_map(|place| place.size);
        if size.is_none() && text.size.is_some() {
            return Err(ChartReason::UnknownTitle);
        }
        let bold = places
            .iter()
            .find_map(|place| place.bold)
            .or_else(|| text.bold.is_none().then_some(true));
        let italic = places.iter().find_map(|place| place.italic);
        let fill = places.iter().find_map(|place| place.fill.clone());
        let title = Title {
            lines,
            size: size.unwrap_or_else(|| text.title_size()),
            font: font.clone(),
            text: shown.lines(rules).zip(bold).map(|(lines, bold)| TitleText {
                lines,
                font,
                bold,
                italic: italic.unwrap_or(false),
                fill,
            }),
            corner,
        };
        Ok(Warned::new(title, warnings))
    }

    /// The title as an axis title that F-Office draws in a chart whose text is `text`, whose
    /// rich text turns as `turn` or not at all, with the warnings of its fills added to
    /// `warnings`; `None` for a title that it does not draw: one with a manual layout or that
    /// overlaps the plot area, one without text of its own or whose text it does not draw
    /// ([`OwnText::Undrawn`]), one of other than one line that is not empty, one turned
    /// otherwise, and one that writes no bold in a chart whose text writes a bold. Its size,
    /// bold, italic, font and fill are those of the first of its places that writes them; a
    /// title that writes no size has the chart text's ([`ChartText::size`]), and one that
    /// writes no bold is bold, as the chart's title is ([`Self::decided`]).
    fn axis_title(
        self,
        turn: TitleTurn,
        text: &ChartText,
        warnings: &mut Warnings<DrawingMlWarning>,
    ) -> Option<AxisTitle> {
        let Self {
            lines: _,
            places,
            text: shown,
            corner,
            turn: written,
            warnings: own,
        } = self;
        if !(written == TitleTurn::Default || written == turn) {
            return None;
        }
        let OwnText::Lines(lines) = shown else {
            return None;
        };
        if !matches!(lines.as_slice(), [line] if !line.is_empty()) {
            return None;
        }
        let bold = places
            .iter()
            .find_map(|place| place.bold)
            .or_else(|| text.bold.is_none().then_some(true))?;
        warnings.extend(own, std::convert::identity);
        Some(AxisTitle {
            size: text.size(places.iter().find_map(|place| place.size)),
            text: TitleText {
                lines,
                font: text.font(places.iter().find_map(|place| place.font.clone())),
                bold,
                italic: places
                    .iter()
                    .find_map(|place| place.italic)
                    .unwrap_or(false),
                fill: places.iter().find_map(|place| place.fill.clone()),
            },
            corner,
        })
    }
}

/// What a target's automatic title depends on: the chart's series in all of its groups, and
/// whether the chart writes that its automatic title is not deleted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AutomaticTitle {
    /// The number of series (`c:ser`).
    pub(crate) series: usize,
    /// Whether the first series has a name (`c:tx`).
    pub(crate) named: bool,
    /// Whether the chart writes `c:autoTitleDeleted`, which is off where this is read.
    pub(crate) marked: bool,
}

/// A manual layout of a chart element (`c:manualLayout`, ECMA-376 Part 1, 21.2.2.95), as the
/// part writes it.
struct ManualLayout {
    /// Which box the layout gives (`c:layoutTarget`).
    target: LayoutTarget,
    /// How `x` and `y` count (`c:xMode`, `c:yMode`).
    modes: [LayoutMode; 2],
    /// How `w` and `h` count (`c:wMode`, `c:hMode`).
    size_modes: [LayoutMode; 2],
    /// The box: `c:x`, `c:y`, `c:w` and `c:h`, when the layout sets them.
    edges: [Option<Decimal>; 4],
}

/// `ST_LayoutTarget`, which box of a plot area a manual layout gives.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LayoutTarget {
    /// The plot area without its tick labels (`inner`).
    Inner,
    /// The plot area with its tick labels (`outer`), the default.
    Outer,
}

/// `ST_LayoutTarget` of ECMA-376 Part 1.
const LAYOUT_TARGET: &Values<LayoutTarget> = &Values::new(&[
    own("inner", LayoutTarget::Inner),
    own("outer", LayoutTarget::Outer),
]);

/// `ST_LayoutMode`, how a value of a manual layout counts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LayoutMode {
    /// As the place of an edge, a part of the chart's size from its top left corner (`edge`).
    Edge,
    /// As a part of the chart's size from the element's automatic place or size (`factor`),
    /// the default.
    Factor,
}

/// `ST_LayoutMode` of ECMA-376 Part 1.
const LAYOUT_MODE: &Values<LayoutMode> = &Values::new(&[
    own("edge", LayoutMode::Edge),
    own("factor", LayoutMode::Factor),
]);

/// A chart group of a plot area.
enum Group {
    /// A bar chart (`c:barChart`).
    Bars(Bars),
    /// A line chart (`c:lineChart`).
    Lines(Lines),
    /// A scatter chart (`c:scatterChart`).
    Scatter(Scatter),
    /// A pie chart (`c:pieChart`).
    Pie(pie::PieGroup),
    /// A doughnut chart (`c:doughnutChart`).
    Doughnut(pie::DoughnutGroup),
}

/// A scatter chart (`c:scatterChart`, ECMA-376 Part 1, 21.2.2.161).
struct Scatter {
    /// Its style (`c:scatterStyle`), `None` when it does not read.
    style: Option<ScatterStyle>,
    /// Whether the group writes that the colors of its points do not vary
    /// (`c:varyColors` of `0` or `false`).
    uniform_colors: bool,
    /// Whether a series adds a trendline or error bars (`c:trendline`, `c:errBars`).
    extras: bool,
    /// The series' lines and markers, read as those of a standard line chart that shows the
    /// chart style's markers, with each series' y values (`c:yVal`) as its values.
    lines: Lines,
    /// The cached x values of each series (`c:xVal`), as [`cached_values`] reads them, in the
    /// order of the series.
    x_values: Vec<Option<Vec<Decimal>>>,
    /// The format code of each series' cached x values, General without one.
    x_formats: Vec<FormatCode>,
}

/// `ST_ScatterStyle`, what a scatter chart draws of its series.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ScatterStyle {
    /// No line and no marker (`none`).
    Nothing,
    /// Straight lines (`line`).
    Line,
    /// Straight lines and markers (`lineMarker`).
    LineMarker,
    /// Markers (`marker`).
    Marker,
    /// Smooth lines (`smooth`).
    Smooth,
    /// Smooth lines and markers (`smoothMarker`).
    SmoothMarker,
}

/// `ST_ScatterStyle` (ECMA-376 Part 1, 21.2.3.40).
const SCATTER_STYLE: &Values<ScatterStyle> = &Values::new(&[
    own("none", ScatterStyle::Nothing),
    own("line", ScatterStyle::Line),
    own("lineMarker", ScatterStyle::LineMarker),
    own("marker", ScatterStyle::Marker),
    own("smooth", ScatterStyle::Smooth),
    own("smoothMarker", ScatterStyle::SmoothMarker),
]);

/// What a series of a line or scatter group draws whose line has no fill (`a:noFill`).
#[derive(Clone, Copy, PartialEq, Eq)]
enum HiddenLine {
    /// No chart, as in a line group: the series has no color ([`ChartReason::SeriesFill`]).
    NoColor,
    /// Its markers alone, in their own look, as in a scatter group.
    MarkersAlone,
}

/// A line chart (`c:lineChart`, ECMA-376 Part 1, 21.2.2.97).
struct Lines {
    /// How the series stack (`c:grouping`: `"standard"` or omitted -> `Clustered`, `"stacked"` ->
    /// `Stacked`, `"percentStacked"` -> `PercentStacked`, unknown -> `None`).
    grouping: Option<BarStacking>,
    /// Whether the group adds drop lines, high-low lines or up-down bars (`c:dropLines`,
    /// `c:hiLowLines`, `c:upDownBars`).
    extras: bool,
    /// Whether the group shows the chart style's markers on the series that set none
    /// (`c:marker val="1"` of the `c:lineChart`).
    shows_markers: bool,
    /// The series (`c:ser`), in their order, each with its line's color as its fill.
    series: Vec<ChartSeries>,
    /// What each series sets of its line and its points, in the same order.
    settings: Vec<SeriesLine>,
    /// Axis IDs (`c:axId`) referenced by this line group.
    ax_ids: Vec<String>,
}

/// What a series of a line chart sets of its line and its points.
struct SeriesLine {
    /// Whether it has no properties (`c:spPr`), so that the chart's style gives its line and
    /// its color.
    styled: bool,
    /// The width of its line (`w` of the `a:ln` of its `c:spPr`), when it reads.
    width: Option<Length>,
    /// The caps and the joins that its line writes.
    ends: LineEnds,
    /// The dash that its line writes.
    dash: SeriesDash,
    /// Whether its line has no fill (`a:noFill` of its `a:ln`).
    hidden: bool,
    /// Its markers as its `c:marker` sets them.
    marker: SeriesMarker,
    /// Whether its line is smoothed (`c:smooth` true).
    smooth: bool,
}

/// The caps and the joins that a series line writes (`cap` and the join of its `a:ln`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LineEnds {
    /// Round caps and round joins (`cap="rnd"` and `a:round`).
    Round,
    /// Each of the cap and the join round or not written, and one of them not written.
    Unwritten,
    /// Another cap or join (`flat`, `sq`, `a:miter` or `a:bevel`).
    Other,
}

/// The dash that a series line writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SeriesDash {
    /// None, or `a:prstDash` `solid`.
    Solid,
    /// Another preset dash.
    Preset(LineDash),
    /// A dash of its own (`a:custDash`) or a preset that does not read.
    Other,
}

/// The preset dashes of a series line by their value of `a:prstDash`.
const PRESET_DASHES: &Values<SeriesDash> = &Values::new(&[
    own("solid", SeriesDash::Solid),
    own("dot", SeriesDash::Preset(LineDash::Dot)),
    own("dash", SeriesDash::Preset(LineDash::Dash)),
    own("lgDash", SeriesDash::Preset(LineDash::LongDash)),
    own("dashDot", SeriesDash::Preset(LineDash::DashDot)),
    own("lgDashDot", SeriesDash::Preset(LineDash::LongDashDot)),
    own("lgDashDotDot", SeriesDash::Preset(LineDash::LongDashDotDot)),
    own("sysDash", SeriesDash::Preset(LineDash::SystemDash)),
    own("sysDot", SeriesDash::Preset(LineDash::SystemDot)),
    own("sysDashDot", SeriesDash::Preset(LineDash::SystemDashDot)),
    own(
        "sysDashDotDot",
        SeriesDash::Preset(LineDash::SystemDashDotDot),
    ),
]);

/// The markers of a line chart's series as its `c:marker` sets them.
enum SeriesMarker {
    /// No `c:marker`: the chart's style gives the markers when the group shows them.
    Styled,
    /// No marker (`c:symbol val="none"`).
    None,
    /// A marker that F-Office can draw, as [`Lines::drawn`] decides under the target's rules: a
    /// symbol that it draws or none, a size or none, and a look that it reads or none.
    Drawn {
        /// Its shape, or `None` for no `c:symbol`.
        symbol: Option<MarkerSymbol>,
        /// Its size (`c:size`), or `None` for the chart style's.
        size: Option<Length>,
        /// Its look (`c:spPr`), or `None` for no `c:spPr`.
        look: Option<MarkerLook>,
    },
    /// A marker that F-Office does not draw: a symbol that it does not draw, or a look with
    /// another fill, an outline of another fill, effects or a 3-D look.
    Other,
}

/// The look of a series' marker as its `c:spPr` writes it.
struct MarkerLook {
    /// Its solid fill (`a:solidFill`), or `None` for no fill element.
    fill: Option<DrawColor>,
    /// Its outline (`a:ln`).
    outline: WrittenOutline,
}

/// A marker's outline as the `a:ln` of its `c:spPr` writes it.
enum WrittenOutline {
    /// No `a:ln`.
    Unwritten,
    /// An `a:ln` of `a:noFill`.
    Hidden,
    /// An `a:ln` of a solid fill, with its width (`w`) or none.
    Solid(DrawColor, Option<Length>),
}

impl MarkerLook {
    /// The marker's fill and outline, each `None` as [`Marker`] reads it: the look's own when
    /// it writes them whole (a solid fill, and an outline of a solid fill with its width), else,
    /// when `fills` holds ([`PlotRules::fills_marker_looks`]), the chart style's for each part
    /// that it leaves out and no outline for an outline of `a:noFill`. `None` when `fills` does
    /// not hold and the look is not whole.
    fn parts(&self, fills: bool) -> Option<(Option<DrawColor>, Option<MarkerOutline>)> {
        let outline = match &self.outline {
            WrittenOutline::Solid(color, Some(width)) => Some(MarkerOutline {
                color: Some(color.clone()),
                width: StyleWidth::Set(*width),
            }),
            _ if !fills => return None,
            WrittenOutline::Solid(color, None) => Some(MarkerOutline {
                color: Some(color.clone()),
                width: StyleWidth::Automatic,
            }),
            WrittenOutline::Unwritten => Some(MarkerOutline::STYLE),
            WrittenOutline::Hidden => None,
        };
        (self.fill.is_some() || fills).then(|| (self.fill.clone(), outline))
    }
}

/// A bar chart (`c:barChart`, ECMA-376 Part 1, 21.2.2.16).
struct Bars {
    /// Which way the bars stand (`c:barDir`).
    direction: BarDirection,
    /// How the series' bars share a category (`c:grouping`).
    grouping: BarGrouping,
    /// The gap between the clusters, as a percentage of a bar's width (`c:gapWidth`).
    gap: i64,
    /// How far the bars of a cluster overlap, as a percentage of a bar's width (`c:overlap`).
    overlap: i64,
    /// Whether the group writes that the colors of its points do not vary
    /// (`c:varyColors` of `0` or `false`), so that each series has one color.
    uniform_colors: bool,
    /// The series (`c:ser`), in their order.
    series: Vec<ChartSeries>,
}

/// A series of a bar or line chart (`c:ser`).
struct ChartSeries {
    /// The series index written in `c:idx`, used for style-2 color indexing across combo groups.
    index: Option<usize>,
    /// The solid fill of its bars (`a:solidFill` of its `c:spPr`), or of a line chart's line
    /// (`a:solidFill` of the `a:ln` of its `c:spPr`), with the warnings of its gradient too.
    fill: Look<Option<DrawColor>>,
    /// The gradient fill of the element whose solid fill is its color (`a:gradFill`), when it
    /// has no solid fill and F-Office paints the gradient ([`LinearGradient::read`]): a bar
    /// series' fill.
    gradient: Option<LinearGradient>,
    /// Whether its properties name a fill of any kind for its bars, such as `a:solidFill`,
    /// `a:gradFill` or `a:noFill`; a bar series without one takes its chart style's color.
    fill_written: bool,
    /// Whether its fill is explicitly `a:noFill` (transparent spacer bar or unmarked hidden line).
    no_fill: bool,
    /// Per-point `<c:dPt>` fills read from bar/column series.
    point_fills: Vec<pie::PointFill>,
    /// Its name, as [`series_name`] reads it.
    name: Option<String>,
    /// Its cached values (`c:numCache` of `c:val`), as [`cached_values`] reads them.
    values: CachedValues,
    /// The format code of its cached values (`c:formatCode` of the cache), General without
    /// one.
    format: FormatCode,
    /// The categories of its points, as [`category_texts`] reads them.
    categories: CategoryCache,
    /// Its data labels, as [`label_markup`] reads them.
    labels: LabelMarkup,
}

/// The categories read from a series' `<c:cat>` element.
#[derive(Clone, Debug, PartialEq, Eq)]
enum CategoryCache {
    /// String categories (`c:strRef/c:strCache` or `c:strLit`), each `None` for a blank point.
    Strings(Vec<Option<String>>),
    /// Numeric categories (`c:numRef/c:numCache` or `c:numLit`), with cache `formatCode` and
    /// each point's parsed [`Decimal`] (`None` for a blank point).
    Numbers {
        /// The cache's `c:formatCode` (General when omitted).
        format: FormatCode,
        /// The cached numeric points in index order.
        points: Vec<Option<Decimal>>,
    },
    /// No `<c:cat>` element on the series (Word falls back to 1-based category numbers on
    /// non-scatter charts).
    Omitted,
    /// Multi-level or unreadable categories (`c:multiLvlStrRef`, uncached reference, or
    /// unreadable points).
    Other,
}

/// `ST_BarDir`, which way the bars of a bar chart stand.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BarDirection {
    /// Across the plot area, from the value axis at its side (`bar`).
    Horizontal,
    /// Up the plot area, as columns (`col`).
    Vertical,
}

/// `ST_BarDir` (ECMA-376 Part 1, 21.2.3.3).
const BAR_DIRECTION: &Values<BarDirection> = &Values::new(&[
    own("bar", BarDirection::Horizontal),
    own("col", BarDirection::Vertical),
]);

/// `ST_BarGrouping`, how the bars of a bar chart's series share a category.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BarGrouping {
    /// Side by side (`clustered`), the default.
    Clustered,
    /// One on another (`stacked`).
    Stacked,
    /// One on another, as shares of the category's sum (`percentStacked`).
    PercentStacked,
    /// One behind another, in 3-D (`standard`).
    Standard,
}

/// `ST_BarGrouping` (ECMA-376 Part 1, 21.2.3.4).
const BAR_GROUPING: &Values<BarGrouping> = &Values::new(&[
    own("clustered", BarGrouping::Clustered),
    own("stacked", BarGrouping::Stacked),
    own("percentStacked", BarGrouping::PercentStacked),
    own("standard", BarGrouping::Standard),
]);

/// An axis of a plot area (`c:catAx`, `c:valAx`, `c:dateAx` or `c:serAx`).
struct Axis {
    /// Which axis it is.
    kind: AxisKind,
    /// The axis' identifier (`c:axId`), if written.
    id: Option<String>,
    /// The side of the plot area that it stands at (`c:axPos`), `None` when it does not read.
    place: Option<AxisPlace>,
    /// Whether it draws minor gridlines (`c:minorGridlines`).
    minor_gridlines: bool,
    /// Whether the axis is deleted (`c:delete`), as [`Flag::is_on`] reads it.
    deleted: bool,
    /// Its scale's bounds and direction (`c:scaling`).
    scaling: Scaling,
    /// The distance between two major tick marks (`c:majorUnit`), when the axis sets it.
    major_unit: Option<Decimal>,
    /// Where its labels stand (`c:tickLblPos`).
    labels: LabelPosition,
    /// The size of its labels, in half-points, as [`text_size`] reads it.
    label_size: Option<i64>,
    /// The font of its labels, as [`text_font`] reads it.
    label_font: Option<FontRef>,
    /// The fill of its labels, as [`text_fill`] reads it.
    label_fill: Look<Option<DrawColor>>,
    /// The line of its major gridlines (`c:majorGridlines/c:spPr`), or `None` without them.
    gridlines: Option<ElementLook>,
    /// The line of the axis itself (`c:spPr`).
    line: ElementLook,
    /// Where it draws its major tick marks (`c:majorTickMark`), `None` when it does not say.
    tick_marks: Option<TickMark>,
    /// Where the axis crosses the other axis (`c:crosses` or `c:crossesAt`).
    crosses: Crossing,
    /// The title that the axis shows (`c:title`), as its part writes it.
    title: Option<OwnTitle>,
    /// The number format code of its labels when the axis sets one of its own (`c:numFmt`
    /// whose `sourceLinked` is off), or `None` when it sets none or takes the source's, the
    /// format code of the series' caches.
    own_format: Option<FormatCode>,
}

/// Where an axis crosses the axis that it stands on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Crossing {
    /// At zero, or at the end of the other axis nearer to zero when zero is not on it
    /// (`autoZero`), the default.
    AutoZero,
    /// At the other axis' highest value (`max`).
    Max,
    /// At the other axis' lowest value (`min`).
    Min,
    /// At a value that `c:crossesAt` sets (`None` when the attribute cannot be parsed).
    At(Option<Decimal>),
}

/// `ST_Crosses` of ECMA-376 Part 1.
const CROSSES: &Values<Crossing> = &Values::new(&[
    own("autoZero", Crossing::AutoZero),
    own("max", Crossing::Max),
    own("min", Crossing::Min),
]);

/// Which axis of a plot area an axis is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AxisKind {
    /// A category axis (`c:catAx`).
    Category,
    /// A value axis (`c:valAx`).
    Value,
    /// A date axis (`c:dateAx`).
    Date,
    /// A series axis of a 3-D chart (`c:serAx`).
    Series,
}

/// `ST_AxPos`, the side of the plot area that an axis stands at.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AxisPlace {
    /// Below it (`b`).
    Bottom,
    /// At its left (`l`).
    Left,
    /// At its right (`r`).
    Right,
    /// Above it (`t`).
    Top,
}

/// `ST_AxPos` (ECMA-376 Part 1, 21.2.3.2).
const AXIS_PLACE: &Values<AxisPlace> = &Values::new(&[
    own("b", AxisPlace::Bottom),
    own("l", AxisPlace::Left),
    own("r", AxisPlace::Right),
    own("t", AxisPlace::Top),
]);

/// The elements of a plot area's axes, each with its kind.
const AXES: [(&str, AxisKind); 4] = [
    ("catAx", AxisKind::Category),
    ("valAx", AxisKind::Value),
    ("dateAx", AxisKind::Date),
    ("serAx", AxisKind::Series),
];

/// The scale of an axis (`c:scaling`, ECMA-376 Part 1, 21.2.2.195).
struct Scaling {
    /// The lowest value of the axis (`c:min`), when the axis sets it.
    min: Option<Decimal>,
    /// The highest value of the axis (`c:max`), when the axis sets it.
    max: Option<Decimal>,
    /// The base of a logarithmic scale (`c:logBase`), for a logarithmic axis.
    log_base: Option<Decimal>,
    /// Which way the values run (`c:orientation`).
    orientation: Orientation,
}

/// `ST_Orientation`, which way the values of an axis run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Orientation {
    /// From the lowest value (`minMax`), the default.
    MinMax,
    /// From the highest value (`maxMin`).
    MaxMin,
}

/// `ST_Orientation` (ECMA-376 Part 1, 21.2.3.30).
const ORIENTATION: &Values<Orientation> = &Values::new(&[
    own("minMax", Orientation::MinMax),
    own("maxMin", Orientation::MaxMin),
]);

/// `ST_TickLblPos`, where the labels of an axis stand.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LabelPosition {
    /// At the side of the plot area where the other axis has its highest value (`high`).
    High,
    /// At the side where the other axis has its lowest value (`low`).
    Low,
    /// Next to the axis (`nextTo`), the default.
    NextTo,
    /// Not shown (`none`).
    None,
}

/// `ST_TickLblPos` (ECMA-376 Part 1, 21.2.3.48).
const LABEL_POSITION: &Values<LabelPosition> = &Values::new(&[
    own("high", LabelPosition::High),
    own("low", LabelPosition::Low),
    own("nextTo", LabelPosition::NextTo),
    own("none", LabelPosition::None),
]);

/// `ST_TickMark`, where an axis draws its tick marks.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TickMark {
    /// Across the axis line (`cross`).
    Cross,
    /// Inside the plot area (`in`).
    Inside,
    /// None (`none`).
    None,
    /// Outside the plot area (`out`).
    Outside,
}

/// `ST_TickMark` (ECMA-376 Part 1, 21.2.3.48 to 21.2.3.50, the simple types of the axes).
const TICK_MARK: &Values<TickMark> = &Values::new(&[
    own("cross", TickMark::Cross),
    own("in", TickMark::Inside),
    own("none", TickMark::None),
    own("out", TickMark::Outside),
]);

/// The axes of a chart that draw their major tick marks outside the plot area
/// (`c:majorTickMark val="out"`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct OutsideTicks {
    /// The category axis, which draws them below itself at each edge of a category's band.
    pub category: bool,
    /// The value axis, which draws them left of itself at each label.
    pub value: bool,
}

/// The lines that a drawn chart takes from its elements, each in the look that
/// [`ElementLook::drawn`] gives it.
struct DrawnLines {
    /// The chart area: its outline and its fill.
    area: ShapeLook,
    /// The major gridlines of the value axis, or `None` without them.
    gridlines: Option<ShapeLook>,
    /// The line of the category axis.
    axis: ShapeLook,
    /// The line of the value axis, without a line when the target does not draw it.
    value_axis: ShapeLook,
    /// The axes that draw their tick marks outside.
    ticks: OutsideTicks,
}

/// Parsed chart style metadata from `<c:style>` / `<c14:style>` elements.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct ChartStyleInfo {
    /// Normalized style number (`1..=48`; omitted defaults to `2`).
    pub(super) number: u32,
    /// `true` when the part writes a non-2 Office 2007 `<c:style>` without a `<c14:style>`
    /// override, which draws bare axes and gridlines in untinted `Dark1` (`#000000`).
    pub(super) legacy_lines: bool,
}

/// How bare chart lines (axes and gridlines) are colored under the chart style look.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StyleLineMode {
    /// No style look applied to bare elements.
    None,
    /// Office 2010+ / default style look: `Dark1` tinted to `CHART_STYLE_LINE_TINT` (`#868686`).
    Tinted,
    /// Office 2007 non-2 `<c:style>` without `<c14:style>`: bare axes and gridlines use untinted
    /// `Dark1` (`#000000`), while the chart area border stays tinted.
    LegacyDarkAxes,
}

impl DrawnLines {
    /// The lines of a chart's `area`, of its `category` axis (its line and tick marks) and of
    /// its `value` axis (its gridlines, line and tick marks): each element without properties
    /// in the style look when `style` is active, and the value axis' line and the tick marks only
    /// when the target draws them (`axis_lines`). Their warnings go to `warnings`.
    fn of(
        area: ElementLook,
        category: (ElementLook, Option<TickMark>),
        value: (Option<ElementLook>, ElementLook, Option<TickMark>),
        (axis_lines, style): (bool, StyleLineMode),
        warnings: &mut Warnings<DrawingMlWarning>,
    ) -> Self {
        let mut drawn = |look: ElementLook, fill: Option<DrawColor>| {
            let geometry = if fill.is_some() {
                Geometry::Rect
            } else {
                Geometry::Line
            };
            let look = look.drawn(style, (geometry, fill));
            warnings.extend(look.warnings, std::convert::identity);
            look.value
        };
        let area = drawn(area, Some(DrawColor::scheme(SchemeSlot::Light1)));
        let gridlines = value.0.map(|look| drawn(look, None));
        let axis = drawn(category.0, None);
        let value_axis = if axis_lines {
            drawn(value.1, None)
        } else {
            ShapeLook::plain(Geometry::Line, None, None)
        };
        let outside = |marks: Option<TickMark>| axis_lines && marks == Some(TickMark::Outside);
        Self {
            area,
            gridlines,
            axis,
            value_axis,
            ticks: OutsideTicks {
                category: outside(category.1),
                value: outside(value.2),
            },
        }
    }
}

/// The fills of the properties of a shape (`EG_FillProperties`, ECMA-376 Part 1, 20.1.8).
const FILLS: [&str; 6] = [
    "noFill",
    "solidFill",
    "gradFill",
    "blipFill",
    "pattFill",
    "grpFill",
];

/// The look of a chart element as its properties (`c:spPr`) give it, and whether it has
/// properties: an element without them takes its chart style's look on a target that draws
/// the style look ([`ElementLook::drawn`]).
struct ElementLook {
    /// The look that its properties give, or the look without properties.
    look: Look<ShapeLook>,
    /// Whether the element has properties (`c:spPr`).
    written: bool,
}

impl ElementLook {
    /// The look of an element that draws no line, such as a deleted axis.
    fn none() -> Self {
        Self {
            look: Warned::new(
                ShapeLook::plain(Geometry::Line, None, None),
                Warnings::new(),
            ),
            written: true,
        }
    }

    /// The look that the element draws: its own, or, in the style look (`style`) for an
    /// element without properties, the theme's first line style in the text color tinted to
    /// [`CHART_STYLE_LINE_TINT`] (or untinted `Dark1` for axes/gridlines under
    /// [`StyleLineMode::LegacyDarkAxes`]), filled with `fill` or not filled, as a shape of
    /// `geometry`.
    fn drawn(
        self,
        style: StyleLineMode,
        (geometry, fill): (Geometry, Option<DrawColor>),
    ) -> Look<ShapeLook> {
        if self.written || style == StyleLineMode::None {
            return self.look;
        }
        let color = if fill.is_none() && style == StyleLineMode::LegacyDarkAxes {
            DrawColor::scheme(SchemeSlot::Dark1)
        } else {
            DrawColor::scheme(SchemeSlot::Dark1).tinted(CHART_STYLE_LINE_TINT)
        };
        // The first line style of the theme's format scheme.
        let look = ShapeLook::in_line_style(geometry, fill, (color, 1));
        Warned::new(look, Warnings::new())
    }
}

/// A data table (`c:dTable`) as read from the chart part before resolving against chart text and
/// chart style defaults.
struct DataTableMarkup {
    borders: DataTableBorders,
    keys: bool,
    border: ElementLook,
    size: Option<i64>,
    font: Option<FontRef>,
    fill: Look<Option<DrawColor>>,
    bold: Option<bool>,
    italic: Option<bool>,
}

impl DataTableMarkup {
    /// Reads `<c:dTable>` flags, border look (`c:spPr`), and text properties (`c:txPr`).
    fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let doc = reader.doc;
        let run = default_run(doc, node);
        let run_bool = |name| {
            run.and_then(|r| doc.attribute(r, None, name))
                .map(f_office_drawingml::boolean)
        };
        Self {
            borders: DataTableBorders {
                horz: Flag::of(doc, node, "showHorzBorder").is_on(),
                vert: Flag::of(doc, node, "showVertBorder").is_on(),
                outline: Flag::of(doc, node, "showOutline").is_on(),
            },
            keys: Flag::of(doc, node, "showKeys").is_on(),
            border: line_look(doc, node),
            size: text_size(reader, node),
            font: text_font(doc, node),
            fill: text_fill(doc, node),
            bold: run_bool("b"),
            italic: run_bool("i"),
        }
    }

    /// Resolves `self` against chart text defaults and `style`, appending any look/fill warnings.
    fn resolve(
        self,
        text: &ChartText,
        style: StyleLineMode,
        warnings: &mut Warnings<DrawingMlWarning>,
    ) -> DataTable {
        let border = self.border.drawn(style, (Geometry::Line, None));
        extend_warnings(warnings, [border.warnings, self.fill.warnings]);
        DataTable {
            borders: self.borders,
            keys: self.keys,
            border: border.value,
            text_size: text.size(self.size),
            text_font: text.font(self.font),
            text_fill: self.fill.value,
            bold: self.bold.unwrap_or_else(|| text.bold.unwrap_or(false)),
            italic: self.italic.unwrap_or(false),
        }
    }
}

/// The legend of a chart (`c:legend`).
struct Legend {
    /// Where it stands (`c:legendPos`).
    position: LegendPosition,
    /// The size of its entries, in half-points, as [`text_size`] reads it.
    label_size: Option<i64>,
    /// The font of its entries, as [`text_font`] reads it.
    font: Option<FontRef>,
    /// The fill of its entries, as [`text_fill`] reads it.
    fill: Look<Option<DrawColor>>,
    /// What else its text sets.
    text: LegendText,
    /// Its manual layout (`c:layout`), when it has one.
    layout: Option<ManualLayout>,
}

impl Legend {
    /// Where the legend of the drawn case stands, or why F-Office does not draw it: a legend
    /// at the top right corner.
    fn drawn_place(&self) -> Result<LegendPlace, ChartReason> {
        match self.position {
            LegendPosition::Bottom => Ok(LegendPlace::Bottom),
            LegendPosition::Top => Ok(LegendPlace::Top),
            LegendPosition::Left => Ok(LegendPlace::Left),
            LegendPosition::Right => Ok(LegendPlace::Right),
            LegendPosition::TopRight => Err(ChartReason::LegendTopRight),
        }
    }
}

/// `ST_LegendPos`, where a chart's legend stands.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LegendPosition {
    /// Below the plot area (`b`).
    Bottom,
    /// At the top right corner (`tr`).
    TopRight,
    /// At the left (`l`).
    Left,
    /// At the right (`r`), the default.
    Right,
    /// Above the plot area (`t`).
    Top,
}

/// `ST_LegendPos` (ECMA-376 Part 1, 21.2.3.24).
const LEGEND_POSITION: &Values<LegendPosition> = &Values::new(&[
    own("b", LegendPosition::Bottom),
    own("tr", LegendPosition::TopRight),
    own("l", LegendPosition::Left),
    own("r", LegendPosition::Right),
    own("t", LegendPosition::Top),
]);

impl ChartModel {
    /// Reads a chart part whose plot area holds only bar and line groups, or gives why it has
    /// no model: a part without a plot area, a chart group of another kind, or a bar group
    /// without a direction that reads (`c:barDir`, which the schema requires).
    fn read(reader: &mut PartReader, space: NodeId) -> Result<Self, ChartReason> {
        let doc = reader.doc;
        let plot = doc
            .child(space, C, "chart")
            .and_then(|chart| doc.child(chart, C, "plotArea").map(|plot| (chart, plot)));
        let (chart, plot) = plot.ok_or(ChartReason::NoPlotArea)?;
        let groups: Vec<NodeId> = doc
            .child_elements(plot)
            .filter(|&node| {
                doc.element(node)
                    .is_some_and(|e| e.name.local.ends_with("Chart"))
            })
            .collect();
        let series: Vec<NodeId> = groups
            .iter()
            .flat_map(|&group| doc.child_elements(group).filter(|&n| doc.is(n, C, "ser")))
            .collect();
        let first_name = series.first().and_then(|&first| series_name(doc, first));
        let automatic = AutomaticTitle {
            series: series.len(),
            named: series
                .first()
                .is_some_and(|&first| doc.child(first, C, "tx").is_some()),
            marked: doc.child(chart, C, "autoTitleDeleted").is_some(),
        };
        let groups = groups
            .into_iter()
            .map(|node| Group::read(reader, node, doc.child(chart, C, "view3D")))
            .collect::<Result<Vec<_>, _>>()?;
        let axes: Vec<(NodeId, AxisKind)> = doc
            .child_elements(plot)
            .filter_map(|node| {
                AXES.into_iter()
                    .find(|(name, _)| doc.is(node, C, name))
                    .map(|(_, kind)| (node, kind))
            })
            .collect();
        let axes = axes
            .into_iter()
            .map(|(node, kind)| Axis::read(reader, node, kind))
            .collect();
        let legend = doc.child(chart, C, "legend").map(|legend| Legend {
            position: val_case(reader, legend, "legendPos", LEGEND_POSITION)
                .unwrap_or(LegendPosition::Right),
            label_size: text_size(reader, legend),
            font: text_font(doc, legend),
            fill: text_fill(doc, legend),
            text: LegendText::read(doc, legend),
            layout: doc
                .child(legend, C, "layout")
                .and_then(|layout| doc.child(layout, C, "manualLayout"))
                .map(|manual| ManualLayout::read(reader, manual)),
        });
        let area_props = doc.child(space, C, "spPr");
        let mut warnings = Warnings::new();
        let area = ShapeLook::read(doc, (area_props, None), &mut warnings);
        // F-Office does not draw a picture fill of a chart area, nor its shadow.
        if area.shadow().is_some() {
            warnings.push(DrawingMlWarning::FeatureNotSupported {
                feature: DrawingMlFeature::Shadow,
            });
        }
        warnings.extend(
            picture_fill_warning(doc, area_props),
            std::convert::identity,
        );
        let area = ElementLook {
            look: Warned::new(area, warnings),
            written: area_props.is_some(),
        };
        Ok(Self {
            style: read_style_info(doc, space),
            text: ChartText {
                size: text_size(reader, space),
                font: text_font(doc, space),
                bold: default_run(doc, space)
                    .and_then(|run| doc.attribute(run, None, "b"))
                    .map(f_office_drawingml::boolean),
                styled: style_nodes(doc, space).any(|node| !doc.is(node, C, "style")),
            },
            groups,
            axes,
            legend,
            title: title(reader, chart, (automatic, first_name)),
            plot_layout: doc
                .child(plot, C, "layout")
                .and_then(|layout| doc.child(layout, C, "manualLayout"))
                .map(|manual| ManualLayout::read(reader, manual)),
            data_table: doc
                .child(plot, C, "dTable")
                .map(|table| DataTableMarkup::read(reader, table)),
            blanks: BlankPoints::read(doc, chart),
            area,
        })
    }
}

impl Group {
    /// Reads a chart group, or gives why it has no model: a group other than a bar, line or
    /// scatter chart, or a bar chart without a direction that reads.
    fn read(
        reader: &mut PartReader,
        node: NodeId,
        view: Option<NodeId>,
    ) -> Result<Self, ChartReason> {
        let doc = reader.doc;
        let series: Vec<NodeId> = doc
            .child_elements(node)
            .filter(|&n| doc.is(n, C, "ser"))
            .collect();
        let group_labels = doc.child(node, C, "dLbls");
        if doc.is(node, C, "lineChart") {
            let grouping = match doc
                .child(node, C, "grouping")
                .and_then(|grouping| doc.attribute(grouping, None, "val"))
            {
                None | Some("standard") => Some(BarStacking::Clustered),
                Some("stacked") => Some(BarStacking::Stacked),
                Some("percentStacked") => Some(BarStacking::PercentStacked),
                Some(_) => None,
            };
            let extras = ["dropLines", "hiLowLines", "upDownBars"]
                .iter()
                .any(|name| doc.child(node, C, name).is_some());
            let shows_markers = Flag::of(doc, node, "marker").is_on();
            let settings = series
                .iter()
                .map(|&ser| SeriesLine::read(reader, ser))
                .collect();
            let series = series
                .into_iter()
                .map(|ser| ChartSeries::read(reader, (ser, group_labels), line_of, "val"))
                .collect();
            return Ok(Self::Lines(Lines {
                grouping,
                extras,
                shows_markers,
                series,
                settings,
                ax_ids: axis_ids_of(doc, node),
            }));
        }
        if doc.is(node, C, "scatterChart") {
            return Ok(Self::Scatter(Scatter::read(
                reader,
                node,
                (series, group_labels),
            )));
        }
        if doc.is(node, C, "pieChart") || doc.is(node, C, "pie3DChart") {
            return Ok(Self::Pie(pie::PieGroup::read(
                reader,
                node,
                (series, group_labels),
                view,
            )));
        }
        if doc.is(node, C, "doughnutChart") {
            return Ok(Self::Doughnut(pie::DoughnutGroup::read(
                reader,
                node,
                (series, group_labels),
            )));
        }
        if !doc.is(node, C, "barChart") {
            return Err(ChartReason::OtherGroup);
        }
        let direction =
            val_case(reader, node, "barDir", BAR_DIRECTION).ok_or(ChartReason::NoBarDirection)?;
        let grouping =
            val_case(reader, node, "grouping", BAR_GROUPING).unwrap_or(BarGrouping::Clustered);
        let mut percent = |name: &str, default: i64| {
            read_value(reader, node, name, f_office_drawingml::chart_percent).unwrap_or(default)
        };
        let (gap, overlap) = (
            percent("gapWidth", CHART_GAP_WIDTH),
            percent("overlap", CHART_OVERLAP),
        );
        let uniform_colors = Flag::of(doc, node, "varyColors") == Flag::Off;
        let series = series
            .into_iter()
            .map(|ser| {
                let mut s =
                    ChartSeries::read(reader, (ser, group_labels), |_, props| Some(props), "val");
                s.point_fills = pie::point_fills_of(reader, ser);
                s
            })
            .collect();
        Ok(Self::Bars(Bars {
            direction,
            grouping,
            gap,
            overlap,
            uniform_colors,
            series,
        }))
    }
}

impl Scatter {
    /// Reads the scatter group `node`, whose series are `series` and whose data labels are
    /// `group_labels`.
    fn read(
        reader: &mut PartReader,
        node: NodeId,
        (series, group_labels): (Vec<NodeId>, Option<NodeId>),
    ) -> Self {
        let doc = reader.doc;
        let extras = series.iter().any(|&ser| {
            ["trendline", "errBars"]
                .iter()
                .any(|name| doc.child(ser, C, name).is_some())
        });
        let x_formats = series
            .iter()
            .map(|&ser| cache_format(doc, ser, "xVal"))
            .collect();
        let x_values = series
            .iter()
            .map(|&ser| cached_values(reader, ser, "xVal").full())
            .collect();
        let settings = series
            .iter()
            .map(|&ser| SeriesLine::read(reader, ser))
            .collect();
        let series = series
            .into_iter()
            .map(|ser| ChartSeries::read(reader, (ser, group_labels), line_of, "yVal"))
            .collect();
        Self {
            style: val_case(reader, node, "scatterStyle", SCATTER_STYLE),
            uniform_colors: Flag::of(reader.doc, node, "varyColors") == Flag::Off,
            extras,
            lines: Lines {
                grouping: Some(BarStacking::Clustered),
                extras: false,
                shows_markers: true,
                series,
                settings,
                ax_ids: Vec::new(),
            },
            x_values,
            x_formats,
        }
    }

    /// The group and the series of a drawn case, with the format of the series' cached x
    /// values, General only when every series' is, or why the group is not a drawn case's: a
    /// style other than straight lines and markers, or than smooth lines and markers on a target
    /// that draws smooth lines (`rules`), colors that vary, a trendline or error
    /// bars, a series without an x value for each of its values or with one below zero, or
    /// lines that are not a drawn case's ([`Lines::drawn`]), where a series whose line has no
    /// fill draws its markers alone.
    fn drawn(
        self,
        palette: Option<StylePalette>,
        rules: PlotRules,
    ) -> Result<(ChartGroup, Vec<ChartSeries>, FormatCode), ChartReason> {
        meets([
            (
                match self.style {
                    Some(ScatterStyle::LineMarker) => true,
                    Some(ScatterStyle::SmoothMarker) => rules.draws_smooth_lines(),
                    _ => false,
                },
                ChartReason::ScatterStyle,
            ),
            (self.uniform_colors, ChartReason::VariedColors),
            (!self.extras, ChartReason::SeriesExtras),
        ])?;
        let x_values: Vec<Vec<Decimal>> = self
            .x_values
            .into_iter()
            .collect::<Option<_>>()
            .ok_or(ChartReason::SeriesValues)?;
        meets([
            (
                x_values
                    .iter()
                    .zip(&self.lines.series)
                    .all(|(xs, series)| match &series.values {
                        CachedValues::Points(ys) => ys.len() == xs.len(),
                        CachedValues::Uncached | CachedValues::Unread => true,
                    }),
                ChartReason::SeriesLengths,
            ),
            (
                !x_values.iter().flatten().any(|x| x.digits.is_negative()),
                ChartReason::NegativeValue,
            ),
        ])?;
        let x_format = self
            .x_formats
            .into_iter()
            .find(|format| !format.is_general())
            .unwrap_or_else(FormatCode::general);
        let (looks, _, series) = self.lines.drawn(palette, HiddenLine::MarkersAlone, rules)?;
        Ok((
            ChartGroup::Scatter {
                looks,
                x_values,
                x_scale: SetScale::default(),
            },
            series,
            x_format,
        ))
    }
}

/// The line (`a:ln`) of a line or scatter series' properties `props`, whose solid fill is the
/// series' color.
fn line_of(doc: &Document, props: NodeId) -> Option<NodeId> {
    doc.child(props, A, "ln")
}

impl ChartSeries {
    /// Reads a series `ser` of a group whose data labels are `group_labels`, whose color is
    /// the solid fill of the element that `colored` finds in its properties (`c:spPr`): the
    /// properties themselves for bars, their line for lines, and whose values are in its child
    /// `values`: `c:val`, or `c:yVal` in a scatter group.
    fn read(
        reader: &mut PartReader,
        (ser, group_labels): (NodeId, Option<NodeId>),
        colored: fn(&Document, NodeId) -> Option<NodeId>,
        values: &str,
    ) -> Self {
        let doc = reader.doc;
        let mut warnings = Warnings::new();
        let colored_element = doc
            .child(ser, C, "spPr")
            .and_then(|props| colored(doc, props));
        let fill_written = colored_element.is_some_and(|element| {
            FILLS
                .iter()
                .any(|name| doc.child(element, A, name).is_some())
        });
        let no_fill =
            colored_element.is_some_and(|element| doc.child(element, A, "noFill").is_some());
        let fill = colored_element
            .and_then(|element| doc.child(element, A, "solidFill"))
            .and_then(|solid| DrawColor::read(doc, solid, &mut warnings));
        let gradient = colored_element
            .filter(|_| fill.is_none())
            .and_then(|element| doc.child(element, A, "gradFill"))
            .and_then(|gradient| LinearGradient::read(doc, gradient, &mut warnings));
        let index = read_value(reader, ser, "idx", point_number);
        let format = cache_format(doc, ser, values);
        let labels = label_markup(reader, doc.child(ser, C, "dLbls").or(group_labels), &format);
        Self {
            index,
            fill: Warned::new(fill, warnings),
            gradient,
            fill_written,
            no_fill,
            point_fills: Vec::new(),
            name: series_name(doc, ser),
            values: cached_values(reader, ser, values),
            format,
            categories: category_texts(reader, ser),
            labels,
        }
    }
}

impl SeriesLine {
    /// Reads what the series `ser` of a line chart sets of its line and its points.
    fn read(reader: &mut PartReader, ser: NodeId) -> Self {
        let marker = SeriesMarker::read(reader, ser);
        let doc = reader.doc;
        let styled = doc.child(ser, C, "spPr").is_none();
        let ln = doc
            .child(ser, C, "spPr")
            .and_then(|props| doc.child(props, A, "ln"));
        let width = ln
            .and_then(|ln| doc.attribute(ln, None, "w"))
            .and_then(|w| w.parse::<i64>().ok())
            .and_then(Length::from_emus);
        let ends = ln.map_or(LineEnds::Other, |ln| LineEnds::read(doc, ln));
        let dash = ln.map_or(SeriesDash::Solid, |ln| SeriesDash::read(doc, ln));
        let smooth = Flag::of(doc, ser, "smooth").is_on();
        Self {
            styled,
            width,
            ends,
            dash,
            hidden: ln.is_some_and(|ln| doc.child(ln, A, "noFill").is_some()),
            marker,
            smooth,
        }
    }
}

impl SeriesLine {
    /// The width and the dash with which the target draws this series' line under `rules`, or
    /// why it leaves the group out: under [`PlotRules::fills_line_strokes`], a width, a cap or a
    /// join that the line leaves out is the chart style's, and a preset dash is drawn; else the
    /// line needs its width, round caps, round joins and no dash.
    fn stroke(&self, rules: PlotRules) -> Result<(StyleWidth, Option<LineDash>), ChartReason> {
        let fills = rules.fills_line_strokes();
        let width = match (self.width, fills) {
            (Some(width), _) => StyleWidth::Set(width),
            (None, true) => StyleWidth::Automatic,
            (None, false) => return Err(ChartReason::LineLook),
        };
        let ends = match self.ends {
            LineEnds::Round => true,
            LineEnds::Unwritten => fills,
            LineEnds::Other => false,
        };
        let dash = match self.dash {
            SeriesDash::Solid => None,
            SeriesDash::Preset(dash) if fills => Some(dash),
            SeriesDash::Preset(_) | SeriesDash::Other => return Err(ChartReason::LineLook),
        };
        if ends {
            Ok((width, dash))
        } else {
            Err(ChartReason::LineLook)
        }
    }
}

impl LineEnds {
    /// Reads the cap and the join of the series line `ln`.
    fn read(doc: &Document, ln: NodeId) -> Self {
        let cap = doc.attribute(ln, None, "cap");
        let joins = ["round", "miter", "bevel"].map(|join| doc.child(ln, A, join).is_some());
        match (cap, joins) {
            (Some("rnd"), [true, false, false]) => Self::Round,
            (None | Some("rnd"), [_, false, false]) => Self::Unwritten,
            _ => Self::Other,
        }
    }
}

impl SeriesDash {
    /// Reads the dash of the series line `ln`.
    fn read(doc: &Document, ln: NodeId) -> Self {
        if doc.child(ln, A, "custDash").is_some() {
            return Self::Other;
        }
        doc.child(ln, A, "prstDash")
            .and_then(|dash| doc.attribute(dash, None, "val"))
            .map_or(Self::Solid, |val| {
                PRESET_DASHES
                    .find(val)
                    .map_or(Self::Other, |(dash, _, _)| *dash)
            })
    }
}

impl SeriesMarker {
    /// The marker that the series at `index` in its group draws, whose line is the chart
    /// style's and whose group shows markers as `(styled, shown)` say, with the chart style's
    /// parts for the parts that it leaves out when `fills` holds
    /// ([`PlotRules::fills_marker_looks`]), or why its group is left out: markers that F-Office
    /// does not draw, or the style's symbols of more series than [`AUTOMATIC_SYMBOLS`] holds.
    fn marker(
        &self,
        index: usize,
        (styled, shown): (bool, bool),
        fills: bool,
    ) -> Result<Option<Marker>, ChartReason> {
        let style_symbol = || {
            AUTOMATIC_SYMBOLS
                .get(index)
                .copied()
                .ok_or(ChartReason::StyleColors)
        };
        match self {
            Self::None => Ok(None),
            Self::Styled if styled && shown => Ok(Some(Marker {
                symbol: style_symbol()?,
                size: None,
                fill: None,
                outline: Some(MarkerOutline::STYLE),
            })),
            Self::Drawn { symbol, size, look } => {
                let symbol = match symbol {
                    Some(symbol) => *symbol,
                    None if fills => style_symbol()?,
                    None => return Err(ChartReason::LineMarkers),
                };
                let (fill, outline) = match look {
                    Some(look) => look.parts(fills).ok_or(ChartReason::LineMarkers)?,
                    None if styled || fills => (None, Some(MarkerOutline::STYLE)),
                    None => return Err(ChartReason::LineMarkers),
                };
                Ok(Some(Marker {
                    symbol,
                    size: *size,
                    fill,
                    outline,
                }))
            }
            Self::Styled | Self::Other => Err(ChartReason::LineMarkers),
        }
    }

    /// Reads the `c:marker` of the series `ser`.
    fn read(reader: &mut PartReader, ser: NodeId) -> Self {
        let Some(marker) = reader.doc.child(ser, C, "marker") else {
            return Self::Styled;
        };
        let symbol = match val_case(reader, marker, "symbol", MARKER_SYMBOLS) {
            Some(SymbolCase::Drawn(symbol)) => Some(symbol),
            Some(SymbolCase::Hidden) => return Self::None,
            Some(SymbolCase::Other) => return Self::Other,
            None => None,
        };
        let size = read_value(reader, marker, "size", |v| v.parse::<i64>().ok())
            .and_then(Length::from_points);
        let doc = reader.doc;
        let Some(props) = doc.child(marker, C, "spPr") else {
            return Self::Drawn {
                symbol,
                size,
                look: None,
            };
        };
        let mut warnings = Warnings::new();
        let solid = |doc: &Document, node: NodeId, warnings: &mut Warnings<_>| {
            doc.child(node, A, "solidFill")
                .and_then(|solid| DrawColor::read(doc, solid, warnings))
        };
        let fill = solid(doc, props, &mut warnings);
        let outline = match doc.child(props, A, "ln") {
            None => WrittenOutline::Unwritten,
            Some(ln) if doc.child(ln, A, "noFill").is_some() => WrittenOutline::Hidden,
            Some(ln) => {
                let Some(color) = solid(doc, ln, &mut warnings) else {
                    return Self::Other;
                };
                let width = doc
                    .attribute(ln, None, "w")
                    .and_then(|w| w.parse::<i64>().ok())
                    .and_then(Length::from_emus);
                WrittenOutline::Solid(color, width)
            }
        };
        // Only a solid fill and an outline: no effect, 3-D look or other fill.
        let plain = doc.child_elements(props).all(|child| {
            doc.is(child, A, "solidFill")
                || doc.is(child, A, "ln")
                || doc.is(child, A, "effectLst") && doc.child_elements(child).next().is_none()
        });
        if !plain || !warnings.is_empty() {
            return Self::Other;
        }
        Self::Drawn {
            symbol,
            size,
            look: Some(MarkerLook { fill, outline }),
        }
    }
}

impl Lines {
    /// The look of each series of a drawn case, with the chart style's colors given to the
    /// series that set none, or why the group is not a drawn case's: no series, stacked lines,
    /// drop lines, high-low lines or up-down bars, a smoothed line on a target that does not draw
    /// smooth lines (`rules`, [`PlotRules::draws_smooth_lines`]), a line whose stroke the target
    /// does not draw ([`SeriesLine::stroke`]), markers that F-Office does not draw or that leave
    /// out a part that the target does not fill ([`PlotRules::fills_marker_looks`]), the style's colors in a
    /// group of more than the six [`ACCENTS`], or a series without properties in a chart that
    /// names a chart style other than style 2 (`default_style` false). A series whose line has
    /// no fill draws what `hidden` says; drawing its markers alone, it takes their fill as its
    /// color.
    fn drawn(
        self,
        palette: Option<StylePalette>,
        hidden: HiddenLine,
        rules: PlotRules,
    ) -> Result<(Vec<LineLook>, BarStacking, Vec<ChartSeries>), ChartReason> {
        self.drawn_with(palette, hidden, rules, None)
    }

    /// Resolves a line group, optionally using `(offset, total)` from a combination chart so
    /// bare styled series index into `style_color_for` by `c:idx` across the combined series
    /// count.
    fn drawn_with(
        mut self,
        palette: Option<StylePalette>,
        hidden: HiddenLine,
        rules: PlotRules,
        combo_colors: Option<(usize, usize)>,
    ) -> Result<(Vec<LineLook>, BarStacking, Vec<ChartSeries>), ChartReason> {
        if self.series.is_empty() {
            return Err(ChartReason::NoSeries);
        }
        let stacking = rules
            .bar_stacking(self.grouping)
            .map_err(|_| ChartReason::StackedLines)?;
        meets([
            (!self.extras, ChartReason::LineExtras),
            (
                rules.draws_smooth_lines() || !self.settings.iter().any(|line| line.smooth),
                ChartReason::SmoothLines,
            ),
        ])?;
        let count = self.series.len();
        let mut looks = Vec::with_capacity(count);
        for (index, (line, series)) in self.settings.iter().zip(&mut self.series).enumerate() {
            let (style_index, style_count) = match combo_colors {
                Some((offset, total)) => (series.index.unwrap_or(offset + index), total),
                None => (index, count),
            };
            let (width, dash) = if line.styled {
                let palette = palette.ok_or(ChartReason::ChartStyle)?;
                let color = style_color_for(palette, style_index, style_count)
                    .ok_or(ChartReason::StyleColors)?;
                series.fill = Warned::new(Some(color), Warnings::new());
                (Some(StyleWidth::Automatic), None)
            } else if line.hidden && hidden == HiddenLine::MarkersAlone {
                (None, None)
            } else {
                let (width, dash) = line.stroke(rules)?;
                (Some(width), dash)
            };
            let marker = line.marker.marker(
                style_index,
                (line.styled, self.shows_markers),
                rules.fills_marker_looks(),
            )?;
            if width.is_none() {
                let fill = marker.as_ref().and_then(|marker| {
                    marker
                        .fill
                        .clone()
                        .or_else(|| marker.outline.as_ref().and_then(|o| o.color.clone()))
                });
                series.fill = Warned::new(fill, Warnings::new());
                series.no_fill = series.fill.value.is_none() && marker.is_none();
            }
            let form = if line.smooth {
                LineForm::Smooth
            } else {
                LineForm::Straight
            };
            looks.push(LineLook {
                width,
                marker,
                form,
                dash,
            });
        }
        Ok((looks, stacking, self.series))
    }
}

/// The series/slice color palette of a supported Office chart style (`1..=8`, `17..=24`,
/// `25..=32` and their Office 2010 `c14:style` counterparts `101..=108`, `117..=124`, `125..=132`,
/// plus omitted style = style 2).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StylePalette {
    /// Column 0 (`1, 17, 25`): monochrome `dk1` cycling [`CHART_STYLE_DARK_TINTS`] across cycles
    /// of six with the lightness ramp.
    DarkMono,
    /// Column 1 (`2, 18, 26`, or omitted): colorful six-accent cycle (`ACCENTS`) across cycles of
    /// six with the lightness ramp.
    Colorful,
    /// Columns 2–7 (`3..=8, 19..=24, 27..=32`): single theme accent stepped linearly across all
    /// items with the lightness ramp.
    AccentMono(SchemeSlot),
}

impl StylePalette {
    /// Resolves a normalized Office chart style number (`1..=48`) into its color palette when the
    /// target supports that style. Without `draws_style_look`, only style 2 resolves (`Colorful`).
    /// Under `draws_style_look`, flat white-background rows 0, 2, and 3 (`1..=8`, `17..=24`,
    /// `25..=32`) resolve by column `(n - 1) % 8`.
    pub(super) fn of(style_number: Option<u32>, draws_style_look: bool) -> Option<Self> {
        let number = style_number?;
        if !draws_style_look {
            return (number == 2).then_some(Self::Colorful);
        }
        let zero_based = number.checked_sub(1)?;
        if !CHART_STYLE_FLAT_ROWS.contains(&(zero_based / CHART_STYLE_COLUMNS)) {
            return None;
        }
        match zero_based % CHART_STYLE_COLUMNS {
            0 => Some(Self::DarkMono),
            1 => Some(Self::Colorful),
            col => ACCENTS
                .get(usize::try_from(col - 2).ok()?)
                .copied()
                .map(Self::AccentMono),
        }
    }
}

/// Applies the linear-light shade/tint step `step` (whole percent around 100%) to `color`.
fn apply_style_step(color: DrawColor, step: i64) -> DrawColor {
    match step.cmp(&PERCENT) {
        std::cmp::Ordering::Less => color.shaded(step * THOUSANDTHS),
        std::cmp::Ordering::Equal => color,
        std::cmp::Ordering::Greater => color.tinted((2 * PERCENT - step) * THOUSANDTHS),
    }
}

/// Whole-percent step `floor + 2 * (100 - floor) * (index + 1) / (count + 1)` across `count`
/// ramp slots (`floor = CHART_STYLE_SHADE_FLOOR = 30`).
fn style_ramp_step(index: usize, count: usize) -> Option<i64> {
    let idx = i64::try_from(index).ok()?;
    let total = i64::try_from(count).ok()?;
    let span = 2 * (PERCENT - CHART_STYLE_SHADE_FLOOR);
    Some(CHART_STYLE_SHADE_FLOOR + span.checked_mul(idx + 1)? / (total + 1))
}

/// The color that `palette` gives item `index` of a group of `count` items (series or slices).
pub(super) fn style_color_for(
    palette: StylePalette,
    index: usize,
    count: usize,
) -> Option<DrawColor> {
    if count == 0 {
        return None;
    }
    let accents = ACCENTS.len();
    match palette {
        StylePalette::Colorful => {
            let slot = *ACCENTS.get(index % accents)?;
            let step = style_ramp_step(index / accents, count / accents + 1)?;
            Some(apply_style_step(DrawColor::scheme(slot), step))
        }
        StylePalette::DarkMono => {
            let tint = *CHART_STYLE_DARK_TINTS.get(index % accents)?;
            let base = DrawColor::scheme(SchemeSlot::Dark1).tinted(tint * THOUSANDTHS);
            let step = style_ramp_step(index / accents, count / accents + 1)?;
            Some(apply_style_step(base, step))
        }
        StylePalette::AccentMono(slot) => {
            let step = style_ramp_step(index, count)?;
            Some(apply_style_step(DrawColor::scheme(slot), step))
        }
    }
}

/// The color that chart style 2 gives item `index` of a group of `count` items.
#[cfg(test)]
fn style_color(index: usize, count: usize) -> Option<DrawColor> {
    style_color_for(StylePalette::Colorful, index, count)
}

/// Reads the normalized Office chart style (`1..=48`) and legacy-line flag from `space`:
/// `c:style` takes `1..=48`, Office 2010 `c14:style` takes `101..=148` (mapped to `1..=48`), and
/// an omitted style defaults to `2`. Returns `None` if any style node is out of range or two
/// nodes disagree.
fn read_style_info(doc: &Document, space: NodeId) -> Option<ChartStyleInfo> {
    let mut found: Option<u32> = None;
    let mut has_c14 = false;
    let mut has_plain = false;
    for node in style_nodes(doc, space) {
        let raw = doc.attribute(node, None, "val")?.parse::<u32>().ok()?;
        let normalized = if doc.is(node, C, "style") {
            has_plain = true;
            (1..=CHART_STYLE_MAX).contains(&raw).then_some(raw)?
        } else {
            has_c14 = true;
            raw.checked_sub(CHART_STYLE_C14_OFFSET)
                .filter(|n| (1..=CHART_STYLE_MAX).contains(n))?
        };
        if let Some(prev) = found
            && prev != normalized
        {
            return None;
        }
        found = Some(normalized);
    }
    let number = found.unwrap_or(2);
    Some(ChartStyleInfo {
        number,
        legacy_lines: has_plain && !has_c14 && number != 2,
    })
}

/// The elements that name the chart style of the chart space `space`: its `style` children and
/// those of the branches of its `mc:AlternateContent`, in any namespace.
fn style_nodes(doc: &Document, space: NodeId) -> impl Iterator<Item = NodeId> + '_ {
    let alternates = doc
        .child_elements(space)
        .filter(|&node| {
            doc.element(node)
                .is_some_and(|e| e.name.local == "AlternateContent")
        })
        .flat_map(|alternate| doc.child_elements(alternate))
        .flat_map(|branch| doc.child_elements(branch));
    doc.child_elements(space)
        .chain(alternates)
        .filter(|&node| doc.element(node).is_some_and(|e| e.name.local == "style"))
}

/// The theme's accents, which the chart's style gives its series in turn.
const ACCENTS: [SchemeSlot; 6] = [
    SchemeSlot::Accent1,
    SchemeSlot::Accent2,
    SchemeSlot::Accent3,
    SchemeSlot::Accent4,
    SchemeSlot::Accent5,
    SchemeSlot::Accent6,
];

impl Axis {
    /// Reads an axis of the kind `kind`.
    fn read(reader: &mut PartReader, node: NodeId, kind: AxisKind) -> Self {
        let doc = reader.doc;
        let scaling = doc.child(node, C, "scaling");
        let mut bound =
            |name: &str| scaling.and_then(|s| read_value(reader, s, name, Decimal::parse));
        let (min, max, log_base) = (bound("min"), bound("max"), bound("logBase"));
        let orientation = scaling
            .and_then(|s| val_case(reader, s, "orientation", ORIENTATION))
            .unwrap_or(Orientation::MinMax);
        Self {
            kind,
            id: value(doc, node, "axId").map(str::to_owned),
            place: val_case(reader, node, "axPos", AXIS_PLACE),
            minor_gridlines: doc.child(node, C, "minorGridlines").is_some(),
            deleted: Flag::of(doc, node, "delete").is_on(),
            scaling: Scaling {
                min,
                max,
                log_base,
                orientation,
            },
            major_unit: read_value(reader, node, "majorUnit", Decimal::parse),
            labels: val_case(reader, node, "tickLblPos", LABEL_POSITION)
                .unwrap_or(LabelPosition::NextTo),
            label_size: text_size(reader, node),
            label_font: text_font(doc, node),
            label_fill: text_fill(doc, node),
            gridlines: doc
                .child(node, C, "majorGridlines")
                .map(|lines| line_look(doc, lines)),
            line: line_look(doc, node),
            tick_marks: val_case(reader, node, "majorTickMark", TICK_MARK),
            crosses: if doc.child(node, C, "crossesAt").is_some() {
                Crossing::At(read_value(reader, node, "crossesAt", Decimal::parse))
            } else {
                val_case(reader, node, "crosses", CROSSES).unwrap_or(Crossing::AutoZero)
            },
            title: doc
                .child(node, C, "title")
                .map(|title| shown_title(reader, title, OwnText::Undrawn)),
            own_format: own_format(doc, node),
        }
    }
}

impl ManualLayout {
    /// Reads a manual layout.
    fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let target =
            val_case(reader, node, "layoutTarget", LAYOUT_TARGET).unwrap_or(LayoutTarget::Outer);
        let mut mode =
            |name: &str| val_case(reader, node, name, LAYOUT_MODE).unwrap_or(LayoutMode::Factor);
        let (modes, size_modes) = (
            [mode("xMode"), mode("yMode")],
            [mode("wMode"), mode("hMode")],
        );
        let edges = ["x", "y", "w", "h"].map(|name| read_value(reader, node, name, Decimal::parse));
        Self {
            target,
            modes,
            size_modes,
            edges,
        }
    }

    /// The box `x`, `y`, `w` and `h` in the edge mode, whose width and height count as parts of
    /// the chart's size and are above zero, or `None` for any other layout.
    fn edge_box(&self) -> Option<LayoutBox> {
        if self.modes != [LayoutMode::Edge; 2] || self.size_modes != [LayoutMode::Factor; 2] {
            return None;
        }
        let [x, y, w, h] = self.edges;
        Some(LayoutBox {
            x: x?,
            y: y?,
            w: w.filter(|w| w.is_positive())?,
            h: h.filter(|h| h.is_positive())?,
        })
    }

    /// The box of a plot area in the edge mode ([`Self::edge_box`]), or `None` for any other
    /// layout.
    fn plot_layout(&self) -> Option<PlotLayout> {
        Some(PlotLayout {
            inner: self.target == LayoutTarget::Inner,
            edges: self.edge_box()?,
        })
    }

    /// The top left corner `x` and `y` in the edge mode of a layout that sets no width and no
    /// height, the layout of a title, or `None` for any other layout.
    fn corner(&self) -> Option<LayoutCorner> {
        let [x, y, w, h] = self.edges;
        if self.modes != [LayoutMode::Edge; 2] || w.is_some() || h.is_some() {
            return None;
        }
        Some(LayoutCorner { x: x?, y: y? })
    }

    /// The box of a legend: [`LegendBox::Manual`] in the edge mode ([`Self::edge_box`]), else
    /// [`LegendBox::Other`].
    fn legend_box(&self) -> LegendBox {
        self.edge_box().map_or(LegendBox::Other, LegendBox::Manual)
    }
}

/// Where a plot area of the manual layout `layout` stands: automatic without one, the layout's
/// box in the edge mode ([`ManualLayout::plot_layout`]), and another place for any other layout.
fn plot_place(layout: Option<&ManualLayout>) -> PlotPlace {
    layout.map_or(PlotPlace::Automatic, |manual| {
        manual
            .plot_layout()
            .map_or(PlotPlace::Other, PlotPlace::Manual)
    })
}

impl Part {
    /// The part that F-Office can draw of a chart, with the warnings of its looks: one
    /// clustered column chart (a bar group with `c:barDir val="col"` and `c:grouping
    /// val="clustered"`) with one category axis and one value axis that are both shown with
    /// their labels next to them, the value axis running from its lowest value without a
    /// logarithm, with a major unit above zero and a set minimum below a set maximum, series
    /// with a solid fill and cached values for every category, not all zero, and labels of one
    /// size on both axes and in the legend. The legend stands at the bottom, the top, the left
    /// or the right, or the chart has none; and the chart's own title is shown, or the
    /// automatic one is deleted. Any other chart gives the reason of the first of these
    /// conditions that it does not meet. Which of these charts a target draws, and which rule
    /// places its plot area, its quirk `ChartPlotArea` says ([`PlotRules::rule`]). On a target
    /// that draws the style look (`rules`, [`PlotRules::draws_style_look`]), a chart that names
    /// no chart style or style 2 draws its elements without properties in that look, and
    /// every chart draws its value axis' line and its tick marks outside the axes. A chart that
    /// shows a data table, which F-Office does not draw, gives [`ChartReason::DataTable`] when
    /// it meets every other condition.
    fn of(chart: ChartModel, rules: PlotRules) -> Result<Look<Self>, ChartReason> {
        let (axis_lines, line_palette, style_palette, style) =
            chart_style_modes(chart.style, rules);
        let DrawnGroup {
            mut group,
            series: drawn_series,
            vary_by_category,
            x_format,
            line_ax_ids,
        } = drawn_group(chart.groups, (line_palette, style_palette), rules)?;
        let (category_axis, value_axis, secondary_val_axis, axis_text) =
            drawn_axes(chart.axes, &chart.text, (&group, &line_ax_ids, rules))?;
        set_scatter_x_scale(&mut group, &category_axis);
        let legend = drawn_legend(chart.legend, &chart.text)?;
        group_limits(x_format.as_ref(), &category_axis)?;
        let mut warnings = Warnings::new();
        let secondary_axis = build_secondary_axis(
            secondary_val_axis,
            (&group, &drawn_series),
            (&chart.text, rules, axis_lines, style),
            &mut warnings,
        )?;
        let title = drawn_title(chart.title, rules, &chart.text, &mut warnings)?;
        let plot_place = plot_place(chart.plot_layout.as_ref());
        let category_crossing =
            category_crossing(&group, (category_axis.crosses, value_axis.crosses), rules);
        let value_format = value_format(&group, &value_axis, &drawn_series, rules);
        let first_categories = first_categories(&group, &drawn_series);
        let series = drawn_series_of(
            drawn_series,
            vary_by_category,
            ((&group, chart.blanks), rules, &chart.text, style_palette),
            &mut warnings,
        )?;
        let (categories, data_table) = resolve_categories_and_data_table(
            &series,
            chart.data_table,
            (axis_lines, plot_place, &group, &chart.text, style),
            &mut warnings,
        )?;
        let category_names = category_names(
            first_categories,
            category_axis.own_format.as_ref(),
            categories,
            rules,
        );
        extend_warnings(
            &mut warnings,
            [legend.fill.warnings, axis_text.titles.warnings],
        );
        let scale = SetScale {
            min: value_axis.scaling.min,
            max: value_axis.scaling.max,
            major_unit: value_axis.major_unit,
        };
        let (lines, category_label_fill, value_label_fill) = drawn_lines(
            chart.area,
            (category_axis, value_axis),
            (axis_lines, style),
            &mut warnings,
        );
        let part = Self {
            area: lines.area,
            columns: Columns {
                other_labels: series.iter().any(|s| s.labels == SeriesLabels::Other),
                series,
                categories,
                group,
                title,
                legend: legend.place,
                legend_box: legend.layout,
                label_size: axis_text.size,
                legend_size: legend.size,
                value_label_size: axis_text.value_size,
                font: axis_text.font,
                gridlines: lines.gridlines,
                axis: lines.axis,
                value_axis: lines.value_axis,
                ticks: lines.ticks,
                plot_place,
                scale,
                category_crossing,
                axis_titles: axis_text.titles.value,
                value_format,
                category_names,
                value_label_fill,
                category_label_fill,
                legend_font: legend.font,
                legend_fill: legend.fill.value,
                legend_text: legend.text,
                axis_forms: axis_text.forms,
                secondary_axis,
                data_table,
            },
        };
        Ok(Warned::new(part, warnings))
    }
}

/// Resolves style-look flags, palettes, and line mode for `style` under `rules`.
fn chart_style_modes(
    style: Option<ChartStyleInfo>,
    rules: PlotRules,
) -> (
    bool,
    Option<StylePalette>,
    Option<StylePalette>,
    StyleLineMode,
) {
    let axis_lines = rules.draws_style_look();
    let line_palette = StylePalette::of(style.map(|s| s.number), axis_lines);
    let style_palette = axis_lines.then_some(line_palette).flatten();
    let mode = match (style_palette, style) {
        (Some(_), Some(info)) if info.legacy_lines => StyleLineMode::LegacyDarkAxes,
        (Some(_), _) => StyleLineMode::Tinted,
        (None, _) => StyleLineMode::None,
    };
    (axis_lines, line_palette, style_palette, mode)
}

/// Validates category count and resolves `data_table` when supported on the target and chart group.
fn resolve_categories_and_data_table(
    series: &[Series],
    data_table: Option<DataTableMarkup>,
    (axis_lines, plot_place, group, text, style): (
        bool,
        PlotPlace,
        &ChartGroup,
        &ChartText,
        StyleLineMode,
    ),
    warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<(usize, Option<Box<DataTable>>), ChartReason> {
    let supported = axis_lines
        && matches!(
            plot_place,
            PlotPlace::Automatic | PlotPlace::Manual(PlotLayout { inner: true, .. })
        )
        && matches!(
            group,
            ChartGroup::Columns { .. } | ChartGroup::Lines { .. } | ChartGroup::Combo { .. }
        );
    let categories = categories_of(series, data_table.is_some() && !supported)?;
    let resolved = data_table.map(|table| Box::new(table.resolve(text, style, warnings)));
    Ok((categories, resolved))
}

/// Appends each warning list in `extras` onto `warnings`.
fn extend_warnings<const N: usize>(
    warnings: &mut Warnings<DrawingMlWarning>,
    extras: [Warnings<DrawingMlWarning>; N],
) {
    for extra in extras {
        warnings.extend(extra, std::convert::identity);
    }
}

/// Resolves the chart area, axis, gridline, tick strokes, and axis label fills for the primary axes.
fn drawn_lines(
    area: ElementLook,
    (category_axis, value_axis): (Axis, Axis),
    (axis_lines, style): (bool, StyleLineMode),
    warnings: &mut Warnings<DrawingMlWarning>,
) -> (DrawnLines, Option<DrawColor>, Option<DrawColor>) {
    extend_warnings(
        warnings,
        [
            value_axis.label_fill.warnings,
            category_axis.label_fill.warnings,
        ],
    );
    let (value_line, value_ticks) =
        shown_axis_line(value_axis.deleted, value_axis.line, value_axis.tick_marks);
    let cat_line = shown_axis_line(
        category_axis.deleted,
        category_axis.line,
        category_axis.tick_marks,
    );
    let lines = DrawnLines::of(
        area,
        cat_line,
        (value_axis.gridlines, value_line, value_ticks),
        (axis_lines, style),
        warnings,
    );
    (
        lines,
        category_axis.label_fill.value,
        value_axis.label_fill.value,
    )
}

/// Copies the scatter x-axis explicit bounds and major unit from `axis` into `group`.
const fn set_scatter_x_scale(group: &mut ChartGroup, axis: &Axis) {
    if let ChartGroup::Scatter { x_scale, .. } = group {
        *x_scale = SetScale {
            min: axis.scaling.min,
            max: axis.scaling.max,
            major_unit: axis.major_unit,
        };
    }
}

/// Resolves `category_crossing` for `group` from the written `(category, value)` axis crossings.
/// Scatter charts use a numeric x-axis and keep only automatic crossings.
fn category_crossing(
    group: &ChartGroup,
    (category, value): (Crossing, Crossing),
    rules: PlotRules,
) -> Option<CategoryCrossing> {
    if matches!(group, ChartGroup::Scatter { .. }) {
        return matches!((category, value), (Crossing::AutoZero, Crossing::AutoZero))
            .then_some(CategoryCrossing::AutoZero);
    }
    rules.category_crossing(category, value)
}

/// The chart's own title as a drawn case holds it, with its fill warnings added to `warnings`,
/// or [`ChartReason::UnknownTitle`] when the part holds a title that F-Office does not draw.
fn drawn_title(
    title: TitleState,
    rules: PlotRules,
    text: &ChartText,
    warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<Option<Title>, ChartReason> {
    let decided = title
        .known()
        .ok_or(ChartReason::UnknownTitle)?
        .shown()
        .map(|own| own.decided(rules, text))
        .transpose()?;
    Ok(decided.map(|title| {
        warnings.extend(title.warnings, std::convert::identity);
        title.value
    }))
}

/// The titles of a drawn case's axes from the titles `category` and `value` that they show,
/// in a chart whose text is `text`, with the warnings of the drawn titles' fills added to
/// `warnings`. Where the chart takes axis titles (`titled_group`: a chart of columns or lines
/// on a target that draws them, [`PlotRules::draws_axis_titles`]), each title in a form that
/// F-Office draws ([`OwnTitle::axis_title`]) is drawn: the value axis' turned upward and the
/// category axis' upright. Any other title gives [`AxisTitles::Other`], and so does a title of
/// a value axis that is deleted (`value_deleted`).
fn axis_titles(
    (category, value): (Option<OwnTitle>, Option<OwnTitle>),
    (titled_group, swapped, value_deleted): (bool, bool, bool),
    text: &ChartText,
    warnings: &mut Warnings<DrawingMlWarning>,
) -> AxisTitles {
    if category.is_none() && value.is_none() {
        return AxisTitles::NONE;
    }
    if !titled_group || (value_deleted && value.is_some()) {
        return AxisTitles::Other;
    }
    let mut drawn = |title: Option<OwnTitle>, turn| match title {
        None => Some(None),
        Some(title) => title
            .axis_title(turn, text, warnings)
            .map(|title| Some(Box::new(title))),
    };
    let (value_turn, category_turn) = if swapped {
        (TitleTurn::Upright, TitleTurn::Upward)
    } else {
        (TitleTurn::Upward, TitleTurn::Upright)
    };
    match (drawn(value, value_turn), drawn(category, category_turn)) {
        (Some(value), Some(category)) => AxisTitles::Drawn { value, category },
        _ => AxisTitles::Other,
    }
}

/// The number of categories of the drawn chart's `series`, or why it is not drawn: no series,
/// series of other lengths, values that are all zero, or a data table (`data_table`), which
/// F-Office does not draw.
fn categories_of(series: &[Series], data_table: bool) -> Result<usize, ChartReason> {
    let categories = series.first().ok_or(ChartReason::NoSeries)?.values.len();
    meets([
        (
            series.iter().all(|s| s.values.len() == categories),
            ChartReason::SeriesLengths,
        ),
        (
            series
                .iter()
                .flat_map(|s| s.values.iter().flatten())
                .any(|v| v.digits != 0),
            ChartReason::AllZero,
        ),
        // The last reason, so that a chart's other reasons show first.
        (!data_table, ChartReason::DataTable),
    ])?;
    Ok(categories)
}

/// Why a drawn scatter chart is not drawn: its x labels, with the format of its series' cached x
/// values `x_format` and the x axis `x_axis`, are not in General, the axis' own format or else
/// the caches'.
fn group_limits(x_format: Option<&FormatCode>, x_axis: &Axis) -> Result<(), ChartReason> {
    let general =
        x_format.is_none_or(|format| x_axis.own_format.as_ref().unwrap_or(format).is_general());
    meets([(general, ChartReason::OtherNumberFormat)])
}

/// The legend of a drawn case as [`Columns`] holds it.
struct DrawnLegend {
    /// Where it stands, or `None` without a legend.
    place: Option<LegendPlace>,
    /// The size of its names, in half-points.
    size: i64,
    /// The font of its names.
    font: FontRef,
    /// The fill of its names.
    fill: Look<Option<DrawColor>>,
    /// What else its text sets.
    text: LegendText,
    /// The box that its entries stand in.
    layout: LegendBox,
}

/// The group of a drawn case with its series ([`drawn_group`]).
struct DrawnGroup {
    /// What the plot area draws of the series.
    group: ChartGroup,
    /// The series, in their order.
    series: Vec<ChartSeries>,
    /// Per-point own fills for a single-series bar/column chart whose colors vary by category.
    /// Whether a single-series bar/column chart varies its bar colors by category from the style
    /// palette (`BarColorMode::ByCategory`).
    vary_by_category: bool,
    /// The format code of the series' cached x values of a scatter group, General only when
    /// every series' is; `None` for another group.
    x_format: Option<FormatCode>,
    /// Axis IDs referenced by the line group of a combination chart.
    line_ax_ids: Vec<String>,
}

/// The group of a drawn case with its series, or why `groups` are not a drawn case's: not one
/// group, horizontal bars, bars that are not clustered, lines that are not a drawn case's
/// ([`Lines::drawn`]), scatter points on a target that does not draw them (`rules`,
/// [`PlotRules::draws_scatter`]) or that are not a drawn case's ([`Scatter::drawn`]).
fn drawn_group(
    groups: Vec<Group>,
    (line_palette, style_palette): (Option<StylePalette>, Option<StylePalette>),
    rules: PlotRules,
) -> Result<DrawnGroup, ChartReason> {
    let hidden_line = if rules.draws_style_look() {
        HiddenLine::MarkersAlone
    } else {
        HiddenLine::NoColor
    };
    let bars = match <[Group; 1]>::try_from(groups) {
        Ok([Group::Bars(bars)]) => bars,
        Ok([Group::Lines(lines)]) => {
            let (looks, stacking, series) = lines.drawn(line_palette, hidden_line, rules)?;
            return Ok(DrawnGroup {
                group: ChartGroup::Lines { looks, stacking },
                series,
                vary_by_category: false,
                x_format: None,
                line_ax_ids: Vec::new(),
            });
        }
        Ok([Group::Scatter(scatter)]) => {
            if !rules.draws_scatter() {
                return Err(ChartReason::Scatter);
            }
            let (group, series, x_format) = scatter.drawn(line_palette, rules)?;
            return Ok(DrawnGroup {
                group,
                series,
                vary_by_category: false,
                x_format: Some(x_format),
                line_ax_ids: Vec::new(),
            });
        }
        // Pies and doughnuts have their own drawn cases ([`pie::part`], [`pie::doughnut_part`]).
        Ok([Group::Pie(_) | Group::Doughnut(_)]) => return Err(ChartReason::OtherGroup),
        Err(groups) => return drawn_combo(groups, (line_palette, style_palette), rules),
    };
    if bars.direction != BarDirection::Vertical && !rules.draws_horizontal_bars() {
        return Err(ChartReason::HorizontalBars);
    }
    let stacking = rules.bar_stacking(match bars.grouping {
        BarGrouping::Clustered => Some(BarStacking::Clustered),
        BarGrouping::Stacked => Some(BarStacking::Stacked),
        BarGrouping::PercentStacked => Some(BarStacking::PercentStacked),
        BarGrouping::Standard => None,
    })?;
    let (gap, overlap) = (bars.gap, bars.overlap);
    let group = match bars.direction {
        BarDirection::Vertical => ChartGroup::Columns {
            gap,
            overlap,
            stacking,
        },
        // quirk: ChartHorizontalBars::Turned (src/quirks.rs)
        BarDirection::Horizontal => ChartGroup::Bars {
            gap,
            overlap,
            stacking,
        },
    };
    let mut series = bars.series;
    // In the style look, a series without a fill of its own takes the chart style's color of
    // its place (or per-category colors for a single-series bar chart whose colors vary).
    let vary_by_category = if let Some(palette) = style_palette {
        match rules.bar_color_mode(bars.uniform_colors, series.len()) {
            BarColorMode::BySeries => {
                let count = series.len();
                for (index, one) in series.iter_mut().enumerate() {
                    if !one.fill_written {
                        let color = style_color_for(palette, index, count)
                            .ok_or(ChartReason::StyleColors)?;
                        one.fill = Warned::new(Some(color), Warnings::new());
                    }
                }
                false
            }
            BarColorMode::ByCategory => true,
            BarColorMode::None => false,
        }
    } else {
        false
    };
    Ok(DrawnGroup {
        group,
        series,
        vary_by_category,
        x_format: None,
        line_ax_ids: Vec::new(),
    })
}

/// Resolves a two-group shared-axis combination chart (`c:barChart` vertical columns +
/// `c:lineChart` standard lines) under `rules`, returning `ChartReason::NotOneGroup` for any
/// other multi-group plot area or when the target does not draw combination charts.
fn drawn_combo(
    groups: Vec<Group>,
    (line_palette, style_palette): (Option<StylePalette>, Option<StylePalette>),
    rules: PlotRules,
) -> Result<DrawnGroup, ChartReason> {
    let Ok([Group::Bars(bars), Group::Lines(lines)] | [Group::Lines(lines), Group::Bars(bars)]) =
        <[Group; 2]>::try_from(groups)
    else {
        return Err(ChartReason::NotOneGroup);
    };
    if bars.direction != BarDirection::Vertical {
        return Err(ChartReason::NotOneGroup);
    }
    let stacking = rules.bar_stacking(match bars.grouping {
        BarGrouping::Clustered => Some(BarStacking::Clustered),
        BarGrouping::Stacked => Some(BarStacking::Stacked),
        BarGrouping::PercentStacked | BarGrouping::Standard => {
            return Err(ChartReason::NotOneGroup);
        }
    })?;
    let bar_count = bars.series.len();
    let total = bar_count + lines.series.len();
    if bar_count == 0 {
        return Err(ChartReason::NoSeries);
    }
    let mut series = bars.series;
    if let Some(palette) = style_palette {
        for (index, one) in series.iter_mut().enumerate() {
            if !one.fill_written {
                let slot = one.index.unwrap_or(index);
                let color =
                    style_color_for(palette, slot, total).ok_or(ChartReason::StyleColors)?;
                one.fill = Warned::new(Some(color), Warnings::new());
            }
        }
    }
    let line_ax_ids = lines.ax_ids.clone();
    let hidden_line = if rules.draws_style_look() {
        HiddenLine::MarkersAlone
    } else {
        HiddenLine::NoColor
    };
    let (looks, line_stacking, line_series) =
        lines.drawn_with(line_palette, hidden_line, rules, Some((bar_count, total)))?;
    if line_stacking == BarStacking::PercentStacked {
        return Err(ChartReason::StackedLines);
    }
    let group = rules.combo_group(
        (bars.gap, bars.overlap, stacking),
        bar_count,
        (looks, line_stacking),
    )?;
    series.extend(line_series);
    Ok(DrawnGroup {
        group,
        series,
        vary_by_category: false,
        x_format: None,
        line_ax_ids,
    })
}

/// Resolves the painted fill of one series (`ChartSeries`) in `group`.
fn resolve_series_fill(
    (fill, gradient, fill_written, no_fill, point_fills): (
        Look<Option<DrawColor>>,
        Option<LinearGradient>,
        bool,
        bool,
        Vec<pie::PointFill>,
    ),
    (is_bar, vary_by_category, single_series, count): (bool, bool, bool, usize),
    (rules, palette): (PlotRules, Option<StylePalette>),
    warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<SeriesFill, ChartReason> {
    if vary_by_category
        && !fill_written
        && let Some(palette) = palette
    {
        return Ok(SeriesFill::Points(pie::slice_fills(
            fill,
            point_fills,
            (count, pie::SliceStyle::ByPoint(palette)),
            warnings,
        )?));
    }
    let styled = rules.draws_style_look();
    if styled && is_bar && pie::has_bar_point_override(&point_fills, count, gradient.is_some()) {
        return pie::resolve_bar_point_fills(
            fill,
            no_fill,
            point_fills,
            (count, single_series),
            warnings,
        );
    }
    warnings.extend(fill.warnings, std::convert::identity);
    match (fill.value, gradient) {
        (Some(color), _) => Ok(SeriesFill::Color(color)),
        (None, Some(gradient)) if is_bar => Ok(SeriesFill::Gradient(gradient)),
        (None, None) if styled && no_fill => Ok(SeriesFill::None),
        _ => Err(ChartReason::SeriesFill),
    }
}

/// The drawn series of a chart's `series` in the chart group `group`, which shows its blank
/// points as `blanks`: each with its fill, its values ([`CachedValues::drawn`]), its name and its
/// value labels as a column group or a line group draws them in the chart's `text`, or the
/// reason of the first series without a fill or without its values. A series without a cache
/// is blank at each category of the first series with one. A series of a column group without
/// a solid fill takes its gradient; a line takes no gradient. The warnings of their fills and
/// labels go to `warnings`.
fn drawn_series_of(
    series: Vec<ChartSeries>,
    vary_by_category: bool,
    ((group, blanks), rules, text, palette): (
        (&ChartGroup, BlankPoints),
        PlotRules,
        &ChartText,
        Option<StylePalette>,
    ),
    warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<Vec<Series>, ChartReason> {
    let single_series = series.len() == 1;
    let mut drawn = Vec::with_capacity(series.len());
    for (
        series_index,
        ChartSeries {
            fill,
            gradient,
            fill_written,
            no_fill,
            point_fills,
            name,
            values,
            labels,
            ..
        },
    ) in series.into_iter().enumerate()
    {
        let is_bar = match group {
            ChartGroup::Columns { .. } | ChartGroup::Bars { .. } => true,
            ChartGroup::Combo { bar_count, .. } => series_index < *bar_count,
            ChartGroup::Lines { .. }
            | ChartGroup::Scatter { .. }
            | ChartGroup::Pie { .. }
            | ChartGroup::Doughnut { .. } => false,
        };
        let drawn_at = drawn_label_positions(group, is_bar);
        let labels = labels.drawn((drawn_at, false, rules), text, warnings);
        let values = values.drawn((group.has_blank_points(), blanks), rules)?;
        let fill = resolve_series_fill(
            (fill, gradient, fill_written, no_fill, point_fills),
            (
                is_bar,
                vary_by_category && series_index == 0,
                single_series,
                values.len(),
            ),
            (rules, palette),
            warnings,
        )?;
        drawn.push(Series {
            fill,
            values,
            name,
            labels,
        });
    }
    Ok(drawn)
}

/// Data label positions supported for a series in `group` (`is_bar` distinguishes bar series
/// from line series in a combo chart).
const fn drawn_label_positions(group: &ChartGroup, is_bar: bool) -> &'static [DataLabelPosition] {
    if is_bar {
        match group.stacking() {
            Some(BarStacking::Clustered) => &COLUMN_LABEL_POSITIONS,
            Some(BarStacking::Stacked | BarStacking::PercentStacked) => &STACKED_LABEL_POSITIONS,
            None => &[],
        }
    } else if matches!(group, ChartGroup::Lines { .. } | ChartGroup::Combo { .. }) {
        &LINE_LABEL_POSITIONS
    } else {
        &[]
    }
}

/// The legend of a drawn case whose chart text is `text`, or why it is not a drawn case's
/// ([`Legend::drawn_place`]): no place without a legend, and the chart text's size and font when
/// the legend names none.
fn drawn_legend(legend: Option<Legend>, text: &ChartText) -> Result<DrawnLegend, ChartReason> {
    let Some(legend) = legend else {
        return Ok(DrawnLegend {
            place: None,
            size: text.size(None),
            font: text.font(None),
            fill: Warned::new(None, Warnings::new()),
            text: LegendText::default(),
            layout: LegendBox::Automatic,
        });
    };
    Ok(DrawnLegend {
        place: Some(legend.drawn_place()?),
        size: text.size(legend.label_size),
        font: text.font(legend.font),
        fill: legend.fill,
        text: legend.text,
        layout: legend
            .layout
            .as_ref()
            .map_or(LegendBox::Automatic, ManualLayout::legend_box),
    })
}

/// The text of a drawn case's axis labels and the forms of its axes, as [`drawn_axes`] gives
/// them.
struct AxisText {
    /// The size of the category axis' labels, in half-points.
    size: i64,
    /// The size of the value axis' labels, in half-points.
    value_size: i64,
    /// The font of the labels.
    font: FontRef,
    /// The forms of the axes.
    forms: AxisForms,
    /// The titles of the axes ([`axis_titles`]).
    titles: Look<AxisTitles>,
}

/// The axis across and the value axis of a drawn case whose group is `group`, with the size
/// of each axis' labels and their font, their own or else the chart text's `text`
/// ([`ChartText::size`], [`ChartText::font`]): the font is the value axis', and when the value
/// axis is deleted both size and font are the category axis'. With the forms of the axes that
/// the target draws under the plot rules `rules` ([`axis_forms`]). Or why `axes` are not those
/// of a drawn case: not one category axis and one value axis, or for a scatter group not its x
/// axis and its value axis ([`x_and_y`]), an axis that the target does not draw in its form, or
/// a scale of the value axis that F-Office does not draw.
fn drawn_axes(
    axes: Vec<Axis>,
    text: &ChartText,
    (group, line_ax_ids, rules): (&ChartGroup, &[String], PlotRules),
) -> Result<(Axis, Axis, Option<Axis>, AxisText), ChartReason> {
    let (mut category_axis, mut value_axis, secondary_axis) = match group {
        ChartGroup::Scatter { .. } => {
            let (x, y) = x_and_y(axes)?;
            (x, y, None)
        }
        ChartGroup::Combo { .. } if axes.len() > 2 => combo_secondary_axes(axes, line_ax_ids)?,
        ChartGroup::Columns { .. }
        | ChartGroup::Bars { .. }
        | ChartGroup::Lines { .. }
        | ChartGroup::Combo { .. } => {
            let (cat, val) = category_and_value(axes).ok_or(ChartReason::Axes)?;
            (cat, val, None)
        }
        // Pies and doughnuts have no axes and their own drawn cases.
        ChartGroup::Pie { .. } | ChartGroup::Doughnut { .. } => return Err(ChartReason::Axes),
    };
    let forms = axis_forms((&category_axis, &value_axis), group, rules)?;
    check_value_scale(&value_axis)?;
    if let Some(sec) = &secondary_axis {
        check_value_scale(sec)?;
    }
    let size = text.size(category_axis.label_size);
    // A deleted value axis draws no labels, so that its text sets nothing.
    let (value_size, font) = if forms.value_deleted {
        (size, text.font(category_axis.label_font.clone()))
    } else {
        (
            text.size(value_axis.label_size),
            text.font(value_axis.label_font.clone()),
        )
    };
    let titled_group = rules.draws_axis_titles()
        && matches!(
            group,
            ChartGroup::Columns { .. }
                | ChartGroup::Bars { .. }
                | ChartGroup::Lines { .. }
                | ChartGroup::Scatter { .. }
                | ChartGroup::Combo { .. }
        );
    let swapped = matches!(group, ChartGroup::Bars { .. });
    let mut warnings = Warnings::new();
    let titles = axis_titles(
        (category_axis.title.take(), value_axis.title.take()),
        (titled_group, swapped, forms.value_deleted),
        text,
        &mut warnings,
    );
    let axis_text = AxisText {
        size,
        value_size,
        font,
        forms,
        titles: Warned::new(titles, warnings),
    };
    Ok((category_axis, value_axis, secondary_axis, axis_text))
}

/// Validates a value axis' scale bounds, orientation, and major unit.
fn check_value_scale(axis: &Axis) -> Result<(), ChartReason> {
    let scaling = &axis.scaling;
    meets([(
        scaling.log_base.is_none()
            && scaling.orientation == Orientation::MinMax
            && axis.major_unit.is_none_or(Decimal::is_positive)
            && scaling
                .min
                .zip(scaling.max)
                .is_none_or(|(min, max)| min < max),
        ChartReason::ValueScale,
    )])
}

/// Resolves the 4 axes of a combination chart with a secondary right value axis: primary
/// `(catAx b, valAx l)` for the column group, plus secondary `(deleted catAx b/t, valAx r)`
/// referenced by `line_ax_ids`.
fn combo_secondary_axes(
    axes: Vec<Axis>,
    line_ax_ids: &[String],
) -> Result<(Axis, Axis, Option<Axis>), ChartReason> {
    let (mut pri_cat, mut pri_val, mut sec_cat, mut sec_val) = (None, None, None, None);
    for axis in axes {
        match (axis.kind, axis.place, axis.deleted) {
            (AxisKind::Category, Some(AxisPlace::Bottom), false) if pri_cat.is_none() => {
                pri_cat = Some(axis);
            }
            (AxisKind::Category, Some(AxisPlace::Bottom | AxisPlace::Top), true)
                if sec_cat.is_none() =>
            {
                sec_cat = Some(axis);
            }
            (AxisKind::Value, Some(AxisPlace::Left), _) if pri_val.is_none() => {
                pri_val = Some(axis);
            }
            (AxisKind::Value, Some(AxisPlace::Right), _) if sec_val.is_none() => {
                sec_val = Some(axis);
            }
            _ => return Err(ChartReason::Axes),
        }
    }
    let (Some(pri_cat), Some(pri_val), Some(_sec_cat), Some(sec_val)) =
        (pri_cat, pri_val, sec_cat, sec_val)
    else {
        return Err(ChartReason::Axes);
    };
    let line_uses_sec = sec_val
        .id
        .as_ref()
        .is_some_and(|id| line_ax_ids.iter().any(|ref_id| ref_id == id));
    if !line_uses_sec || sec_val.minor_gridlines || sec_val.gridlines.is_some() {
        return Err(ChartReason::Axes);
    }
    if sec_val.title.is_some() {
        return Err(ChartReason::AxisTitle);
    }
    Ok((pri_cat, pri_val, Some(sec_val)))
}

/// Reads all `<c:axId val="..."/>` identifiers referenced by a chart group node.
fn axis_ids_of(doc: &Document, node: NodeId) -> Vec<String> {
    doc.child_elements(node)
        .filter(|&n| doc.is(n, C, "axId"))
        .filter_map(|n| doc.attribute(n, None, "val").map(str::to_owned))
        .collect()
}

/// Builds a [`SecondaryValueAxis`] from the optional parsed secondary right `valAx`.
fn build_secondary_axis(
    sec: Option<Axis>,
    (group, series): (&ChartGroup, &[ChartSeries]),
    (text, rules, axis_lines, style): (&ChartText, PlotRules, bool, StyleLineMode),
    warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<Option<Box<SecondaryValueAxis>>, ChartReason> {
    let Some(sec) = sec else {
        return Ok(None);
    };
    let labels_hidden = sec.deleted || sec.labels == LabelPosition::None;
    if !labels_hidden && sec.labels != LabelPosition::NextTo {
        return Err(ChartReason::AxisNotShown);
    }
    let bar_count = match *group {
        ChartGroup::Combo { bar_count, .. } => bar_count,
        _ => 0,
    };
    let line_series = series.get(bar_count..).unwrap_or_default();
    let format =
        value_format(group, &sec, line_series, rules).ok_or(ChartReason::OtherNumberFormat)?;
    let (sec_line, sec_ticks) = shown_axis_line(sec.deleted, sec.line, sec.tick_marks);
    let line = if axis_lines {
        let drawn = sec_line.drawn(style, (Geometry::Line, None));
        warnings.extend(drawn.warnings, std::convert::identity);
        drawn.value
    } else {
        ShapeLook::plain(Geometry::Line, None, None)
    };
    warnings.extend(sec.label_fill.warnings, std::convert::identity);
    Ok(Some(Box::new(SecondaryValueAxis {
        scale: SetScale {
            min: sec.scaling.min,
            max: sec.scaling.max,
            major_unit: sec.major_unit,
        },
        format,
        label_size: text.size(sec.label_size),
        label_fill: sec.label_fill.value,
        line,
        ticks: axis_lines && sec_ticks == Some(TickMark::Outside),
        labels_hidden,
    })))
}

/// The line and tick marks of an axis, omitted when the axis is deleted (`c:delete val="1"`).
fn shown_axis_line(
    deleted: bool,
    line: ElementLook,
    ticks: Option<TickMark>,
) -> (ElementLook, Option<TickMark>) {
    if deleted {
        (ElementLook::none(), None)
    } else {
        (line, ticks)
    }
}

/// The forms of a drawn case's axes `category` and `value` in its group `group` under the plot
/// rules `rules`, or [`ChartReason::AxisNotShown`] for an axis that is deleted or whose labels
/// stand elsewhere than next to it, besides deleted or `none`-labeled axes under
/// [`PlotRules::draws_deleted_axis`] and `low` category labels under
/// [`PlotRules::draws_low_labels`].
fn axis_forms(
    (category, value): (&Axis, &Axis),
    group: &ChartGroup,
    rules: PlotRules,
) -> Result<AxisForms, ChartReason> {
    let allow_hidden = rules.draws_deleted_axis();
    let forms = AxisForms {
        value_deleted: (value.deleted || value.labels == LabelPosition::None)
            && !matches!(group, ChartGroup::Scatter { .. })
            && allow_hidden,
        category_hidden: (category.deleted || category.labels == LabelPosition::None)
            && allow_hidden,
        low_labels: !category.deleted
            && category.labels == LabelPosition::Low
            && matches!(
                group,
                ChartGroup::Columns { .. }
                    | ChartGroup::Bars { .. }
                    | ChartGroup::Lines { .. }
                    | ChartGroup::Combo { .. }
            )
            && rules.draws_low_labels(),
    };
    let category_shown = forms.category_hidden
        || (!category.deleted && (category.labels == LabelPosition::NextTo || forms.low_labels));
    let value_shown =
        forms.value_deleted || (!value.deleted && value.labels == LabelPosition::NextTo);
    meets([(category_shown && value_shown, ChartReason::AxisNotShown)])?;
    Ok(forms)
}

/// The x axis and the value axis of a scatter group's `axes`: its two value axes, the one below
/// the plot area (`c:axPos val="b"`) and the one at its left (`l`), or why not: another set of
/// axes, an x axis that draws gridlines, or one that sets its scale (its bounds, its major
/// unit, a logarithm or the other direction).
fn x_and_y(axes: Vec<Axis>) -> Result<(Axis, Axis), ChartReason> {
    let [first, second] = <[Axis; 2]>::try_from(axes).map_err(|_| ChartReason::ScatterAxes)?;
    let (x, y) = match (first.place, second.place) {
        (Some(AxisPlace::Bottom), Some(AxisPlace::Left)) => (first, second),
        (Some(AxisPlace::Left), Some(AxisPlace::Bottom)) => (second, first),
        _ => return Err(ChartReason::ScatterAxes),
    };
    let scaling = &x.scaling;
    meets([
        (
            x.kind == AxisKind::Value && y.kind == AxisKind::Value,
            ChartReason::ScatterAxes,
        ),
        (
            x.gridlines.is_none() && !x.minor_gridlines,
            ChartReason::XGridlines,
        ),
        (
            scaling.log_base.is_none()
                && scaling.orientation == Orientation::MinMax
                && x.major_unit.is_none_or(Decimal::is_positive)
                && scaling.min.is_none_or(|min| !min.digits.is_negative())
                && scaling.max.is_none_or(Decimal::is_positive)
                && scaling
                    .min
                    .zip(scaling.max)
                    .is_none_or(|(min, max)| min < max),
            ChartReason::ValueScale,
        ),
    ])?;
    Ok((x, y))
}

/// The one category axis and the one value axis of `axes`, or `None` when it has another
/// number of either.
fn category_and_value(axes: Vec<Axis>) -> Option<(Axis, Axis)> {
    let (mut category, mut value) = (None, None);
    for axis in axes {
        let slot = match axis.kind {
            AxisKind::Category => &mut category,
            AxisKind::Value => &mut value,
            AxisKind::Date | AxisKind::Series => continue,
        };
        if slot.replace(axis).is_some() {
            return None;
        }
    }
    Some((category?, value?))
}

/// The line of a chart element (`a:ln` of its `c:spPr`), as a shape whose geometry is a line,
/// with the warnings of its reading, and whether the element has properties.
fn line_look(doc: &Document, node: NodeId) -> ElementLook {
    let mut warnings = Warnings::new();
    let props = doc.child(node, C, "spPr");
    let look = ShapeLook::read_line(doc, props, &mut warnings);
    ElementLook {
        look: Warned::new(look, warnings),
        written: props.is_some(),
    }
}

/// The `val` attribute of a child of `node`, such as `c:barDir`.
fn value<'a>(doc: &'a Document, node: NodeId, name: &str) -> Option<&'a str> {
    doc.child(node, C, name)
        .and_then(|child| doc.attribute(child, None, "val"))
}

/// The case of the `val` attribute of the child `name` of `node`, such as `c:legendPos`, as
/// the simple type's table `table` reads it: `None` when the child or its value is missing,
/// and when the value is no name of the type, with a warning that it counts as missing.
fn val_case<T: Clone>(
    reader: &mut PartReader,
    node: NodeId,
    name: &str,
    table: &'static Values<T>,
) -> Option<T> {
    let child = reader.doc.child(node, C, name)?;
    reader.enumeration_in(child, (None, "val"), table)
}

/// The `val` attribute of the child `name` of `node`, such as `c:gapWidth`, read by `parse`: a
/// value that does not read counts as missing, with a warning.
fn read_value<T>(
    reader: &mut PartReader,
    node: NodeId,
    name: &str,
    parse: impl FnOnce(&str) -> Option<T>,
) -> Option<T> {
    let child = reader.doc.child(node, C, name)?;
    reader.or_missing_in(child, (None, "val"), parse)
}

/// The name of a series (`c:tx`): the first cached point of its cell reference
/// (`c:strRef/c:strCache`), or its own text (`c:v`).
fn series_name(doc: &Document, ser: NodeId) -> Option<String> {
    let tx = doc.child(ser, C, "tx")?;
    let value = match doc.child(tx, C, "strRef") {
        Some(reference) => {
            let cache = doc.child(reference, C, "strCache")?;
            let point = doc
                .child_elements(cache)
                .find(|&n| doc.is(n, C, "pt") && doc.attribute(n, None, "idx") == Some("0"))?;
            doc.child(point, C, "v")?
        }
        None => doc.child(tx, C, "v")?,
    };
    Some(doc.text_content(value))
}

/// A count or an index of a chart's points (`xsd:unsignedInt`), as [`f_office_drawingml::integer`]
/// reads it.
fn point_number(value: &str) -> Option<usize> {
    usize::try_from(f_office_drawingml::integer(value)?).ok()
}

/// The label format of the value labels of a chart whose value axis is `axis` and whose series
/// are `series` under `rules`: the axis' own, else the first series' cache format (or General
/// without series), or `None` when the target does not write the format.
fn value_format(
    group: &ChartGroup,
    axis: &Axis,
    series: &[ChartSeries],
    rules: PlotRules,
) -> Option<LabelFormat> {
    let place = LabelPlace::ValueAxis;
    if let Some(own) = &axis.own_format {
        return own.decided(rules, place);
    }
    let percent_default = matches!(group.line_stacking(), Some(BarStacking::PercentStacked));
    series.first().map_or_else(
        || {
            if percent_default {
                FormatCode("0%".to_owned()).decided(rules, place)
            } else {
                FormatCode::general().decided(rules, place)
            }
        },
        |first| {
            if percent_default && first.format.is_general() {
                FormatCode("0%".to_owned()).decided(rules, place)
            } else {
                first.format.decided(rules, place)
            }
        },
    )
}

/// The number format code that an axis sets for its labels (`c:numFmt`), or `None` when it sets
/// none or takes the source's (`sourceLinked` on). A format without its format code gives an
/// empty code, which no target writes.
fn own_format(doc: &Document, axis: NodeId) -> Option<FormatCode> {
    let format = doc.child(axis, C, "numFmt")?;
    let linked = doc
        .attribute(format, None, "sourceLinked")
        .and_then(crate::on_off::read)
        .unwrap_or(false);
    if linked {
        return None;
    }
    Some(FormatCode(
        doc.attribute(format, None, "formatCode")
            .unwrap_or_default()
            .to_owned(),
    ))
}

/// The format code of a series' cached values (`c:formatCode` of the `c:numCache` of its child
/// `values`, such as `c:val`): General without one. Only line breaks are trimmed so trailing
/// literal spaces (such as `0.0\ \ `) stay intact.
fn cache_format(doc: &Document, ser: NodeId, values: &str) -> FormatCode {
    doc.child(ser, C, values)
        .and_then(|val| doc.child(val, C, "numRef"))
        .and_then(|num| doc.child(num, C, "numCache"))
        .and_then(|cache| doc.child(cache, C, "formatCode"))
        .map_or_else(FormatCode::general, |code| {
            FormatCode(doc.text_content(code).trim_matches(['\r', '\n']).to_owned())
        })
}

/// The cached values of a series (`c:numCache` of its child `values`, such as `c:val`), as
/// [`CachedValues`] tells them apart.
fn cached_values(reader: &mut PartReader, ser: NodeId, values: &str) -> CachedValues {
    let doc = reader.doc;
    let Some(reference) = doc
        .child(ser, C, values)
        .and_then(|val| doc.child(val, C, "numRef"))
    else {
        return CachedValues::Unread;
    };
    let Some(cache) = doc.child(reference, C, "numCache") else {
        return CachedValues::Uncached;
    };
    cached_points(reader, cache, Decimal::parse).map_or(CachedValues::Unread, CachedValues::Points)
}

/// The categories of a series (`c:cat`): string points (`c:strRef/c:strCache` or `c:strLit`),
/// numeric points (`c:numRef/c:numCache` or `c:numLit` with their `c:formatCode`),
/// [`CategoryCache::Omitted`] without `c:cat`, or [`CategoryCache::Other`] for multi-level,
/// uncached, or unreadable categories.
fn category_texts(reader: &mut PartReader, ser: NodeId) -> CategoryCache {
    let doc = reader.doc;
    let Some(categories) = doc.child(ser, C, "cat") else {
        return CategoryCache::Omitted;
    };
    if let Some(cache) = doc
        .child(categories, C, "strRef")
        .and_then(|reference| doc.child(reference, C, "strCache"))
        .or_else(|| doc.child(categories, C, "strLit"))
    {
        return cached_points(reader, cache, |text| Some(text.to_owned()))
            .map_or(CategoryCache::Other, CategoryCache::Strings);
    }
    if let Some(cache) = doc
        .child(categories, C, "numRef")
        .and_then(|reference| doc.child(reference, C, "numCache"))
        .or_else(|| doc.child(categories, C, "numLit"))
    {
        let format = doc
            .child(cache, C, "formatCode")
            .map_or_else(FormatCode::general, |code| {
                FormatCode(doc.text_content(code).trim_matches(['\r', '\n']).to_owned())
            });
        return cached_points(reader, cache, Decimal::parse).map_or(
            CategoryCache::Other,
            |points| CategoryCache::Numbers { format, points },
        );
    }
    CategoryCache::Other
}

/// The points of a cache of a chart's data (`c:numCache`, `c:strCache` or their literal forms),
/// each read with `parse`, one for each index below the cache's count, `None` at an index
/// without a point (a blank point); `None` for a cache without a count, a count above
/// [`MAX_CHART_POINTS`], or a point whose index or value does not read.
fn cached_points<T: Clone>(
    reader: &mut PartReader,
    cache: NodeId,
    parse: impl Fn(&str) -> Option<T>,
) -> Option<Vec<Option<T>>> {
    let doc = reader.doc;
    let points = read_value(reader, cache, "ptCount", point_number)?;
    // The count sets the size of the vector, so a count above the limit gives no points.
    if points > MAX_CHART_POINTS {
        return None;
    }
    let mut values = vec![None; points];
    for point in doc.child_elements(cache).filter(|&n| doc.is(n, C, "pt")) {
        let index = reader.or_missing_in(point, (None, "idx"), point_number)?;
        let text = doc.child(point, C, "v").map(|v| doc.text_content(v))?;
        *values.get_mut(index)? = Some(parse(&text)?);
    }
    Some(values)
}

/// The values of a series as its part caches them (`c:numCache` of its `c:val`, or of another
/// values element such as `c:yVal`).
#[derive(Clone, Debug, PartialEq, Eq)]
enum CachedValues {
    /// A value for each index below the cache's count, `None` at an index whose point the cache
    /// leaves out (a blank point), as [`cached_points`] reads them.
    Points(Vec<Option<Decimal>>),
    /// A reference without a cache (`c:numRef` without `c:numCache`).
    Uncached,
    /// Values that F-Office does not read: no reference (such as values of the series' own,
    /// `c:numLit`), or a cache that [`cached_points`] does not read.
    Unread,
}

impl CachedValues {
    /// The values when the cache holds one for each index below its count.
    fn full(&self) -> Option<Vec<Decimal>> {
        match self {
            Self::Points(points) => points.iter().copied().collect(),
            Self::Uncached | Self::Unread => None,
        }
    }

    /// The values of a drawn series in a chart that shows its blank points as `blanks`, one
    /// for each category, `None` at a blank point that draws nothing. On a target that draws
    /// blank points (`rules`, [`PlotRules::draws_blank_points`]), a blank point of a chart
    /// group that has them (`blank_group`, [`ChartGroup::has_blank_points`]) is a gap or the
    /// value zero; any other blank point, a series without a cache, a blank point that a line
    /// spans, and values that F-Office does not read give [`ChartReason::SeriesValues`].
    fn drawn(
        self,
        (blank_group, blanks): (bool, BlankPoints),
        rules: PlotRules,
    ) -> Result<Vec<Option<Decimal>>, ChartReason> {
        let points = match self {
            Self::Points(points) if points.iter().all(Option::is_some) => return Ok(points),
            Self::Points(points) => points,
            Self::Uncached | Self::Unread => return Err(ChartReason::SeriesValues),
        };
        if !rules.draws_blank_points() || !blank_group {
            return Err(ChartReason::SeriesValues);
        }
        match blanks {
            BlankPoints::Gap => Ok(points),
            BlankPoints::Zero => Ok(points
                .into_iter()
                .map(|point| Some(point.unwrap_or(Decimal::ZERO)))
                .collect()),
            BlankPoints::Span => Err(ChartReason::SeriesValues),
        }
    }
}

/// How a chart shows the blank points of its series (`c:dispBlanksAs` of `c:chart`, ECMA-376
/// Part 1, 21.2.2.42).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BlankPoints {
    /// `gap`: a blank point draws nothing.
    Gap,
    /// `zero`: a blank point draws as the value zero.
    Zero,
    /// `span`: a line joins the points beside a blank point.
    Span,
}

impl BlankPoints {
    /// How the chart `chart` (`c:chart`) shows its blank points: as its `c:dispBlanksAs` says,
    /// and as zero, the attribute's default, without the element or its value, or for a value
    /// that the schema does not name.
    fn read(doc: &Document, chart: NodeId) -> Self {
        match doc
            .child(chart, C, "dispBlanksAs")
            .and_then(|node| doc.attribute(node, None, "val"))
        {
            Some("gap") => Self::Gap,
            Some("span") => Self::Span,
            _ => Self::Zero,
        }
    }
}

/// The names of a drawn chart's categories from the texts of its first series' categories
/// `texts`, each `None` for a category whose text the cache leaves out: on a target that draws
/// blank points (`rules`, [`PlotRules::draws_blank_points`]), such a category takes an empty
/// name; elsewhere a chart with one has no names.
/// The first series' category cache for non-scatter chart groups (`None` for scatter charts).
fn first_categories(group: &ChartGroup, series: &[ChartSeries]) -> Option<CategoryCache> {
    if matches!(group, ChartGroup::Scatter { .. }) {
        return None;
    }
    series.first().map(|first| first.categories.clone())
}

/// The category names drawn for `cache` over `count` categories under `rules`, using
/// `axis_own` (`c:catAx/c:numFmt` with `sourceLinked="0"`) over a numeric cache's own
/// `c:formatCode` when present.
fn category_names(
    cache: Option<CategoryCache>,
    axis_own: Option<&FormatCode>,
    count: usize,
    rules: PlotRules,
) -> Option<Vec<String>> {
    let names = match cache? {
        CategoryCache::Strings(texts) => string_category_names(texts, rules)?,
        CategoryCache::Numbers { format, points } => {
            let code = axis_own.unwrap_or(&format);
            let label_format = code.decided(rules, LabelPlace::CategoryAxis)?;
            numeric_category_names(points, &label_format, rules)?
        }
        CategoryCache::Omitted => {
            FormatCode::general().decided(rules, LabelPlace::CategoryAxis)?;
            (1..=count).map(|index| index.to_string()).collect()
        }
        CategoryCache::Other => return None,
    };
    (names.len() == count).then_some(names)
}

/// Resolves string category points into strings, turning blank points into empty strings when
/// `rules` draws blank points.
fn string_category_names(texts: Vec<Option<String>>, rules: PlotRules) -> Option<Vec<String>> {
    if rules.draws_blank_points() {
        Some(texts.into_iter().map(Option::unwrap_or_default).collect())
    } else {
        texts.into_iter().collect()
    }
}

/// Formats numeric category points with `format`, turning blank points into empty strings when
/// `rules` draws blank points and leaving out labels whose format sets a section color.
fn numeric_category_names(
    points: Vec<Option<Decimal>>,
    format: &LabelFormat,
    rules: PlotRules,
) -> Option<Vec<String>> {
    let blanks = rules.draws_blank_points();
    points
        .into_iter()
        .map(|point| match point {
            Some(value) => plain_written(&format.write(value)?),
            None if blanks => Some(String::new()),
            None => None,
        })
        .collect()
}

/// Flattens a `WrittenLabel` without a section color into plain text (mapping space-wide blanks
/// to ASCII spaces).
fn plain_written(written: &WrittenLabel) -> Option<String> {
    if written.color.is_some() {
        return None;
    }
    let mut out = String::new();
    for piece in &written.pieces {
        match piece {
            LabelPiece::Text(text) => out.push_str(text),
            LabelPiece::Blank(_) => out.push(' '),
        }
    }
    Some(out)
}

/// The size of the text of a chart element (`a:defRPr sz` of its `c:txPr`), in half-points.
fn text_size(reader: &mut PartReader, node: NodeId) -> Option<i64> {
    let hundredths = default_run(reader.doc, node)
        .and_then(|run| reader.or_missing_in(run, (None, "sz"), f_office_drawingml::integer))?;
    Some(hundredths * HALF_POINTS_PER_POINT / PERCENT)
}

/// The fill of the text of a chart element (`a:solidFill` of its `a:defRPr`), or `None` when it
/// sets none.
fn text_fill(doc: &Document, node: NodeId) -> Look<Option<DrawColor>> {
    let mut warnings = Warnings::new();
    let fill = default_run(doc, node)
        .and_then(|run| doc.child(run, A, "solidFill"))
        .and_then(|solid| DrawColor::read(doc, solid, &mut warnings));
    Warned::new(fill, warnings)
}

/// The font of the text of a chart element (`a:latin` of its `a:defRPr`).
fn text_font(doc: &Document, node: NodeId) -> Option<FontRef> {
    let latin = default_run(doc, node).and_then(|run| doc.child(run, A, "latin"))?;
    doc.attribute(latin, None, "typeface")
        .map(FontRef::of_typeface)
}

/// The default run properties of a chart element's text (`c:txPr/a:p/a:pPr/a:defRPr`).
fn default_run(doc: &Document, node: NodeId) -> Option<NodeId> {
    let text = doc.child(node, C, "txPr")?;
    let paragraph = doc.child(text, A, "p")?;
    let props = doc.child(paragraph, A, "pPr")?;
    doc.child(props, A, "defRPr")
}

/// The chart's title: shown when the chart has a `c:title` and does not delete its automatic
/// title (`c:autoTitleDeleted`, read as [`Flag::is_on`] reads it), deleted when it deletes its
/// automatic title and has no `c:title`, the automatic title of a chart whose series are as
/// `automatic` says when it has neither, and else unknown. A shown title's lines are the
/// paragraphs of its own text (`c:rich`), or one line for an automatic title. `series` gives
/// the automatic title and the cached name of the chart's first series.
fn title(
    reader: &mut PartReader,
    chart: NodeId,
    series: (AutomaticTitle, Option<String>),
) -> TitleState {
    let doc = reader.doc;
    let deleted = Flag::of(doc, chart, "autoTitleDeleted").is_on();
    let (automatic, first_name) = series;
    let series = TitleSeries {
        automatic,
        first_name,
    };
    match doc.child(chart, C, "title") {
        None if deleted => TitleState::Deleted,
        None => TitleState::Automatic(automatic),
        Some(node) if !deleted => TitleState::Shown(Box::new(shown_title(
            reader,
            node,
            OwnText::Placeholder(series),
        ))),
        _ => TitleState::Unknown,
    }
}

/// A title (`c:title`) of a chart or an axis: its lines, what its places write, its text, the
/// corner of its manual layout and its turn. F-Office does not draw the text of a title that
/// overlaps the plot area or whose manual layout gives no corner ([`ManualLayout::corner`]); a
/// title without text of its own (`c:tx`) has the text `placeholder`: the target's placeholder
/// for a chart's series, or none.
fn shown_title(reader: &mut PartReader, node: NodeId, placeholder: OwnText) -> OwnTitle {
    let doc = reader.doc;
    let rich = doc
        .child(node, C, "tx")
        .and_then(|tx| doc.child(tx, C, "rich"));
    let paragraphs: Vec<NodeId> = rich.map_or_default(|rich| {
        doc.child_elements(rich)
            .filter(|&n| doc.is(n, A, "p"))
            .collect()
    });
    let mut warnings = Warnings::new();
    let mut place = |props: Option<NodeId>| {
        props.map_or_default(|props| TitleProps::read(reader, props, &mut warnings))
    };
    let first_run = paragraphs
        .iter()
        .flat_map(|&p| doc.child_elements(p).filter(|&n| doc.is(n, A, "r")))
        .find_map(|r| doc.child(r, A, "rPr"));
    let paragraph_default = paragraphs
        .first()
        .and_then(|&p| doc.child(p, A, "pPr"))
        .and_then(|props| doc.child(props, A, "defRPr"));
    let places = [
        place(first_run),
        place(paragraph_default),
        place(default_run(doc, node)),
    ];
    let layout = doc
        .child(node, C, "layout")
        .and_then(|layout| doc.child(layout, C, "manualLayout"))
        .map(|manual| ManualLayout::read(reader, manual));
    let corner = layout.as_ref().and_then(ManualLayout::corner);
    let text = if (layout.is_some() && corner.is_none()) || Flag::of(doc, node, "overlay").is_on() {
        OwnText::Undrawn
    } else if doc.child(node, C, "tx").is_none() {
        placeholder
    } else {
        title_lines(reader, node, &paragraphs, &places[0]).map_or(OwnText::Undrawn, OwnText::Lines)
    };
    OwnTitle {
        lines: paragraphs.len().max(1),
        places,
        text,
        corner,
        turn: TitleTurn::of(doc, node),
        warnings,
    }
}

/// The text of each line of the chart's own title `node` whose rich text has `paragraphs` and
/// whose first run writes `first`: each paragraph's runs, or the cached text of its reference
/// (`c:strRef`). `None` for a title that F-Office does not draw: one without text of its own,
/// one whose rich text holds a line break or a field, and one with a run whose properties
/// differ from the first run's.
fn title_lines(
    reader: &mut PartReader,
    node: NodeId,
    paragraphs: &[NodeId],
    first: &TitleProps,
) -> Option<Vec<String>> {
    let doc = reader.doc;
    let tx = doc.child(node, C, "tx")?;
    if let Some(reference) = doc.child(tx, C, "strRef") {
        let cache = doc.child(reference, C, "strCache")?;
        let point = doc
            .child_elements(cache)
            .find(|&n| doc.is(n, C, "pt") && doc.attribute(n, None, "idx") == Some("0"))?;
        return Some(vec![doc.text_content(doc.child(point, C, "v")?)]);
    }
    doc.child(tx, C, "rich")?;
    paragraphs
        .iter()
        .map(|&paragraph| paragraph_line(reader, paragraph, first))
        .collect()
}

/// The text of the title's paragraph `paragraph`: its runs joined, or `None` when it holds
/// something other than runs and their properties, or a run whose properties differ from
/// `first`.
fn paragraph_line(
    reader: &mut PartReader,
    paragraph: NodeId,
    first: &TitleProps,
) -> Option<String> {
    let doc = reader.doc;
    let mut line = String::new();
    for child in doc.child_elements(paragraph) {
        if doc.is(child, A, "r") {
            let mut warnings = Warnings::new();
            let props = doc
                .child(child, A, "rPr")
                .map_or_default(|props| TitleProps::read(reader, props, &mut warnings));
            if props != *first {
                return None;
            }
            line.push_str(
                &doc.child(child, A, "t")
                    .map_or_default(|t| doc.text_content(t)),
            );
        } else if !(doc.is(child, A, "pPr") || doc.is(child, A, "endParaRPr")) {
            return None;
        }
    }
    Some(line)
}

#[cfg(test)]
impl Columns {
    /// A chart of `series` over `categories` in the plain look, for the tests of layout: no
    /// gridlines, axis lines without a line, no tick marks, the minor font at 9 pt, a legend at
    /// the bottom and the automatic plot area, scale and crossings.
    pub(crate) fn plain(
        series: Vec<Series>,
        categories: usize,
        group: ChartGroup,
        title: Option<Title>,
    ) -> Self {
        Self {
            series,
            categories,
            group,
            title,
            legend: Some(LegendPlace::Bottom),
            legend_box: LegendBox::Automatic,
            label_size: 18,
            legend_size: 18,
            value_label_size: 18,
            font: FontRef::MinorLatin,
            gridlines: None,
            axis: ShapeLook::plain(Geometry::Line, None, None),
            value_axis: ShapeLook::plain(Geometry::Line, None, None),
            ticks: OutsideTicks::default(),
            plot_place: PlotPlace::Automatic,
            scale: SetScale::default(),
            category_crossing: Some(CategoryCrossing::AutoZero),
            axis_titles: AxisTitles::NONE,
            value_format: Some(LabelFormat::all_digits()),
            category_names: None,
            value_label_fill: None,
            category_label_fill: None,
            legend_font: FontRef::MinorLatin,
            legend_fill: None,
            legend_text: LegendText::default(),
            other_labels: false,
            axis_forms: AxisForms::default(),
            secondary_axis: None,
            data_table: None,
        }
    }
}

mod label_format;
mod pie;
pub(crate) use pie::PieView;

pub(crate) use label_format::all_digits;
pub use label_format::{LabelFormat, LabelPiece, LabelPlace, WrittenLabel};

#[cfg(test)]
mod tests;