f-office-drawingml 0.2.2

DrawingML shapes, pictures, fills, lines, themes and colors.
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
//! The look of a shape (ECMA-376 Part 1, 20.1.2 and 20.1.9): its preset geometry, its fill
//! and its line, and the display items that draw them.

use f_office_paint::stroke::{self, StrokeCap};
use f_office_paint::{
    FillRule, GradientItem, GradientStop, Item, Opacity, PathCommand, PathItem, Point, Rgb,
};
use f_office_units::scale::{DRAWING_WHOLE, FULL_TURN, QUARTER_TURN};
use f_office_units::{Edges, Length, div_round_i128, fixed};
use f_office_warnings::{Name, Warnings};
use f_office_xml::enumeration::{Values, own};
use f_office_xml::{Document, NodeId};

use crate::color::{DrawColor, SchemeColors};
use crate::custom::{self, CustomGeometry, OutOfRange, Place};
use crate::dash::{DashStyle, LineDash, MAX_DASHES, ReadDash, read_cap, read_dash};
use crate::effect::{Glow, OuterShadow, Reflection};
use crate::gradient::{
    EffectGradientKind, PathGradientKind, ResolvedEffectGradient, ResolvedEffectGradientKind,
    ShapeFillGradient, linear_axis,
};
use crate::line_end::{LineEnds, ReadEnds, read_ends, trim_polyline};
use crate::theme::{ShapeTheme, StyleReference};
use crate::{A, Feature, Warning, attribute_of, effect, emus_of, enumeration, integer_of, preset};

pub use crate::preset::TextRect;

/// The outline of a shape, from its preset geometry (`a:prstGeom`) or its custom paths
/// (`a:custGeom`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Geometry {
    /// Guides and paths in the shape's box: a custom geometry, or the definition of a preset
    /// shape that F-Office does not draw in its own way.
    Custom(CustomGeometry),
    /// A rectangle.
    #[default]
    Rect,
    /// A rectangle with rounded corners. The radius is a share of the shorter side, in
    /// 100,000ths.
    RoundRect(i64),
    /// An ellipse in the box.
    Ellipse,
    /// A straight line from the top left corner of the box to the bottom right one, before
    /// flips: `line` and `straightConnector1`.
    Line,
    /// A geometry of no outline that F-Office draws.
    Other,
}

impl Geometry {
    /// Whether the outline is one that F-Office draws and that is not a rectangle: a rounded
    /// rectangle, an ellipse, a line or custom paths. A picture in such an outline fills its
    /// whole box ([`Feature::ShapedPicture`]).
    #[must_use]
    pub const fn is_shaped(&self) -> bool {
        matches!(
            self,
            Self::RoundRect(_) | Self::Ellipse | Self::Line | Self::Custom(_)
        )
    }

    /// Whether the outline is a closed non-rectangle shape that can clip a picture
    /// (`RoundRect`, `Ellipse`, or `Custom`).
    #[must_use]
    pub const fn is_closed_shape(&self) -> bool {
        matches!(self, Self::RoundRect(_) | Self::Ellipse | Self::Custom(_))
    }
}

/// The parallel bands selected by `a:ln/@cmpd` (ECMA-376 Part 1, 20.1.10.15).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CompoundLine {
    /// One line.
    #[default]
    Single,
    /// Two equal lines.
    Double,
    /// A thick line followed by a thin line.
    ThickThin,
    /// A thin line followed by a thick line.
    ThinThick,
    /// Three lines.
    Triple,
}

/// `ST_CompoundLine`: each name is drawn on a straight line, and on another outline as one
/// line, with a warning ([`ShapeLook::compound_left_out`]); a missing name is one line.
const COMPOUND: &Values<CompoundLine> = &Values::new(&[
    own("sng", CompoundLine::Single),
    own("dbl", CompoundLine::Double),
    own("thickThin", CompoundLine::ThickThin),
    own("thinThick", CompoundLine::ThinThick),
    own("tri", CompoundLine::Triple),
]);

/// A preset shape that F-Office draws.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Preset {
    Rect,
    RoundRect,
    Ellipse,
    /// `line` and `straightConnector1`.
    Line,
}

/// The 187 names of `ST_ShapeType`, the type of `a:prstGeom`, in the order of the schema
/// `dml-main.xsd` of ISO/IEC 29500-4:2016.
pub(crate) const SHAPE_TYPES: [&str; 187] = [
    "line",
    "lineInv",
    "triangle",
    "rtTriangle",
    "rect",
    "diamond",
    "parallelogram",
    "trapezoid",
    "nonIsoscelesTrapezoid",
    "pentagon",
    "hexagon",
    "heptagon",
    "octagon",
    "decagon",
    "dodecagon",
    "star4",
    "star5",
    "star6",
    "star7",
    "star8",
    "star10",
    "star12",
    "star16",
    "star24",
    "star32",
    "roundRect",
    "round1Rect",
    "round2SameRect",
    "round2DiagRect",
    "snipRoundRect",
    "snip1Rect",
    "snip2SameRect",
    "snip2DiagRect",
    "plaque",
    "ellipse",
    "teardrop",
    "homePlate",
    "chevron",
    "pieWedge",
    "pie",
    "blockArc",
    "donut",
    "noSmoking",
    "rightArrow",
    "leftArrow",
    "upArrow",
    "downArrow",
    "stripedRightArrow",
    "notchedRightArrow",
    "bentUpArrow",
    "leftRightArrow",
    "upDownArrow",
    "leftUpArrow",
    "leftRightUpArrow",
    "quadArrow",
    "leftArrowCallout",
    "rightArrowCallout",
    "upArrowCallout",
    "downArrowCallout",
    "leftRightArrowCallout",
    "upDownArrowCallout",
    "quadArrowCallout",
    "bentArrow",
    "uturnArrow",
    "circularArrow",
    "leftCircularArrow",
    "leftRightCircularArrow",
    "curvedRightArrow",
    "curvedLeftArrow",
    "curvedUpArrow",
    "curvedDownArrow",
    "swooshArrow",
    "cube",
    "can",
    "lightningBolt",
    "heart",
    "sun",
    "moon",
    "smileyFace",
    "irregularSeal1",
    "irregularSeal2",
    "foldedCorner",
    "bevel",
    "frame",
    "halfFrame",
    "corner",
    "diagStripe",
    "chord",
    "arc",
    "leftBracket",
    "rightBracket",
    "leftBrace",
    "rightBrace",
    "bracketPair",
    "bracePair",
    "straightConnector1",
    "bentConnector2",
    "bentConnector3",
    "bentConnector4",
    "bentConnector5",
    "curvedConnector2",
    "curvedConnector3",
    "curvedConnector4",
    "curvedConnector5",
    "callout1",
    "callout2",
    "callout3",
    "accentCallout1",
    "accentCallout2",
    "accentCallout3",
    "borderCallout1",
    "borderCallout2",
    "borderCallout3",
    "accentBorderCallout1",
    "accentBorderCallout2",
    "accentBorderCallout3",
    "wedgeRectCallout",
    "wedgeRoundRectCallout",
    "wedgeEllipseCallout",
    "cloudCallout",
    "cloud",
    "ribbon",
    "ribbon2",
    "ellipseRibbon",
    "ellipseRibbon2",
    "leftRightRibbon",
    "verticalScroll",
    "horizontalScroll",
    "wave",
    "doubleWave",
    "plus",
    "flowChartProcess",
    "flowChartDecision",
    "flowChartInputOutput",
    "flowChartPredefinedProcess",
    "flowChartInternalStorage",
    "flowChartDocument",
    "flowChartMultidocument",
    "flowChartTerminator",
    "flowChartPreparation",
    "flowChartManualInput",
    "flowChartManualOperation",
    "flowChartConnector",
    "flowChartPunchedCard",
    "flowChartPunchedTape",
    "flowChartSummingJunction",
    "flowChartOr",
    "flowChartCollate",
    "flowChartSort",
    "flowChartExtract",
    "flowChartMerge",
    "flowChartOfflineStorage",
    "flowChartOnlineStorage",
    "flowChartMagneticTape",
    "flowChartMagneticDisk",
    "flowChartMagneticDrum",
    "flowChartDisplay",
    "flowChartDelay",
    "flowChartAlternateProcess",
    "flowChartOffpageConnector",
    "actionButtonBlank",
    "actionButtonHome",
    "actionButtonHelp",
    "actionButtonInformation",
    "actionButtonForwardNext",
    "actionButtonBackPrevious",
    "actionButtonEnd",
    "actionButtonBeginning",
    "actionButtonReturn",
    "actionButtonDocument",
    "actionButtonSound",
    "actionButtonMovie",
    "gear6",
    "gear9",
    "funnel",
    "mathPlus",
    "mathMinus",
    "mathMultiply",
    "mathDivide",
    "mathEqual",
    "mathNotEqual",
    "cornerTabs",
    "squareTabs",
    "plaqueTabs",
    "chartX",
    "chartStar",
    "chartPlus",
];

/// `ST_ShapeType`: F-Office draws five preset shapes in its own way, every other preset shape
/// from its definition ([`preset::geometry`]), and one without a definition, `upArrow`, as
/// nothing ([`Geometry::Other`]).
const PRESETS: &Values<Option<Preset>> = &Values::with_others(
    &[
        own("rect", Some(Preset::Rect)),
        own("roundRect", Some(Preset::RoundRect)),
        own("ellipse", Some(Preset::Ellipse)),
        own("line", Some(Preset::Line)),
        own("straightConnector1", Some(Preset::Line)),
    ],
    &SHAPE_TYPES,
    None,
);

/// The width of a line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Width {
    /// The width that the shape gives.
    Exact(Length),
    /// The width of the theme's line style with this index, from 1.
    Style(usize),
}

/// The dash pattern of a shape's stroke: its own (`None` for solid) or inherited from a theme
/// line style by 1-based index.
#[derive(Clone, Debug, PartialEq, Eq)]
enum StrokeDash {
    Own(Option<LineDash>),
    Style(usize),
}

/// The end cap of a shape's stroke: its own, inherited from a theme line style, or default
/// (flat).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StrokeCapSource {
    Own(StrokeCap),
    Style(usize),
    Default,
}

/// The arrowheads of an open stroke: its own or inherited from a theme line style.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StrokeEnds {
    Own(LineEnds),
    Style(usize),
}

/// Resolved gradient axis (in final page coordinates) and stops ready for [`GradientItem`].
struct ResolvedGradient {
    axis: (Point, Point),
    stops: Vec<GradientStop>,
}

/// How a stroke's color resolves against a theme line style (`a:lnStyleLst`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LineStyleColor {
    /// Own line color, drawn as it is.
    Own,
    /// Chart style look: resolves through [`ShapeTheme::line_style`] and omits the line when
    /// the theme lacks a drawable line style at this index (counting from 1).
    Required(usize),
    /// Shape `a:lnRef`: applies the theme line style's `phClr` modifiers when drawable, and
    /// keeps the reference color as it is otherwise.
    Style(usize),
}

/// The line along the outline of a shape.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Stroke {
    color: DrawColor,
    width: Width,
    /// How `color` resolves against a theme line style's placeholder color (`phClr`).
    in_style: LineStyleColor,
    /// The line's dash pattern, if any.
    dash: StrokeDash,
    /// The line's end cap (`a:ln/@cap`).
    cap: StrokeCapSource,
    /// The line's arrowheads (`a:headEnd`, `a:tailEnd`).
    ends: StrokeEnds,
}

/// Inherited fill context from the nearest enclosing DrawingML group (`wpg:wgp` / `wpg:grpSp`)
/// for resolving child `<a:grpFill/>` elements.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GroupFill {
    /// The ancestor `wpg:grpSpPr` element carrying an explicit fill (`solidFill`, `gradFill`,
    /// `noFill`, `blipFill`, or `pattFill`), or `None` when no ancestor group specifies a fill.
    pub props: Option<NodeId>,
    /// The fill-owning group's bounding box expressed relative to the child shape's top-left
    /// corner, used as the coordinate box when inheriting an `a:gradFill`.
    pub frame: Edges<Length>,
}

