f-office-docx 0.2.3

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
use f_office_drawingml::color::DrawColor;
use f_office_drawingml::gradient::LinearGradient;
use f_office_drawingml::shape::{Geometry, ShapeLook};
use f_office_paint::{GradientItem, Item, PathCommand, Point, Rgb};
use f_office_units::{Edges, Length};
use f_office_warnings::Warnings;
use f_office_xml::{Document, Limits};

use super::{
    Clusters, LabelLines, MarkerPart, Scale, SideLines, ValueAxis, layout_edges, legend_props,
    manual_plot, marker_span, room_units,
};
use crate::chart::{
    AxisForms, ChartGroup, Columns, DataLabelText, Decimal, LabelFormat, LayoutBox, LegendBox,
    LegendPlace, LegendText, LineForm, LineLook, PlotLayout, PlotPlace, Series, SeriesFill,
    SeriesLabels, SetScale, StyleWidth, Title, all_digits,
};
use crate::layout::testing::with_layout_on;
use crate::params::{CHART_LINES_OUTER_GAP, CHART_PLOT_RIGHT};
use crate::props::FontRef;
use crate::quirks::{ChartAxisOrder, ChartDataLabels, ChartPlotArea};

/// A chart of two series in two categories, with the file's `gap` and `overlap`.
fn columns(gap: i64, overlap: i64) -> Columns {
    let one = Series {
        fill: SeriesFill::Color(DrawColor::rgb(Rgb::default())),
        values: vec![
            Some(Decimal {
                digits: 1,
                exponent: 0,
            });
            2
        ],
        name: None,
        labels: crate::chart::SeriesLabels::Hidden,
    };
    Columns::plain(
        vec![one.clone(), one],
        2,
        ChartGroup::Columns {
            gap,
            overlap,
            stacking: crate::chart::BarStacking::Clustered,
        },
        Some(Title {
            lines: 1,
            size: 28,
            font: crate::props::FontRef::MinorLatin,
            text: None,
            corner: None,
        }),
    )
}

#[test]
fn places_the_bars_of_a_cluster_or_none_beyond_a_length() {
    // Two series of a hundred parts each and the gap of 150 in each of the two bands.
    let chart = columns(150, 0);
    let span = Length::from_units(7_000);
    let clusters = Clusters::of(&chart, (150, 0), span).unwrap();
    assert_eq!(clusters.parts, 700);
    assert_eq!(clusters.thickness, Length::from_units(1_000));
    // The second series' bar in the second band: half the span, the half gap of 7,000 × 150
    // / 1,400 and one bar of 7,000 × 100 / 700.
    assert_eq!(
        clusters.start((1, 1)),
        Some(Length::from_units(3_500 + 750 + 1_000))
    );
    // A file's overlap or gap at the end of the range gives no parts, and no bar's place.
    assert!(Clusters::of(&chart, (150, i64::MAX), span).is_none());
    assert!(Clusters::of(&chart, (i64::MAX, 0), span).is_none());
    let too_wide = Clusters {
        gap: i64::MAX,
        ..clusters
    };
    assert_eq!(too_wide.start((1, 1)), None);
}

fn scale(max: &str) -> (String, i64) {
    let scale = Scale::of(Decimal::parse(max).unwrap()).unwrap();
    (all_digits(scale.unit), scale.steps)
}

#[test]
fn scales_the_value_axis_by_ones_twos_and_fives() {
    assert_eq!(scale("4.5"), ("0.5".to_owned(), 10));
    assert_eq!(scale("5"), ("1".to_owned(), 6));
    assert_eq!(scale("40000"), ("5000".to_owned(), 9));
    assert_eq!(scale("0.45"), ("0.05".to_owned(), 10));
    assert_eq!(scale("8"), ("1".to_owned(), 9));
    assert_eq!(scale("9.6"), ("2".to_owned(), 6));
    assert!(Scale::of(Decimal::parse("0").unwrap()).is_none());
}

#[test]
fn keeps_the_powers_of_the_scale_in_range() {
    // The powers of ten that the scale tries stay in range at the exponent limit, and give
    // no scale beyond the 32 bits of an exponent.
    assert_eq!(scale("1E350").1, 6);
    let largest = Decimal {
        digits: 1,
        exponent: i32::MAX,
    };
    assert!(Scale::of(largest).is_none());
}

#[test]
fn writes_axis_values_in_the_general_format() {
    let text = |s: &str| all_digits(Decimal::parse(s).unwrap());
    assert_eq!(text("0"), "0");
    assert_eq!(text("0.5"), "0.5");
    assert_eq!(text("2.5"), "2.5");
    assert_eq!(text("45000"), "45000");
    assert_eq!(text("0.05"), "0.05");
}

fn decimal(text: &str) -> Decimal {
    Decimal::parse(text).unwrap()
}

/// The box of the manual layouts of the plot area in these tests.
fn plot_box() -> LayoutBox {
    LayoutBox {
        x: decimal("0.1"),
        y: decimal("0.15"),
        w: decimal("0.8"),
        h: decimal("0.6"),
    }
}

/// The lowest and highest values, the major unit and the crossing of the value axis of
/// `ChartPlotArea::FontLines` for one series of `values` and the set minimum, maximum and
/// major unit `set`.
fn axis_of(values: &[&str], set: [Option<&str>; 3]) -> [String; 4] {
    let mut chart = columns(150, 0);
    chart.series.truncate(1);
    chart.series[0].values = values.iter().map(|v| Some(decimal(v))).collect();
    chart.categories = values.len();
    let [min, max, major_unit] = set.map(|v| v.map(decimal));
    chart.scale = SetScale {
        min,
        max,
        major_unit,
    };
    let axis = ValueAxis::of(&chart).unwrap();
    [axis.low, axis.high, axis.unit, axis.crossing].map(all_digits)
}

/// The cases of the value axis: the values, the set minimum, maximum and major unit, and the
/// lowest and highest values, the major unit and the crossing that the axis takes.
type AxisCase = (
    &'static [&'static str],
    [Option<&'static str>; 3],
    [&'static str; 4],
);

#[test]
fn scales_the_value_axis_below_zero_and_as_the_axis_sets_it() {
    let auto = [None; 3];
    let cases: [AxisCase; 10] = [
        (&["4.3", "2.5", "5"], auto, ["0", "6", "1", "0"]),
        // A cache that writes a value with 17 digits counts the ends below the digits of a
        // decimal.
        (
            &["4.4000000000000004", "2", "5"],
            auto,
            ["0", "6", "1", "0"],
        ),
        (
            &["-4.4000000000000004", "2", "5"],
            auto,
            ["-6", "6", "2", "0"],
        ),
        // Values below zero take the headroom at both ends, and the axis crosses at zero.
        (&["4.3", "-2.5", "5"], auto, ["-3", "6", "1", "0"]),
        // Values all below zero end at zero, where the axis crosses.
        (&["-4.3", "-2.5", "-5"], auto, ["-6", "0", "1", "0"]),
        (&["4.76", "2"], auto, ["0", "5", "0.5", "0"]),
        (&["4.3", "5"], [None, Some("8"), None], ["0", "8", "1", "0"]),
        // A set minimum starts the units, and the axis crosses there when zero is not on it.
        (
            &["4.3", "5", "1.8"],
            [Some("1"), None, None],
            ["1", "5.5", "0.5", "1"],
        ),
        (&["4.3", "5"], [None, None, Some("2")], ["0", "6", "2", "0"]),
        (
            &["4.3", "-2.5", "5"],
            [Some("-4"), None, Some("1")],
            ["-4", "6", "1", "0"],
        ),
    ];
    for (values, set, expected) in cases {
        assert_eq!(
            axis_of(values, set),
            expected.map(str::to_owned),
            "{values:?} {set:?}"
        );
    }
    // A set maximum at or below the lowest value gives no axis.
    let mut chart = columns(150, 0);
    chart.scale.min = Some(decimal("8"));
    chart.scale.max = Some(decimal("8"));
    assert!(ValueAxis::of(&chart).is_none());
}

#[test]
fn scales_values_at_and_above_zero_as_the_default_chart() {
    // On values that are not below zero and an axis that sets nothing, the axis of
    // `FontLines` is that of `DefaultChart`.
    for max in ["5", "4.76", "0.43", "120", "9.99", "1E-5", "3E7"] {
        let mut chart = columns(150, 0);
        chart.series[0].values = vec![Some(decimal(max)), Some(decimal("0"))];
        assert_eq!(ValueAxis::of(&chart), ValueAxis::from_zero(&chart), "{max}");
    }
}

fn points(points: i64) -> Length {
    Length::from_points(points).unwrap()
}

#[test]
fn places_the_plot_area_of_a_manual_layout_in_the_frame() {
    let frame = Edges {
        left: points(100),
        top: points(200),
        right: points(500),
        bottom: points(400),
    };
    let layout = |inner| PlotLayout {
        inner,
        edges: plot_box(),
    };
    let edges = |[left, top, right, bottom]: [i64; 4]| Edges {
        left: points(left),
        top: points(top),
        right: points(right),
        bottom: points(bottom),
    };
    // Labels of a 12 pt line and a 9 pt top: a part of the top of 3 pt and a band of 15 pt.
    let lines = LabelLines {
        size: points(10),
        line: points(12),
        top: points(9),
        single_top: points(9),
        single_line: points(12),
    };
    let sides = SideLines {
        left: lines,
        below: lines,
    };
    assert_eq!(
        manual_plot(layout(true), frame, points(20), sides),
        Some(edges([140, 230, 460, 350]))
    );
    // The outer box holds the gap and the value labels' region at its left, half a line at
    // its top, and the gap, a band and a part of the top below.
    let outer = edges([160, 236, 460, 332]);
    assert_eq!(
        manual_plot(layout(false), frame, points(20), sides),
        Some(Edges {
            left: outer.left + CHART_LINES_OUTER_GAP,
            bottom: outer.bottom - CHART_LINES_OUTER_GAP,
            ..outer
        })
    );
}

/// The plot areas of `chart` on `ChartPlotArea::FontLines` in a frame of 432 by 252 pt, for
/// each legend and title of `cases`, or `None` where it draws none.
fn font_line_plots(
    chart: &Columns,
    cases: &[(Option<LegendPlace>, Option<Title>)],
) -> Vec<Option<Edges<Length>>> {
    let mut plots = Vec::new();
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let frame = Edges {
                left: Length::ZERO,
                top: Length::ZERO,
                right: points(432),
                bottom: points(252),
            };
            for (legend, title) in cases {
                let chart = Columns {
                    title: title.clone(),
                    legend: *legend,
                    ..chart.clone()
                };
                let axis = ValueAxis::of(&chart);
                plots.push(axis.and_then(|axis| layout.font_line_plot(&chart, &axis, frame)));
            }
        },
    );
    plots
}

/// A chart whose two series are named "A" and "Longer".
fn named_columns() -> Columns {
    let mut chart = columns(219, -27);
    for (series, name) in chart.series.iter_mut().zip(["A", "Longer"]) {
        series.name = Some(name.to_owned());
    }
    chart
}

#[test]
fn moves_the_plot_area_with_a_legend_at_the_top_and_the_title_on_font_lines() {
    let title = Some(Title {
        lines: 1,
        size: 28,
        font: crate::props::FontRef::MinorLatin,
        text: None,
        corner: None,
    });
    let cases = [
        (Some(LegendPlace::Bottom), title.clone()),
        (Some(LegendPlace::Top), title.clone()),
        (None, title),
        (Some(LegendPlace::Bottom), None),
    ];
    let plots = font_line_plots(&named_columns(), &cases);
    let [Some(bottom), Some(top), Some(none), Some(untitled)] = plots[..] else {
        panic!("{plots:?}");
    };
    // A legend at the top moves the plot area down by the room that it takes below.
    let room = none.bottom - bottom.bottom;
    assert!(room > Length::ZERO);
    assert_eq!(
        (top.top - bottom.top, top.bottom, none.top),
        (room, none.bottom, bottom.top)
    );
    // Without a title, the plot area starts higher.
    assert!(untitled.top < bottom.top);
}

#[test]
fn keeps_no_band_below_the_plot_area_when_the_category_labels_stand_inside_on_font_lines() {
    let mut below = named_columns();
    below.series[0].values[0] = Some(decimal("-1"));
    let cases = [(Some(LegendPlace::Bottom), None), (None, None)];
    let [Some(above_zero), _] = font_line_plots(&named_columns(), &cases)[..] else {
        panic!("no plot area above zero");
    };
    let plots = font_line_plots(&below, &cases);
    let [Some(legend), Some(none)] = plots[..] else {
        panic!("{plots:?}");
    };
    // The category axis crosses at zero, above the lowest value: the plot area reaches down
    // to the legend's room and the untitled edge, which lie closer to the frame's bottom than
    // the bands of the category labels and the legend.
    let mut lines = None;
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| lines = layout.label_lines(&below),
    );
    let lines = lines.unwrap();
    let edge = points(252) - lines.untitled_edge();
    assert_eq!(
        (legend.bottom, none.bottom),
        (edge - lines.legend_room().unwrap(), edge)
    );
    assert!(legend.bottom > above_zero.bottom);
    assert_eq!(legend.top, above_zero.top);
}

#[test]
fn takes_the_room_of_a_legend_at_a_side_on_font_lines() {
    let title = Some(Title {
        lines: 1,
        size: 28,
        font: crate::props::FontRef::MinorLatin,
        text: None,
        corner: None,
    });
    let cases = [
        (Some(LegendPlace::Bottom), title.clone()),
        (None, title.clone()),
        (Some(LegendPlace::Right), title.clone()),
        (Some(LegendPlace::Left), title.clone()),
    ];
    let plots = font_line_plots(&named_columns(), &cases);
    let [Some(bottom), Some(none), Some(right), Some(left)] = plots[..] else {
        panic!("{plots:?}");
    };
    // A legend at a side takes the same width from either side.
    let side = bottom.right - right.right;
    assert!(side > Length::ZERO);
    assert_eq!(
        (left.left - bottom.left, left.bottom, right.bottom),
        (side, none.bottom, none.bottom)
    );
    // A legend at a side needs the names of its series.
    let mut unnamed = named_columns();
    unnamed.series[1].name = None;
    let plots = font_line_plots(&unnamed, &[(Some(LegendPlace::Right), title)]);
    assert_eq!(plots, [None]);
}

#[test]
fn places_the_axis_labels_from_the_label_lines() {
    // Labels of 10 pt with a 12 pt win line and a 9 pt win top: a win descent of 3 pt.
    let lines = LabelLines {
        size: points(10),
        line: points(12),
        top: points(9),
        single_top: points(9),
        single_line: points(12),
    };
    // The gap before the plot area is half the line and a third of the top; a value
    // label's baseline lies (10 + 9 - 3 × 3) / 4 pt below its value; a category
    // label's baseline lies the top and two thirds of it below the plot area.
    assert_eq!(lines.label_gap(), Some(points(9)));
    assert_eq!(lines.value_baseline(), Some(points(10).div_toward_zero(4)));
    assert_eq!(lines.category_baseline(), Some(points(15)));
}

/// The glyph runs of `chart`'s items in a frame of 432 by 252 pt on `area`: each run's text,
/// first glyph's place and baseline.
fn label_runs(chart: &Columns, area: ChartPlotArea) -> Vec<(String, Length, Length)> {
    let mut runs = Vec::new();
    with_layout_on(
        |p| p.with_variant(area),
        |layout| {
            let frame = Edges {
                left: Length::ZERO,
                top: Length::ZERO,
                right: points(432),
                bottom: points(252),
            };
            let items = layout.columns(chart, frame).map(|(items, _)| items);
            for item in items.unwrap_or_default() {
                if let f_office_paint::Item::Glyphs(run) = item {
                    let first = run.glyphs.first().map(|g| (g.x, g.y)).unwrap();
                    runs.push((run.text, first.0, first.1));
                }
            }
        },
    );
    runs
}

/// Whether the items of `chart` in a frame of 432 by 252 pt on `area` hold all of its text, or
/// `None` when F-Office does not draw it.
fn all_text(chart: &Columns, area: ChartPlotArea) -> Option<bool> {
    let mut all = None;
    with_layout_on(
        |p| p.with_variant(area),
        |layout| {
            let frame = Edges {
                left: Length::ZERO,
                top: Length::ZERO,
                right: points(432),
                bottom: points(252),
            };
            all = layout
                .columns(chart, frame)
                .map(|(_, drawn)| drawn.axes_and_legend);
        },
    );
    all
}

/// `named_columns` with category names and no title, whose text these rules draw in full.
fn drawn_text_columns() -> Columns {
    Columns {
        category_names: Some(vec!["One".to_owned(), "Two".to_owned()]),
        title: None,
        ..named_columns()
    }
}

#[test]
fn says_whether_a_drawn_chart_holds_all_of_its_text() {
    let mut chart = drawn_text_columns();
    assert_eq!(all_text(&chart, ChartPlotArea::FontLines), Some(true));
    // A title is not drawn.
    let titled = Columns {
        title: Some(Title {
            lines: 1,
            size: 28,
            font: crate::props::FontRef::MinorLatin,
            text: None,
            corner: None,
        }),
        ..chart.clone()
    };
    assert_eq!(all_text(&titled, ChartPlotArea::FontLines), Some(false));
    chart.legend = None;
    assert_eq!(all_text(&chart, ChartPlotArea::FontLines), Some(true));
    // Without cached names, the category axis shows numbers, which are not drawn.
    let unnamed = Columns {
        category_names: None,
        ..chart.clone()
    };
    assert_eq!(all_text(&unnamed, ChartPlotArea::FontLines), Some(false));
    // Word's default chart, with its title and its legend, has no axis labels on
    // `DefaultChart`.
    assert_eq!(
        all_text(&named_columns(), ChartPlotArea::DefaultChart),
        Some(false)
    );
}

#[test]
fn draws_a_legend_at_the_bottom_the_top_the_right_and_the_left_in_its_own_font() {
    let place = |legend| Columns {
        legend: Some(legend),
        ..drawn_text_columns()
    };
    for legend in [
        LegendPlace::Bottom,
        LegendPlace::Top,
        LegendPlace::Right,
        LegendPlace::Left,
    ] {
        assert_eq!(
            all_text(&place(legend), ChartPlotArea::FontLines),
            Some(true),
            "{legend:?}"
        );
    }
    let other_font = Columns {
        legend_font: FontRef::Name("Georgia".to_owned()),
        ..place(LegendPlace::Right)
    };
    assert_eq!(all_text(&other_font, ChartPlotArea::FontLines), Some(true));
}

#[test]
fn draws_the_axis_labels_on_font_lines_only() {
    let mut chart = named_columns();
    chart.category_names = Some(vec!["One".to_owned(), "Two".to_owned()]);
    chart.legend = None;
    let runs = label_runs(&chart, ChartPlotArea::FontLines);
    let texts: Vec<&str> = runs.iter().map(|(text, _, _)| text.as_str()).collect();
    // The values 1 and 1 give an axis from 0 to 1.2 in steps of 0.2, and one label for each
    // step, from the lowest; then the categories.
    assert_eq!(
        texts,
        ["0", "0.2", "0.4", "0.6", "0.8", "1", "1.2", "One", "Two"]
    );
    // The value labels' baselines go up the plot area; the category labels share one
    // baseline below the lowest value label's, and the second stands right of the first.
    let baselines: Vec<Length> = runs.iter().map(|&(_, _, y)| y).collect();
    assert!(baselines[..7].windows(2).all(|pair| pair[0] > pair[1]));
    assert_eq!(baselines[7], baselines[8]);
    assert!(baselines[7] > baselines[0]);
    assert!(runs[8].1 > runs[7].1);
    // Without the names of the categories, only the value labels are drawn, and the other
    // rule draws none.
    chart.category_names = None;
    assert_eq!(label_runs(&chart, ChartPlotArea::FontLines).len(), 7);
    assert_eq!(label_runs(&chart, ChartPlotArea::DefaultChart), Vec::new());
}