/// The geometry, fill and line of a shape, with its flips and rotation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShapeLook {
    /// The outline.
    pub geometry: Geometry,
    /// The explicitly selected compound line; absent or unrecognized values are single.
    pub compound: CompoundLine,
    fill: Option<DrawColor>,
    /// The shape's own drawable gradient fill (`a:gradFill`), if any.
    fill_gradient: Option<ShapeFillGradient>,
    /// When `fill_gradient` was inherited via `a:grpFill`, the owning group's box relative to
    /// this shape's top-left corner.
    fill_gradient_frame: Option<Edges<Length>>,
    line: Option<Stroke>,
    /// The width of a line that the shape gives without a fill (`a:ln` with `a:noFill`).
    blank_line: Option<Length>,
    /// Whether the shape is mirrored across and down (`flipH`, `flipV`).
    flip: [bool; 2],
    /// The clockwise rotation, in 60,000ths of a degree.
    rotation: i64,
    /// The style references whose styles of the theme the shape takes its fill, its line, the
    /// dash and the ends of its line, and its effects from, where its properties leave them out.
    styles: [Option<StyleReference>; 5],
    /// The shape's `a:effectRef` (1-based index and its optional color) when the shape's own
    /// properties give no `a:effectLst` or `a:effectDag`.
    effect_ref: Option<(usize, Option<DrawColor>)>,
    /// Its own outer shadow that a layout can draw.
    shadow: Option<OuterShadow>,
    /// Its own glow (`a:glow`) that a layout can draw.
    glow: Option<Glow>,
    /// Its own reflection (`a:reflection`) that a layout can draw.
    reflection: Option<Reflection>,
}

/// The line width that F-Office uses when neither the shape nor its style gives one.
const DEFAULT_LINE_EMUS: i64 = 9_525;

/// The thinnest line drawn, one dot of a 300 dpi grid, for a line of width 0.
const THINNEST: Length = Length::from_units(Length::UNITS_PER_DOT);

/// The largest corner radius of a rounded rectangle, half its shorter side, in 100,000ths of
/// that side.
const HALF_SIDE_SHARE: i64 = DRAWING_WHOLE / 2;

impl ShapeLook {
    /// Whether the shape is neither rotated nor flipped (`rot == 0`, `flipH == 0`, `flipV == 0`).
    #[must_use]
    pub const fn is_upright(&self) -> bool {
        self.rotation == 0 && !self.flip[0] && !self.flip[1]
    }
    /// Reads a shape's properties (`spPr`) and its style (`wps:style` or `p:style`), whose
    /// references (`a:fillRef`, `a:lnRef`) give the fill and the line that the properties
    /// leave out. A line width or a name of an enumeration that does not read counts as
    /// missing, and a name that F-Office does not draw is drawn as another or not at all, each
    /// with a warning in `warnings`. Each [`Feature`] that F-Office does not draw warns too,
    /// except a picture fill, which the caller draws or warns of ([`picture_fill`]).
    #[must_use]
    pub fn read(
        doc: &Document,
        (props, style): (Option<NodeId>, Option<NodeId>),
        warnings: &mut Warnings<Warning>,
    ) -> Self {
        let geometry = props.map_or(Geometry::Other, |p| geometry(doc, p, warnings));
        Self::read_with(doc, (props, style), geometry, None, warnings)
    }

    /// Reads a shape inside a DrawingML group (`wpg:wgp` / `wpg:grpSp`), resolving `<a:grpFill/>`
    /// against `group_fill`.
    #[must_use]
    pub fn read_in_group(
        doc: &Document,
        (props, style): (Option<NodeId>, Option<NodeId>),
        group_fill: GroupFill,
        warnings: &mut Warnings<Warning>,
    ) -> Self {
        let geometry = props.map_or(Geometry::Other, |p| geometry(doc, p, warnings));
        Self::read_with(doc, (props, style), geometry, Some(group_fill), warnings)
    }

    /// Reads the properties `props` of an element that draws only a line, such as a chart's
    /// axis, as [`Self::read`] reads them, as a shape whose geometry is a line, which has no
    /// fill.
    #[must_use]
    pub fn read_line(
        doc: &Document,
        props: Option<NodeId>,
        warnings: &mut Warnings<Warning>,
    ) -> Self {
        Self::read_with(doc, (props, None), Geometry::Line, None, warnings)
    }

    /// Reads the background (`wpc:bg`) and whole-canvas formatting (`wpc:whole`) of a drawing
    /// canvas (`wpc:wpc`) as a rectangle shape: the fill from `bg`, and the line, compound line
    /// and outer shadow from `whole`.
    #[must_use]
    pub fn read_canvas(
        doc: &Document,
        (bg, whole): (Option<NodeId>, Option<NodeId>),
        warnings: &mut Warnings<Warning>,
    ) -> Self {
        let (shadow, glow, reflection) =
            whole.map_or_default(|w| shape_effects(doc, w, false, warnings));
        let compound = whole
            .and_then(|w| doc.child(w, A, "ln"))
            .and_then(|ln| enumeration(doc, ln, "cmpd", (COMPOUND, warnings)))
            .unwrap_or_default();
        let (fill, fill_gradient, fill_gradient_frame, _) =
            fill(doc, (bg, None), true, None, warnings);
        let (line, _) = line(doc, (whole, None), false, warnings);
        let blank_line = whole
            .and_then(|w| doc.child(w, A, "ln"))
            .filter(|ln| doc.child(*ln, A, "noFill").is_some())
            .and_then(|ln| emus_of(doc, ln, "w", warnings));
        Self {
            compound,
            fill,
            fill_gradient,
            fill_gradient_frame,
            geometry: Geometry::Rect,
            line,
            blank_line,
            flip: [false; 2],
            rotation: 0,
            styles: [None; 5],
            effect_ref: None,
            shadow,
            glow,
            reflection,
        }
    }

    /// [`Self::read`] with the shape's geometry and optional enclosing group fill.
    fn read_with(
        doc: &Document,
        (props, style): (Option<NodeId>, Option<NodeId>),
        geometry: Geometry,
        group_fill: Option<GroupFill>,
        warnings: &mut Warnings<Warning>,
    ) -> Self {
        // A style reference's index (`idx`, `ST_StyleMatrixColumnIndex`) that does not read
        // counts as missing, 0, with a warning.
        let reference = |name: &str, warnings: &mut Warnings<Warning>| {
            let node = style.and_then(|s| doc.child(s, A, name))?;
            let index =
                attribute_of(doc, node, "idx", |i| i.parse::<usize>().ok(), warnings).unwrap_or(0);
            Some((index, node))
        };
        let xfrm = props.and_then(|p| doc.child(p, A, "xfrm"));
        let flag = |name: &str| {
            xfrm.and_then(|x| doc.attribute(x, None, name))
                .is_some_and(crate::boolean)
        };
        // A rotation that does not read, or lies beyond the range of `ST_Angle`, counts as
        // none, with a warning, as a picture's does.
        let rotation = xfrm
            .and_then(|x| integer_of(doc, x, "rot", warnings))
            .unwrap_or(0);
        // A line has no area to fill, so its fill is no feature that F-Office leaves out.
        let area = geometry != Geometry::Line;
        let flip = [flag("flipH"), flag("flipV")];
        let flipped = flip != [false; 2];
        let (raw_shadow, glow, reflection) =
            props.map_or_default(|props| shape_effects(doc, props, flipped, warnings));
        let shadow = raw_shadow.map(|shadow| shadow.rotated_by(rotation));
        let compound = props
            .and_then(|p| doc.child(p, A, "ln"))
            .and_then(|ln| enumeration(doc, ln, "cmpd", (COMPOUND, warnings)))
            .unwrap_or_default();
        let fill_reference = reference("fillRef", warnings);
        let (fill, fill_gradient, fill_gradient_frame, fill_style) =
            fill(doc, (props, fill_reference), area, group_fill, warnings);
        let open = matches!(geometry, Geometry::Line | Geometry::Custom(_));
        let line_reference = reference("lnRef", warnings);
        let (line, [line_style, dash_style, ends_style]) =
            line(doc, (props, line_reference), open, warnings);
        // The effects of the style apply where the properties give no effects of their own.
        let own_effects = props.is_some_and(|p| {
            ["effectLst", "effectDag"]
                .iter()
                .any(|name| doc.child(p, A, name).is_some())
        });
        let effect_ref = reference("effectRef", warnings)
            .filter(|(index, _)| *index > 0 && !own_effects)
            .map(|(index, node)| (index, DrawColor::read(doc, node, warnings)));
        let effect_style = effect_ref
            .as_ref()
            .map(|(index, _)| StyleReference::Effect(*index));
        Self {
            compound,
            fill,
            fill_gradient,
            fill_gradient_frame,
            geometry,
            line,
            blank_line: props
                .and_then(|p| doc.child(p, A, "ln"))
                .filter(|ln| doc.child(*ln, A, "noFill").is_some())
                .and_then(|ln| emus_of(doc, ln, "w", warnings)),
            flip,
            rotation,
            styles: [fill_style, line_style, dash_style, ends_style, effect_style],
            effect_ref,
            shadow,
            glow,
            reflection,
        }
    }

    /// The shape's own outer shadow that a layout can draw ([`OuterShadow`]), of which the
    /// reader gave no warning: a caller that does not draw it warns of [`Feature::Shadow`].
    #[must_use]
    pub const fn shadow(&self) -> Option<&OuterShadow> {
        self.shadow.as_ref()
    }

    /// The shape's own glow (`a:glow`) that a layout can draw ([`Glow`]), of which the reader
    /// gave no warning: a caller that does not draw it warns of [`Feature::Glow`].
    #[must_use]
    pub const fn glow(&self) -> Option<&Glow> {
        self.glow.as_ref()
    }

    /// The shape's own reflection (`a:reflection`) that a layout can draw ([`Reflection`]), of
    /// which the reader gave no warning: a caller that does not draw it warns of
    /// [`Feature::Reflection`].
    #[must_use]
    pub const fn reflection(&self) -> Option<&Reflection> {
        self.reflection.as_ref()
    }

    /// The outer shadow of the shape resolved against `theme`: its own shadow ([`Self::shadow`]),
    /// or the outer shadow of the theme's effect style named by `a:effectRef` (substituting
    /// `a:effectRef`'s color for `phClr`) when the shadow stays fixed on the page
    /// (`!turns_with_shape` or shape not rotated/flipped).
    #[must_use]
    pub fn shadow_in(&self, theme: &ShapeTheme) -> Option<OuterShadow> {
        if let Some(shadow) = &self.shadow {
            return Some(shadow.clone());
        }
        let (index, color) = self.effect_ref.as_ref()?;
        let flipped = self.flip != [false; 2];
        theme
            .effect_shadow(*index, color.as_ref())
            .filter(|shadow| !shadow.turns_with_shape() || !flipped)
            .map(|shadow| shadow.rotated_by(self.rotation))
    }

    /// The width of the line that a text box keeps its text inside of: the drawn line, or a
    /// line without a fill that the shape gives a width.
    #[must_use]
    pub fn inset_line_width(&self, theme: &ShapeTheme) -> Option<Length> {
        self.line(theme)
            .map(|(_, _, width)| width)
            .or(self.blank_line)
    }

    /// The whole quarter turns of the shape's rotation, clockwise from 0 to 3, or `None` for
    /// another angle, which [`ShapeLook::items`] does not draw ([`quarter_turns`]).
    #[must_use]
    pub fn quarter_turns(&self) -> Option<i64> {
        quarter_turns(self.rotation)
    }

    /// Whether the shape is mirrored across and down (`flipH`, `flipV`).
    #[must_use]
    pub const fn flips(&self) -> [bool; 2] {
        self.flip
    }

    /// The whole quarter turns, clockwise from 0 to 3, by which Word turns the text of the
    /// shape about its box's centre: those of its rotation, and a half turn more for a shape
    /// mirrored down, whose text Word does not mirror but turns; `None` for another angle.
    #[must_use]
    pub fn text_quarter_turns(&self) -> Option<i64> {
        let mirrored_down = if self.flip[1] { FULL_TURN / 2 } else { 0 };
        quarter_turns(self.rotation + mirrored_down)
    }

    /// A shape whose line is the theme's line style `index`, counting from 1, in `color` in
    /// place of the style's placeholder color ([`ShapeTheme::line_style`]), and that is filled
    /// with `fill` or not filled, such as an element of a chart in its chart style's look. A
    /// theme that lacks the line style, or whose style F-Office does not draw, gives no line.
    #[must_use]
    pub fn in_line_style(
        geometry: Geometry,
        fill: Option<DrawColor>,
        (color, index): (DrawColor, usize),
    ) -> Self {
        Self {
            geometry,
            compound: CompoundLine::Single,
            fill,
            fill_gradient: None,
            fill_gradient_frame: None,
            line: Some(Stroke {
                color,
                width: Width::Style(index),
                in_style: LineStyleColor::Required(index),
                dash: StrokeDash::Style(index),
                cap: StrokeCapSource::Style(index),
                ends: StrokeEnds::Style(index),
            }),
            blank_line: None,
            flip: [false; 2],
            rotation: 0,
            styles: [None; 5],
            effect_ref: None,
            shadow: None,
            glow: None,
            reflection: None,
        }
    }

    /// A shape with plain colors and an exact line width, such as one that VML describes.
    #[must_use]
    pub fn plain(geometry: Geometry, fill: Option<Rgb>, line: Option<(Rgb, Length)>) -> Self {
        Self {
            geometry,
            compound: CompoundLine::Single,
            fill: fill.map(DrawColor::rgb),
            fill_gradient: None,
            fill_gradient_frame: None,
            line: line.map(|(rgb, width)| Stroke {
                color: DrawColor::rgb(rgb),
                width: Width::Exact(width),
                in_style: LineStyleColor::Own,
                dash: StrokeDash::Own(None),
                cap: StrokeCapSource::Default,
                ends: StrokeEnds::Own(LineEnds::default()),
            }),
            blank_line: None,
            flip: [false; 2],
            rotation: 0,
            styles: [None; 5],
            effect_ref: None,
            shadow: None,
            glow: None,
            reflection: None,
        }
    }

    /// The shape mirrored across (`flip[0]`) and down (`flip[1]`), such as a line that runs up
    /// to the right.
    #[must_use]
    pub fn flipped(self, flip: [bool; 2]) -> Self {
        Self { flip, ..self }
    }

    /// The shape turned clockwise about the center of its box by `rotation`, in 60,000ths of a
    /// degree, as a DrawingML shape's `rot` turns it.
    #[must_use]
    pub fn turned(self, rotation: i64) -> Self {
        Self { rotation, ..self }
    }

    /// Composes an additional clockwise rotation `rotation` (in 60,000ths of a degree) after this
    /// shape's own flip and rotation.
    #[must_use]
    pub fn rotated_by(self, rotation: i64) -> Self {
        Self {
            rotation: (self.rotation + rotation).rem_euclid(FULL_TURN),
            ..self
        }
    }

    /// Composes an outer axis-aligned orthogonal group transform `matrix` (entries in `-1..=1`,
    /// an element of D4) onto this shape's own flip and rotation.
    #[must_use]
    pub fn compose_outer(self, matrix: [[i32; 2]; 2]) -> Self {
        if matrix == [[1, 0], [0, 1]] {
            return self;
        }
        let det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
        let flip_h = det < 0;
        let col0 = if flip_h {
            [-matrix[0][0], -matrix[1][0]]
        } else {
            [matrix[0][0], matrix[1][0]]
        };
        let quarters = match col0 {
            [1, 0] => 0,
            [0, 1] => 1,
            [-1, 0] => 2,
            _ => 3,
        };
        let signed = if flip_h {
            -self.rotation
        } else {
            self.rotation
        };
        let rotation = (signed + quarters * QUARTER_TURN).rem_euclid(FULL_TURN);
        Self {
            flip: [self.flip[0] ^ flip_h, self.flip[1]],
            rotation,
            ..self
        }
    }

    /// The fill color and its opacity, if the shape is filled.
    #[must_use]
    pub fn fill(&self, theme: &ShapeTheme) -> Option<(Rgb, Opacity)> {
        if self.geometry == Geometry::Line {
            return None;
        }
        let color = self.fill.as_ref()?.clone();
        let color = match self.styles[0] {
            Some(StyleReference::Fill(index)) => theme.fill_color(index, color),
            _ => color,
        };
        color.resolve(&theme.colors)
    }

    /// The features that F-Office does not draw in the styles of the theme that the shape
    /// takes, each once, which the caller, which holds the theme, warns of:
    /// [`Feature::ThemeStyle`] for a fill, line or effect style such as a gradient fill, a
    /// color modifier of the style, a double line or a shadow, as the shape takes only the
    /// color of the style reference, and no effect; [`Feature::LineDash`] and
    /// [`Feature::LineEnd`] for the dash and the ends of a line style.
    #[must_use]
    pub fn theme_features(&self, theme: &ShapeTheme) -> Vec<Feature> {
        let mut features = Vec::new();
        for feature in self
            .styles
            .iter()
            .flatten()
            .filter_map(|s| theme.feature(*s))
        {
            if !features.contains(&feature) {
                features.push(feature);
            }
        }
        if let Some(StyleReference::Fill(index)) = self.styles[0]
            && theme.has_fill_gradient(index)
            && theme.fill_gradient(index, self.fill.as_ref()).is_none()
            && !features.contains(&Feature::ThemeStyle)
        {
            features.push(Feature::ThemeStyle);
        }
        if let Some((index, _)) = &self.effect_ref
            && theme.has_effect_shadow(*index)
            && self.shadow_in(theme).is_none()
            && !features.contains(&Feature::Shadow)
        {
            features.push(Feature::Shadow);
        }
        features
    }

    /// The line color, its opacity and its width, if the shape has a line.
    #[must_use]
    pub fn line(&self, theme: &ShapeTheme) -> Option<(Rgb, Opacity, Length)> {
        let stroke = self.line.as_ref()?;
        let color = match stroke.in_style {
            LineStyleColor::Own => stroke.color.clone(),
            LineStyleColor::Required(index) => theme.line_style(index, stroke.color.clone())?.0,
            LineStyleColor::Style(index) => theme.line_color(index, stroke.color.clone()),
        };
        let (rgb, alpha) = color.resolve(&theme.colors)?;
        let width = match stroke.width {
            Width::Exact(width) => Some(width),
            Width::Style(index) => theme.line_width(index),
        }
        .or_else(|| Length::from_emus(DEFAULT_LINE_EMUS))?;
        Some((rgb, alpha, width))
    }

    /// Whether [`Self::items`] draws the shape's own compound line as one line of its full
    /// width ([`Feature::CompoundOutline`]): a compound line other than a single one on a
    /// custom or complex preset geometry, which is still drawn as one stroke.
    #[must_use]
    pub fn compound_left_out(&self) -> bool {
        self.compound != CompoundLine::Single && matches!(self.geometry, Geometry::Custom(_))
    }

    /// The items that draw the shape in its box `frame`: the fill, then the line centered on
    /// the outline. A shape that is turned by other than a quarter turn, or
    /// whose geometry is [`Geometry::Other`], gives no items.
    /// `parts` gives alternating line and gap proportions, starting with a line, for a
    /// straight line's compound stroke. The format crate supplies these drawing rules.
    ///
    /// # Errors
    ///
    /// [`OutOfRange`] when a point of a custom path maps beyond [`Length::FILE_LIMIT`] from the
    /// box, which only a path with a tiny size and a far point does.
    pub fn items(
        &self,
        frame: Edges<Length>,
        fill: Option<Rgb>,
        line: Option<(Rgb, Length)>,
        parts: &[i64],
    ) -> Result<Vec<Item>, OutOfRange> {
        let dash = line.and_then(|(_, width)| self.resolve_dash(None, width));
        let ends = self.resolve_ends(None);
        self.items_with_style(None, frame, fill, line, parts, (dash.as_ref(), ends))
    }

    /// Like [`Self::items`], also resolving any theme fill gradient, line-style dash, cap, or
    /// arrowheads against `theme`.
    ///
    /// # Errors
    ///
    /// As [`Self::items`].
    pub fn items_with_theme(
        &self,
        theme: &ShapeTheme,
        frame: Edges<Length>,
        fill: Option<Rgb>,
        line: Option<(Rgb, Length)>,
        parts: &[i64],
    ) -> Result<Vec<Item>, OutOfRange> {
        let dash = line.and_then(|(_, width)| self.resolve_dash(Some(theme), width));
        let ends = self.resolve_ends(Some(theme));
        self.items_with_style(Some(theme), frame, fill, line, parts, (dash.as_ref(), ends))
    }

    /// The shape's own drawable gradient fill, or the gradient of its theme `a:fillRef` style
    /// when resolved against `theme`.
    fn resolve_gradient(&self, theme: Option<&ShapeTheme>) -> Option<ShapeFillGradient> {
        if self.geometry == Geometry::Line {
            return None;
        }
        if let Some(gradient) = &self.fill_gradient {
            return Some(gradient.clone());
        }
        if let Some(StyleReference::Fill(index)) = self.styles[0] {
            return theme?.fill_gradient(index, self.fill.as_ref());
        }
        None
    }

    /// Resolves a path (`circle`, `rect`, `shape`) or translucent linear gradient fill on this
    /// shape for `frame` against `theme`, returning `None` when the shape has no effect-picture
    /// gradient fill (including opaque linear gradients, which [`Self::items_with_theme`] paints
    /// directly as vector `Item::Gradient`).
    ///
    /// # Errors
    ///
    /// [`OutOfRange`] when transforming a focus or axis coordinate overflows `Length`.
    pub fn resolve_effect_gradient(
        &self,
        theme: &ShapeTheme,
        frame: Edges<Length>,
    ) -> Result<Option<ResolvedEffectGradient>, OutOfRange> {
        let Some(ShapeFillGradient::Effect(grad)) = self.resolve_gradient(Some(theme)) else {
            return Ok(None);
        };
        let Some(stops) = grad.resolve_stops(&theme.colors) else {
            return Ok(None);
        };
        let (grad_frame, shown, exact_quarters) = self.gradient_box(frame);
        let kind = match grad.kind() {
            EffectGradientKind::Linear { angle, scaled } => {
                let Some((start, end)) = self.linear_axis_in_page(
                    (angle, scaled, grad.rot_with_shape()),
                    grad_frame,
                    shown,
                    exact_quarters,
                )?
                else {
                    return Ok(None);
                };
                ResolvedEffectGradientKind::Linear { start, end }
            }
            EffectGradientKind::Path {
                kind: PathGradientKind::Circle,
                ..
            } => {
                let center = box_center(shown);
                let radius = hypot_length(
                    grad_frame.width().div_toward_zero(2),
                    grad_frame.height().div_toward_zero(2),
                );
                ResolvedEffectGradientKind::Radial {
                    center,
                    rx: radius,
                    ry: radius,
                }
            }
            EffectGradientKind::Path {
                kind: PathGradientKind::Shape,
                ..
            } if self.geometry == Geometry::Ellipse && exact_quarters.is_some() => {
                ResolvedEffectGradientKind::Radial {
                    center: box_center(shown),
                    rx: shown.width().div_toward_zero(2),
                    ry: shown.height().div_toward_zero(2),
                }
            }
            EffectGradientKind::Path {
                kind: PathGradientKind::Rect,
                focus,
            } => {
                let center = self.focus_point_in_page(
                    focus,
                    grad.rot_with_shape(),
                    grad_frame,
                    shown,
                    exact_quarters,
                )?;
                if exact_quarters.is_some() {
                    ResolvedEffectGradientKind::Rect {
                        center,
                        bounds: shown,
                    }
                } else {
                    ResolvedEffectGradientKind::Shape { center }
                }
            }
            EffectGradientKind::Path {
                kind: PathGradientKind::Shape,
                focus,
            } => {
                let center = self.focus_point_in_page(
                    focus,
                    grad.rot_with_shape(),
                    grad_frame,
                    shown,
                    exact_quarters,
                )?;
                if self.geometry == Geometry::Rect && exact_quarters.is_some() {
                    ResolvedEffectGradientKind::Rect {
                        center,
                        bounds: shown,
                    }
                } else {
                    ResolvedEffectGradientKind::Shape { center }
                }
            }
        };
        Ok(Some(ResolvedEffectGradient { kind, stops }))
    }