/// The items of `chart` on `FontLines` in a frame of 432 by 252 pt, with the chart's label
/// lines.
fn font_line_items(chart: &Columns) -> (Vec<Item>, LabelLines) {
    let mut out = None;
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let frame = Edges {
                left: Length::ZERO,
                top: Length::ZERO,
                right: points(432),
                bottom: points(252),
            };
            let items = layout.columns(chart, frame).map(|(items, _)| items);
            out = Some((items.unwrap(), layout.label_lines(chart).unwrap()));
        },
    );
    out.unwrap()
}

/// The text, the first glyph's place and the baseline of each glyph run of `items`.
fn runs_of(items: &[Item]) -> Vec<(&str, Length, Length)> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::Glyphs(run) => {
                let first = run.glyphs.first()?;
                Some((run.text.as_str(), first.x, first.y))
            }
            _ => None,
        })
        .collect()
}

/// The left edges and middles of the squares of `side` in `items`, the legend's keys.
fn keys_of(items: &[Item], side: Length) -> Vec<(Length, Length)> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::Rect(rect) if rect.width == side && rect.height == side => {
                Some((rect.x, rect.y + side.div_toward_zero(2)))
            }
            _ => None,
        })
        .collect()
}

#[test]
fn draws_the_keys_and_names_of_a_legend_at_the_right_on_font_lines() {
    let chart = Columns {
        legend: Some(LegendPlace::Right),
        ..named_columns()
    };
    let (items, lines) = font_line_items(&chart);
    let runs = runs_of(&items);
    let texts: Vec<&str> = runs.iter().map(|&(text, _, _)| text).collect();
    assert_eq!(texts[texts.len() - 2..], ["A", "Longer"]);
    // Each key is 0.450 of the labels' line; its name starts 0.32 pt less than half a key
    // after it, with its baseline a value label's below the key's middle.
    let side = lines.of_line(450).unwrap();
    let keys = keys_of(&items, side);
    let gap = side.div_toward_zero(2) - hundredths(32);
    let down = lines.value_baseline().unwrap();
    let starts: Vec<(Length, Length)> = keys
        .iter()
        .map(|k| (k.0 + side + gap, k.1 + down))
        .collect();
    let drawn: Vec<(Length, Length)> = runs[runs.len() - 2..]
        .iter()
        .map(|&(_, x, y)| (x, y))
        .collect();
    assert_eq!(drawn, starts);
    // A legend at the left draws its keys at `frame.left + 8.25 pt + side / 2` with the same
    // vertical row step and centering as a legend at the right.
    let left = Columns {
        legend: Some(LegendPlace::Left),
        ..named_columns()
    };
    let (left_items, _) = font_line_items(&left);
    let left_keys = keys_of(&left_items, side);
    assert_eq!(left_keys.len(), 2);
    assert_eq!(left_keys[0].0, hundredths(825) + side.div_toward_zero(2));
    assert_eq!(left_keys[0].0, left_keys[1].0);
    assert_eq!(left_keys[0].1, keys[0].1);
    assert_eq!(left_keys[1].1, keys[1].1);
}

/// The widths of the names "A" and "Longer" in the legend's face, and the keys, of a chart
/// without a title whose legend stands at `place` with the text properties `legend_text`.
fn styled_keys(
    place: LegendPlace,
    legend_text: LegendText,
) -> (Vec<Length>, Vec<(Length, Length)>) {
    let chart = Columns {
        title: None,
        legend: Some(place),
        legend_text,
        ..named_columns()
    };
    let (items, lines) = font_line_items(&chart);
    let keys = keys_of(&items, lines.of_line(450).unwrap());
    (name_widths(&chart, &["A", "Longer"]), keys)
}

/// The boxes of the points of the paths of `items` that stand alone, outside a group: the
/// series lines of a line chart without a clip and the line keys of its legend.
fn path_boxes(items: &[Item]) -> Vec<Edges<Length>> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::Path(path) => {
                let points: Vec<_> = path.commands.iter().flat_map(PathCommand::points).collect();
                Some(Edges {
                    left: points.iter().map(|p| p.x).min()?,
                    top: points.iter().map(|p| p.y).min()?,
                    right: points.iter().map(|p| p.x).max()?,
                    bottom: points.iter().map(|p| p.y).max()?,
                })
            }
            _ => None,
        })
        .collect()
}

/// The line keys' boxes of `items`, a line chart of two series with lines of 1 pt and a
/// legend, and the places of the legend's two names. Each key is a stroke of 19.2 pt with round
/// caps of half the line's 1 pt, in the middle of its area; the name starts 0.32 pt before the
/// area's end, its baseline a value label's (`down`) below the key's middle.
fn line_keys_and_names(
    items: &[Item],
    down: Length,
    place: LegendPlace,
) -> (Vec<Edges<Length>>, Vec<(Length, Length)>) {
    use crate::params::{CHART_LINE_KEY_AREA, CHART_LINE_KEY_STROKE};
    let keys: Vec<Edges<Length>> = path_boxes(items)
        .into_iter()
        .filter(|b| b.right - b.left == CHART_LINE_KEY_STROKE + points(1))
        .collect();
    assert_eq!(keys.len(), 2, "{place:?}");
    let runs = runs_of(items);
    let names: Vec<(Length, Length)> = runs[runs.len() - 2..]
        .iter()
        .map(|&(_, x, y)| (x, y))
        .collect();
    for (key, &(x, y)) in keys.iter().zip(&names) {
        assert_eq!(key.bottom - key.top, points(1));
        let middle = key.top + hundredths(50);
        let start = key.left + hundredths(50) + CHART_LINE_KEY_STROKE.div_toward_zero(2)
            - CHART_LINE_KEY_AREA.div_toward_zero(2);
        assert_eq!(x, start + CHART_LINE_KEY_AREA - hundredths(32), "{place:?}");
        assert_eq!(y, middle + down, "{place:?}");
    }
    (keys, names)
}

#[test]
fn draws_a_line_charts_legend_with_line_keys_in_areas_of_24_points() {
    for place in [LegendPlace::Right, LegendPlace::Bottom, LegendPlace::Top] {
        let twin = Columns {
            title: None,
            legend: Some(place),
            ..named_columns()
        };
        let chart = Columns {
            group: ChartGroup::Lines {
                looks: vec![plain_look(); 2],
                stacking: crate::chart::BarStacking::Clustered,
            },
            ..twin.clone()
        };
        let (items, lines) = font_line_items(&chart);
        let side = lines.of_line(450).unwrap();
        let (keys, names) = line_keys_and_names(&items, lines.value_baseline().unwrap(), place);
        // The squares of the column twin stand at the same height; a row's entries are wider by
        // the areas' difference, and at the right the names stand where the twin's stand.
        let (twin_items, _) = font_line_items(&twin);
        let squares = keys_of(&twin_items, side);
        assert_eq!(squares.len(), 2);
        let twin_runs = runs_of(&twin_items);
        let twin_names: Vec<Length> = twin_runs[twin_runs.len() - 2..]
            .iter()
            .map(|r| r.1)
            .collect();
        let step = names[1].0 - names[0].0;
        let twin_step = twin_names[1] - twin_names[0];
        if place == LegendPlace::Right {
            let off: Vec<i64> = names
                .iter()
                .zip(&twin_names)
                .map(|(name, twin)| (name.0 - *twin).units().abs())
                .collect();
            assert!(off.iter().all(|&o| o <= 2), "{off:?}");
            assert_eq!(step, twin_step);
        } else {
            assert!(step > twin_step, "{place:?}");
        }
        let heights: Vec<Length> = keys.iter().map(|k| k.top + hundredths(50)).collect();
        let square_heights: Vec<Length> = squares.iter().map(|s| s.1).collect();
        assert_eq!(heights, square_heights, "{place:?}");
    }
}

#[test]
fn gives_dashed_line_keys_a_wider_area_and_caps_a_keys_marker_below_the_legends_size() {
    use super::legend::Keys;
    use crate::chart::{LineDash, Marker, MarkerSymbol};
    use crate::params::{CHART_LINE_KEY_AREA, CHART_LINE_KEY_DASHED_AREA};
    let lines_of = |looks: Vec<LineLook>| Columns {
        title: None,
        legend: Some(LegendPlace::Bottom),
        group: ChartGroup::Lines {
            looks,
            stacking: crate::chart::BarStacking::Clustered,
        },
        ..named_columns()
    };
    let dashed = LineLook {
        dash: Some(LineDash::Dash),
        ..plain_look()
    };
    assert_eq!(
        Keys::of(&lines_of(vec![plain_look(); 2])),
        Keys::Lines(CHART_LINE_KEY_AREA)
    );
    // One dashed series widens every key's area of the legend.
    assert_eq!(
        Keys::of(&lines_of(vec![plain_look(), dashed])),
        Keys::Lines(CHART_LINE_KEY_DASHED_AREA)
    );
    // A square marker of 17 pt shows at 0.6 of the legend's whole points, cut to a whole point,
    // at the key, on whole dots of the layout device, and at 17 pt at the points: 8.5 pt
    // counts as 8 pt.
    let marked = LineLook {
        marker: Some(Marker {
            symbol: MarkerSymbol::Square,
            size: Some(points(17)),
            fill: None,
            outline: None,
        }),
        ..plain_look()
    };
    for (half_points, cap) in [
        (12, 3),
        (15, 4),
        (17, 4),
        (18, 5),
        (22, 6),
        (27, 7),
        (48, 14),
    ] {
        let chart = Columns {
            legend_size: half_points,
            ..lines_of(vec![marked.clone(); 2])
        };
        let (items, _) = font_line_items(&chart);
        let small: Vec<Length> = path_boxes(&items)
            .into_iter()
            .filter(|b| b.right - b.left == b.bottom - b.top && b.right - b.left < points(16))
            .map(|b| b.right - b.left)
            .collect();
        assert_eq!(small.len(), 2, "{half_points}");
        for width in small {
            let off = (width - points(cap)).units().abs();
            assert!(off <= hundredths(12).units(), "{half_points} {width:?}");
        }
    }
}

#[test]
fn draws_an_italic_legend_in_its_face_and_leaves_out_one_with_entries_of_its_own() {
    let italic = LegendText {
        italic: true,
        ..LegendText::default()
    };
    let entries = LegendText {
        own_entries: true,
        ..LegendText::default()
    };
    for place in [LegendPlace::Bottom, LegendPlace::Right] {
        let (_, regular) = styled_keys(place, LegendText::default());
        assert_eq!(regular.len(), 2);
        // The fake italic glyphs are as wide as the regular ones, so the italic keys lie where
        // the regular keys lie.
        assert_eq!(styled_keys(place, italic).1, regular, "{place:?}");
        assert_eq!(styled_keys(place, entries).1, [], "{place:?}");
    }
}

#[test]
fn draws_a_bold_legend_with_the_advances_of_its_face() {
    let bold = LegendText {
        bold: true,
        ..LegendText::default()
    };
    // The fake bold glyphs are wider: the row spaces the bold names further apart.
    let (widths, keys) = styled_keys(LegendPlace::Bottom, bold);
    let (regular_widths, regular) = styled_keys(LegendPlace::Bottom, LegendText::default());
    let wider = widths[1] - regular_widths[1];
    assert!(wider > Length::ZERO);
    assert!(keys[1].0 - keys[0].0 > regular[1].0 - regular[0].0);
    // A legend at the right takes the widest bold name from the plot area, so its keys start
    // as much further left.
    let (_, keys) = styled_keys(LegendPlace::Right, bold);
    let (_, regular) = styled_keys(LegendPlace::Right, LegendText::default());
    assert_eq!(keys[0].0, regular[0].0 - wider);
}

#[test]
fn caps_a_nearly_full_legend_row_and_leaves_out_a_row_past_the_cap() {
    let chart = Columns {
        title: None,
        legend: Some(LegendPlace::Bottom),
        ..named_columns()
    };
    let (_, lines) = font_line_items(&chart);
    let side = lines.of_line(450).unwrap();
    let gap = side.div_toward_zero(2) - hundredths(32);
    let cap = points(432).checked_mul(900).unwrap().div_toward_zero(1_000);
    let named = |letters: usize| {
        let mut row = chart.clone();
        for series in &mut row.series {
            series.name = Some("n".repeat(letters));
        }
        row
    };
    // A row of two names of `letters` letters: their widths, the names and two key sides of
    // each, and what its entries count.
    let sums = |letters: usize| {
        let name = "n".repeat(letters);
        let widths = name_widths(&chart, &[&name, &name]);
        let mut sides = Length::ZERO;
        let mut entries = Length::ZERO;
        for &width in &widths {
            let entry = width + side.checked_mul(2).unwrap();
            sides += entry;
            entries += entry.checked_mul(1_200).unwrap().div_toward_zero(1_000);
        }
        (widths, sides, entries)
    };
    let last = (1..400).find(|&n| sums(n + 1).1 > cap).unwrap();
    let (widths, sides, entries) = sums(last);
    // The last row on one line counts more than the cap by its entries, so the cap and a
    // quarter of the line give its three equal spaces.
    assert!(sides <= cap && entries > cap);
    let keys = keys_of(&font_line_items(&named(last)).0, side);
    assert_eq!(keys.len(), 2);
    let drawn = [widths[0] + side + gap, widths[1] + side + gap];
    let space = (cap + lines.of_line(250).unwrap() - drawn[0] - drawn[1]).div_toward_zero(3);
    assert_eq!(keys[1].0 - keys[0].0, drawn[0] + space);
    // One letter more puts the names and sides past the cap: Word wraps the legend into a
    // two-row uniform grid stepping vertically by `row_step`.
    let wrapped = keys_of(&font_line_items(&named(last + 1)).0, side);
    assert_eq!(wrapped.len(), 2);
    assert_eq!(wrapped[0].0, wrapped[1].0);
    let step = points(6) + lines.of_line(990).unwrap();
    assert_eq!(wrapped[1].1 - wrapped[0].1, step);
}

/// The widths of `names` in the legend's face of `chart`, the sums of their advances.
fn name_widths(chart: &Columns, names: &[&str]) -> Vec<Length> {
    let mut out = Vec::new();
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let props = legend_props(chart);
            out = names
                .iter()
                .map(|name| layout.chart_text(&props, name).unwrap().width())
                .collect();
        },
    );
    out
}

#[test]
fn spaces_and_centers_a_legend_row_at_the_bottom_and_the_top_on_font_lines() {
    let chart = Columns {
        title: None,
        legend: Some(LegendPlace::Bottom),
        ..named_columns()
    };
    let (items, lines) = font_line_items(&chart);
    let side = lines.of_line(450).unwrap();
    let keys = keys_of(&items, side);
    assert_eq!(keys.len(), 2);
    // The keys' middle lies 8.90 pt and half the line inside the frame's bottom.
    let inset = hundredths(890) + lines.line.div_toward_zero(2);
    assert_eq!([keys[0].1, keys[1].1], [points(252) - inset; 2]);
    // Each entry counts 1.2 of its name and two key sides, the row a quarter of the line, and
    // what this leaves beyond the drawn entries is shared by three spaces.
    let widths = name_widths(&chart, &["A", "Longer"]);
    let gap = side.div_toward_zero(2) - hundredths(32);
    let drawn: Vec<Length> = widths.iter().map(|&width| side + gap + width).collect();
    let counted = widths
        .iter()
        .fold(lines.of_line(250).unwrap(), |sum, &width| {
            let entry = width + side.checked_mul(2).unwrap();
            sum + entry.checked_mul(1_200).unwrap().div_toward_zero(1_000)
        });
    let space = (counted - drawn[0] - drawn[1]).div_toward_zero(3);
    assert_eq!(keys[1].0 - keys[0].0, drawn[0] + space);
    // The extent from 1.15 pt and half a key before the first key to the last name's end is
    // centered on the frame.
    let twice = keys[0].0 - (side.div_toward_zero(2) + hundredths(115)) + keys[1].0 + drawn[1];
    let units = Length::from_units(2);
    assert!((points(432) - units..=points(432) + units).contains(&twice));
    // At the top, without a title, the keys lie as far inside the frame's top.
    let top = Columns {
        legend: Some(LegendPlace::Top),
        ..chart.clone()
    };
    let (items, _) = font_line_items(&top);
    let top_keys = keys_of(&items, side);
    assert_eq!(top_keys, [(keys[0].0, inset), (keys[1].0, inset)]);
}

#[test]
fn centers_the_rows_of_a_legend_at_the_right_in_its_area_below_the_title() {
    let chart = Columns {
        title: Some(Title {
            lines: 1,
            size: 28,
            font: crate::props::FontRef::MinorLatin,
            text: None,
            corner: None,
        }),
        legend: Some(LegendPlace::Right),
        ..named_columns()
    };
    let (items, lines) = font_line_items(&chart);
    let side = lines.of_line(450).unwrap();
    let keys = keys_of(&items, side);
    assert_eq!(keys.len(), 2);
    assert_eq!(keys[0].0, keys[1].0);
    // The rows step by 6 pt and 0.990 of the line.
    assert_eq!(
        keys[1].1 - keys[0].1,
        points(6) + lines.of_line(990).unwrap()
    );
    // Their middle is the middle of the area below the title's line and 9 pt.
    let mut title_line = None;
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| title_line = layout.chart_line(&chart, 28),
    );
    let area_top = title_line.unwrap() + points(9);
    let twice = keys[0].1 + keys[1].1 - (area_top + points(252));
    let unit = Length::from_units(1);
    assert!((-unit..=unit).contains(&twice));
}

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

/// A length of `thousandths` thousandths of a point.
fn thousandths(thousandths: i64) -> Length {
    Length::from_units(thousandths * Length::UNITS_PER_POINT / 1_000)
}

#[test]
fn the_labels_lines_limit_the_units_of_an_automatic_axis() {
    let room = |height, line| room_units(hundredths(height), hundredths(line));
    // Calibri labels of 9 pt in a plot area of 168.87 pt: 14 lines fit, the limit is 10.
    assert_eq!(room(16_887, 1_099), 10);
    // Labels of 20 pt in 128.95 pt: 4 lines fit beside the room of 10 pt.
    assert_eq!(room(12_895, 2_441), 4);
    // Labels of 14 pt in 42.98 pt: one line fits, and so does a second only past the room.
    assert_eq!(room(4_298, 1_709), 1);
    // A plot area lower than the room still takes one unit, and no line takes the limit.
    assert_eq!(room(500, 1_709), 1);
    assert_eq!(room_units(hundredths(4_298), Length::ZERO), 10);
    // Lines that just fit: 5 lines of 16.80 pt and 10 pt in 94.00 pt.
    assert_eq!(room(9_400, 1_680), 5);
    assert_eq!(room(9_399, 1_680), 4);
}

#[test]
fn an_axis_of_fewer_units_takes_the_next_unit_of_the_series() {
    let values = ["37", "89", "137", "64"];
    let mut chart = columns(150, 0);
    chart.series.truncate(1);
    chart.series[0].values = values.iter().map(|v| Some(decimal(v))).collect();
    chart.categories = values.len();
    let shown = |most| {
        let axis = ValueAxis::with_most(&chart, most).unwrap();
        [axis.high, axis.unit].map(all_digits)
    };
    assert_eq!(shown(10), ["160", "20"]);
    assert_eq!(shown(4), ["150", "50"]);
    assert_eq!(shown(2), ["200", "100"]);
    assert_eq!(shown(1), ["200", "200"]);
}