    /// Transforms a normalized `a:fillToRect` focus `(cx, cy)` in `0..=100_000` into final page
    /// coordinates, honoring `rot_with_shape`, flips, and rotation.
    fn focus_point_in_page(
        &self,
        (fx, fy): (i64, i64),
        rot_with_shape: bool,
        frame: Edges<Length>,
        shown: Edges<Length>,
        exact_quarters: Option<i64>,
    ) -> Result<Point, OutOfRange> {
        let place_in = |box_: Edges<Length>, (cx, cy): (i64, i64)| {
            let x = box_.left
                + Length::from_units(
                    i64::try_from(div_round_i128(
                        i128::from(box_.width().units()) * i128::from(cx),
                        i128::from(DRAWING_WHOLE),
                    ))
                    .unwrap_or(0),
                );
            let y = box_.top
                + Length::from_units(
                    i64::try_from(div_round_i128(
                        i128::from(box_.height().units()) * i128::from(cy),
                        i128::from(DRAWING_WHOLE),
                    ))
                    .unwrap_or(0),
                );
            point(x, y)
        };
        if !rot_with_shape {
            let bounds = if exact_quarters.is_some() {
                shown
            } else {
                let (low, high) = rotated_frame_bounds(frame, self.rotation)?;
                Edges {
                    left: low.x,
                    top: low.y,
                    right: high.x,
                    bottom: high.y,
                }
            };
            return Ok(place_in(bounds, (fx, fy)));
        }
        let fx = if self.flip[0] { DRAWING_WHOLE - fx } else { fx };
        let fy = if self.flip[1] { DRAWING_WHOLE - fy } else { fy };
        let pt = place_in(frame, (fx, fy));
        match exact_quarters {
            Some(0) => Ok(pt),
            Some(quarters) => {
                let center = (
                    frame.left + frame.width().div_toward_zero(2),
                    frame.top + frame.height().div_toward_zero(2),
                );
                let (tx, ty) = custom::turned((pt.x, pt.y), center, quarters);
                Ok(point(tx, ty))
            }
            None => {
                let center2 = frame_center_doubled(frame)?;
                rotate_point_about(pt, center2, self.rotation)
            }
        }
    }

    /// Computes the `(start, end)` gradient axis in final page coordinates for a linear shade
    /// `(angle, scaled, rot_with_shape)` on a shape with unrotated box `frame`, quarter-turned
    /// box `shown`, flips `self.flip`, and rotation `self.rotation`.
    fn linear_axis_in_page(
        &self,
        (angle, scaled, rot_with_shape): (i64, bool, bool),
        frame: Edges<Length>,
        shown: Edges<Length>,
        exact_quarters: Option<i64>,
    ) -> Result<Option<(Point, Point)>, OutOfRange> {
        let box_corners =
            |box_: Edges<Length>| (point(box_.left, box_.top), point(box_.right, box_.bottom));
        if !rot_with_shape {
            let bounds = match exact_quarters {
                Some(_) => box_corners(shown),
                None => rotated_frame_bounds(frame, self.rotation)?,
            };
            return Ok(linear_axis(angle, scaled, bounds));
        }
        let Some((start, end)) = linear_axis(angle, scaled, box_corners(frame)) else {
            return Ok(None);
        };
        let flip_pt = |pt: Point| Point {
            x: if self.flip[0] {
                frame.left + (frame.right - pt.x)
            } else {
                pt.x
            },
            y: if self.flip[1] {
                frame.top + (frame.bottom - pt.y)
            } else {
                pt.y
            },
        };
        let (start, end) = (flip_pt(start), flip_pt(end));
        match exact_quarters {
            Some(0) => Ok(Some((start, end))),
            Some(quarters) => {
                let center = (
                    frame.left + frame.width().div_toward_zero(2),
                    frame.top + frame.height().div_toward_zero(2),
                );
                let turn = |pt: Point| {
                    let (tx, ty) = custom::turned((pt.x, pt.y), center, quarters);
                    point(tx, ty)
                };
                Ok(Some((turn(start), turn(end))))
            }
            None => {
                let center2 = frame_center_doubled(frame)?;
                Ok(Some((
                    rotate_point_about(start, center2, self.rotation)?,
                    rotate_point_about(end, center2, self.rotation)?,
                )))
            }
        }
    }

    /// Resolves this shape's dash pattern and end cap for drawn line width `width`, consulting
    /// `theme` when the shape inherits its dash or cap from `a:lnRef`.
    fn resolve_dash(&self, theme: Option<&ShapeTheme>, width: Length) -> Option<DashStyle> {
        let stroke = self.line.as_ref()?;
        let dash = match &stroke.dash {
            StrokeDash::Own(dash) => dash.as_ref()?,
            StrokeDash::Style(index) => theme?.line_dash(*index)?,
        };
        let cap = match stroke.cap {
            StrokeCapSource::Own(cap) => cap,
            StrokeCapSource::Style(index) => {
                theme.and_then(|t| t.line_cap(index)).unwrap_or_default()
            }
            StrokeCapSource::Default => StrokeCap::Flat,
        };
        let drawn = half_width(width) * 2;
        dash.resolve(drawn, cap)
    }

    /// Resolves this shape's arrowheads (`a:headEnd`, `a:tailEnd`), consulting `theme` when the
    /// shape inherits its ends from `a:lnRef`.
    fn resolve_ends(&self, theme: Option<&ShapeTheme>) -> LineEnds {
        let Some(stroke) = self.line.as_ref() else {
            return LineEnds::default();
        };
        match stroke.ends {
            StrokeEnds::Own(ends) => ends,
            StrokeEnds::Style(index) => theme.and_then(|t| t.line_ends(index)).unwrap_or_default(),
        }
    }

    /// Returns `(grad_frame, shown, exact_quarters)` for evaluating this shape's gradient fill:
    /// uses the fill-owning group's page box when the gradient was inherited via `a:grpFill`.
    fn gradient_box(&self, frame: Edges<Length>) -> (Edges<Length>, Edges<Length>, Option<i64>) {
        if let Some(rel) = self.fill_gradient_frame {
            let group_box = Edges {
                left: frame.left + rel.left,
                top: frame.top + rel.top,
                right: frame.left + rel.right,
                bottom: frame.top + rel.bottom,
            };
            return (group_box, group_box, Some(0));
        }
        let exact_quarters = quarter_turns(self.rotation);
        let shown = shown_box(frame, exact_quarters.unwrap_or(0));
        (frame, shown, exact_quarters)
    }

    /// Resolves the gradient stops and final-page axis for this shape, or `Ok(None)` when it has
    /// no drawable gradient or a stop references a missing scheme color.
    fn resolved_gradient(
        &self,
        theme: Option<&ShapeTheme>,
        frame: Edges<Length>,
    ) -> Result<Option<ResolvedGradient>, OutOfRange> {
        let Some(ShapeFillGradient::Linear(grad)) = self.resolve_gradient(theme) else {
            return Ok(None);
        };
        let colors = theme.map_or_else(SchemeColors::default, |t| t.colors);
        let Some(stops) = grad.resolve_stops(&colors) else {
            return Ok(None);
        };
        let (grad_frame, shown, exact_quarters) = self.gradient_box(frame);
        Ok(self
            .linear_axis_in_page(grad.linear_params(), grad_frame, shown, exact_quarters)?
            .map(|axis| ResolvedGradient { axis, stops }))
    }

    /// Renders the shape's fill and (solid/dashed/arrowed) outline into display items.
    fn items_with_style(
        &self,
        theme: Option<&ShapeTheme>,
        frame: Edges<Length>,
        fill: Option<Rgb>,
        line: Option<(Rgb, Length)>,
        parts: &[i64],
        (dash, ends): (Option<&DashStyle>, LineEnds),
    ) -> Result<Vec<Item>, OutOfRange> {
        if self.geometry == Geometry::Other {
            return Ok(Vec::new());
        }
        let exact_quarters = quarter_turns(self.rotation);
        let quarters = exact_quarters.unwrap_or(0);
        let center = (
            frame.left + frame.width().div_toward_zero(2),
            frame.top + frame.height().div_toward_zero(2),
        );
        let shown = shown_box(frame, quarters);
        let gradient = self.resolved_gradient(theme, frame)?;
        let fill_color = if gradient.is_some() {
            Some(Rgb::BLACK)
        } else {
            fill
        };
        let (mut fill_item, mut stroke_items) = if let Geometry::Custom(geometry) = &self.geometry {
            let place = Place {
                frame,
                flip: self.flip,
                quarters,
            };
            let line = line.map(|(color, width)| (color, half_width(width)));
            let (filled, stroked) =
                custom::fill_and_stroke(geometry, &place, fill_color, line, dash, ends)?;
            (
                filled.map(Item::Path),
                stroked.map(Item::Path).into_iter().collect(),
            )
        } else if self.geometry == Geometry::Line {
            (
                None,
                self.line_items(
                    self.line_ends(frame, quarters, center),
                    line,
                    parts,
                    (dash, ends),
                ),
            )
        } else {
            let filled = fill_color
                .map(|color| path(self.outline(shown, Length::ZERO), color, FillRule::NonZero));
            let stroked = line.map_or_else(Vec::new, |(color, width)| {
                self.stroke_closed(shown, color, half_width(width), parts, dash)
            });
            (filled, stroked)
        };
        if exact_quarters.is_none() {
            rotate_items(fill_item.as_mut_slice(), frame, self.rotation)?;
            rotate_items(&mut stroke_items, frame, self.rotation)?;
        }
        if let (Some(ResolvedGradient { axis, stops }), Some(Item::Path(path_item))) =
            (gradient, &mut fill_item)
        {
            fill_item = Some(Item::Gradient(GradientItem::new(
                std::mem::take(&mut path_item.commands),
                path_item.fill_rule,
                axis,
                stops,
            )));
        }
        let mut items = Vec::with_capacity(usize::from(fill_item.is_some()) + stroke_items.len());
        items.extend(fill_item);
        items.extend(stroke_items);
        Ok(items)
    }

    /// Strokes a closed preset shape (`Rect`, `RoundRect`, or `Ellipse`) solid or dashed,
    /// splitting into concentric bands when `parts` describes a compound outline.
    fn stroke_closed(
        &self,
        shown: Edges<Length>,
        color: Rgb,
        half: Length,
        parts: &[i64],
        dash: Option<&DashStyle>,
    ) -> Vec<Item> {
        if parts.len() > 1 {
            return self.stroke_closed_compound(shown, color, half, parts, dash);
        }
        if let Some(style) = dash {
            let points = self.dashed_outline_points(shown);
            if let Some(commands) =
                stroke::dashes(&points, half, &style.pattern, style.cap, MAX_DASHES)
            {
                return vec![path(commands, color, FillRule::NonZero)];
            }
        }
        let mut ring = self.outline(shown, half);
        if shown.width() > half * 2 && shown.height() > half * 2 {
            ring.extend(self.outline(shown, -half));
        }
        vec![path(ring, color, FillRule::EvenOdd)]
    }