/// A theme whose first line style is `emus` wide.
fn theme_with_first_line(emus: u32) -> f_office_drawingml::theme::ShapeTheme {
    let xml = format!(
        r#"<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:themeElements><a:fmtScheme><a:lnStyleLst><a:ln w="{emus}"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln><a:ln w="12700"/><a:ln w="19050"/></a:lnStyleLst></a:fmtScheme></a:themeElements></a:theme>"#
    );
    let doc =
        f_office_xml::Document::parse(xml.as_bytes(), &f_office_xml::Limits::default()).unwrap();
    f_office_drawingml::theme::ShapeTheme::read(
        &doc,
        doc.root().unwrap(),
        &mut f_office_warnings::Warnings::new(),
    )
}

#[test]
fn gives_the_style_lines_and_markers_their_widths_and_sizes_from_the_theme() {
    use super::{line_width, marker_size};
    use crate::chart::{Marker, MarkerOutline, MarkerSymbol, StyleWidth};
    let marker = Marker {
        symbol: MarkerSymbol::Diamond,
        size: None,
        fill: None,
        outline: Some(MarkerOutline::STYLE),
    };
    // Word's lines and markers under themes whose first line style is 0.25 to 2 pt.
    for (emus, line_emus, points) in [
        (3_175, 9_525, 4),
        (6_350, 19_050, 6),
        (7_620, 22_860, 6),
        (9_525, 28_575, 7),
        (12_700, 38_100, 9),
        (15_875, 47_625, 10),
        (19_050, 57_150, 12),
        (25_400, 76_200, 15),
    ] {
        let theme = theme_with_first_line(emus);
        assert_eq!(
            line_width(StyleWidth::Automatic, &theme, 3),
            Length::from_emus(line_emus),
            "{emus}"
        );
        assert_eq!(
            marker_size(&marker, &theme),
            Length::from_points(points),
            "{emus}"
        );
    }
    let set = Marker {
        size: Length::from_points(5),
        ..marker
    };
    assert_eq!(
        marker_size(&set, &theme_with_first_line(6_350)),
        Length::from_points(5)
    );
}

#[test]
fn places_each_marker_part_on_whole_or_half_dots() {
    // A device of 600 dots per inch, whose dot is 0.12 pt: a marker of 5 pt is 41.67 dots, one
    // of 3 pt 25 dots, and an outline of 0.6 pt is 5 dots, an odd number.
    let device = crate::grid::Device::per_inch(600).expect("a dot is whole units");
    let dots = |tenths: i64| device.dots(tenths).div_toward_zero(10);
    let point = device.dots(100);
    let span = |part, points, odd, (place, after)| {
        marker_span(
            &device,
            part,
            Length::from_points(points).unwrap(),
            odd,
            (place, after),
        )
    };
    // Without an odd outline, a part stands around the dot nearest to the point: a diamond of
    // 5 pt is 42 dots, the size made even, and a square of 3 pt 25 dots from 13 before it.
    assert_eq!(
        span(MarkerPart::Even, 5, false, (point, true)),
        (device.dots(79), device.dots(42))
    );
    assert_eq!(
        span(MarkerPart::Whole, 3, false, (point, true)),
        (device.dots(87), device.dots(25))
    );
    // Under an odd outline, around the middle of the dot that holds the point: the square loses
    // a dot and starts on a half dot, and the lines of an x keep whole dots and gain one.
    let past = point + dots(3);
    assert_eq!(
        span(MarkerPart::Whole, 3, true, (past, true)),
        (dots(875), device.dots(24))
    );
    assert_eq!(
        span(MarkerPart::Lines, 3, true, (past, true)),
        (device.dots(88), device.dots(25))
    );
    // A point on a dot takes the dot after it across and the dot before it down.
    assert_eq!(span(MarkerPart::Even, 3, true, (point, true)).0, dots(885));
    assert_eq!(span(MarkerPart::Even, 3, true, (point, false)).0, dots(875));
}

/// The first glyph's place of each run of `text` among the items of `chart` in a frame of 432 by
/// 252 pt on the plot rule `FontLines` and the variant `labels`, and whether the items hold all
/// of its data labels, or `None` when F-Office does not draw it.
fn data_label_runs(
    chart: &Columns,
    labels: ChartDataLabels,
    text: &str,
) -> (Vec<(Length, Length)>, Option<bool>) {
    let (mut runs, mut all) = (Vec::new(), None);
    with_layout_on(
        |p| {
            p.with_variant(ChartPlotArea::FontLines)
                .with_variant(labels)
        },
        |layout| {
            let frame = Edges {
                left: Length::ZERO,
                top: Length::ZERO,
                right: points(432),
                bottom: points(252),
            };
            if let Some((items, drawn)) = layout.columns(chart, frame) {
                all = Some(drawn.data_labels);
                for item in items {
                    if let Item::Glyphs(run) = item
                        && run.text == text
                    {
                        let first = run.glyphs.first().map(|g| (g.x, g.y)).unwrap();
                        runs.push(first);
                    }
                }
            }
        },
    );
    (runs, all)
}

/// A chart of two series that show their values, the first of them `first`, in a text box of
/// the insets `top` and `bottom` and none at the sides.
fn labelled_columns(first: Decimal, (top, bottom): (Length, Length)) -> Columns {
    let mut chart = drawn_text_columns();
    for series in &mut chart.series {
        series.values[0] = Some(first);
        series.labels = SeriesLabels::Values(DataLabelText {
            position: crate::chart::DataLabelPosition::Default,
            size: 18,
            font: FontRef::MinorLatin,
            fill: None,
            insets: Edges {
                left: Length::ZERO,
                top,
                right: Length::ZERO,
                bottom,
            },
            format: LabelFormat::all_digits(),
            parts: crate::chart::DataLabelParts::default(),
            show_default: true,
            point_overrides: Vec::new(),
        });
    }
    chart
}

/// The first value of [`labelled_columns`] above the crossing: 2.25.
const ABOVE: Decimal = Decimal {
    digits: 225,
    exponent: -2,
};

#[test]
fn draws_the_value_labels_at_the_outer_end_where_the_target_does() {
    let chart = labelled_columns(ABOVE, (Length::ZERO, Length::ZERO));
    // Where the target leaves them out, the chart is drawn without them and says so.
    assert_eq!(
        data_label_runs(&chart, ChartDataLabels::LeftOut, "2.25"),
        (Vec::new(), Some(false))
    );
    let (runs, all) = data_label_runs(&chart, ChartDataLabels::OuterEnd, "2.25");
    assert_eq!((runs.len(), all), (2, Some(true)));
    // The two bars of the first category stand side by side: so do their labels, on one
    // baseline.
    assert!(runs[0].0 < runs[1].0 && runs[0].1 == runs[1].1);
    // Labels in another form are not drawn, and the chart says so.
    let mut other = chart;
    other.series[1].labels = SeriesLabels::Other;
    other.other_labels = true;
    let (runs, all) = data_label_runs(&other, ChartDataLabels::OuterEnd, "2.25");
    assert_eq!((runs.len(), all), (1, Some(false)));
}

#[test]
fn puts_the_top_inset_between_a_bar_and_its_label_on_both_sides_of_the_crossing() {
    // The first glyph of the first label of the value `first`, shown as `text`, in a text box
    // of the insets `insets`.
    let place = |first: Decimal, text: &str, insets| {
        let chart = labelled_columns(first, insets);
        data_label_runs(&chart, ChartDataLabels::OuterEnd, text).0[0]
    };
    // Above a bar, the top inset raises the label by as much; the bottom inset does not move it.
    let plain = place(ABOVE, "2.25", (Length::ZERO, Length::ZERO));
    let raised = place(ABOVE, "2.25", (points(1), Length::ZERO));
    assert_eq!(raised, (plain.0, plain.1 - points(1)));
    assert_eq!(place(ABOVE, "2.25", (Length::ZERO, points(1))), plain);
    // Below a bar under the crossing, the top inset lowers it by as much; the bottom inset does
    // not move it.
    let negative = Decimal {
        digits: -225,
        exponent: -2,
    };
    let plain = place(negative, "-2.25", (Length::ZERO, Length::ZERO));
    let lowered = place(negative, "-2.25", (points(1), Length::ZERO));
    assert_eq!(lowered, (plain.0, plain.1 + points(1)));
    assert_eq!(place(negative, "-2.25", (Length::ZERO, points(1))), plain);
}

#[test]
fn sums_a_value_of_seventeen_digits_and_a_value_of_other_powers_of_ten() {
    let value = |text: &str| Decimal::parse(text).unwrap();
    // 1500 - 3.4500000000000002 = 1496.5499999999999998 has 20 digits; it keeps its highest
    // 19, rounded half away from zero.
    let total = super::sum(value("1500"), value("-3.4500000000000002")).unwrap();
    assert_eq!(total, value("1496.55"));
    let total = super::sum(value("1500"), value("-3.4500000000000042")).unwrap();
    assert_eq!(total, value("1496.549999999999996"));
    assert_eq!(super::sum(value("1"), value("2")).unwrap(), value("3"));
}

#[test]
fn writes_data_labels_in_their_format_with_its_blanks_and_its_color() {
    let separators = crate::NumberSeparators::new('.', ',').unwrap();
    let in_format = |first: Decimal, code: &str| {
        let mut chart = labelled_columns(first, (Length::ZERO, Length::ZERO));
        for series in &mut chart.series {
            if let SeriesLabels::Values(labels) = &mut series.labels {
                labels.format = LabelFormat::code(code, separators).unwrap();
            }
        }
        chart
    };
    let first_run = |chart: &Columns, text: &str| {
        let mut found = None;
        with_layout_on(
            |p| {
                p.with_variant(ChartPlotArea::FontLines)
                    .with_variant(ChartDataLabels::OuterEnd)
            },
            |layout| {
                let frame = Edges {
                    left: Length::ZERO,
                    top: Length::ZERO,
                    right: points(432),
                    bottom: points(252),
                };
                let (items, _) = layout.columns(chart, frame).unwrap();
                found = items.into_iter().find_map(|item| match item {
                    Item::Glyphs(run) if run.text == text => {
                        Some((run.glyphs[0].x, run.glyphs[0].y, run.color))
                    }
                    _ => None,
                });
            },
        );
        found.unwrap()
    };
    let accounting = r"#,##0.0_);[Red]\(#,##0.0\)";
    // A blank before the text is as wide as a parenthesis, and the label centered with it on
    // its bar: the text starts right of the same text without the blank, by less than the
    // blank. The blank at the end takes no room.
    let plain = first_run(&in_format(ABOVE, "0.0"), "2.3");
    let blank = first_run(&in_format(ABOVE, "_(0.0"), "2.3");
    assert!(blank.0 > plain.0 && blank.0 - plain.0 < points(3));
    assert_eq!((blank.1, blank.2), (plain.1, plain.2));
    assert_eq!(first_run(&in_format(ABOVE, accounting), "2.3"), plain);
    // Below zero, the second section writes the value in parentheses, in red.
    let negative = Decimal {
        digits: -225,
        exponent: -2,
    };
    let red = first_run(&in_format(negative, accounting), "(2.3)");
    assert_eq!(red.2, crate::params::CHART_FORMAT_RED);
    // A blank at the end of the value labels takes the room of a space, whatever its
    // character: the labels end as far left of the labels' gap, and the plot area starts as
    // far right, with its bars and their data labels, as with a space written at the end.
    let axis = |code: &str| {
        let mut chart = labelled_columns(ABOVE, (Length::ZERO, Length::ZERO));
        chart.value_format = LabelFormat::code(code, separators);
        chart
    };
    let (plain, blank, spaced) = (axis("0.0"), axis("0.0_)"), axis("0.0\\ "));
    assert_eq!(first_run(&blank, "2.5").0, first_run(&plain, "2.5").0);
    assert_eq!(first_run(&blank, "2.25").0, first_run(&spaced, "2.25").0);
    assert!(first_run(&blank, "2.25").0 > first_run(&plain, "2.25").0);
}

#[test]
fn centers_each_line_of_a_title_and_steps_its_baselines_by_the_single_line() {
    use crate::chart::TitleText;
    use crate::params::CHART_TITLE_LINE_TOP;
    let text = |lines: &[&str]| TitleText {
        lines: lines.iter().map(|&line| line.to_owned()).collect(),
        font: FontRef::MinorLatin,
        bold: false,
        italic: false,
        fill: None,
    };
    let title = |lines: &[&str]| Title {
        lines: lines.len(),
        size: 28,
        font: crate::props::FontRef::MinorLatin,
        text: Some(text(lines)),
        corner: None,
    };
    let frame = Edges {
        left: points(10),
        top: points(20),
        right: points(442),
        bottom: points(272),
    };
    let chart = columns(219, -27);
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let face = layout
                .shaper
                .face(&super::chart_props(&chart, 28), true)
                .and_then(|face| layout.shaper.faces().get(face).copied())
                .unwrap();
            let (line, descent) = (face.line_height(), face.win_line() - face.win_top());
            let items = layout
                .chart_title(&title(&["Ab", "", "Wide"]), frame)
                .unwrap();
            let runs: Vec<_> = items
                .into_iter()
                .filter_map(|item| match item {
                    Item::Glyphs(run) => Some(run),
                    _ => None,
                })
                .collect();
            // The empty line draws nothing and keeps its place.
            assert_eq!(runs.len(), 2);
            let first = frame.top + CHART_TITLE_LINE_TOP + line - descent;
            assert_eq!(runs[0].glyphs[0].y, first);
            assert_eq!(runs[1].glyphs[0].y, first + line * 2);
            for (run, shown) in runs.iter().zip(["Ab", "Wide"]) {
                let width = layout
                    .chart_text(&super::chart_props(&chart, 28), shown)
                    .unwrap()
                    .width();
                let middle = (frame.left + frame.right).div_toward_zero(2);
                assert_eq!(run.glyphs[0].x, middle - width.div_toward_zero(2));
            }
            // A word alone wider than the title's share of the frame draws no title.
            let narrow = Edges {
                right: frame.left + points(5),
                ..frame
            };
            assert!(layout.chart_title(&title(&["Wide"]), narrow).is_none());
            // A title whose text the reader does not keep draws none.
            let kept = Title {
                text: None,
                ..title(&["Ab"])
            };
            assert!(layout.chart_title(&kept, frame).is_none());
        },
    );
}

#[test]
fn puts_a_title_at_the_corner_of_its_manual_layout_centered_on_its_widest_line() {
    use crate::chart::{Decimal, LayoutCorner, TitleText};
    use crate::params::{CHART_TITLE_CORNER_LEFT, CHART_TITLE_CORNER_TOP};
    let part = |digits| Decimal {
        digits,
        exponent: -2,
    };
    let title = |x| Title {
        lines: 2,
        size: 28,
        font: crate::props::FontRef::MinorLatin,
        text: Some(TitleText {
            lines: vec!["Ab".to_owned(), "Wide".to_owned()],
            font: FontRef::MinorLatin,
            bold: false,
            italic: false,
            fill: None,
        }),
        corner: Some(LayoutCorner {
            x: part(x),
            y: part(5),
        }),
    };
    let frame = Edges {
        left: points(10),
        top: points(20),
        right: points(442),
        bottom: points(280),
    };
    let chart = columns(219, -27);
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let props = super::chart_props(&chart, 28);
            let face = layout
                .shaper
                .face(&props, true)
                .and_then(|face| layout.shaper.faces().get(face).copied())
                .unwrap();
            let (line, descent) = (face.line_height(), face.win_line() - face.win_top());
            let short = layout.chart_text(&props, "Ab").unwrap().width();
            let wide = layout.chart_text(&props, "Wide").unwrap().width();
            let starts = |layout: &mut crate::layout::Layout<'_>, x| {
                let items = layout.chart_title(&title(x), frame).unwrap();
                let runs: Vec<_> = items
                    .into_iter()
                    .filter_map(|item| match item {
                        Item::Glyphs(run) => Some((run.glyphs[0].x, run.glyphs[0].y)),
                        _ => None,
                    })
                    .collect();
                runs
            };
            // At 0.25 and 0.05 of the frame: the box at 118 pt and 33 pt.
            let runs = starts(layout, 25);
            let first = points(33) + CHART_TITLE_CORNER_TOP + line - descent;
            let left = points(118) + CHART_TITLE_CORNER_LEFT;
            let middle = left + wide.div_toward_zero(2);
            assert_eq!(runs[0], (middle - short.div_toward_zero(2), first));
            assert_eq!(runs[1], (left, first + line));
            // Near the right edge, the box moves left so that the widest line ends inside it.
            let runs = starts(layout, 99);
            assert_eq!(runs[1].0, frame.right - CHART_TITLE_CORNER_LEFT - wide);
        },
    );
}

#[test]
fn breaks_a_title_wider_than_its_share_of_the_frame_at_its_spaces() {
    use crate::chart::TitleText;
    use crate::params::{CHART_TITLE_LINE_INSET, CHART_TITLE_LINE_SHARE};
    let title = |line: &str| Title {
        lines: 1,
        size: 28,
        font: crate::props::FontRef::MinorLatin,
        text: Some(TitleText {
            lines: vec![line.to_owned()],
            font: FontRef::MinorLatin,
            bold: false,
            italic: false,
            fill: None,
        }),
        corner: None,
    };
    let chart = columns(219, -27);
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let props = super::chart_props(&chart, 28);
            let two = layout.chart_text(&props, "Ab Cd").unwrap().width();
            let three = layout.chart_text(&props, "Ab Cd Ef").unwrap().width();
            // A frame whose share, less the inset, holds the first two words and not the third.
            let width = (two + CHART_TITLE_LINE_INSET)
                .checked_mul(1000)
                .unwrap()
                .div_toward_zero(CHART_TITLE_LINE_SHARE)
                + points(1);
            let frame = Edges {
                left: points(10),
                top: points(20),
                right: points(10) + width,
                bottom: points(272),
            };
            let limit = width
                .checked_mul(CHART_TITLE_LINE_SHARE)
                .unwrap()
                .div_toward_zero(1000)
                - CHART_TITLE_LINE_INSET;
            assert!(two <= limit && three > limit);
            let items = layout.chart_title(&title("Ab Cd Ef"), frame).unwrap();
            let runs: Vec<_> = items
                .into_iter()
                .filter_map(|item| match item {
                    Item::Glyphs(run) => Some(run),
                    _ => None,
                })
                .collect();
            let shown: Vec<usize> = runs.iter().map(|run| run.glyphs.len()).collect();
            assert_eq!(shown, [5, 2]);
            let face = layout
                .shaper
                .face(&props, true)
                .and_then(|face| layout.shaper.faces().get(face).copied())
                .unwrap();
            assert_eq!(
                runs[1].glyphs[0].y - runs[0].glyphs[0].y,
                face.line_height()
            );
            assert_eq!(layout.title_line_count(&title("Ab Cd Ef"), frame), Some(2));
            // Two spaces in a row in a title to break: no text, and the reader's one line.
            assert!(layout.chart_title(&title("Ab  Cd Ef"), frame).is_none());
            assert_eq!(layout.title_line_count(&title("Ab  Cd Ef"), frame), Some(1));
            // A title that fits stays on one line.
            assert_eq!(layout.title_line_count(&title("Ab Cd"), frame), Some(1));
        },
    );
}