    /// Strokes a closed preset shape with concentric compound bands (`dbl`, `thickThin`,
    /// `thinThick`, `tri`).
    fn stroke_closed_compound(
        &self,
        shown: Edges<Length>,
        color: Rgb,
        half: Length,
        parts: &[i64],
        dash: Option<&DashStyle>,
    ) -> Vec<Item> {
        let bands = compound_bands(half, parts);
        if let Some(style) = dash {
            let items = self.stroke_closed_dashed_bands(shown, color, &bands, style);
            if !items.is_empty() {
                return items;
            }
        }
        let mut rings = Vec::new();
        for (outer, inner) in bands {
            let outer_box = grow_edges(shown, outer);
            if outer_box.width() <= Length::ZERO || outer_box.height() <= Length::ZERO {
                continue;
            }
            rings.extend(self.compound_outline(shown, outer));
            let inner_box = grow_edges(shown, inner);
            if inner_box.width() > Length::ZERO && inner_box.height() > Length::ZERO {
                rings.extend(self.compound_outline(shown, inner));
            }
        }
        (!rings.is_empty())
            .then(|| path(rings, color, FillRule::EvenOdd))
            .into_iter()
            .collect()
    }

    /// Strokes each compound band of a closed preset shape with a dash pattern scaled to the
    /// full outline width.
    fn stroke_closed_dashed_bands(
        &self,
        shown: Edges<Length>,
        color: Rgb,
        bands: &[(Length, Length)],
        style: &DashStyle,
    ) -> Vec<Item> {
        let mut items = Vec::with_capacity(bands.len());
        for &(outer, inner) in bands {
            let mid = (outer + inner).div_toward_zero(2);
            let band_half = (outer - inner).div_toward_zero(2);
            if band_half <= Length::ZERO {
                continue;
            }
            let band_box = grow_edges(shown, mid);
            if band_box.width() <= Length::ZERO || band_box.height() <= Length::ZERO {
                continue;
            }
            let points = self.dashed_outline_points(band_box);
            if let Some(commands) =
                stroke::dashes(&points, band_half, &style.pattern, style.cap, MAX_DASHES)
            {
                items.push(path(commands, color, FillRule::NonZero));
            }
        }
        items
    }

    /// The outline of a closed preset shape at concentric offset `grow` for a compound band:
    /// rectangles round outward corners by `grow` (round join) and keep inward corners square.
    fn compound_outline(&self, shown: Edges<Length>, grow: Length) -> Vec<PathCommand> {
        match self.geometry {
            Geometry::Rect => rounded(grow_edges(shown, grow), grow.max(Length::ZERO)),
            _ => self.outline(shown, grow),
        }
    }

    /// The bands of a straight line, reflected with the whole shape, with any arrowheads.
    fn line_items(
        &self,
        ends: [(Length, Length); 2],
        line: Option<(Rgb, Length)>,
        parts: &[i64],
        (dash, arrows): (Option<&DashStyle>, LineEnds),
    ) -> Vec<Item> {
        let Some((color, width)) = line else {
            return Vec::new();
        };
        let half = half_width(width);
        let drawn_width = half * 2;
        let start = point(ends[0].0, ends[0].1);
        let end = point(ends[1].0, ends[1].1);
        let head_trim = arrows.head.map_or(Length::ZERO, |e| e.shorten(drawn_width));
        let tail_trim = arrows.tail.map_or(Length::ZERO, |e| e.shorten(drawn_width));
        let shaft_pts = if arrows.any() {
            trim_polyline(&[start, end], head_trim, tail_trim)
        } else {
            vec![start, end]
        };
        let mut items = self.line_shaft_items(&shaft_pts, color, half, parts, dash);
        if arrows.any() {
            let mut arrow_cmds = Vec::new();
            if let Some(head) = arrows.head {
                arrow_cmds.extend(head.commands(end, start, drawn_width));
            }
            if let Some(tail) = arrows.tail {
                arrow_cmds.extend(tail.commands(start, end, drawn_width));
            }
            if !arrow_cmds.is_empty() {
                items.push(path(arrow_cmds, color, FillRule::NonZero));
            }
        }
        items
    }

    /// Strokes the (possibly shortened) shaft of a straight line.
    fn line_shaft_items(
        &self,
        shaft_pts: &[Point],
        color: Rgb,
        half: Length,
        parts: &[i64],
        dash: Option<&DashStyle>,
    ) -> Vec<Item> {
        let [a, b] = *shaft_pts else {
            return Vec::new();
        };
        let ends = [(a.x, a.y), (b.x, b.y)];
        if parts.len() <= 1 {
            if let Some(style) = dash
                && let Some(commands) =
                    stroke::dashes(shaft_pts, half, &style.pattern, style.cap, MAX_DASHES)
            {
                return vec![path(commands, color, FillRule::NonZero)];
            }
            return stroke_line(ends, half, color).into_iter().collect();
        }
        // Reflect the whole outline, not only its centerline. One reflection
        // reverses handedness; quarter turns preserve it.
        let sign = if self.flip[0] == self.flip[1] { 1 } else { -1 };
        compound_line(ends, half, color, parts, sign)
    }

    /// The flattened centerline polyline of a closed preset shape, matching the starting corner
    /// and winding direction used by Word's PDF dash phase.
    fn dashed_outline_points(&self, shown: Edges<Length>) -> Vec<Point> {
        let Edges {
            left,
            top,
            right,
            bottom,
        } = shown;
        match self.geometry {
            Geometry::RoundRect(adjust) => {
                let shorter = (right - left).min(bottom - top);
                let share = adjust.clamp(0, HALF_SIDE_SHARE);
                let r = (shorter * share)
                    .div_toward_zero(DRAWING_WHOLE)
                    .min(shorter.div_toward_zero(2))
                    .max(Length::ZERO);
                if r == Length::ZERO {
                    return rect_dash_points(shown);
                }
                let k = stroke::kappa(r);
                let mut pts = vec![point(left, top + r)];
                pts.extend(stroke::cubic_points([
                    point(left, top + r),
                    point(left, top + r - k),
                    point(left + r - k, top),
                    point(left + r, top),
                ]));
                pts.push(point(right - r, top));
                pts.extend(stroke::cubic_points([
                    point(right - r, top),
                    point(right - r + k, top),
                    point(right, top + r - k),
                    point(right, top + r),
                ]));
                pts.push(point(right, bottom - r));
                pts.extend(stroke::cubic_points([
                    point(right, bottom - r),
                    point(right, bottom - r + k),
                    point(right - r + k, bottom),
                    point(right - r, bottom),
                ]));
                pts.push(point(left + r, bottom));
                pts.extend(stroke::cubic_points([
                    point(left + r, bottom),
                    point(left + r - k, bottom),
                    point(left, bottom - r + k),
                    point(left, bottom - r),
                ]));
                pts.push(point(left, top + r));
                pts
            }
            Geometry::Ellipse => {
                let (cx, cy) = (
                    (left + right).div_toward_zero(2),
                    (top + bottom).div_toward_zero(2),
                );
                let (kx, ky) = (
                    stroke::kappa((right - left).div_toward_zero(2)),
                    stroke::kappa((bottom - top).div_toward_zero(2)),
                );
                let mut pts = vec![point(left, cy)];
                pts.extend(stroke::cubic_points([
                    point(left, cy),
                    point(left, cy - ky),
                    point(cx - kx, top),
                    point(cx, top),
                ]));
                pts.extend(stroke::cubic_points([
                    point(cx, top),
                    point(cx + kx, top),
                    point(right, cy - ky),
                    point(right, cy),
                ]));
                pts.extend(stroke::cubic_points([
                    point(right, cy),
                    point(right, cy + ky),
                    point(cx + kx, bottom),
                    point(cx, bottom),
                ]));
                pts.extend(stroke::cubic_points([
                    point(cx, bottom),
                    point(cx - kx, bottom),
                    point(left, cy + ky),
                    point(left, cy),
                ]));
                pts
            }
            _ => rect_dash_points(shown),
        }
    }

    /// The ends of a line shape in its box `frame` after its flips and quarter turns.
    fn line_ends(
        &self,
        frame: Edges<Length>,
        quarters: i64,
        center: (Length, Length),
    ) -> [(Length, Length); 2] {
        let [flip_x, flip_y] = self.flip;
        let Edges {
            left,
            top,
            right,
            bottom,
        } = frame;
        let start = (
            if flip_x { right } else { left },
            if flip_y { bottom } else { top },
        );
        let end = (
            if flip_x { left } else { right },
            if flip_y { top } else { bottom },
        );
        [start, end].map(|point| custom::turned(point, center, quarters))
    }

    /// The outline of the shape in the box `shown`, grown by `grow` on every side.
    fn outline(&self, shown: Edges<Length>, grow: Length) -> Vec<PathCommand> {
        let Edges {
            left,
            top,
            right,
            bottom,
        } = shown;
        let grown = Edges {
            left: left - grow,
            top: top - grow,
            right: right + grow,
            bottom: bottom + grow,
        };
        match self.geometry {
            Geometry::RoundRect(adjust) => {
                // The radius is `adjust` 100,000ths of the shorter side, from none to half of
                // it. The share is bounded before the product, which then fits: a share above
                // a half gives the half, as the bounded radius did.
                let shorter = (right - left).min(bottom - top);
                let share = adjust.clamp(0, HALF_SIDE_SHARE);
                let radius = (shorter * share).div_toward_zero(DRAWING_WHOLE) + grow;
                rounded(grown, radius.max(Length::ZERO))
            }
            Geometry::Ellipse => ellipse(grown),
            _ => rounded(grown, Length::ZERO),
        }
    }
}

/// Grows `edges` outward on every side by `grow` (negative values shrink inward).
fn grow_edges(edges: Edges<Length>, grow: Length) -> Edges<Length> {
    Edges {
        left: edges.left - grow,
        top: edges.top - grow,
        right: edges.right + grow,
        bottom: edges.bottom + grow,
    }
}

/// The `(outer, inner)` concentric offsets in `[-half, +half]` of the drawn line bands of a
/// compound outline whose alternating line and gap proportions are `parts`, ordered from outside
/// (`+half`) inward to `-half`.
fn compound_bands(half: Length, parts: &[i64]) -> Vec<(Length, Length)> {
    let total: i64 = parts.iter().sum();
    if total <= 0 || parts.iter().any(|part| *part <= 0) {
        return vec![(half, -half)];
    }
    let span = i128::from(half.units()) * 2;
    let offset = |pos: i64| -> Length {
        let delta = div_round_i128(span * i128::from(pos), i128::from(total));
        let delta = i64::try_from(delta).unwrap_or(0);
        Length::from_units(half.units().saturating_sub(delta))
    };
    let mut bands = Vec::with_capacity(parts.len().div_ceil(2));
    let mut acc = 0_i64;
    for (index, &part) in parts.iter().enumerate() {
        let next = acc + part;
        if index % 2 == 0 {
            bands.push((offset(acc), offset(next)));
        }
        acc = next;
    }
    bands
}

/// Half the drawn width of a line of `width`: a line drawn at least [`THINNEST`].
fn half_width(width: Length) -> Length {
    width.max(THINNEST).div_toward_zero(2)
}

/// Reads the preset geometry of a shape, with the warnings of its names in `warnings`.
fn geometry(doc: &Document, props: NodeId, warnings: &mut Warnings<Warning>) -> Geometry {
    if let Some(custom) = doc.child(props, A, "custGeom") {
        return custom::read(doc, custom, warnings).map_or(Geometry::Other, Geometry::Custom);
    }
    doc.child(props, A, "prstGeom")
        .map_or(Geometry::Other, |preset| {
            preset_geometry(doc, preset, warnings)
        })
}