#[test]
fn takes_as_many_x_units_as_the_frame_holds_at_seven_and_a_half_zeros() {
    use super::scatter::x_units;
    // Zeros of 5 pt need 37.5 pt for a unit: a frame of 172 pt less 22 pt holds exactly 4.
    let zero = points(5);
    assert_eq!(x_units(points(172), zero), 4);
    assert_eq!(x_units(points(171), zero), 3);
    // At least one unit, at most ten, and ten for a zero without an advance.
    assert_eq!(x_units(points(10), zero), 1);
    assert_eq!(x_units(points(1_000), zero), 10);
    assert_eq!(x_units(points(172), Length::ZERO), 10);
}

/// One series of the values 3, 5, 1, 8 and 4 in a chart of `group` without a legend or a title.
fn five_points(group: ChartGroup) -> Columns {
    let one = Series {
        fill: SeriesFill::Color(DrawColor::rgb(Rgb::default())),
        values: ["3", "5", "1", "8", "4"].map(|v| Some(decimal(v))).to_vec(),
        name: None,
        labels: SeriesLabels::Hidden,
    };
    Columns {
        legend: None,
        ..Columns::plain(vec![one], 5, group, None)
    }
}

/// The x values 0, 2.25, 4.5, 6.75 and 9 of the series of [`five_points`].
fn quarter_x_values() -> Vec<Vec<Decimal>> {
    vec![["0", "2.25", "4.5", "6.75", "9"].map(decimal).to_vec()]
}

/// A line of 1 pt without markers.
fn plain_look() -> LineLook {
    LineLook {
        width: Some(StyleWidth::Set(points(1))),
        marker: None,
        form: LineForm::Straight,
        dash: None,
    }
}

#[test]
fn ends_a_scatter_charts_plot_area_half_its_last_x_label_left_of_its_twins() {
    use super::scatter::x_units;
    let scatter = five_points(ChartGroup::Scatter {
        looks: vec![plain_look()],
        x_values: quarter_x_values(),
        x_scale: SetScale::default(),
    });
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let frame = Edges {
                left: Length::ZERO,
                top: Length::ZERO,
                right: points(300),
                bottom: points(216),
            };
            let plot = Edges {
                left: points(21),
                top: points(10),
                right: points(289),
                bottom: points(180),
            };
            let props = super::chart_props(&scatter, scatter.label_size);
            let zero = layout.chart_text(&props, "0").unwrap().width();
            let (axis, right) = layout
                .x_axis(
                    &scatter,
                    (&quarter_x_values(), SetScale::default()),
                    (frame, plot),
                )
                .unwrap();
            // The axis over the quarter-step x values, from zero to the first multiple of its unit
            // at or above 1.05 times 9, in no more units than the frame holds.
            assert!(axis.steps <= x_units(points(300), zero));
            assert_eq!(axis.low, decimal("0"));
            assert!(axis.high >= decimal("9.45"));
            let last = all_digits(axis.label(axis.steps).unwrap());
            let width = layout.chart_text(&props, &last).unwrap().width();
            assert_eq!(right, plot.right - width.div_toward_zero(2));
            // The points at the axis' ends lie exactly at the plot area's edges.
            let span = (plot.left, right);
            assert_eq!(layout.place(&axis, span, axis.low), Some(plot.left));
            assert_eq!(layout.place(&axis, span, axis.high), Some(right));
        },
    );
}

#[test]
fn draws_a_scatter_chart_with_its_line_chart_twins_value_labels_and_its_x_labels() {
    let twin = five_points(ChartGroup::Lines {
        looks: vec![plain_look()],
        stacking: crate::chart::BarStacking::Clustered,
    });
    let scatter = five_points(ChartGroup::Scatter {
        looks: vec![plain_look()],
        x_values: quarter_x_values(),
        x_scale: SetScale::default(),
    });
    let twin_runs = label_runs(&twin, ChartPlotArea::FontLines);
    let runs = label_runs(&scatter, ChartPlotArea::FontLines);
    // The twin has no category names, so its runs are its value labels, which the scatter
    // chart draws first and alike.
    assert!(twin_runs.len() >= 2);
    assert_eq!(runs.get(..twin_runs.len()), Some(&twin_runs[..]));
    assert_x_labels(runs.get(twin_runs.len()..).unwrap_or_default(), &twin_runs);
    assert_eq!(all_text(&scatter, ChartPlotArea::FontLines), Some(true));
}

/// Asserts that `x_labels` start at 0 and stand from left to right on one baseline below the
/// value labels `value_labels`.
fn assert_x_labels(
    x_labels: &[(String, Length, Length)],
    value_labels: &[(String, Length, Length)],
) {
    assert!(x_labels.len() >= 2);
    assert_eq!(x_labels[0].0, "0");
    let baseline = x_labels[0].2;
    assert!(x_labels.iter().all(|label| label.2 == baseline));
    assert!(value_labels.iter().all(|label| label.2 < baseline));
    assert!(x_labels.windows(2).all(|pair| pair[0].1 < pair[1].1));
}

#[test]
fn clips_a_scatter_charts_lines_on_the_dots_to_its_plot_area_and_three_quarters_of_a_point_more() {
    use crate::params::CHART_SCATTER_CLIP_ROOM;
    use f_office_paint::GroupClip;
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let dot = layout.device.dots(1).units();
            let at = Length::from_units;
            let plot = Edges {
                left: at(dot * 100 + dot / 2),
                top: at(dot * 40 + 1),
                right: at(dot * 900 + dot / 3),
                bottom: at(dot * 500),
            };
            // The left edge and the top go down to their dots; the right edge and the bottom
            // reach 0.75 pt further and go down to theirs.
            let down = |units: i64| units.div_euclid(dot) * dot;
            let room = CHART_SCATTER_CLIP_ROOM.units();
            let right = down(dot * 900 + dot / 3 + room);
            let bottom = down(dot * 500 + room);
            assert_eq!(
                layout.lines_clip(plot),
                GroupClip::rect(
                    at(dot * 100),
                    at(dot * 40),
                    at(right - dot * 100),
                    at(bottom - dot * 40)
                )
            );
        },
    );
}

/// The groups of `chart`'s items in a frame of 432 by 252 pt on font lines: whether each has a
/// clip, and its items' count.
fn groups_of(chart: &Columns) -> Vec<(bool, usize)> {
    let (items, _) = font_line_items(chart);
    items
        .iter()
        .filter_map(|item| match item {
            Item::Group(group) => Some((group.clip.is_some(), group.items.len())),
            _ => None,
        })
        .collect()
}

#[test]
fn draws_each_scatter_line_alone_in_a_clip_and_a_line_charts_without_one() {
    let scatter = five_points(ChartGroup::Scatter {
        looks: vec![plain_look()],
        x_values: quarter_x_values(),
        x_scale: SetScale::default(),
    });
    assert_eq!(groups_of(&scatter), vec![(true, 1)]);
    let twin = five_points(ChartGroup::Lines {
        looks: vec![plain_look()],
        stacking: crate::chart::BarStacking::Clustered,
    });
    assert_eq!(groups_of(&twin), Vec::new());
}

/// The places in the items of `chart`, with an axis line across of its own color, on font lines
/// and the axis order `order` in a frame of 432 by 252 pt: of the axis line across, and of the
/// first item that is neither a rectangle nor glyphs (the first series line, alone or in its
/// clip).
fn axis_and_first_line(chart: &Columns, order: ChartAxisOrder) -> (Option<usize>, Option<usize>) {
    let axis_color = Rgb { r: 1, g: 2, b: 3 };
    let chart = Columns {
        axis: ShapeLook::plain(Geometry::Line, None, Some((axis_color, points(1)))),
        ..chart.clone()
    };
    let mut out = None;
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines).with_variant(order),
        |layout| {
            let frame = Edges {
                left: Length::ZERO,
                top: Length::ZERO,
                right: points(432),
                bottom: points(252),
            };
            out = layout.columns(&chart, frame).map(|(items, _)| items);
        },
    );
    let items = out.unwrap();
    let axis = items
        .iter()
        .position(|item| matches!(item, Item::Rect(rect) if rect.color == axis_color));
    let line = items
        .iter()
        .position(|item| !matches!(item, Item::Rect(_) | Item::Glyphs(_)));
    (axis, line)
}

#[test]
fn paints_the_axis_line_across_before_the_series_lines_where_the_target_does() {
    let scatter = five_points(ChartGroup::Scatter {
        looks: vec![plain_look()],
        x_values: quarter_x_values(),
        x_scale: SetScale::default(),
    });
    let twin = five_points(ChartGroup::Lines {
        looks: vec![plain_look()],
        stacking: crate::chart::BarStacking::Clustered,
    });
    for chart in [&scatter, &twin] {
        let (axis, line) = axis_and_first_line(chart, ChartAxisOrder::BeforeLines);
        assert!(axis.is_some() && line.is_some() && axis < line);
        let (axis, line) = axis_and_first_line(chart, ChartAxisOrder::Unknown);
        assert!(axis.is_some() && line.is_some() && axis > line);
    }
}

/// A point `x` and `y` tenths of a point from the page's corner.
fn tenths(x: i64, y: i64) -> f_office_paint::Point {
    f_office_paint::Point {
        x: Length::from_units(x * Length::UNITS_PER_POINT / 10),
        y: Length::from_units(y * Length::UNITS_PER_POINT / 10),
    }
}

#[test]
fn puts_a_smooth_lines_control_points_along_its_tangents() {
    use super::smooth::curves;
    // The tangents: at the first point a third of the first chord, (2, 0); at the inner point a
    // sixth of its neighbors' difference, (3.6, 4.8), 6 pt long; at the last point a third of
    // the last chord, (5.2, 9.6). The first chord is 6 pt long, so the longer tangent may reach
    // 3 pt and both tangents of the first curve are halved; the second chord is long enough for
    // both of its tangents.
    let (first, inner, last) = (tenths(0, 0), tenths(60, 0), tenths(216, 288));
    assert_eq!(
        curves(&[first, inner, last]),
        vec![
            [first, tenths(10, 0), tenths(42, -24), inner],
            [inner, tenths(96, 48), tenths(164, 192), last],
        ]
    );
    // Two points give a straight curve, with its control points a third of the way in.
    assert_eq!(
        curves(&[first, inner]),
        vec![[first, tenths(20, 0), tenths(40, 0), inner]]
    );
    assert_eq!(curves(&[first]).len(), 0);
}

#[test]
fn draws_a_smooth_series_in_curves_and_a_straight_one_in_pieces() {
    // The starts of the outlines of the series line, the chart's first path: a piece between
    // each two of its points
    // and a disc at each, so that five straight points give 4 pieces and 5 discs, and five
    // smooth points the 16 pieces of each of their 4 curves and a disc at each piece's ends.
    let starts = |form| {
        let chart = five_points(ChartGroup::Lines {
            looks: vec![LineLook {
                form,
                ..plain_look()
            }],
            stacking: crate::chart::BarStacking::Clustered,
        });
        let mut out = None;
        with_layout_on(
            |p| {
                p.with_variant(ChartPlotArea::FontLines)
                    .with_variant(ChartAxisOrder::BeforeLines)
            },
            |layout| {
                let frame = Edges {
                    left: Length::ZERO,
                    top: Length::ZERO,
                    right: points(432),
                    bottom: points(252),
                };
                out = layout.columns(&chart, frame).map(|(items, _)| items);
            },
        );
        let items = out.unwrap();
        let line = items.iter().find_map(|item| match item {
            Item::Path(path) => Some(path),
            _ => None,
        });
        line.unwrap()
            .commands
            .iter()
            .filter(|command| matches!(command, f_office_paint::PathCommand::MoveTo(_)))
            .count()
    };
    assert_eq!(starts(LineForm::Straight), 4 + 5);
    assert_eq!(starts(LineForm::Smooth), 4 * 16 + (4 * 16 + 1));
}

#[test]
fn shortens_each_dash_of_a_preset_by_a_width_and_lengthens_each_gap() {
    use super::dash_lengths;
    use crate::chart::LineDash;
    let width = Length::from_emus(28_575).unwrap();
    let quarters = |list: &[i64]| -> Vec<Length> {
        list.iter()
            .map(|&q| Length::from_units(q * Length::UNITS_PER_POINT / 4))
            .collect()
    };
    // At 2.25 pt, the arrays that Word writes for these presets.
    assert_eq!(
        dash_lengths(LineDash::Dash, width),
        Some(quarters(&[27, 36]))
    );
    assert_eq!(
        dash_lengths(LineDash::SystemDot, width),
        Some(quarters(&[0, 18]))
    );
    assert_eq!(
        dash_lengths(LineDash::LongDashDotDot, width),
        Some(quarters(&[63, 36, 0, 36, 0, 36]))
    );
}

#[test]
fn draws_a_dashed_series_line_as_its_dashes_and_leaves_out_a_chart_of_too_many() {
    use crate::chart::LineDash;
    // The outlines of the series line, the chart's first path, of a line `width` wide with the
    // dash `dash`, or `None` when the chart is left out.
    let starts = |width: Length, dash: Option<LineDash>| {
        let chart = five_points(ChartGroup::Lines {
            looks: vec![LineLook {
                width: Some(StyleWidth::Set(width)),
                dash,
                ..plain_look()
            }],
            stacking: crate::chart::BarStacking::Clustered,
        });
        let mut out = None;
        with_layout_on(
            |p| {
                p.with_variant(ChartPlotArea::FontLines)
                    .with_variant(ChartAxisOrder::BeforeLines)
            },
            |layout| {
                let frame = Edges {
                    left: Length::ZERO,
                    top: Length::ZERO,
                    right: points(432),
                    bottom: points(252),
                };
                out = Some(layout.columns(&chart, frame).map(|(items, _)| items));
            },
        );
        out.unwrap().map(|items| {
            let line = items.iter().find_map(|item| match item {
                Item::Path(path) => Some(path),
                _ => None,
            });
            line.unwrap()
                .commands
                .iter()
                .filter(|command| matches!(command, f_office_paint::PathCommand::MoveTo(_)))
                .count()
        })
    };
    let solid = starts(points(1), None).unwrap();
    assert_eq!(solid, 4 + 5);
    // Dots of 0 and gaps of 2 pt along a line of more than 300 pt: two discs for each dot.
    let dots = starts(points(1), Some(LineDash::SystemDot)).unwrap();
    assert!(dots > 2 * 150 && dots % 2 == 0, "{dots}");
    // A line of one unit of `Length` would take more dashes than the limit.
    assert_eq!(
        starts(Length::from_units(1), Some(LineDash::SystemDot)),
        None
    );
}

#[test]
fn clips_a_line_charts_lines_where_the_target_does() {
    use crate::quirks::ChartLineClip;
    // A line chart in a frame of 432 by 252 pt on font lines under the quirk `clip`: whether
    // each group of its items has a clip, and its items' count.
    let groups = |clip: ChartLineClip| {
        let chart = five_points(ChartGroup::Lines {
            looks: vec![plain_look()],
            stacking: crate::chart::BarStacking::Clustered,
        });
        let mut out = None;
        with_layout_on(
            |p| p.with_variant(ChartPlotArea::FontLines).with_variant(clip),
            |layout| {
                let frame = Edges {
                    left: Length::ZERO,
                    top: Length::ZERO,
                    right: points(432),
                    bottom: points(252),
                };
                out = layout.columns(&chart, frame).map(|(items, _)| items);
            },
        );
        out.unwrap()
            .iter()
            .filter_map(|item| match item {
                Item::Group(group) => Some((group.clip.is_some(), group.items.len())),
                _ => None,
            })
            .collect::<Vec<_>>()
    };
    assert_eq!(groups(ChartLineClip::PlotArea), vec![(true, 1)]);
    assert_eq!(groups(ChartLineClip::Unknown), Vec::new());
}

/// A chart of `group` without a title in the categories North and South, with three series
/// named A, B and C whose values are 1, 2 and 3 in the first category and 4, 5 and 6 in the
/// second, each in a red of its own (1, 2 and 3), and the legend at the bottom.
fn three_reds(group: ChartGroup) -> Columns {
    let series = (1_u8..=3)
        .map(|red| Series {
            fill: SeriesFill::Color(DrawColor::rgb(Rgb { r: red, g: 0, b: 0 })),
            values: vec![
                Some(decimal(&red.to_string())),
                Some(decimal(&(red + 3).to_string())),
            ],
            name: Some(["A", "B", "C"][usize::from(red - 1)].to_owned()),
            labels: SeriesLabels::Hidden,
        })
        .collect();
    Columns {
        category_names: Some(vec!["North".to_owned(), "South".to_owned()]),
        ..Columns::plain(series, 2, group, None)
    }
}

/// The red of each rectangle in one of the reds of [`three_reds`] among `items`, with the
/// rectangle, in painting order.
fn reds_of(items: &[Item]) -> Vec<(u8, f_office_paint::Rect)> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::Rect(rect) if rect.color.g == 0 && rect.color.b == 0 && rect.color.r > 0 => {
                Some((rect.color.r, rect.clone()))
            }
            _ => None,
        })
        .collect()
}

/// A gradient from red through green to blue at 270°, from the bottom to the top, with
/// `scaled` 0, as Word 2007's chart style writes three stops.
fn upward_gradient() -> LinearGradient {
    let xml = format!(
        r#"<a:gradFill xmlns:a="{}" rotWithShape="1"><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs><a:gs pos="80000"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst><a:lin ang="16200000" scaled="0"/></a:gradFill>"#,
        crate::ns::A
    );
    let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
    LinearGradient::read(&doc, doc.root().unwrap(), &mut Warnings::new()).unwrap()
}

/// The box of a gradient item that fills a box, from its top left to its bottom right corner.
fn gradient_box(item: &GradientItem) -> (Point, Point) {
    match item.commands[..] {
        [
            PathCommand::MoveTo(top_left),
            _,
            PathCommand::LineTo(bottom_right),
            ..,
        ] => (top_left, bottom_right),
        _ => panic!("not a box"),
    }
}

/// The gradient items among `items`, in painting order.
fn gradients_of(items: &[Item]) -> Vec<&GradientItem> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::Gradient(gradient) => Some(gradient),
            _ => None,
        })
        .collect()
}

/// The box of a rectangle, from its top left to its bottom right corner.
fn rect_box(rect: &f_office_paint::Rect) -> (Point, Point) {
    (
        Point {
            x: rect.x,
            y: rect.y,
        },
        Point {
            x: rect.x + rect.width,
            y: rect.y + rect.height,
        },
    )
}

/// Checks that the gradient bar `gradient` lies within a dot of `twin`, the box of the same
/// bar in a color, on the same bottom, the category axis, with its axis from the middle of its
/// bottom to the middle of its top.
fn assert_bar_beside_twin(gradient: &GradientItem, twin: (Point, Point)) {
    let near = |a: Point, b: Point| {
        (a.x - b.x).units().abs() < Length::UNITS_PER_DOT
            && (a.y - b.y).units().abs() < Length::UNITS_PER_DOT
    };
    let (top_left, bottom_right) = gradient_box(gradient);
    assert!(near(top_left, twin.0) && near(bottom_right, twin.1));
    assert_eq!(bottom_right.y, twin.1.y);
    let middle = (top_left.x + bottom_right.x).div_toward_zero(2);
    assert_eq!(gradient.start.x, gradient.end.x);
    assert!((gradient.start.x - middle).units().abs() <= 1);
    assert_eq!(
        (gradient.start.y, gradient.end.y),
        (bottom_right.y, top_left.y)
    );
}

#[test]
fn paints_a_gradient_series_at_its_exact_places_and_its_key_over_the_key() {
    let solid = three_reds(ChartGroup::Columns {
        gap: 219,
        overlap: -27,
        stacking: crate::chart::BarStacking::Clustered,
    });
    let mut chart = solid.clone();
    chart.series[1].fill = SeriesFill::Gradient(upward_gradient());
    let solid_reds = reds_of(&font_line_items(&solid).0);
    let (items, _) = font_line_items(&chart);
    let gradients = gradients_of(&items);
    // The two bars of the second series and its key, which no longer paint a rectangle.
    assert_eq!(gradients.len(), 3);
    assert_eq!(reds_of(&items).len(), 6);
    let twins: Vec<_> = solid_reds
        .iter()
        .filter(|(red, _)| *red == 2)
        .map(|(_, rect)| rect_box(rect))
        .collect();
    for (gradient, twin) in gradients.iter().zip(&twins) {
        assert_bar_beside_twin(gradient, *twin);
    }
    // At least one edge of a bar lies off the device, where its twin's lies on it.
    assert!(
        gradients
            .iter()
            .take(2)
            .zip(&twins)
            .any(|(gradient, twin)| gradient_box(gradient) != *twin)
    );
    // The key fills the box of its twin's key.
    assert_eq!(gradient_box(gradients[2]), twins[2]);
}

/// The run of `runs` whose text is `text`.
fn run<'a>(runs: &[(&'a str, Length, Length)], text: &str) -> (&'a str, Length, Length) {
    runs.iter()
        .find(|(found, _, _)| *found == text)
        .copied()
        .unwrap()
}

#[test]
fn turns_the_bars_of_a_horizontal_bar_chart_up_from_the_bottom() {
    let chart = three_reds(ChartGroup::Bars {
        gap: 219,
        overlap: -27,
        stacking: crate::chart::BarStacking::Clustered,
    });
    let (items, _) = font_line_items(&chart);
    let reds = reds_of(&items);
    // Six bars, by series and then by category, and the legend's three keys after them.
    assert_eq!(reds.len(), 9);
    let bars = &reds[..6];
    let bar = |red: u8, category: usize| bars[usize::from(red - 1) * 2 + category].1.clone();
    assert!(
        bars.iter()
            .zip([1, 1, 2, 2, 3, 3])
            .all(|(found, red)| found.0 == red)
    );
    // Every bar starts at the category axis, and a larger value gives a longer bar.
    assert!(bars.iter().all(|(_, rect)| rect.x == bars[0].1.x));
    let mut by_value: Vec<_> = (1..=3)
        .flat_map(|red| [(red, bar(red, 0)), (red + 3, bar(red, 1))])
        .collect();
    by_value.sort_by_key(|&(value, _)| value);
    assert!(
        by_value
            .windows(2)
            .all(|two| two[0].1.width < two[1].1.width)
    );
    // The first category's band lies below the second's, and in a band the first series'
    // bar stands lowest.
    assert!((1..=3).all(|red| bar(red, 0).y > bar(3, 1).y + bar(3, 1).height));
    assert!((1..3).all(|red| bar(red, 0).y > bar(red + 1, 0).y));
    assert!((1..3).all(|red| bar(red, 1).y > bar(red + 1, 1).y));
}

#[test]
fn names_the_series_of_a_horizontal_bar_chart_in_the_reverse_order_in_its_legend() {
    let chart = three_reds(ChartGroup::Bars {
        gap: 219,
        overlap: -27,
        stacking: crate::chart::BarStacking::Clustered,
    });
    let (items, _) = font_line_items(&chart);
    let reds = reds_of(&items);
    // The legend's three keys follow the six bars: C, B and A from the left.
    assert_eq!(reds.len(), 9);
    let mut keys = reds[6..].to_vec();
    keys.sort_by_key(|(_, rect)| rect.x);
    assert_eq!(
        keys.iter().map(|(red, _)| *red).collect::<Vec<_>>(),
        [3, 2, 1]
    );
    let names: Vec<_> = runs_of(&items)
        .into_iter()
        .filter(|(text, _, _)| ["A", "B", "C"].contains(text))
        .map(|(text, _, _)| text)
        .collect();
    assert_eq!(names, ["C", "B", "A"]);
}

#[test]
fn draws_the_value_labels_of_horizontal_bars_across_the_bottom_and_the_categories_at_the_left() {
    let chart = three_reds(ChartGroup::Bars {
        gap: 219,
        overlap: -27,
        stacking: crate::chart::BarStacking::Clustered,
    });
    let twin = three_reds(ChartGroup::Columns {
        gap: 219,
        overlap: -27,
        stacking: crate::chart::BarStacking::Clustered,
    });
    let (items, lines) = font_line_items(&chart);
    let runs = runs_of(&items);
    let (twin_items, _) = font_line_items(&twin);
    let twin_runs = runs_of(&twin_items);
    // The value labels stand on one baseline from the left, on the twin's category labels'
    // baseline, as the plot area keeps the twin's bottom.
    let values: Vec<_> = runs
        .iter()
        .filter(|(text, _, _)| text.parse::<i64>().is_ok())
        .collect();
    assert!(values.len() >= 4 && values[0].0 == "0");
    assert!(
        values
            .windows(2)
            .all(|two| two[0].1 < two[1].1 && two[0].2 == two[1].2)
    );
    assert_eq!(values[0].2, run(&twin_runs, "North").2);
    // The category labels stand at the left, the first one lowest, each a band apart.
    let (north, south) = (run(&runs, "North"), run(&runs, "South"));
    assert!(north.1 < values[0].1 && north.2 > south.2);
    let band = north.2 - south.2;
    assert!(band > lines.line);
    assert_eq!(all_text(&chart, ChartPlotArea::FontLines), Some(true));
}

#[test]
fn centers_the_data_labels_of_horizontal_bars_on_their_bars_and_keeps_the_gap_beyond_them() {
    // The first glyph of the label 1 of the first series in a text box of `insets`.
    let place = |insets: Edges<Length>| {
        let mut chart = three_reds(ChartGroup::Bars {
            gap: 219,
            overlap: -27,
            stacking: crate::chart::BarStacking::Clustered,
        });
        chart.series[0].labels = SeriesLabels::Values(DataLabelText {
            position: crate::chart::DataLabelPosition::Default,
            size: 18,
            font: FontRef::MinorLatin,
            fill: None,
            insets,
            format: LabelFormat::all_digits(),
            parts: crate::chart::DataLabelParts::default(),
            show_default: true,
            point_overrides: Vec::new(),
        });
        let (runs, all) = data_label_runs(&chart, ChartDataLabels::OuterEnd, "1");
        assert_eq!(all, Some(true));
        runs[0]
    };
    let none = Edges {
        left: Length::ZERO,
        top: Length::ZERO,
        right: Length::ZERO,
        bottom: Length::ZERO,
    };
    let plain = place(none);
    // The left inset moves the label right by as much; the right inset does not move it.
    let left = place(Edges {
        left: points(1),
        ..none
    });
    assert_eq!(left, (plain.0 + points(1), plain.1));
    assert_eq!(
        place(Edges {
            right: points(1),
            ..none
        }),
        plain
    );
    // The box is centered up and down: a top inset lowers the text by half of it, a bottom
    // inset raises it by half.
    let half = points(1).div_toward_zero(2);
    assert_eq!(
        place(Edges {
            top: points(1),
            ..none
        }),
        (plain.0, plain.1 + half)
    );
    assert_eq!(
        place(Edges {
            bottom: points(1),
            ..none
        }),
        (plain.0, plain.1 - half)
    );
}

#[test]
fn puts_the_legend_of_horizontal_bars_at_the_right_where_the_twins_stands() {
    let at_right = |group| Columns {
        legend: Some(LegendPlace::Right),
        ..three_reds(group)
    };
    let left_edges = |chart: &Columns| {
        let (items, _) = font_line_items(chart);
        let reds = reds_of(&items);
        let keys = &reds[reds.len() - 3..];
        keys.iter().map(|(_, rect)| rect.x).collect::<Vec<_>>()
    };
    let bars = left_edges(&at_right(ChartGroup::Bars {
        gap: 219,
        overlap: -27,
        stacking: crate::chart::BarStacking::Clustered,
    }));
    let twin = left_edges(&at_right(ChartGroup::Columns {
        gap: 219,
        overlap: -27,
        stacking: crate::chart::BarStacking::Clustered,
    }));
    assert_eq!(bars, twin);
}

/// `shown` with its value axis deleted.
fn with_deleted_value_axis(shown: &Columns) -> Columns {
    Columns {
        axis_forms: AxisForms {
            value_deleted: true,
            ..AxisForms::default()
        },
        ..shown.clone()
    }
}

/// The legends of the charts of the tests of a deleted value axis: at the bottom, none, and
/// at the right.
const DELETED_AXIS_LEGENDS: [(Option<LegendPlace>, Option<Title>); 3] = [
    (Some(LegendPlace::Bottom), None),
    (None, None),
    (Some(LegendPlace::Right), None),
];

#[test]
fn gives_the_room_of_a_deleted_value_axis_to_the_plot_area_on_font_lines() {
    let shown = drawn_text_columns();
    let deleted = with_deleted_value_axis(&shown);
    let shown_plots = font_line_plots(&shown, &DELETED_AXIS_LEGENDS);
    let deleted_plots = font_line_plots(&deleted, &DELETED_AXIS_LEGENDS);
    for (shown, deleted) in shown_plots.into_iter().zip(deleted_plots) {
        let (shown, deleted) = (shown.unwrap(), deleted.unwrap());
        // The plot area starts as far inside the frame's left edge as it ends inside its
        // right edge, and keeps its top, its right and its bottom.
        assert_eq!(
            deleted,
            Edges {
                left: CHART_PLOT_RIGHT,
                ..shown
            }
        );
        assert!(shown.left > deleted.left);
    }
}

#[test]
fn draws_no_value_labels_of_a_deleted_value_axis_and_keeps_the_category_labels() {
    let shown = drawn_text_columns();
    let deleted = with_deleted_value_axis(&shown);
    let texts = |chart| {
        label_runs(chart, ChartPlotArea::FontLines)
            .into_iter()
            .map(|run| run.0)
            .collect::<Vec<_>>()
    };
    let numbers = |texts: &[String]| texts.iter().filter(|t| t.parse::<f64>().is_ok()).count();
    assert!(numbers(&texts(&shown)) > 0);
    let deleted_texts = texts(&deleted);
    assert_eq!(numbers(&deleted_texts), 0);
    assert!(deleted_texts.contains(&"One".to_owned()));
    assert_eq!(all_text(&deleted, ChartPlotArea::FontLines), Some(true));
}

#[test]
fn places_the_inner_box_of_a_manual_layout_beside_a_deleted_value_axis() {
    // In a manual layout, the inner box is the plot area; the outer box holds the value
    // labels, and these rules do not place it without them.
    let deleted = with_deleted_value_axis(&drawn_text_columns());
    let manual = |inner| Columns {
        plot_place: PlotPlace::Manual(PlotLayout {
            inner,
            edges: plot_box(),
        }),
        ..deleted.clone()
    };
    let legends = &DELETED_AXIS_LEGENDS[..1];
    let inner = font_line_plots(&manual(true), legends);
    assert_eq!(
        inner[0].map(|plot| plot.left),
        Some(Length::from_emus(548_640).unwrap())
    );
    assert_eq!(font_line_plots(&manual(false), legends), [None]);
}

#[test]
fn ends_the_bars_of_a_deleted_value_axis_at_the_column_charts_right_edge() {
    // An axis up to 6, the longest bar's value, so that the longest bar ends at the plot
    // area's right edge.
    let shown = Columns {
        scale: SetScale {
            max: Some(decimal("6")),
            ..SetScale::default()
        },
        ..three_reds(ChartGroup::Bars {
            gap: 219,
            overlap: -27,
            stacking: crate::chart::BarStacking::Clustered,
        })
    };
    let deleted = Columns {
        axis_forms: AxisForms {
            value_deleted: true,
            ..AxisForms::default()
        },
        ..shown.clone()
    };
    let bars = |chart: &Columns| {
        let (items, _) = font_line_items(chart);
        reds_of(&items)[..6].to_vec()
    };
    let (shown_bars, deleted_bars) = (bars(&shown), bars(&deleted));
    // The bars start at the same category axis, after the category labels, and grow longer
    // with the wider plot area; the bands reach lower without the band of value labels.
    assert!(
        shown_bars
            .iter()
            .zip(&deleted_bars)
            .all(|(a, b)| a.1.x == b.1.x && a.1.width < b.1.width && a.1.y < b.1.y)
    );
    // The longest bar ends within a point of the right edge of a column chart's plot area.
    let longest = deleted_bars
        .iter()
        .map(|(_, rect)| rect.x + rect.width)
        .max()
        .unwrap();
    let right = points(432) - CHART_PLOT_RIGHT;
    assert!(longest.max(right) - longest.min(right) <= points(1));
    // No value labels across the bottom, and all of the chart's text.
    let runs = runs_of(&font_line_items(&deleted).0)
        .into_iter()
        .filter(|(text, _, _)| text.parse::<f64>().is_ok())
        .count();
    assert_eq!(runs, 0);
    assert_eq!(all_text(&deleted, ChartPlotArea::FontLines), Some(true));
}

#[test]
fn draws_low_category_labels_below_the_plot_area_on_font_lines() {
    let mut inside = drawn_text_columns();
    inside.series[0].values[0] = Some(decimal("-1"));
    let low = Columns {
        axis_forms: AxisForms {
            low_labels: true,
            ..AxisForms::default()
        },
        ..inside.clone()
    };
    let cases = [(Some(LegendPlace::Bottom), None)];
    let above_zero = font_line_plots(&drawn_text_columns(), &cases)[0].unwrap();
    let inside_plot = font_line_plots(&inside, &cases)[0].unwrap();
    let low_plot = font_line_plots(&low, &cases)[0].unwrap();
    // Low labels keep their band below the plot area, as above zero.
    assert_eq!(low_plot.bottom, above_zero.bottom);
    assert!(inside_plot.bottom > low_plot.bottom);
    // They stand below the plot area, on the baseline of labels at an axis at its bottom,
    // and the chart holds all of its text.
    let runs = label_runs(&low, ChartPlotArea::FontLines);
    let lines = font_line_items(&low).1;
    let one = run(
        &runs
            .iter()
            .map(|(text, x, y)| (text.as_str(), *x, *y))
            .collect::<Vec<_>>(),
        "One",
    );
    assert_eq!(one.2, low_plot.bottom + lines.category_baseline().unwrap());
    assert_eq!(all_text(&low, ChartPlotArea::FontLines), Some(true));
    assert_eq!(all_text(&inside, ChartPlotArea::FontLines), Some(true));
    let inside_runs = label_runs(&inside, ChartPlotArea::FontLines);
    let inside_one = run(
        &inside_runs
            .iter()
            .map(|(text, x, y)| (text.as_str(), *x, *y))
            .collect::<Vec<_>>(),
        "One",
    );
    assert!(inside_one.2 < one.2);
}

#[test]
fn cuts_a_pie_into_the_shares_of_its_values_from_its_first_angle() {
    let values = |all: &[i64]| -> Vec<Option<Decimal>> {
        all.iter()
            .map(|&digits| {
                Some(Decimal {
                    digits,
                    exponent: 0,
                })
            })
            .collect()
    };
    // From the top, clockwise: a quarter, a half and a quarter of a turn.
    assert_eq!(
        super::pie::slice_angles(&values(&[1, 2, 1]), 0),
        Some(vec![
            (-5_400_000, 5_400_000),
            (0, 10_800_000),
            (10_800_000, 5_400_000)
        ])
    );
    // A first angle of 90 degrees starts at the right; the ends round to the nearest.
    assert_eq!(
        super::pie::slice_angles(&values(&[1, 1, 1]), 90),
        Some(vec![
            (0, 7_200_000),
            (7_200_000, 7_200_000),
            (14_400_000, 7_200_000)
        ])
    );
    assert_eq!(super::pie::slice_angles(&values(&[0, 0]), 0), None);
    assert_eq!(super::pie::slice_angles(&values(&[2, -1]), 0), None);
}

#[test]
fn draws_a_3d_pie_as_one_picture_of_its_plot_area() {
    use crate::chart::PieView;
    use f_office_paint::ImageFormat;
    let hundredths = |value: i64| Length::from_units(value * Length::UNITS_PER_POINT / 100);
    let plot = Edges {
        left: hundredths(8_300),
        top: hundredths(9_644),
        right: hundredths(8_300 + 40_998),
        bottom: hundredths(9_644 + 22_998),
    };
    let view = PieView {
        tilt: 30,
        field_of_view: 15,
    };
    let colors = [
        Rgb {
            r: 68,
            g: 114,
            b: 196,
        },
        Rgb {
            r: 237,
            g: 125,
            b: 49,
        },
    ];
    let angles = [(-5_400_000, 12_600_000), (7_200_000, 9_000_000)];
    let Item::Image(picture) = super::pie::PiePicture::of(plot, view, &angles, &colors, &[0, 0])
        .unwrap()
        .item()
    else {
        panic!("no picture");
    };
    assert_eq!((picture.x, picture.y), (plot.left, plot.top));
    assert_eq!(picture.width, plot.right - plot.left);
    assert_eq!(picture.height, plot.bottom - plot.top);
    assert_eq!(picture.image.format, ImageFormat::EffectPicture);
    // 409.98 by 229.98 pt at 200 pixels per inch, rounded, and one pixel more, as on Word's page.
    let drawn = f_office_effects::draw(&picture.image.load_bytes().unwrap(), u64::MAX).unwrap();
    assert_eq!((drawn.width, drawn.height), (1140, 640));
}

#[test]
fn shrinks_the_picture_of_a_3d_pie_whose_labels_may_stand_outside() {
    use crate::chart::PieView;
    let hundredths = |value: i64| Length::from_units(value * Length::UNITS_PER_POINT / 100);
    let plot = Edges {
        left: hundredths(8_300),
        top: hundredths(9_644),
        right: hundredths(8_300 + 40_998),
        bottom: hundredths(9_644 + 22_998),
    };
    let view = PieView {
        tilt: 30,
        field_of_view: 15,
    };
    let angles = [(-5_400_000, 21_600_000)];
    let colors = [Rgb { r: 0, g: 0, b: 0 }];
    assert_eq!(super::pie::picture_plot(plot, false), Some(plot));
    let shrunk = super::pie::picture_plot(plot, true).unwrap();
    let middle = |low: Length, high: Length| (low + high).div_toward_zero(2);
    let close = |a: Length, b: Length| (a - b).units().abs() <= 1;
    assert!(close(
        middle(shrunk.left, shrunk.right),
        middle(plot.left, plot.right)
    ));
    assert!(close(
        middle(shrunk.top, shrunk.bottom),
        middle(plot.top, plot.bottom)
    ));
    // Word draws this pie with labels at the outer end in 990 by 552 pixels.
    let Item::Image(picture) = super::pie::PiePicture::of(shrunk, view, &angles, &colors, &[0])
        .unwrap()
        .item()
    else {
        panic!("no picture");
    };
    let drawn = f_office_effects::draw(&picture.image.load_bytes().unwrap(), u64::MAX).unwrap();
    assert_eq!((drawn.width, drawn.height), (990, 552));
}