/// Reads a preset geometry (`a:prstGeom`), with the warnings of its name in `warnings`.
fn preset_geometry(doc: &Document, preset: NodeId, warnings: &mut Warnings<Warning>) -> Geometry {
    // The name of the preset is required.
    let Some(name) = doc.attribute(preset, None, "prst") else {
        warnings.push(Warning::InvalidValue {
            element: Name::new("prstGeom"),
            attribute: Name::new("prst"),
        });
        return Geometry::Other;
    };
    if let Some((None, ..)) = PRESETS.find(name)
        && let Some(geometry) = preset::geometry(name, &adjust_values(doc, preset), warnings)
    {
        return Geometry::Custom(geometry);
    }
    match enumeration(doc, preset, "prst", (PRESETS, warnings)).flatten() {
        Some(Preset::Rect) => Geometry::Rect,
        Some(Preset::RoundRect) => {
            // ECMA-376 Part 1, 20.1.10.56 and the preset's definition: the corner radius is
            // `adj` 100,000ths of the shorter side, 16,667 by default. F-Office reads the
            // formula of a value (`val N`) only, and another formula counts as missing, with a
            // warning.
            let adjust = doc
                .child(preset, A, "avLst")
                .into_iter()
                .flat_map(|list| doc.child_elements(list))
                .filter(|gd| doc.attribute(*gd, None, "name") == Some("adj"))
                .find(|gd| doc.attribute(*gd, None, "fmla").is_some())
                .and_then(|gd| attribute_of(doc, gd, "fmla", guide_value, warnings))
                .unwrap_or(16_667);
            Geometry::RoundRect(adjust)
        }
        Some(Preset::Ellipse) => Geometry::Ellipse,
        Some(Preset::Line) => Geometry::Line,
        None => Geometry::Other,
    }
}

/// The adjust values of a preset geometry (`a:avLst` of `a:prstGeom`), each a name and a
/// formula.
fn adjust_values(doc: &Document, preset: NodeId) -> Vec<(&str, &str)> {
    doc.child(preset, A, "avLst")
        .into_iter()
        .flat_map(|list| doc.child_elements(list))
        .filter(|gd| doc.is(*gd, A, "gd"))
        .filter_map(|gd| {
            Some((
                doc.attribute(gd, None, "name")?,
                doc.attribute(gd, None, "fmla")?,
            ))
        })
        .collect()
}

/// The text rectangle of the preset geometry of a shape whose properties are `props`
/// (`a:prstGeom` in `spPr`), which the shape's text lies in, inside the insets of its text
/// body, or `None` for a shape of no preset or of a preset without a definition. An adjust
/// value that does not read keeps the definition's, as in the outline, whose reading
/// ([`ShapeLook::read`]) warns of it.
#[must_use]
pub fn text_rect(doc: &Document, props: NodeId) -> Option<TextRect> {
    let preset = doc.child(props, A, "prstGeom")?;
    let name = doc.attribute(preset, None, "prst")?;
    preset::text_rect(name, &adjust_values(doc, preset))
}

/// The value of a shape guide's formula (`fmla` of `a:gd`, ECMA-376 Part 1, 20.1.9.11) that
/// sets a value (`val N`), the only formula that F-Office reads.
fn guide_value(formula: &str) -> Option<i64> {
    formula.strip_prefix("val ")?.trim().parse().ok()
}

/// The whole quarter turns clockwise, from 0 to 3, of a rotation in 60,000ths of a degree, or
/// `None` for a rotation that is not a whole number of quarter turns, which F-Office does not
/// draw ([`Feature::Turn`]).
#[must_use]
pub fn quarter_turns(rotation: i64) -> Option<i64> {
    let turn = rotation.rem_euclid(FULL_TURN);
    (turn % QUARTER_TURN == 0).then_some(turn / QUARTER_TURN)
}

/// The point `point` on a page, whose y grows downwards, turned clockwise about `center` by
/// `rotation` in 60,000ths of a degree, rounded to the nearest whole unit with no float, so that
/// every machine computes the same point; `None` when the point lands beyond the range of an
/// `i64`.
#[must_use]
pub fn turned_clockwise(point: [i64; 2], center: [i64; 2], rotation: i64) -> Option<[i64; 2]> {
    let [sin, cos] = fixed::sin_cos(i128::from(rotation) * fixed::ONE);
    let ([x, y], [cx, cy]) = (point.map(i128::from), center.map(i128::from));
    let (dx, dy) = (x - cx, y - cy);
    let x = cx + fixed::product(dx, cos) - fixed::product(dy, sin);
    let y = cy + fixed::product(dx, sin) + fixed::product(dy, cos);
    Some([i64::try_from(x).ok()?, i64::try_from(y).ok()?])
}

/// The box of `frame` turned by `quarters` quarter turns around its center.
fn shown_box(frame: Edges<Length>, quarters: i64) -> Edges<Length> {
    let (width, height) = (frame.width(), frame.height());
    let cx = frame.left + width.div_toward_zero(2);
    let cy = frame.top + height.div_toward_zero(2);
    let (w, h) = if quarters % 2 == 1 {
        (height, width)
    } else {
        (width, height)
    };
    let (left, top) = (cx - w.div_toward_zero(2), cy - h.div_toward_zero(2));
    Edges {
        left,
        top,
        right: left + w,
        bottom: top + h,
    }
}

/// Center point of `edges`.
fn box_center(edges: Edges<Length>) -> Point {
    point(
        edges.left + edges.width().div_toward_zero(2),
        edges.top + edges.height().div_toward_zero(2),
    )
}

/// Pure-integer Euclidean length `sqrt(a^2 + b^2)`.
fn hypot_length(a: Length, b: Length) -> Length {
    let (a, b) = (i128::from(a.units()), i128::from(b.units()));
    let sum = a.saturating_mul(a).saturating_add(b.saturating_mul(b));
    Length::from_units(i64::try_from(sum.isqrt()).unwrap_or(i64::MAX))
}

/// Doubled center coordinates `[2 * cx, 2 * cy]` of `frame` so odd dimensions keep exact centers.
fn frame_center_doubled(frame: Edges<Length>) -> Result<[i64; 2], OutOfRange> {
    let cx2 = frame
        .left
        .units()
        .checked_add(frame.right.units())
        .ok_or(OutOfRange)?;
    let cy2 = frame
        .top
        .units()
        .checked_add(frame.bottom.units())
        .ok_or(OutOfRange)?;
    Ok([cx2, cy2])
}

/// Rotates `pt` clockwise about doubled center `center2` by `rotation` (in 60,000ths of a degree).
fn rotate_point_about(pt: Point, center2: [i64; 2], rotation: i64) -> Result<Point, OutOfRange> {
    let x2 = pt.x.units().checked_mul(2).ok_or(OutOfRange)?;
    let y2 = pt.y.units().checked_mul(2).ok_or(OutOfRange)?;
    let [rx2, ry2] = turned_clockwise([x2, y2], center2, rotation).ok_or(OutOfRange)?;
    Ok(Point {
        x: Length::from_units(rx2).div_round(2),
        y: Length::from_units(ry2).div_round(2),
    })
}

/// Axis-aligned bounding box of `frame`'s four corners after rotating clockwise by `rotation`.
fn rotated_frame_bounds(frame: Edges<Length>, rotation: i64) -> Result<(Point, Point), OutOfRange> {
    let center2 = frame_center_doubled(frame)?;
    let corners = [
        point(frame.left, frame.top),
        point(frame.right, frame.top),
        point(frame.right, frame.bottom),
        point(frame.left, frame.bottom),
    ];
    let mut rotated = corners
        .into_iter()
        .map(|pt| rotate_point_about(pt, center2, rotation));
    let first = rotated.next().ok_or(OutOfRange)??;
    let (mut min_x, mut min_y, mut max_x, mut max_y) = (first.x, first.y, first.x, first.y);
    for pt in rotated {
        let pt = pt?;
        min_x = min_x.min(pt.x);
        min_y = min_y.min(pt.y);
        max_x = max_x.max(pt.x);
        max_y = max_y.max(pt.y);
    }
    Ok((point(min_x, min_y), point(max_x, max_y)))
}

/// Rotates every path point of `items` clockwise about the exact center of `frame` by `rotation`
/// (in 60,000ths of a degree), using doubled coordinates so odd box dimensions keep exact centers.
fn rotate_items(items: &mut [Item], frame: Edges<Length>, rotation: i64) -> Result<(), OutOfRange> {
    let center2 = frame_center_doubled(frame)?;
    let mut failed = false;
    let mut turn_pt = |pt: Point| {
        if let Ok(rotated) = rotate_point_about(pt, center2, rotation) {
            rotated
        } else {
            failed = true;
            pt
        }
    };
    for item in items {
        item.map_places(&mut turn_pt, |length| length);
    }
    if failed { Err(OutOfRange) } else { Ok(()) }
}

/// The picture fill (`a:blipFill`) of a shape's properties `props`. [`ShapeLook`] draws no
/// picture: a reader that draws the picture over the shape reads it here, and one that does
/// not warns of [`Feature::PictureFill`].
#[must_use]
pub fn picture_fill(doc: &Document, props: NodeId) -> Option<NodeId> {
    doc.child(props, A, "blipFill")
}

/// The line of a picture (`a:ln` of `pic:spPr`) that F-Office can draw: a single solid line of
/// one color, of the width that the line gives or else 0.75 pt.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureLine {
    color: DrawColor,
    width: Length,
}

impl PictureLine {
    /// The color of the line, its opacity and its width.
    #[must_use]
    pub fn resolve(&self, theme: &ShapeTheme) -> Option<(Rgb, Opacity, Length)> {
        let (rgb, alpha) = self.color.resolve(&theme.colors)?;
        Some((rgb, alpha, self.width))
    }
}

/// The outer shadow and glow of the properties `props` of a shape that a layout can draw
/// ([`effect::shape_effects_of`]), keeping the shadow only where it stays fixed on the page
/// (`!rotWithShape` or not `turned`). A shadow that turns and flips with a turned or flipped
/// shape is not drawn, with a warning in `warnings`.
fn shape_effects(
    doc: &Document,
    props: NodeId,
    turned: bool,
    warnings: &mut Warnings<Warning>,
) -> (Option<OuterShadow>, Option<Glow>, Option<Reflection>) {
    let (raw_shadow, glow, raw_reflection) = effect::shape_effects_of(doc, props, warnings);
    let shadow = raw_shadow.filter(|shadow| {
        let fixed = !shadow.turns_with_shape() || !turned;
        if !fixed {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::Shadow,
            });
        }
        fixed
    });
    let reflection = raw_reflection.filter(|reflection| {
        let fixed = !reflection.turns_with_shape() || !turned;
        if !fixed {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::Reflection,
            });
        }
        fixed
    });
    (shadow, glow, reflection)
}

/// What F-Office can draw of the properties of a picture (`pic:spPr`): its outline geometry, the
/// line around it, its own outer shadow, its soft-edge radius, its glow, and its reflection.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PictureLook {
    /// The outline geometry of the picture (`Geometry::Rect` by default).
    pub geometry: Geometry,
    /// The line around the picture, where it has one that F-Office can draw.
    pub line: Option<PictureLine>,
    /// The picture's own outer shadow that a layout can draw ([`OuterShadow`]), of which the
    /// reader does not warn: a layout that does not draw it warns of [`Feature::Shadow`].
    pub shadow: Option<OuterShadow>,
    /// The soft-edge radius (`a:softEdge/@rad`) when above zero, of which the reader does not
    /// warn: a layout that cannot draw it warns of [`Feature::SoftEdge`].
    pub soft_edge: Option<Length>,
    /// The picture's own glow (`a:glow`) that a layout can draw ([`Glow`]), of which the reader
    /// does not warn: a layout that cannot draw it warns of [`Feature::Glow`].
    pub glow: Option<Glow>,
    /// The picture's own reflection (`a:reflection`) that a layout can draw ([`Reflection`]), of
    /// which the reader does not warn: a layout that cannot draw it warns of
    /// [`Feature::Reflection`].
    pub reflection: Option<Reflection>,
}

/// Reads the outline geometry of a picture (`pic:spPr`), warning on [`Feature::ShapedPicture`]
/// only for non-closed or unreadable shaped geometries.
fn picture_geometry(doc: &Document, props: NodeId, warnings: &mut Warnings<Warning>) -> Geometry {
    if let Some(custom) = doc.child(props, A, "custGeom") {
        if let Some(geom) = custom::read(doc, custom, warnings) {
            return Geometry::Custom(geom);
        }
        warnings.push(Warning::FeatureNotSupported {
            feature: Feature::ShapedPicture,
        });
        return Geometry::Rect;
    }
    let Some(preset) = doc.child(props, A, "prstGeom") else {
        return Geometry::Rect;
    };
    match preset_geometry(doc, preset, warnings) {
        geom @ (Geometry::Rect
        | Geometry::RoundRect(_)
        | Geometry::Ellipse
        | Geometry::Custom(_)) => geom,
        Geometry::Line => {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::ShapedPicture,
            });
            Geometry::Rect
        }
        Geometry::Other => Geometry::Rect,
    }
}

/// Reads the properties `props` of a picture (`pic:spPr`): its outline geometry, the line that
/// F-Office can draw around the picture, its outer shadow, and its soft-edge radius. Warns in
/// `warnings` of each unsupported feature, drawing the picture in its box without them.
pub fn picture_properties(
    doc: &Document,
    props: NodeId,
    warnings: &mut Warnings<Warning>,
) -> PictureLook {
    let geometry = picture_geometry(doc, props, warnings);
    // The reader of the picture warns of a rotation that does not read; any rotation but 0
    // turns the picture here.
    let turned = doc.child(props, A, "xfrm").is_some_and(|xfrm| {
        let flag = |name| doc.attribute(xfrm, None, name).is_some_and(crate::boolean);
        flag("flipH")
            || flag("flipV")
            || doc
                .attribute(xfrm, None, "rot")
                .is_some_and(|rot| rot.trim().parse::<i64>() != Ok(0))
    });
    let (raw_shadow, soft_edge, glow, raw_reflection) =
        effect::picture_effects_of(doc, props, warnings);
    let shadow = raw_shadow.filter(|shadow| {
        let fixed = !shadow.turns_with_shape() || !turned;
        if !fixed {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::Shadow,
            });
        }
        fixed
    });
    let reflection = raw_reflection.filter(|reflection| {
        let fixed = !reflection.turns_with_shape() || !turned;
        if !fixed {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::Reflection,
            });
        }
        fixed
    });
    let line = doc.child(props, A, "ln").and_then(|ln| {
        let line = picture_line(doc, ln, warnings);
        let filled = color_holder(doc, ln).is_some() || other_fill(doc, ln).is_some();
        if line.is_none() && filled {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::PictureLine,
            });
        }
        line
    });
    PictureLook {
        geometry,
        line,
        shadow,
        soft_edge,
        glow,
        reflection,
    }
}

/// The line `ln` of a picture when it is single, solid and of one color (`a:solidFill`).
fn picture_line(
    doc: &Document,
    ln: NodeId,
    warnings: &mut Warnings<Warning>,
) -> Option<PictureLine> {
    let (holder, None) = color_holder(doc, ln)? else {
        return None;
    };
    let compound = enumeration(doc, ln, "cmpd", (COMPOUND, warnings)).unwrap_or_default();
    if compound != CompoundLine::Single
        || !matches!(read_dash(doc, ln), ReadDash::Omitted | ReadDash::Solid)
    {
        return None;
    }
    let width = emus_of(doc, ln, "w", warnings).or_else(|| Length::from_emus(DEFAULT_LINE_EMUS))?;
    Some(PictureLine {
        color: DrawColor::read(doc, holder, warnings)?,
        width,
    })
}

/// The ring of a line of `width` drawn wholly outside the box `frame`, as a stroke with round
/// joins along the box grown by half the width draws it: its outer corners round by half the
/// width, its inner corners square. A line of width 0 is drawn one dot of a 300 dpi grid wide.
#[must_use]
pub fn outside_ring(frame: Edges<Length>, width: Length, color: Rgb) -> Item {
    let width = width.max(THINNEST);
    let grown = Edges {
        left: frame.left - width,
        top: frame.top - width,
        right: frame.right + width,
        bottom: frame.bottom + width,
    };
    let mut ring = rounded(grown, width.div_toward_zero(2));
    ring.extend(rounded(frame, Length::ZERO));
    path(ring, color, FillRule::EvenOdd)
}

/// Corner radius of a rounded rectangle in `frame` with adjustment share `adjust`.
fn round_radius(frame: Edges<Length>, adjust: i64) -> Length {
    let shorter = frame.width().min(frame.height());
    let share = adjust.clamp(0, HALF_SIDE_SHARE);
    (shorter * share)
        .div_toward_zero(DRAWING_WHOLE)
        .max(Length::ZERO)
}

/// The closed vector clip path of a shaped picture (`RoundRect`, `Ellipse`, or `Custom`) inside
/// its un-turned box `frame`, or `None` for a rectangle or open geometry.
#[must_use]
pub fn picture_clip_path(
    geometry: &Geometry,
    frame: Edges<Length>,
) -> Option<(Vec<PathCommand>, FillRule)> {
    match geometry {
        Geometry::RoundRect(adjust) => Some((
            rounded(frame, round_radius(frame, *adjust)),
            FillRule::EvenOdd,
        )),
        Geometry::Ellipse => Some((ellipse(frame), FillRule::EvenOdd)),
        Geometry::Custom(custom) => {
            let place = Place {
                frame,
                flip: [false, false],
                quarters: 0,
            };
            let (filled, _) = custom::fill_and_stroke(
                custom,
                &place,
                Some(Rgb::BLACK),
                None,
                None,
                LineEnds::default(),
            )
            .ok()?;
            let filled = filled?;
            Some((filled.commands, filled.fill_rule))
        }
        Geometry::Rect | Geometry::Line | Geometry::Other => None,
    }
}

/// The line of `width` drawn around a picture of `geometry` in `frame`: wholly outside for
/// `Rect`, `RoundRect`, and `Ellipse`, and stroked along the custom outline for `Custom`.
#[must_use]
pub fn picture_outside_ring(
    geometry: &Geometry,
    frame: Edges<Length>,
    width: Length,
    color: Rgb,
) -> Option<Item> {
    let width = width.max(THINNEST);
    match geometry {
        Geometry::Rect | Geometry::Line | Geometry::Other => {
            Some(outside_ring(frame, width, color))
        }
        Geometry::RoundRect(adjust) => {
            let inner_r = round_radius(frame, *adjust);
            let outer_r = if inner_r == Length::ZERO {
                width.div_toward_zero(2)
            } else {
                inner_r + width
            };
            let mut ring = rounded(grow_edges(frame, width), outer_r);
            ring.extend(rounded(frame, inner_r));
            Some(path(ring, color, FillRule::EvenOdd))
        }
        Geometry::Ellipse => {
            let mut ring = ellipse(grow_edges(frame, width));
            ring.extend(ellipse(frame));
            Some(path(ring, color, FillRule::EvenOdd))
        }
        Geometry::Custom(custom) => {
            let place = Place {
                frame,
                flip: [false, false],
                quarters: 0,
            };
            let (_, stroked) = custom::fill_and_stroke(
                custom,
                &place,
                None,
                Some((color, width.div_toward_zero(2))),
                None,
                LineEnds::default(),
            )
            .ok()?;
            stroked.map(Item::Path)
        }
    }
}

/// The fills that a shape's area or line can have and that F-Office does not draw as a color,
/// with the feature that the fill of an area is.
const OTHER_FILLS: [(&str, Option<Feature>); 3] = [
    ("blipFill", None),
    ("pattFill", Some(Feature::PatternFill)),
    ("grpFill", Some(Feature::GroupFill)),
];

/// The fill of [`OTHER_FILLS`] directly inside `node`, if it has one: its element's name and
/// the feature that the fill of an area is.
fn other_fill(doc: &Document, node: NodeId) -> Option<(&'static str, Option<Feature>)> {
    OTHER_FILLS
        .into_iter()
        .find(|(name, _)| doc.child(node, A, name).is_some())
}

/// Resolved fill fields of a shape: solid/fallback color, optional gradient, optional
/// group-relative gradient box (for `a:grpFill`), and optional theme style reference.
type ReadFill = (
    Option<DrawColor>,
    Option<ShapeFillGradient>,
    Option<Edges<Length>>,
    Option<StyleReference>,
);

/// Reads an explicit fill element directly inside `props` (`noFill`, `solidFill`, `gradFill`,
/// `blipFill`, `pattFill`), optionally attaching `gradient_frame` when inherited from a group.
fn explicit_fill(
    doc: &Document,
    props: NodeId,
    area: bool,
    gradient_frame: Option<Edges<Length>>,
    warnings: &mut Warnings<Warning>,
) -> Option<ReadFill> {
    if doc.child(props, A, "noFill").is_some() {
        return Some((None, None, None, None));
    }
    if let Some(solid) = doc.child(props, A, "solidFill") {
        return Some((DrawColor::read(doc, solid, warnings), None, None, None));
    }
    if let Some(grad_node) = doc.child(props, A, "gradFill") {
        return Some(read_grad_fill(
            doc,
            grad_node,
            area,
            gradient_frame,
            warnings,
        ));
    }
    if doc.child(props, A, "blipFill").is_some() {
        // Standalone `blipFill` is handled by the caller (`picture_fill`); an inherited group
        // `blipFill` cannot be drawn at the child's box and warns `PictureFill`.
        if area && gradient_frame.is_some() {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::PictureFill,
            });
        }
        return Some((None, None, None, None));
    }
    if doc.child(props, A, "pattFill").is_some() {
        if area {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::PatternFill,
            });
        }
        return Some((None, None, None, None));
    }
    None
}

/// Reads an `a:gradFill` element into a [`ReadFill`].
fn read_grad_fill(
    doc: &Document,
    grad_node: NodeId,
    area: bool,
    gradient_frame: Option<Edges<Length>>,
    warnings: &mut Warnings<Warning>,
) -> ReadFill {
    if area {
        let mut grad_warnings = Warnings::new();
        if let Some(gradient) = ShapeFillGradient::read_shape(doc, grad_node, &mut grad_warnings) {
            warnings.extend(grad_warnings, std::convert::identity);
            return (gradient.first_color(), Some(gradient), gradient_frame, None);
        }
        warnings.push(Warning::FeatureNotSupported {
            feature: Feature::GradientFill,
        });
    }
    let stop = doc
        .child(grad_node, A, "gsLst")
        .and_then(|list| doc.child(list, A, "gs"))
        .unwrap_or(grad_node);
    (DrawColor::read(doc, stop, warnings), None, None, None)
}

/// The fill of a shape: its own (solid, drawable gradient, or inherited `a:grpFill`), or else the
/// one its style refers to, with the fill style of the theme that an `area` then takes.
fn fill(
    doc: &Document,
    (props, reference): (Option<NodeId>, Option<(usize, NodeId)>),
    area: bool,
    group_fill: Option<GroupFill>,
    warnings: &mut Warnings<Warning>,
) -> ReadFill {
    if let Some(props) = props {
        if let Some(found) = explicit_fill(doc, props, area, None, warnings) {
            return found;
        }
        if doc.child(props, A, "grpFill").is_some() {
            return resolve_group_fill_element(doc, area, group_fill, warnings);
        }
    }
    let Some((index, node)) = reference.filter(|(index, _)| *index > 0) else {
        return (None, None, None, None);
    };
    let style = area.then_some(StyleReference::Fill(index));
    (DrawColor::read(doc, node, warnings), None, None, style)
}