#[test]
fn puts_a_3d_pie_of_a_manual_layout_over_its_box_inner_or_outer() {
    let frame = Edges {
        left: Length::ZERO,
        top: Length::ZERO,
        right: points(400),
        bottom: points(200),
    };
    let manual = |inner| Columns {
        plot_place: PlotPlace::Manual(PlotLayout {
            inner,
            edges: plot_box(),
        }),
        ..drawn_text_columns()
    };
    let mut plots = Vec::new();
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            for (inner, three_d) in [(true, true), (false, true), (true, false)] {
                let plot = layout.pie_plot(&manual(inner), frame, three_d);
                plots.push(plot.map(|(plot, _)| plot));
            }
        },
    );
    // The box (0.1, 0.15, 0.8, 0.6) of the frame of 400 by 200 pt; a 2-D pie leaves it out.
    let expected = Edges {
        left: points(40),
        top: points(30),
        right: points(360),
        bottom: points(150),
    };
    assert_eq!(plots, [Some(expected), Some(expected), None]);
}

#[test]
fn centers_the_labels_of_a_3d_pie_on_its_top_face() {
    use crate::chart::PieView;
    let plot = Edges {
        left: points(100),
        top: points(100),
        right: points(500),
        bottom: points(300),
    };
    let view = PieView {
        tilt: 30,
        field_of_view: 15,
    };
    let angles = [(-5_400_000, 21_600_000)];
    let colors = [Rgb { r: 0, g: 0, b: 0 }];
    let picture = super::pie::PiePicture::of(plot, view, &angles, &colors, &[0]).unwrap();
    let at = |degrees: i64| picture.label_center(degrees * 60_000, 0).unwrap();
    let (right, near, left, far) = (at(0), at(90), at(180), at(270));
    let middle = points(300);
    assert_eq!(right.y, left.y);
    assert_eq!((right.x - middle) + (left.x - middle), Length::ZERO);
    assert!((near.x - middle).units().abs() <= 1 && (far.x - middle).units().abs() <= 1);
    // The near half of the top face looks larger than the far half in perspective.
    assert!(near.y - right.y > right.y - far.y);
    assert!(far.y > plot.top && near.y < plot.bottom);
}

#[test]
fn shifts_a_3d_pie_label_center_outward_when_its_slice_is_pulled_out() {
    use crate::chart::PieView;
    let plot = Edges {
        left: points(100),
        top: points(100),
        right: points(500),
        bottom: points(300),
    };
    let view = PieView {
        tilt: 30,
        field_of_view: 15,
    };
    let angles = [(-5_400_000, 10_800_000), (5_400_000, 10_800_000)];
    let colors = [
        Rgb { r: 0, g: 0, b: 0 },
        Rgb {
            r: 100,
            g: 100,
            b: 100,
        },
    ];
    let plain = super::pie::PiePicture::of(plot, view, &angles, &colors, &[0, 0]).unwrap();
    let pulled = super::pie::PiePicture::of(plot, view, &angles, &colors, &[25, 0]).unwrap();
    assert!(pulled.label_center(0, 25).unwrap().x > plain.label_center(0, 0).unwrap().x);
    assert!(pulled.label_center(0, 0).unwrap().x < plain.label_center(0, 0).unwrap().x);
}

#[test]
fn places_3d_pie_labels_at_inner_end_and_outer_end() {
    use crate::chart::{PieLabelPlace, PieView};
    let plot = Edges {
        left: points(100),
        top: points(100),
        right: points(500),
        bottom: points(300),
    };
    let view = PieView {
        tilt: 30,
        field_of_view: 15,
    };
    let angles = [(-5_400_000, 21_600_000)];
    let colors = [Rgb { r: 0, g: 0, b: 0 }];
    let picture = super::pie::PiePicture::of(plot, view, &angles, &colors, &[0]).unwrap();
    let size = (points(18), points(10));
    let at = |place, degrees: i64| picture.label_box_center(place, degrees * 60_000, 0, size);
    let center_right = at(PieLabelPlace::Center, 0).unwrap();
    let inner_right = at(PieLabelPlace::InnerEnd, 0).unwrap();
    let outer_right = at(PieLabelPlace::OuterEnd, 0).unwrap();
    assert!(inner_right.x > center_right.x && outer_right.x > inner_right.x);
    let inner_front = at(PieLabelPlace::InnerEnd, 90).unwrap();
    let outer_front = at(PieLabelPlace::OuterEnd, 90).unwrap();
    let inner_back = at(PieLabelPlace::InnerEnd, 270).unwrap();
    let outer_back = at(PieLabelPlace::OuterEnd, 270).unwrap();
    assert!(outer_front.y > inner_front.y && outer_back.y < inner_back.y);
    assert_eq!(at(PieLabelPlace::BestFit, 0), None);
}

#[test]
fn lists_categories_in_forward_order_for_varied_single_series_bar_legend() {
    use crate::chart::{ChartGroup, SeriesFill};
    use f_office_drawingml::color::{DrawColor, SchemeSlot};
    let fills = vec![
        DrawColor::scheme(SchemeSlot::Accent1),
        DrawColor::scheme(SchemeSlot::Accent2),
    ];
    let mut chart = drawn_text_columns();
    chart.group = ChartGroup::Bars {
        gap: 150,
        overlap: 0,
        stacking: crate::chart::BarStacking::Clustered,
    };
    chart.category_names = Some(vec!["Cat 1".to_owned(), "Cat 2".to_owned()]);
    chart.series.truncate(1);
    chart.series[0].fill = SeriesFill::Points(fills);
    let names: Vec<_> = super::legend::legend_entries(&chart)
        .into_iter()
        .map(|(name, _)| name)
        .collect();
    assert_eq!(names, vec![Some("Cat 1"), Some("Cat 2")]);
}

#[test]
fn shrinks_a_2d_pie_by_series_explosion_and_shifts_each_slice_apex() {
    use f_office_paint::Point;
    let base = points(100);
    assert_eq!(super::pie::exploded_radius(base, 0), Some(points(100)));
    assert_eq!(super::pie::exploded_radius(base, 25), Some(points(80)));
    let center = Point {
        x: points(200),
        y: points(200),
    };
    let shifted = super::pie::slice_center(center, points(80), 0, 25).unwrap();
    assert_eq!((shifted.x, shifted.y), (points(220), points(200)));
    assert_eq!(
        super::pie::slice_center(center, points(80), 0, 0),
        Some(center)
    );
}

#[test]
fn places_the_labels_of_a_pie_at_the_inner_and_the_outer_end() {
    use crate::chart::PieLabelPlace;
    use f_office_paint::Point;
    let center = Point {
        x: points(200),
        y: points(200),
    };
    let place = |place, bisector| {
        let size = (points(20), points(10));
        let found = super::pie::box_center(place, (center, points(100)), bisector, size).unwrap();
        (found.x - center.x, found.y - center.y)
    };
    // At the inner end on the right, a box 20 pt wide reaches 10 pt along the bisector and
    // stays 3.7 pt inside the circle: 86.3 pt from the center.
    assert_eq!(
        place(PieLabelPlace::InnerEnd, 0),
        (Length::from_units(2_192_020), Length::ZERO)
    );
    // At the outer end on the right, the point lies 5.11 pt out, and 1.016 of the box's half
    // width beyond it: 115.27 pt.
    assert_eq!(
        place(PieLabelPlace::OuterEnd, 0),
        (Length::from_units(2_927_858), Length::ZERO)
    );
    // Straight down, the point lies 4 pt out and the box's top stands at it.
    assert_eq!(
        place(PieLabelPlace::OuterEnd, 5_400_000),
        (Length::ZERO, points(109))
    );
    // Down and 45 degrees to the right, the box's near corner stands at the point.
    let (end, _) =
        f_office_drawingml::custom::circle_arc(center, points(100), [2_700_000, 0]).unwrap();
    let (across, down) = (end.x - center.x, end.y - center.y);
    assert_eq!(
        place(PieLabelPlace::OuterEnd, 2_700_000),
        (
            across
                + across.checked_mul(511).unwrap().div_round(10_000)
                + Length::from_units(258_064),
            down + down.div_round(25) + points(5)
        )
    );
}

#[test]
fn keeps_seven_eighths_of_a_pie_and_its_edge_for_labels_outside() {
    // 117 pt and the 11-pt edge are 128 pt, of which 7/8 are 112 pt: a radius of 101 pt.
    assert_eq!(
        super::pie::inside_labels_radius(points(117)),
        Some(points(101))
    );
}

/// The chart of [`named_columns`] without a title, whose legend at `place` stands in the box
/// `x`, `y`, `w` and `h` of its manual layout, in thousandths of the frame.
fn boxed_chart(place: LegendPlace, edges: [i64; 4]) -> Columns {
    let [x, y, w, h] = edges.map(|digits| Decimal {
        digits,
        exponent: -3,
    });
    Columns {
        title: None,
        legend: Some(place),
        legend_box: LegendBox::Manual(LayoutBox { x, y, w, h }),
        ..named_columns()
    }
}

/// The keys of the legend of `chart` drawn in the frame of [`font_line_items`], the box of
/// its manual layout `edges` in that frame, the drawn widths of its entries "A" and "Longer"
/// (key, gap and name) and the keys' side.
fn boxed_keys_of(chart: &Columns, edges: [i64; 4]) -> BoxedKeys {
    let (items, lines) = font_line_items(chart);
    let side = lines.of_line(450).unwrap();
    let gap = side.div_toward_zero(2) - hundredths(32);
    let drawn = name_widths(chart, &["A", "Longer"])
        .into_iter()
        .map(|width| side + gap + width)
        .collect();
    let frame = Edges {
        left: Length::ZERO,
        top: Length::ZERO,
        right: points(432),
        bottom: points(252),
    };
    let [x, y, w, h] = edges.map(|digits| Decimal {
        digits,
        exponent: -3,
    });
    BoxedKeys {
        keys: keys_of(&items, side),
        edges: layout_edges(frame, LayoutBox { x, y, w, h }).unwrap(),
        drawn,
        side,
    }
}

/// What [`boxed_keys_of`] gives.
struct BoxedKeys {
    keys: Vec<(Length, Length)>,
    edges: Edges<Length>,
    drawn: Vec<Length>,
    side: Length,
}

#[test]
fn puts_a_legend_whose_entries_fit_in_its_box_in_one_row_with_equal_spaces() {
    let edges = [100, 800, 800, 150];
    let BoxedKeys {
        keys,
        edges: area,
        drawn,
        side,
    } = boxed_keys_of(&boxed_chart(LegendPlace::Bottom, edges), edges);
    let [(first, middle), (second, other)] = keys[..] else {
        panic!("{keys:?}")
    };
    assert_eq!(
        middle,
        area.top + (area.bottom - area.top).div_toward_zero(2)
    );
    assert_eq!(other, middle);
    // Each key stands a quarter of its side and 2.763 pt into its entry, which counts 2.847 pt
    // beyond its drawn width; equal spaces stand before, between and after the entries.
    let into = side.div_toward_zero(2).div_toward_zero(2) + thousandths(2_763);
    let counted: Vec<Length> = drawn.iter().map(|&d| d + thousandths(2_847)).collect();
    let before = first - into - area.left;
    let between = second - first - counted[0];
    let after = area.right - (second - into + counted[1]);
    assert_eq!(before, between);
    let unit = Length::from_units(3);
    assert!(
        (-unit..=unit).contains(&(after - before)),
        "{before:?} {after:?}"
    );
}

#[test]
fn puts_a_legend_in_one_column_at_a_side_and_at_the_bottom_of_its_narrow_box() {
    let edges = [700, 100, 100, 800];
    let right = boxed_keys_of(&boxed_chart(LegendPlace::Right, edges), edges);
    let bottom = boxed_keys_of(&boxed_chart(LegendPlace::Bottom, edges), edges);
    let area = right.edges;
    let (width, row) = (
        area.right - area.left,
        (area.bottom - area.top).div_toward_zero(2),
    );
    let widest = right.drawn[1].max(right.drawn[0]);
    let half_side = right.side.div_toward_zero(2);
    // At the right, the widest drawn entry less half a key's side is centered, and the keys
    // stand 0.170 pt before its left edge; at the bottom, its counted width less half a key's
    // side is centered, and the keys stand 2.763 pt into it.
    let left = area.left + (width - widest + half_side).div_toward_zero(2) - thousandths(170);
    let middles = [
        area.top + row.div_toward_zero(2),
        area.top + row + row.div_toward_zero(2),
    ];
    assert_eq!(right.keys, middles.map(|middle| (left, middle)));
    let column = widest + thousandths(2_847);
    let left = area.left + (width - column + half_side).div_toward_zero(2) + thousandths(2_763);
    assert_eq!(bottom.keys, middles.map(|middle| (left, middle)));
}

#[test]
fn leaves_out_a_legend_in_a_box_too_low_for_its_rows_or_in_another_mode() {
    let edges = [700, 100, 150, 40];
    let low = boxed_keys_of(&boxed_chart(LegendPlace::Right, edges), edges);
    assert_eq!(low.keys, []);
    let other = Columns {
        legend_box: LegendBox::Other,
        ..boxed_chart(LegendPlace::Right, edges)
    };
    assert_eq!(boxed_keys_of(&other, edges).keys, []);
}

#[test]
fn a_part_of_a_ligature_draws_no_glyph_of_a_chart_text() {
    use crate::layout::testing::{LamAlef, with_layout_of};
    // A lam with an alef, one glyph of 1,000 units, and a yeh of 500 units, at 10 pt. The
    // alef, a part of the ligature, draws no glyph and takes no room, and its letter follows
    // the lam in the ligature's text.
    with_layout_of(&LamAlef, crate::profile::Profile::clone, |layout| {
        let props = crate::props::RunProps {
            size: Some(20),
            ..crate::props::RunProps::default()
        };
        let text = layout
            .chart_text(&props, "\u{0644}\u{0627}\u{064A}")
            .unwrap();
        assert_eq!(text.width(), points(15));
        let Some(Item::Glyphs(run)) = text.item(Length::ZERO, Length::ZERO, Rgb::default()) else {
            panic!("a chart text draws a glyph run");
        };
        let glyphs: Vec<(u32, &str, Length)> = run
            .glyphs
            .iter()
            .map(|g| {
                let range = g.text_start as usize..g.text_end as usize;
                (g.id, run.text.get(range).unwrap_or(""), g.x)
            })
            .collect();
        assert_eq!(
            glyphs,
            [
                (900, "\u{0644}\u{0627}", Length::ZERO),
                (0x064A, "\u{064A}", points(10))
            ]
        );
    });
}

#[test]
fn wraps_a_category_label_at_its_spaces_into_lines_that_fit() {
    // Each character is 1 pt wide.
    let measure = |text: &str| Some(points(i64::try_from(text.len()).unwrap_or(i64::MAX)));
    let rows = |text, width| super::categories::wrapped_lines(text, points(width), measure);
    let owned = |rows: &[&str]| Some(rows.iter().map(|&row| row.to_owned()).collect::<Vec<_>>());
    assert_eq!(rows("Quite often able", 16), owned(&["Quite often able"]));
    assert_eq!(
        rows("Quite often able", 15),
        owned(&["Quite often", "able"])
    );
    assert_eq!(
        rows("Not often never able", 9),
        owned(&["Not often", "never", "able"])
    );
    // A word wider than the width turns the labels in Word.
    assert_eq!(rows("Commissioned services", 10), None);
}

#[test]
fn takes_a_side_of_the_square_whose_diagonal_a_length_is() {
    let side = |length| super::categories::diagonal(length).map(Length::units);
    let ten = points(10).units();
    // Ten points over the square root of two, toward zero, either way.
    assert_eq!(
        side(points(10)),
        Some(
            (i128::from(ten) * i128::from(ten) / 2)
                .isqrt()
                .try_into()
                .unwrap_or(0)
        )
    );
    assert_eq!(side(points(-10)), side(points(10)).map(|units| -units));
    assert_eq!(side(Length::ZERO), Some(0));
}

#[test]
fn gives_turned_labels_the_height_of_their_line_box_less_a_line() {
    use super::categories::{CategoryForm, diagonal};
    let lines = LabelLines {
        size: points(9),
        line: points(12),
        top: points(9),
        single_top: points(9),
        single_line: points(12),
    };
    let upright = CategoryForm::Upright(vec![vec!["a".to_owned(), "b".to_owned()]]);
    assert_eq!(upright.room(lines), Some(points(12)));
    assert_eq!(
        CategoryForm::Diagonal(vec![points(20), points(48)]).room(lines),
        diagonal(points(60)).map(|height| height - points(12))
    );
    assert_eq!(
        CategoryForm::Vertical(points(48)).room(lines),
        Some(points(36))
    );
    assert_eq!(
        CategoryForm::Vertical(points(10)).room(lines),
        Some(Length::ZERO)
    );
}

#[test]
fn reaches_left_by_the_label_that_most_passes_its_middle() {
    use super::categories::{CategoryForm, diagonal};
    // In a span of 400 pt over four categories the middles lie 50, 150, 250 and 350 pt in.
    let form = CategoryForm::Diagonal(vec![points(100), points(300), Length::ZERO, points(10)]);
    let reach = |width, middle| diagonal(points(width)).map(|side| side - points(middle));
    assert_eq!(form.left_reach(points(400)), reach(300, 150));
    let short = CategoryForm::Diagonal(vec![points(10), points(10)]);
    assert_eq!(short.left_reach(points(400)), reach(10, 100));
    assert_eq!(
        CategoryForm::Vertical(points(300)).left_reach(points(400)),
        None
    );
}

/// A chart without a legend and a title, the same chart with the axis titles "Amount" and
/// "Quarter" at 10 pt, and the same chart with a value axis title too long for its side.
fn axis_title_charts() -> [Columns; 3] {
    use crate::chart::{AxisTitle, AxisTitles, TitleText};
    let title = |line: &str| {
        Some(Box::new(AxisTitle {
            size: 20,
            text: TitleText {
                lines: vec![line.to_owned()],
                font: FontRef::MinorLatin,
                bold: false,
                italic: false,
                fill: None,
            },
            corner: None,
        }))
    };
    let plain = Columns {
        legend: None,
        title: None,
        ..columns(219, -27)
    };
    let with_titles = |value, category| Columns {
        axis_titles: AxisTitles::Drawn { value, category },
        ..plain.clone()
    };
    let titled = with_titles(title("Amount"), title("Quarter"));
    let long = with_titles(title(&"Amount ".repeat(40)), None);
    [plain, titled, long]
}

/// The frame of the axis title tests, 432 by 252 pt.
fn axis_title_frame() -> Edges<Length> {
    Edges {
        left: Length::ZERO,
        top: Length::ZERO,
        right: points(432),
        bottom: points(252),
    }
}

/// The plot areas without and with axis titles, the lines of a title's face, the items of the
/// titles, and the items of a long title, as [`axis_title_layout`] gives them.
type AxisTitleLayout = ([Edges<Length>; 2], LabelLines, Vec<Item>, Option<Vec<Item>>);

/// The layout on `ChartPlotArea::FontLines` with the fonts `fonts` of the charts of
/// [`axis_title_charts`] in [`axis_title_frame`]: the plot areas of the chart without and with
/// titles, the lines of the chart's font at 10 pt, and the items of the titles and of the long
/// title in the plot area with titles.
fn axis_title_layout(fonts: &dyn crate::Fonts) -> AxisTitleLayout {
    let [plain, titled, long] = axis_title_charts();
    let frame = axis_title_frame();
    let mut found = None;
    crate::layout::testing::with_layout_of(
        fonts,
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let mut plot = |chart: &Columns| {
                let axis = ValueAxis::of(chart).unwrap();
                layout.font_line_plot(chart, &axis, frame).unwrap()
            };
            let plots = [plot(&plain), plot(&titled)];
            let axis = ValueAxis::of(&titled).unwrap();
            let lines = layout.lines_of(&super::chart_props(&plain, 20)).unwrap();
            let items = layout
                .axis_title_items(&titled, (&axis, plots[1]), frame)
                .unwrap();
            let long_items = layout.axis_title_items(&long, (&axis, plots[1]), frame);
            found = Some((plots, lines, items, long_items));
        },
    );
    found.unwrap()
}

#[test]
fn takes_the_room_of_axis_titles_from_the_plot_area() {
    use crate::layout::testing::{Fake, Gapped};
    use crate::params::CHART_AXIS_TITLE_GAP;
    for fonts in [&Fake as &dyn crate::Fonts, &Gapped] {
        let ([before, after], lines, _, long_items) = axis_title_layout(fonts);
        // Each title takes its single line and the gap from its side, and leaves the other
        // sides.
        let room = lines.single_line + CHART_AXIS_TITLE_GAP;
        assert_eq!(
            (after.left - before.left, before.bottom - after.bottom),
            (room, room)
        );
        assert_eq!((after.top, after.right), (before.top, before.right));
        // A title longer than its side of the plot area is not drawn.
        assert_eq!(long_items, None);
    }
    // The single line of the face with a gap holds an external leading of 100 units at 10 pt
    // beyond its win line, and the room takes it.
    let lines = axis_title_layout(&Gapped).1;
    assert_eq!(lines.single_line - lines.line, points(1));
}

/// Asserts the places of the axis titles of [`axis_title_layout`] with the fonts `fonts`: the
/// value axis' title reads upward from its baseline, its external leading and win ascent right
/// of the start of its line box; the category axis' title stands upright with its line box
/// ending above the frame's bottom, its baseline its win descent higher.
fn assert_axis_title_places(fonts: &dyn crate::Fonts) {
    use crate::params::{CHART_CATEGORY_TITLE_BOTTOM, CHART_VALUE_TITLE_LEFT};
    let ([_, plot], lines, items, _) = axis_title_layout(fonts);
    let [Item::Glyphs(value), Item::Glyphs(category)] = &items[..] else {
        panic!("{items:?}");
    };
    assert_eq!(value.turn, Some(super::categories::UPWARD));
    assert_eq!(value.glyphs[0].x, CHART_VALUE_TITLE_LEFT + lines.single_top);
    assert!(value.glyphs[0].y > (plot.top + plot.bottom).div_toward_zero(2));
    assert_eq!(category.turn, None);
    assert_eq!(
        category.glyphs[0].y,
        axis_title_frame().bottom - CHART_CATEGORY_TITLE_BOTTOM - (lines.line - lines.top)
    );
    assert!(category.glyphs[0].x > plot.left);
}

#[test]
fn draws_axis_titles_beside_the_plot_area() {
    use crate::layout::testing::{Fake, Gapped};
    assert_axis_title_places(&Fake);
    assert_axis_title_places(&Gapped);
    // With a gap, the value axis' title stands the leading further right than its win ascent.
    let lines = axis_title_layout(&Gapped).1;
    assert_eq!(lines.single_top - lines.top, points(1));
}

#[test]
fn skips_blank_points_in_bars_and_blank_categories() {
    // Columns: a blank point skips its bar while keeping the remaining bars in their slots.
    let mut full = three_reds(ChartGroup::Columns {
        gap: 219,
        overlap: -27,
        stacking: crate::chart::BarStacking::Clustered,
    });
    full.legend = None;
    let mut gapped = full.clone();
    gapped.series[1].values[0] = None;
    let reds = reds_of(&font_line_items(&gapped).0);
    assert_eq!(reds.len(), 5);
    assert_eq!(reds.iter().filter(|(r, _)| *r == 2).count(), 1);
    let full_reds = reds_of(&font_line_items(&full).0);
    // Series 1 and 3 in category 0 keep the exact horizontal positions they had without the blank.
    assert_eq!(reds[0].1.x, full_reds[0].1.x);
    assert_eq!(reds[3].1.x, full_reds[4].1.x);

    // Horizontal bars: an empty category label draws the remaining labels and keeps the chart.
    let mut blank_bar_cat = three_reds(ChartGroup::Bars {
        gap: 219,
        overlap: -27,
        stacking: crate::chart::BarStacking::Clustered,
    });
    blank_bar_cat.category_names = Some(vec!["North".to_owned(), String::new()]);
    let bar_runs = label_runs(&blank_bar_cat, ChartPlotArea::FontLines);
    assert!(bar_runs.iter().any(|(text, _, _)| text == "North"));
    assert_eq!(
        all_text(&blank_bar_cat, ChartPlotArea::FontLines),
        Some(true)
    );
}

#[test]
fn skips_blank_points_in_lines_and_pies() {
    // Lines: a blank splits a line into contiguous runs of 2+ points; an isolated point draws
    // no line stroke, only its marker when markers are present.
    let mut lines_chart = five_points(ChartGroup::Lines {
        looks: vec![LineLook {
            marker: Some(crate::chart::Marker {
                symbol: crate::chart::MarkerSymbol::Square,
                size: Length::from_points(5),
                fill: None,
                outline: None,
            }),
            ..plain_look()
        }],
        stacking: crate::chart::BarStacking::Clustered,
    });
    // [3, 5, None, 8, None] -> one 2-point line run + 3 markers.
    lines_chart.series[0].values[2] = None;
    lines_chart.series[0].values[4] = None;
    let line_items = font_line_items(&lines_chart).0;
    let paths: Vec<_> = line_items
        .iter()
        .filter(|item| matches!(item, Item::Path(_)))
        .collect();
    // 1 line path (for [3, 5]) + 3 square markers (at 3, 5, 8); isolated point 8 draws no line.
    assert_eq!(paths.len(), 4);

    // Pies: a blank slice has zero swing and leaves the other slices their shares of the rest.
    let angles = super::pie::slice_angles(
        &[
            Some(decimal("1")),
            None,
            Some(decimal("2")),
            Some(decimal("1")),
        ],
        0,
    );
    assert_eq!(
        angles,
        Some(vec![
            (-5_400_000, 5_400_000),
            (0, 0),
            (0, 10_800_000),
            (10_800_000, 5_400_000),
        ])
    );
}

#[test]
fn stacks_positive_and_negative_segments_for_axis_bounds() {
    let mut stacked = three_reds(ChartGroup::Columns {
        gap: 219,
        overlap: 100,
        stacking: crate::chart::BarStacking::Stacked,
    });
    stacked.series[0].values = vec![Some(decimal("4")), Some(decimal("-2"))];
    stacked.series[1].values = vec![Some(decimal("-3")), Some(decimal("5"))];
    stacked.series[2].values = vec![Some(decimal("2")), None];
    let segs = super::bars::stacked_segments(&stacked).unwrap();
    assert_eq!(segs.get(0, 0), Some((decimal("0"), decimal("4"))));
    assert_eq!(segs.get(1, 0), Some((decimal("0"), decimal("-3"))));
    assert_eq!(segs.get(2, 0), Some((decimal("4"), decimal("6"))));
    assert_eq!(segs.get(0, 1), Some((decimal("0"), decimal("-2"))));
    assert_eq!(segs.get(1, 1), Some((decimal("0"), decimal("5"))));
    assert_eq!(segs.get(2, 1), None);
    let axis = ValueAxis::of(&stacked).unwrap();
    assert_eq!((axis.low, axis.high), (decimal("-4"), decimal("8")));
}

#[test]
fn normalizes_percent_stacked_segments_and_caps_axis() {
    let mut percent = three_reds(ChartGroup::Columns {
        gap: 219,
        overlap: 100,
        stacking: crate::chart::BarStacking::PercentStacked,
    });
    percent.series[0].values = vec![Some(decimal("1")), Some(decimal("0"))];
    percent.series[1].values = vec![Some(decimal("3")), Some(decimal("0"))];
    percent.series[2].values = vec![None, Some(decimal("0"))];
    let psegs = super::bars::stacked_segments(&percent).unwrap();
    assert_eq!(psegs.get(0, 0), Some((decimal("0"), decimal("0.25"))));
    assert_eq!(psegs.get(1, 0), Some((decimal("0.25"), decimal("1"))));
    assert_eq!(psegs.get(0, 1), Some((decimal("0"), decimal("0"))));
    let paxis = ValueAxis::of(&percent).unwrap();
    assert_eq!(
        (paxis.low, paxis.high, paxis.unit),
        (decimal("0"), decimal("1"), decimal("0.1"))
    );
}

#[test]
fn stacked_bars_meet_seamlessly_and_keep_forward_horizontal_legend() {
    use crate::chart::BarStacking::Stacked;

    let mut cols = three_reds(ChartGroup::Columns {
        gap: 219,
        overlap: 100,
        stacking: Stacked,
    });
    cols.legend = None;
    cols.series[0].values = vec![Some(decimal("4")), Some(decimal("2"))];
    cols.series[1].values = vec![Some(decimal("3")), Some(decimal("5"))];
    cols.series[2].values = vec![Some(decimal("2")), Some(decimal("1"))];
    let reds = reds_of(&font_line_items(&cols).0);
    assert_eq!(reds.len(), 6);
    let cat0: Vec<_> = reds.iter().step_by(2).map(|(_, r)| r).collect();
    assert_eq!(cat0[0].x, cat0[1].x);
    assert_eq!(cat0[1].x, cat0[2].x);
    assert_eq!(cat0[0].width, cat0[1].width);
    assert_eq!(cat0[1].y + cat0[1].height, cat0[0].y);
    assert_eq!(cat0[2].y + cat0[2].height, cat0[1].y);

    let bars = three_reds(ChartGroup::Bars {
        gap: 219,
        overlap: 100,
        stacking: Stacked,
    });
    let names: Vec<_> = super::bars::legend_order(&bars)
        .into_iter()
        .map(|s| s.name.as_deref())
        .collect();
    assert_eq!(names, vec![Some("A"), Some("B"), Some("C")]);
}

#[test]
fn scales_stacked_combo_across_both_groups_and_draws_wide_bar_legend_keys() {
    use crate::chart::{BarStacking, LineForm, LineLook, StyleWidth};
    let mut combo = three_reds(ChartGroup::Combo {
        gap: 150,
        overlap: 100,
        stacking: BarStacking::Stacked,
        bar_count: 2,
        looks: vec![LineLook {
            width: Some(StyleWidth::Automatic),
            dash: None,
            form: LineForm::Straight,
            marker: None,
        }],
        line_stacking: BarStacking::Clustered,
    });
    // Stacked bar sums are 4+3=7 and 2+1=3; line reaches 8, driving the axis past 7 to 9.
    combo.series[0].values = vec![Some(decimal("4")), Some(decimal("2"))];
    combo.series[1].values = vec![Some(decimal("3")), Some(decimal("1"))];
    combo.series[2].values = vec![Some(decimal("5")), Some(decimal("8"))];
    let axis = super::ValueAxis::of(&combo).unwrap();
    assert_eq!(axis.high, decimal("9"));
    assert!(matches!(
        super::legend::Keys::of(&combo),
        super::legend::Keys::Lines(_)
    ));
    let (items, _) = font_line_items(&combo);
    // Wide bar legend keys have width CHART_LINE_KEY_STROKE (19.2 pt) rather than a square side.
    let wide_keys = reds_of(&items)
        .into_iter()
        .filter(|(_, r)| r.width == crate::params::CHART_LINE_KEY_STROKE)
        .count();
    assert_eq!(wide_keys, 2);
}

#[test]
fn places_manual_axis_titles_and_keeps_scatter_manual_inner_right() {
    use crate::chart::{AxisTitle, AxisTitles, LayoutCorner, PlotLayout, PlotPlace, TitleText};
    use crate::layout::testing::Fake;
    use crate::params::{CHART_TITLE_CORNER_LEFT, CHART_TITLE_CORNER_TOP};
    let corner = |x, y| LayoutCorner {
        x: decimal(x),
        y: decimal(y),
    };
    let mk = |text: &str, c| {
        Some(Box::new(AxisTitle {
            size: 20,
            text: TitleText {
                lines: vec![text.to_owned()],
                font: FontRef::MinorLatin,
                bold: false,
                italic: false,
                fill: None,
            },
            corner: Some(c),
        }))
    };
    let (vc, cc) = (corner("0.04", "0.35"), corner("0.40", "0.88"));
    let frame = axis_title_frame();
    let chart = Columns {
        legend: None,
        title: None,
        axis_titles: AxisTitles::Drawn {
            value: mk("Amount", vc),
            category: mk("Quarter", cc),
        },
        ..columns(219, -27)
    };
    let mut sc = five_points(ChartGroup::Scatter {
        looks: vec![LineLook {
            width: Some(crate::chart::StyleWidth::Automatic),
            dash: None,
            form: crate::chart::LineForm::Straight,
            marker: None,
        }],
        x_values: vec![vec![decimal("1"), decimal("2"), decimal("3")]],
        x_scale: SetScale::default(),
    });
    sc.plot_place = PlotPlace::Manual(PlotLayout {
        inner: true,
        edges: plot_box(),
    });
    crate::layout::testing::with_layout_of(
        &Fake,
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let axis = ValueAxis::of(&chart).unwrap();
            let plot = layout.font_line_plot(&chart, &axis, frame).unwrap();
            let items = layout
                .axis_title_items(&chart, (&axis, plot), frame)
                .unwrap();
            let lines = layout.lines_of(&super::chart_props(&chart, 20)).unwrap();
            let (left_x, _) = super::layout_corner(frame, vc).unwrap();
            let (cat_x, cat_y) = super::layout_corner(frame, cc).unwrap();
            let [Item::Glyphs(v), Item::Glyphs(c)] = &items[..] else {
                panic!("expected two axis title glyph runs");
            };
            assert_eq!(
                (v.glyphs[0].x, c.glyphs[0].x, c.glyphs[0].y),
                (
                    left_x + CHART_TITLE_CORNER_TOP + lines.single_top,
                    cat_x + CHART_TITLE_CORNER_LEFT,
                    cat_y + CHART_TITLE_CORNER_TOP + lines.single_top,
                )
            );
            let sc_axis = ValueAxis::of(&sc).unwrap();
            let sc_plot = layout.font_line_plot(&sc, &sc_axis, frame).unwrap();
            let (_, right) = layout
                .x_axis(
                    &sc,
                    (
                        &[vec![decimal("1"), decimal("2"), decimal("3")]],
                        SetScale::default(),
                    ),
                    (frame, sc_plot),
                )
                .unwrap();
            assert_eq!(right, sc_plot.right);
        },
    );
}

#[test]
fn places_shifted_category_crossing_and_interior_labels_for_columns_and_bars() {
    let mut shifted = drawn_text_columns();
    shifted.category_crossing = Some(crate::chart::CategoryCrossing::At(decimal("0.5")));
    let axis = ValueAxis::for_chart(&shifted, 10).unwrap();
    assert_eq!(axis.crossing, decimal("0.5"));
    let mut clamped = shifted.clone();
    clamped.category_crossing = Some(crate::chart::CategoryCrossing::At(decimal("99")));
    assert_eq!(
        ValueAxis::for_chart(&clamped, 10).unwrap().crossing,
        axis.high
    );
    let mut at_min = drawn_text_columns();
    at_min.series[0].values[0] = Some(decimal("-2"));
    at_min.category_crossing = Some(crate::chart::CategoryCrossing::Min);
    let min_axis = ValueAxis::for_chart(&at_min, 10).unwrap();
    assert_eq!(min_axis.crossing, min_axis.low);
    // Horizontal bars with an interior category crossing expand plot.left and place category
    // labels just left of the shifted crossing line.
    let mut hbar = drawn_text_columns();
    hbar.group = ChartGroup::Bars {
        gap: 150,
        overlap: 0,
        stacking: crate::chart::BarStacking::Clustered,
    };
    hbar.legend = None;
    hbar.category_crossing = Some(crate::chart::CategoryCrossing::At(decimal("0.5")));
    assert_eq!(all_text(&hbar, ChartPlotArea::FontLines), Some(true));
}

#[test]
fn applies_explicit_scatter_x_scale_and_keeps_unclamped_clipped_slope() {
    let x_scale = SetScale {
        min: Some(decimal("2")),
        max: Some(decimal("8")),
        major_unit: Some(decimal("2")),
    };
    let xs = vec![vec![
        decimal("0"),
        decimal("3"),
        decimal("5"),
        decimal("7"),
        decimal("10"),
    ]];
    let scatter = five_points(ChartGroup::Scatter {
        looks: vec![plain_look()],
        x_values: xs.clone(),
        x_scale,
    });
    with_layout_on(
        |p| p.with_variant(ChartPlotArea::FontLines),
        |layout| {
            let frame = Edges {
                left: Length::ZERO,
                top: Length::ZERO,
                right: points(300),
                bottom: points(216),
            };
            let y_axis = ValueAxis::of(&scatter).unwrap();
            let plot = layout.font_line_plot(&scatter, &y_axis, frame).unwrap();
            let (axis, right) = layout
                .x_axis(&scatter, (&xs, x_scale), (frame, plot))
                .unwrap();
            assert_eq!(
                (axis.low, axis.high, axis.unit),
                (decimal("2"), decimal("8"), decimal("2"))
            );
            let span = (plot.left, right);
            // Out-of-range x = 0 lies left of plot.left and x = 10 lies right of plot.right.
            assert!(axis.along_unclamped(span, decimal("0")).unwrap() < plot.left);
            assert!(axis.along_unclamped(span, decimal("10")).unwrap() > right);
            assert_eq!(axis.along(span, decimal("0")), Some(plot.left));
        },
    );
}

#[test]
fn places_bar_inside_and_line_data_labels_with_marker_clearance() {
    use crate::chart::{DataLabelPosition, LineForm, LineLook, Marker, MarkerSymbol};
    let make_labels = |position| {
        SeriesLabels::Values(DataLabelText {
            position,
            size: 18,
            font: FontRef::MinorLatin,
            fill: None,
            insets: Edges {
                left: Length::from_emus(38_100).unwrap(),
                top: Length::from_emus(19_050).unwrap(),
                right: Length::from_emus(38_100).unwrap(),
                bottom: Length::from_emus(19_050).unwrap(),
            },
            format: LabelFormat::all_digits(),
            parts: crate::chart::DataLabelParts::default(),
            show_default: true,
            point_overrides: Vec::new(),
        })
    };
    // Clustered column inEnd < ctr < inBase vertically (increasing y downward).
    let col_y = |pos| {
        let mut chart = drawn_text_columns();
        chart.series[0].values[0] = Some(decimal("4"));
        chart.series[0].labels = make_labels(pos);
        data_label_runs(&chart, ChartDataLabels::OuterEnd, "4").0[0].1
    };
    let (y_out, y_in_end, y_ctr, y_in_base) = (
        col_y(DataLabelPosition::OutsideEnd),
        col_y(DataLabelPosition::InsideEnd),
        col_y(DataLabelPosition::Center),
        col_y(DataLabelPosition::InsideBase),
    );
    assert!(y_out < y_in_end && y_in_end < y_ctr && y_ctr < y_in_base);
    // Line chart: Default == Right, Left < Center < Right, Top < Center < Bottom, and a 9 pt
    // marker shifts Top upward by 2 pt relative to a 5 pt or absent marker.
    let line_pos = |pos, marker_pt: Option<i64>| {
        let marker = marker_pt.map(|pt| Marker {
            symbol: MarkerSymbol::Circle,
            size: Some(points(pt)),
            fill: None,
            outline: None,
        });
        let look = LineLook {
            width: None,
            marker,
            form: LineForm::Straight,
            dash: None,
        };
        let mut chart = Columns::plain(
            vec![Series {
                fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
                values: vec![Some(decimal("2")), Some(decimal("4"))],
                name: Some("S1".into()),
                labels: make_labels(pos),
            }],
            2,
            ChartGroup::Lines {
                looks: vec![look],
                stacking: crate::chart::BarStacking::Clustered,
            },
            None,
        );
        chart.category_names = Some(vec!["A".into(), "B".into()]);
        data_label_runs(&chart, ChartDataLabels::OuterEnd, "4").0[0]
    };
    let (def, ctr, right, left, top0, bot0, top5, top9) = (
        line_pos(DataLabelPosition::Default, None),
        line_pos(DataLabelPosition::Center, None),
        line_pos(DataLabelPosition::Right, None),
        line_pos(DataLabelPosition::Left, None),
        line_pos(DataLabelPosition::Top, None),
        line_pos(DataLabelPosition::Bottom, None),
        line_pos(DataLabelPosition::Top, Some(5)),
        line_pos(DataLabelPosition::Top, Some(9)),
    );
    assert_eq!(def, right);
    assert!(left.0 < ctr.0 && ctr.0 < right.0);
    assert!(top0.1 < ctr.1 && ctr.1 < bot0.1);
    assert_eq!(top5.1, top0.1);
    assert_eq!(top0.1 - top9.1, points(2));
}