/// Resolves `<a:grpFill/>` against the enclosing group's [`GroupFill`], or warns
/// [`Feature::GroupFill`] when used outside a group.
fn resolve_group_fill_element(
    doc: &Document,
    area: bool,
    group_fill: Option<GroupFill>,
    warnings: &mut Warnings<Warning>,
) -> ReadFill {
    let Some(group_fill) = group_fill else {
        if area {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::GroupFill,
            });
        }
        return (None, None, None, None);
    };
    let Some(group_props) = group_fill.props else {
        return (None, None, None, None);
    };
    explicit_fill(doc, group_props, area, Some(group_fill.frame), warnings)
        .unwrap_or((None, None, None, None))
}

/// The element that holds the color of a solid fill directly inside `node`, or of the first
/// stop of a gradient fill there, with [`Feature::GradientFill`] for a gradient's.
fn color_holder(doc: &Document, node: NodeId) -> Option<(NodeId, Option<Feature>)> {
    if let Some(solid) = doc.child(node, A, "solidFill") {
        return Some((solid, None));
    }
    let gradient = doc.child(node, A, "gradFill")?;
    let stop = doc
        .child(gradient, A, "gsLst")
        .and_then(|list| doc.child(list, A, "gs"))
        .unwrap_or(gradient);
    Some((stop, Some(Feature::GradientFill)))
}

/// The line of a shape: its own (`a:ln`), with the color and width that its style refers to
/// where it gives none, and the parts of the line style of the theme that a drawn line takes:
/// its fill and compound line where the line takes its color from the style, and its dash and,
/// on an `open` outline, its ends where the line gives none. A gradient takes
/// its first color, and a picture, pattern or group fill takes the color of the style, each
/// with a warning in `warnings`, as are an unsupported dash and an unsupported end of a drawn line.
fn line(
    doc: &Document,
    (props, reference): (Option<NodeId>, Option<(usize, NodeId)>),
    open: bool,
    warnings: &mut Warnings<Warning>,
) -> (Option<Stroke>, [Option<StyleReference>; 3]) {
    let own = props.and_then(|p| doc.child(p, A, "ln"));
    let reference = reference.filter(|(index, _)| *index > 0);
    if own.is_some_and(|ln| doc.child(ln, A, "noFill").is_some()) {
        return (None, [None; 3]);
    }
    let own_holder = own.and_then(|ln| color_holder(doc, ln));
    let feature = match own_holder {
        Some((_, feature)) => feature,
        None => own
            .filter(|ln| other_fill(doc, *ln).is_some())
            .map(|_| Feature::LineFill),
    };
    if let Some(feature) = feature {
        warnings.push(Warning::FeatureNotSupported { feature });
    }
    let style = match own_holder {
        Some(_) => None,
        None => reference.map(|(index, _)| StyleReference::Line(index)),
    };
    let holder = own_holder
        .map(|(node, _)| node)
        .or_else(|| reference.map(|(_, node)| node));
    let Some(color) = holder.and_then(|holder| DrawColor::read(doc, holder, warnings)) else {
        return (None, [None; 3]);
    };
    let index = reference.map(|(index, _)| index);
    let (dash, cap, ends, dash_style, ends_style) =
        line_decorations(doc, own, index, open, warnings);
    let styles = [style, dash_style, ends_style];
    let width = own
        .and_then(|ln| emus_of(doc, ln, "w", warnings))
        .map(Width::Exact)
        .or_else(|| index.map(Width::Style))
        .unwrap_or(Width::Exact(
            Length::from_emus(DEFAULT_LINE_EMUS).unwrap_or(Length::ZERO),
        ));
    let in_style = match style {
        Some(StyleReference::Line(index)) => LineStyleColor::Style(index),
        _ => LineStyleColor::Own,
    };
    (
        Some(Stroke {
            color,
            width,
            in_style,
            dash,
            cap,
            ends,
        }),
        styles,
    )
}

/// Reads the dash pattern, cap, and open-outline line ends of `own` (`a:ln`), falling back to
/// theme style `index` where omitted and warning on unsupported explicit values.
fn line_decorations(
    doc: &Document,
    own: Option<NodeId>,
    index: Option<usize>,
    open: bool,
    warnings: &mut Warnings<Warning>,
) -> (
    StrokeDash,
    StrokeCapSource,
    StrokeEnds,
    Option<StyleReference>,
    Option<StyleReference>,
) {
    let own_dash = own.map_or(ReadDash::Omitted, |ln| read_dash(doc, ln));
    if own_dash == ReadDash::Unsupported {
        warnings.push(Warning::FeatureNotSupported {
            feature: Feature::LineDash,
        });
    }
    let own_ends = own.map_or(ReadEnds::Omitted, |ln| read_ends(doc, ln));
    if open && own_ends == ReadEnds::Unsupported {
        warnings.push(Warning::FeatureNotSupported {
            feature: Feature::LineEnd,
        });
    }
    let dash_style = index
        .filter(|_| own_dash == ReadDash::Omitted)
        .map(StyleReference::LineDash);
    let ends_style = index
        .filter(|_| open && own_ends == ReadEnds::Omitted)
        .map(StyleReference::LineEnds);
    let dash = match own_dash {
        ReadDash::Omitted => index.map_or(StrokeDash::Own(None), StrokeDash::Style),
        ReadDash::Solid | ReadDash::Unsupported => StrokeDash::Own(None),
        ReadDash::Dashed(dash) => StrokeDash::Own(Some(dash)),
    };
    let cap = match own.and_then(|ln| read_cap(doc, ln)) {
        Some(cap) => StrokeCapSource::Own(cap),
        None => index.map_or(StrokeCapSource::Default, StrokeCapSource::Style),
    };
    let ends = match own_ends {
        ReadEnds::Omitted => index.map_or(StrokeEnds::Own(LineEnds::default()), StrokeEnds::Style),
        ReadEnds::Present(ends) => StrokeEnds::Own(ends),
        ReadEnds::Unsupported => StrokeEnds::Own(LineEnds::default()),
    };
    (dash, cap, ends, dash_style, ends_style)
}

/// Centerline polyline of a rectangle matching PDF `re` (bottom-left counter-clockwise in y-down).
fn rect_dash_points(shown: Edges<Length>) -> Vec<Point> {
    let Edges {
        left,
        top,
        right,
        bottom,
    } = shown;
    vec![
        point(left, bottom),
        point(right, bottom),
        point(right, top),
        point(left, top),
        point(left, bottom),
    ]
}

const fn point(x: Length, y: Length) -> Point {
    Point { x, y }
}

fn path(commands: Vec<PathCommand>, color: Rgb, fill_rule: FillRule) -> Item {
    Item::Path(PathItem {
        commands,
        color,
        fill_rule,
    })
}

/// A rectangle with corners of `radius`, which 0 makes square.
fn rounded(shown: Edges<Length>, radius: Length) -> Vec<PathCommand> {
    let Edges {
        left,
        top,
        right,
        bottom,
    } = shown;
    let r = radius
        .min((right - left).div_toward_zero(2))
        .min((bottom - top).div_toward_zero(2))
        .max(Length::ZERO);
    if r == Length::ZERO {
        return vec![
            PathCommand::MoveTo(point(left, top)),
            PathCommand::LineTo(point(right, top)),
            PathCommand::LineTo(point(right, bottom)),
            PathCommand::LineTo(point(left, bottom)),
            PathCommand::Close,
        ];
    }
    let k = stroke::kappa(r);
    vec![
        PathCommand::MoveTo(point(left + r, top)),
        PathCommand::LineTo(point(right - r, top)),
        PathCommand::CubicTo(
            point(right - r + k, top),
            point(right, top + r - k),
            point(right, top + r),
        ),
        PathCommand::LineTo(point(right, bottom - r)),
        PathCommand::CubicTo(
            point(right, bottom - r + k),
            point(right - r + k, bottom),
            point(right - r, bottom),
        ),
        PathCommand::LineTo(point(left + r, bottom)),
        PathCommand::CubicTo(
            point(left + r - k, bottom),
            point(left, bottom - r + k),
            point(left, bottom - r),
        ),
        PathCommand::LineTo(point(left, top + r)),
        PathCommand::CubicTo(
            point(left, top + r - k),
            point(left + r - k, top),
            point(left + r, top),
        ),
        PathCommand::Close,
    ]
}

/// The ellipse that fills a box, in four quarter curves.
fn ellipse(shown: Edges<Length>) -> Vec<PathCommand> {
    let Edges {
        left,
        top,
        right,
        bottom,
    } = shown;
    // The middle of two ends rounds toward zero, as `i64::midpoint` does.
    let (cx, cy) = (
        (left + right).div_toward_zero(2),
        (top + bottom).div_toward_zero(2),
    );
    let control = |side: Length| stroke::kappa(side.div_toward_zero(2));
    let (kx, ky) = (control(right - left), control(bottom - top));
    vec![
        PathCommand::MoveTo(point(cx, top)),
        PathCommand::CubicTo(point(cx + kx, top), point(right, cy - ky), point(right, cy)),
        PathCommand::CubicTo(
            point(right, cy + ky),
            point(cx + kx, bottom),
            point(cx, bottom),
        ),
        PathCommand::CubicTo(
            point(cx - kx, bottom),
            point(left, cy + ky),
            point(left, cy),
        ),
        PathCommand::CubicTo(point(left, cy - ky), point(cx - kx, top), point(cx, top)),
        PathCommand::Close,
    ]
}

/// A straight line between two points, `half` thick on each side, with flat ends.
fn stroke_line(ends: [(Length, Length); 2], half: Length, color: Rgb) -> Option<Item> {
    stroke_band(ends, [half, -half], color)
}

/// Parallel flat-ended bands, divided within the full line's width.
fn compound_line(
    ends: [(Length, Length); 2],
    half: Length,
    color: Rgb,
    parts: &[i64],
    sign: i64,
) -> Vec<Item> {
    let total: i64 = parts.iter().sum();
    if total <= 0 || parts.iter().any(|part| *part <= 0) {
        return Vec::new();
    }
    // The parts are the format crate's few small proportions, so the products fit.
    let mut used = 0;
    parts
        .iter()
        .enumerate()
        .filter_map(|(index, part)| {
            let low = (half * (2 * used)).div_toward_zero(total) - half;
            used += part;
            let high = (half * (2 * used)).div_toward_zero(total) - half;
            (index % 2 == 0)
                .then(|| stroke_band(ends, [low * sign, high * sign], color))
                .flatten()
        })
        .collect()
}

/// A band bounded by two signed distances along the line's normal.
fn stroke_band(
    [(x0, y0), (x1, y1)]: [(Length, Length); 2],
    [low, high]: [Length; 2],
    color: Rgb,
) -> Option<Item> {
    // The normal's share of a distance multiplies two lengths, in `i128`.
    let (dx, dy) = (i128::from((x1 - x0).units()), i128::from((y1 - y0).units()));
    let length = (dx * dx + dy * dy).isqrt();
    if length == 0 {
        return None;
    }
    let side = |d: i128, offset: Length| {
        Length::from_units(i64::try_from(d * i128::from(offset.units()) / length).unwrap_or(0))
    };
    let (lx, ly) = (side(-dy, low), side(dx, low));
    let (hx, hy) = (side(-dy, high), side(dx, high));
    let commands = vec![
        PathCommand::MoveTo(point(x0 + lx, y0 + ly)),
        PathCommand::LineTo(point(x1 + lx, y1 + ly)),
        PathCommand::LineTo(point(x1 + hx, y1 + hy)),
        PathCommand::LineTo(point(x0 + hx, y0 + hy)),
        PathCommand::Close,
    ];
    Some(path(commands, color, FillRule::NonZero))
}

#[cfg(test)]
mod tests;