#[test]
fn draws_scatter_legends_with_line_or_square_marker_keys_beside_twin_plot() {
    use super::legend::Keys;
    use crate::chart::{LineDash, Marker, MarkerSymbol};
    use crate::params::{CHART_LINE_KEY_AREA, CHART_LINE_KEY_DASHED_AREA};

    let marker_only = LineLook {
        width: None,
        marker: Some(Marker {
            symbol: MarkerSymbol::Circle,
            size: Some(points(7)),
            fill: Some(DrawColor::rgb(Rgb::BLACK)),
            outline: None,
        }),
        form: LineForm::Straight,
        dash: None,
    };
    let mut dashed = plain_look();
    dashed.dash = Some(LineDash::Dash);

    let make = |looks: Vec<LineLook>, legend: LegendPlace| {
        let mut chart = five_points(ChartGroup::Scatter {
            looks,
            x_values: quarter_x_values(),
            x_scale: SetScale::default(),
        });
        chart.series[0].name = Some("Alpha".into());
        chart.legend = Some(legend);
        chart
    };

    let lined_right = make(vec![plain_look()], LegendPlace::Right);
    let dashed_bottom = make(vec![dashed], LegendPlace::Bottom);
    let markers_right = make(vec![marker_only], LegendPlace::Right);

    assert_eq!(Keys::of(&lined_right), Keys::Lines(CHART_LINE_KEY_AREA));
    assert_eq!(
        Keys::of(&dashed_bottom),
        Keys::Lines(CHART_LINE_KEY_DASHED_AREA)
    );
    assert_eq!(Keys::of(&markers_right), Keys::Squares);

    // Right legend text stands at the same x for lined and markers-alone scatter charts because
    // both anchor to their twin plot area (before subtracting half the last x-label) and the
    // twin plot's right edge shifts by the difference in key side room.
    let (lined_items, _) = font_line_items(&lined_right);
    let (marker_items, _) = font_line_items(&markers_right);
    let alpha_x = |items: &[Item]| {
        runs_of(items)
            .into_iter()
            .find(|(text, _, _)| *text == "Alpha")
            .map(|(_, x, _)| x)
            .unwrap()
    };
    assert_eq!(alpha_x(&lined_items), alpha_x(&marker_items));
}

#[test]
fn stacks_lines_algebraically_treats_blanks_as_zero_and_reverses_side_legend() {
    use super::bars::{legend_order, stacked_line_values};
    use crate::chart::BarStacking;

    let mut chart = Columns::plain(
        vec![
            Series {
                fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
                values: vec![Some(decimal("4")), Some(decimal("3"))],
                name: Some("Alpha".into()),
                labels: SeriesLabels::Hidden,
            },
            Series {
                fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
                values: vec![None, Some(decimal("-4.5"))],
                name: Some("Beta".into()),
                labels: SeriesLabels::Hidden,
            },
            Series {
                fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
                values: vec![Some(decimal("2")), Some(decimal("2"))],
                name: Some("Gamma".into()),
                labels: SeriesLabels::Hidden,
            },
        ],
        2,
        ChartGroup::Lines {
            looks: vec![plain_look(); 3],
            stacking: BarStacking::Stacked,
        },
        None,
    );
    chart.legend = Some(LegendPlace::Right);
    chart.category_names = Some(vec!["Q1".into(), "Q2".into()]);

    // Algebraic cumulative sums: Q1 blank in Beta plots at Alpha's running total (4); Q2 dips
    // algebraically to -1.5 then returns to 0.5.
    let stacked = stacked_line_values(&chart).unwrap();
    assert_eq!(stacked[0], vec![Some(decimal("4")), Some(decimal("3"))]);
    assert_eq!(stacked[1], vec![Some(decimal("4")), Some(decimal("-1.5"))]);
    assert_eq!(stacked[2], vec![Some(decimal("6")), Some(decimal("0.5"))]);

    let axis = super::ValueAxis::of(&chart).unwrap();
    assert_eq!(axis.low, decimal("-2"));
    assert_eq!(axis.high, decimal("7"));

    // Right legend reverses stacked line series top-to-bottom; bottom legend stays forward.
    let right_names: Vec<_> = legend_order(&chart)
        .into_iter()
        .map(|s| s.name.as_deref().unwrap())
        .collect();
    assert_eq!(right_names, vec!["Gamma", "Beta", "Alpha"]);

    chart.legend = Some(LegendPlace::Bottom);
    let bottom_names: Vec<_> = legend_order(&chart)
        .into_iter()
        .map(|s| s.name.as_deref().unwrap())
        .collect();
    assert_eq!(bottom_names, vec!["Alpha", "Beta", "Gamma"]);
}

#[test]
fn lays_out_combo_secondary_right_axis_with_independent_scale_and_right_legend() {
    use crate::chart::{BarStacking, LabelFormat, SecondaryValueAxis};
    use f_office_drawingml::shape::{Geometry, ShapeLook};

    let mut chart = Columns::plain(
        vec![
            Series {
                fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
                values: vec![Some(decimal("40")), Some(decimal("45"))],
                name: Some("Bars".into()),
                labels: SeriesLabels::Hidden,
            },
            Series {
                fill: SeriesFill::Color(DrawColor::rgb(Rgb::BLACK)),
                values: vec![Some(decimal("2")), Some(decimal("9"))],
                name: Some("Rate".into()),
                labels: SeriesLabels::Hidden,
            },
        ],
        2,
        ChartGroup::Combo {
            gap: 150,
            overlap: 0,
            stacking: BarStacking::Clustered,
            bar_count: 1,
            looks: vec![plain_look()],
            line_stacking: BarStacking::Clustered,
        },
        None,
    );
    chart.category_names = Some(vec!["Q1".into(), "Q2".into()]);
    chart.legend = Some(LegendPlace::Right);
    chart.secondary_axis = Some(Box::new(SecondaryValueAxis {
        scale: SetScale::default(),
        format: LabelFormat::all_digits(),
        label_size: chart.value_label_size,
        label_fill: None,
        line: ShapeLook::plain(Geometry::Line, None, None),
        ticks: false,
        labels_hidden: false,
    }));

    // Primary axis scales only over bar series (0..50), independent of line values (2..9).
    let primary = super::ValueAxis::of(&chart).unwrap();
    assert_eq!(primary.high, decimal("50"));

    // Right-axis labels are left-aligned at the same x and sit to the left of the right legend.
    let (items, _) = font_line_items(&chart);
    let runs = runs_of(&items);
    let right_top_x = runs
        .iter()
        .find(|(t, x, _)| *t == "10" && *x > points(300))
        .map(|(_, x, _)| *x)
        .unwrap();
    let right_bottom_x = runs
        .iter()
        .find(|(t, x, _)| *t == "0" && *x > points(300))
        .map(|(_, x, _)| *x)
        .unwrap();
    let legend_x = runs
        .iter()
        .find(|(t, _, _)| *t == "Bars")
        .map(|(_, x, _)| *x)
        .unwrap();
    assert_eq!(right_top_x, right_bottom_x);
    assert!(legend_x > right_top_x);
}

#[test]
fn formats_pie_hamilton_percents_and_two_line_default_separator() {
    use crate::chart::{
        DataLabelParts, DataLabelPosition, PercentMode, PieExplosion, PieLabelPlace,
    };
    let mut chart = drawn_text_columns();
    chart.group = ChartGroup::Pie {
        first_angle: 0,
        view: None,
        fills: vec![DrawColor::rgb(Rgb::default()); 4],
        labels: PieLabelPlace::Center,
        explosion: PieExplosion {
            series: 0,
            slices: vec![0; 4],
        },
    };
    chart.legend = None;
    chart.title = None;
    chart.category_names = Some(vec!["A".into(), "B".into(), "C".into(), "D".into()]);
    chart.series = vec![Series {
        fill: SeriesFill::Color(DrawColor::rgb(Rgb::default())),
        values: [5, 1, 2, 3].map(|v| Some(decimal(&v.to_string()))).to_vec(),
        name: Some("Share".into()),
        labels: SeriesLabels::Values(DataLabelText {
            position: DataLabelPosition::Center,
            size: 18,
            font: FontRef::MinorLatin,
            fill: None,
            insets: Edges {
                left: Length::from_emus(38_100).unwrap(),
                top: Length::from_emus(19_050).unwrap(),
                right: Length::from_emus(38_100).unwrap(),
                bottom: Length::from_emus(19_050).unwrap(),
            },
            format: LabelFormat::all_digits(),
            parts: DataLabelParts {
                show_ser_name: false,
                show_cat_name: true,
                show_val: false,
                percent: PercentMode::Integer,
                separator: None,
            },
            show_default: true,
            point_overrides: Vec::new(),
        }),
    }];
    let (items, _) = font_line_items(&chart);
    let runs = runs_of(&items);
    let texts: Vec<&str> = runs.iter().map(|(t, _, _)| *t).collect();
    // Hamilton largest-remainder rounding on [5, 1, 2, 3] / 11 gives 46%, 9%, 18%, 27%,
    // and omitted separator with `PercentMode::Integer` splits cat and percent onto two lines.
    for expected in ["A", "46%", "B", "9%", "C", "18%", "D", "27%"] {
        assert!(texts.contains(&expected), "missing {expected} in {texts:?}");
    }
    let y_a = runs.iter().find(|(t, _, _)| *t == "A").unwrap().2;
    let y_46 = runs.iter().find(|(t, _, _)| *t == "46%").unwrap().2;
    assert!(y_46 > y_a);
}

#[test]
fn applies_per_point_delete_rich_text_and_manual_layout_offsets() {
    use crate::chart::{
        DataLabelParts, DataLabelPosition, PercentMode, PointLabelLayout, PointLabelOverride,
        PointLabelSpec,
    };

    let mut chart = drawn_text_columns();
    chart.categories = 4;
    chart.legend = None;
    chart.title = None;
    chart.category_names = Some(vec!["Q1".into(), "Q2".into(), "Q3".into(), "Q4".into()]);
    let base_text = DataLabelText {
        position: DataLabelPosition::OutsideEnd,
        size: 18,
        font: FontRef::MinorLatin,
        fill: None,
        insets: Edges {
            left: Length::from_emus(38_100).unwrap(),
            top: Length::from_emus(19_050).unwrap(),
            right: Length::from_emus(38_100).unwrap(),
            bottom: Length::from_emus(19_050).unwrap(),
        },
        format: LabelFormat::all_digits(),
        parts: DataLabelParts {
            show_ser_name: false,
            show_cat_name: false,
            show_val: true,
            percent: PercentMode::Hidden,
            separator: None,
        },
        show_default: true,
        point_overrides: Vec::new(),
    };
    let mut shifted_text = base_text.clone();
    shifted_text.point_overrides.clear();
    let mut rich_text = base_text.clone();
    rich_text.point_overrides.clear();
    let mut with_overrides = base_text.clone();
    with_overrides.point_overrides = vec![
        (
            0,
            PointLabelOverride::Custom(Box::new(PointLabelSpec {
                label: shifted_text,
                rich_lines: None,
                layout: PointLabelLayout::Offset {
                    dx: decimal("0.1"),
                    dy: decimal("0"),
                },
            })),
        ),
        (1, PointLabelOverride::Deleted),
        (
            2,
            PointLabelOverride::Custom(Box::new(PointLabelSpec {
                label: rich_text,
                rich_lines: Some(vec!["Peak".into()]),
                layout: PointLabelLayout::Automatic,
            })),
        ),
    ];
    chart.series = vec![Series {
        fill: SeriesFill::Color(DrawColor::rgb(Rgb::default())),
        values: [11, 22, 33, 44]
            .map(|v| Some(decimal(&v.to_string())))
            .to_vec(),
        name: Some("S".into()),
        labels: SeriesLabels::Values(base_text),
    }];
    let render = |chart: &Columns| {
        let mut out = None;
        with_layout_on(
            |p| {
                p.with_variant(ChartPlotArea::FontLines)
                    .with_variant(ChartDataLabels::OuterEnd)
            },
            |layout| {
                let frame = Edges {
                    left: Length::ZERO,
                    top: Length::ZERO,
                    right: points(432),
                    bottom: points(252),
                };
                out = layout.columns(chart, frame).map(|(items, _)| items);
            },
        );
        out.unwrap()
    };
    let base_items = render(&chart);
    let base_runs = runs_of(&base_items);
    let base_x0 = base_runs.iter().find(|(t, _, _)| *t == "11").unwrap().1;

    chart.series[0].labels = SeriesLabels::Values(with_overrides);
    let items = render(&chart);
    let runs = runs_of(&items);
    let texts: Vec<&str> = runs.iter().map(|(t, _, _)| *t).collect();
    assert!(texts.contains(&"11"));
    assert!(!texts.contains(&"22"), "point 1 should be deleted");
    assert!(texts.contains(&"Peak"));
    assert!(!texts.contains(&"33"), "point 2 should use rich text");
    assert!(texts.contains(&"44"));
    let shifted_x0 = runs.iter().find(|(t, _, _)| *t == "11").unwrap().1;
    // Frame width is 432 pt (`6 in`), so `dx = 0.1` shifts right by 43.2 pt.
    let expected_dx = Length::from_units(points(432).units() / 10);
    assert!((shifted_x0 - base_x0 - expected_dx).units().abs() <= 10);
}

#[test]
fn lays_out_and_paints_chart_data_table_borders_keys_and_cells() {
    use crate::chart::{DataTable, DataTableBorders};
    use f_office_drawingml::shape::{Geometry, ShapeLook};

    let make_chart = |outline, horz, vert, keys| {
        let mut chart = named_columns();
        chart.legend = None;
        chart.title = None;
        chart.category_names = Some(vec!["Q1".into(), "Q2".into()]);
        chart.series[0].name = Some("Alpha".into());
        chart.series[1].name = Some("Beta".into());
        chart.data_table = Some(Box::new(DataTable {
            borders: DataTableBorders {
                horz,
                vert,
                outline,
            },
            keys,
            border: ShapeLook::plain(
                Geometry::Line,
                None,
                Some((
                    Rgb {
                        r: 0x86,
                        g: 0x86,
                        b: 0x86,
                    },
                    points(1),
                )),
            ),
            text_size: 18,
            text_font: crate::props::FontRef::MinorLatin,
            text_fill: None,
            bold: false,
            italic: false,
        }));
        chart
    };
    let render = |chart: &Columns| {
        let mut out = None;
        with_layout_on(
            |p| p.with_variant(ChartPlotArea::FontLines),
            |layout| {
                let frame = Edges {
                    left: Length::ZERO,
                    top: Length::ZERO,
                    right: points(432),
                    bottom: points(252),
                };
                out = layout.columns(chart, frame);
            },
        );
        out.unwrap()
    };
    let border_count = |items: &[Item]| {
        items
            .iter()
            .filter(|item| {
                matches!(
                    item,
                    Item::Rect(rect) if rect.color == Rgb { r: 0x86, g: 0x86, b: 0x86 }
                )
            })
            .count()
    };

    let (all_items, drawn) = render(&make_chart(true, true, true, true));
    let texts: Vec<&str> = runs_of(&all_items).into_iter().map(|(t, _, _)| t).collect();
    let (outline_only, _) = render(&make_chart(true, false, false, true));
    let (interior_only, _) = render(&make_chart(false, true, true, false));
    assert_eq!(
        (
            drawn.axes_and_legend,
            border_count(&all_items),
            border_count(&outline_only),
            border_count(&interior_only),
            ["Q1", "Q2", "Alpha", "Beta"]
                .iter()
                .all(|label| texts.contains(label)),
        ),
        (true, 8, 6, 2, true)
    );
}

#[test]
fn places_manual_inner_data_table_and_clamps_narrow_left_margin() {
    use crate::chart::{DataTable, DataTableBorders, PlotLayout, PlotPlace};
    use f_office_drawingml::shape::{Geometry, ShapeLook};

    let make = |x: &str| {
        let mut chart = named_columns();
        chart.legend = None;
        chart.title = None;
        chart.category_names = Some(vec!["Q1".into(), "Q2".into()]);
        chart.series[0].name = Some("Alpha".into());
        chart.series[1].name = Some("Beta".into());
        chart.plot_place = PlotPlace::Manual(PlotLayout {
            inner: true,
            edges: LayoutBox {
                x: decimal(x),
                y: decimal("0.05"),
                w: decimal("0.70"),
                h: decimal("0.65"),
            },
        });
        chart.data_table = Some(Box::new(DataTable {
            borders: DataTableBorders {
                horz: true,
                vert: true,
                outline: true,
            },
            keys: true,
            border: ShapeLook::plain(
                Geometry::Line,
                None,
                Some((
                    Rgb {
                        r: 0x86,
                        g: 0x86,
                        b: 0x86,
                    },
                    points(1),
                )),
            ),
            text_size: 18,
            text_font: crate::props::FontRef::MinorLatin,
            text_fill: None,
            bold: false,
            italic: false,
        }));
        chart
    };
    let bounds = |chart: &Columns| {
        let mut out = None;
        with_layout_on(
            |p| p.with_variant(ChartPlotArea::FontLines),
            |layout| {
                let frame = Edges {
                    left: Length::ZERO,
                    top: Length::ZERO,
                    right: points(432),
                    bottom: points(252),
                };
                let (items, _) = layout.columns(chart, frame).unwrap();
                let border = Rgb {
                    r: 0x86,
                    g: 0x86,
                    b: 0x86,
                };
                let edges = items.iter().filter_map(|item| match item {
                    Item::Rect(r) if r.color == border => Some((r.x, r.x + r.width)),
                    _ => None,
                });
                let stub_left = edges.clone().map(|(l, _)| l).min().unwrap();
                let plot_right = edges.map(|(_, r)| r).max().unwrap();
                out = Some((stub_left, plot_right));
            },
        );
        out.unwrap()
    };
    let (wide_stub, wide_right) = bounds(&make("0.25"));
    let (clamped_stub, clamped_right) = bounds(&make("0.05"));
    assert!(wide_stub > points(50));
    assert!((clamped_stub - points(12)).units().abs() <= points(1).units());
    assert!(clamped_right > points(324) && wide_right > clamped_right);
}