f-office-docx 0.2.4

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

use f_office_units::{Edges, Length, lowest_terms};
use f_office_vml::shape_type::TextRect;
use f_office_warnings::Name;
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};

use crate::body::{Block, read_story};
use crate::ns::{self, A, C, CX, DGM, MC, PIC, W14, WP, WP14, WPC, WPG, WPS};
use crate::picture::{BLIP_IMAGE, Picture, embedded_image};
use crate::props::Align;
use crate::reader::PartReader;
use crate::warnings::{ChartReason, Drawing, GroupTransform, Reason};
use f_office_drawingml::Feature;
use f_office_drawingml::color::{DrawColor, percentage};
use f_office_drawingml::shape::{
    GroupFill, ShapeLook, TextRect as PresetTextRect, picture_fill, quarter_turns, text_rect,
};

/// What a floating position is measured from (`relativeFrom`): an area of the page, as a
/// relative size is, or the anchor paragraph, the anchor's line or the text column, which only
/// a position can name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Relative {
    /// An area of the page ([`PageArea`]).
    Area(PageArea),
    /// The anchor paragraph.
    Paragraph,
    /// The line that holds the anchor (`relativeFrom="line"` of `wp:positionV`, `ST_RelFromV`
    /// of ECMA-376 Part 1). Across, and on a target that counts from the paragraph's top
    /// (`FromLine::ParagraphTop`), it is the anchor paragraph.
    Line,
    /// The text column that holds the anchor: in a table cell, the cell's text column.
    Column,
}

/// An area of the page that a floating position or a relative size counts from (`relativeFrom`
/// of `wp:positionH` and `wp:positionV`, and of `wp14:sizeRelH` and `wp14:sizeRelV`,
/// `ST_SizeRelFromH` and `ST_SizeRelFromV`). A position can also count from the anchor
/// paragraph or the text column ([`Relative`]); a size cannot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PageArea {
    /// The page.
    Page,
    /// The space between the margins.
    Margin,
    /// The left or the top margin area.
    StartMargin,
    /// The right or the bottom margin area.
    EndMargin,
}

/// The names of `relativeFrom` of a position (`wp:positionH` and `wp:positionV`, `ST_RelFromH`
/// and `ST_RelFromV` of ECMA-376 Part 1, 20.4.3.4 and 20.4.3.5), read on either axis: the page,
/// the margins, a margin area, where the left, top or inside margin starts the page on its axis
/// and the right, bottom or outside margin ends it, the anchor paragraph, its line and the text
/// column. A position relative to the character (`character`) counts from the margins.
const POSITION_FROM: &Values<Relative> = &Values::new(&[
    own("page", Relative::Area(PageArea::Page)),
    own("margin", Relative::Area(PageArea::Margin)),
    own("leftMargin", Relative::Area(PageArea::StartMargin)),
    own("topMargin", Relative::Area(PageArea::StartMargin)),
    own("insideMargin", Relative::Area(PageArea::StartMargin)),
    own("rightMargin", Relative::Area(PageArea::EndMargin)),
    own("bottomMargin", Relative::Area(PageArea::EndMargin)),
    own("outsideMargin", Relative::Area(PageArea::EndMargin)),
    own("paragraph", Relative::Paragraph),
    own("line", Relative::Line),
    own("column", Relative::Column),
    another("character", Relative::Area(PageArea::Margin)),
]);

/// The names of `relativeFrom` of a relative size (`wp14:sizeRelH` and `wp14:sizeRelV`,
/// `ST_SizeRelFromH` and `ST_SizeRelFromV`), read on either axis: the page, the margins and the
/// margin areas, as [`POSITION_FROM`] reads them.
const SIZE_FROM: &Values<PageArea> = &Values::new(&[
    own("page", PageArea::Page),
    own("margin", PageArea::Margin),
    own("leftMargin", PageArea::StartMargin),
    own("topMargin", PageArea::StartMargin),
    own("insideMargin", PageArea::StartMargin),
    own("rightMargin", PageArea::EndMargin),
    own("bottomMargin", PageArea::EndMargin),
    own("outsideMargin", PageArea::EndMargin),
]);

impl Default for Relative {
    /// The space between the margins, which a position counts from when it names no area: a
    /// drawing without the position element, a position without `relativeFrom`, or one whose
    /// value is text outside the types of [`POSITION_FROM`].
    fn default() -> Self {
        Self::Area(PageArea::Margin)
    }
}

impl Relative {
    /// Whether a position counts from the anchor's text, its paragraph or its line, and so
    /// moves with the text.
    #[must_use]
    pub const fn follows_text(self) -> bool {
        matches!(self, Self::Paragraph | Self::Line)
    }
}

/// One axis of a floating position.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Position {
    /// What it is measured from.
    pub from: Relative,
    /// The offset from the start of that area.
    pub offset: Length,
    /// The alignment in that area, which wins over the offset.
    pub align: Option<Align>,
    /// The offset as a share of that area, in thousandths of a percent
    /// (`wp14:pctPosHOffset` or `wp14:pctPosVOffset`), which wins over `offset`.
    pub share: Option<i64>,
}

/// The sides of a drawing that the text of its wrap flows on (`wrapText`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WrapSides {
    /// Both sides, where there is room (`bothSides`).
    #[default]
    Both,
    /// Only the left side (`left`).
    Left,
    /// Only the right side (`right`).
    Right,
    /// Only the side with more room (`largest`).
    Largest,
}

/// `ST_WrapText`, the sides of a DrawingML wrap (`wrapText`): each name is drawn, and a
/// missing name is both sides.
const WRAP_TEXT: &Values<WrapSides> = &Values::new(&[
    own("bothSides", WrapSides::Both),
    own("left", WrapSides::Left),
    own("right", WrapSides::Right),
    own("largest", WrapSides::Largest),
]);

/// How the text of a text box runs in its box: across it, or turned, down or up the box.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TextFlow {
    /// Across the box.
    Across,
    /// Turned a quarter turn clockwise: the lines run down the box.
    Down,
    /// Turned a quarter turn counterclockwise: the lines run up the box.
    Up,
    /// Turned as `Down`, with the characters of the East Asian font side upright.
    EastAsianDown,
    /// Turned in another of the vertical forms, which F-Office lays out across the box.
    Turned,
}

/// `ST_TextVerticalType` of a text box (`vert` of `wps:bodyPr`, ECMA-376 Part 1, 21.1.2.1.1):
/// `horz` runs across the box, `vert` down it and `vert270` up it, `eaVert` down it with its East
/// Asian characters upright; every other name turns the
/// text in a form that F-Office lays out across the box with the warning
/// `turned-text-box-not-supported`.
const TEXT_VERTICAL: &Values<TextFlow> = &Values::new(&[
    own("horz", TextFlow::Across),
    own("vert", TextFlow::Down),
    own("vert270", TextFlow::Up),
    own("wordArtVert", TextFlow::Turned),
    own("eaVert", TextFlow::EastAsianDown),
    own("mongolianVert", TextFlow::Turned),
    own("wordArtVertRtl", TextFlow::Turned),
]);

/// How the text of a text box turns on the page.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextTurn {
    /// Upright, across the box.
    #[default]
    Upright,
    /// Turned by its body, a quarter turn clockwise: laid out in a frame as long as the box is
    /// high, whose lines run down the page and stack from the box's right side.
    Down,
    /// Turned by its body, a quarter turn counterclockwise: the lines run up the page and stack
    /// from the box's left side.
    Up,
    /// Turned by its body as `Down`, with each glyph of a character of the East Asian font side
    /// upright on the page.
    EastAsianDown,
    /// Turned with its shape: laid out upright in the box before the shape's quarter turns, and
    /// turned with the shape about the box's centre.
    WithShape,
}

/// Where the lines of a text box's body end.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BodyWrap {
    /// At the width of the text area, and at the body's own breaks.
    Area,
    /// Only at the body's own breaks.
    Unbroken,
}

/// `ST_TextWrappingType` of a text box (`wrap` of `wps:bodyPr`, ECMA-376 Part 1, 21.1.2.1.1).
const TEXT_WRAPPING: &Values<BodyWrap> = &Values::new(&[
    own("square", BodyWrap::Area),
    own("none", BodyWrap::Unbroken),
]);

/// `ST_AlignH` of a floating drawing's alignment across (`wp:align` in `wp:positionH`):
/// `inside` is drawn at the left and `outside` at the right, on every page.
const ALIGN_H: &Values<Align> = &Values::new(&[
    own("left", Align::Start),
    own("center", Align::Center),
    own("right", Align::End),
    own("inside", Align::Inside),
    own("outside", Align::Outside),
]);

/// `ST_AlignV` of a floating drawing's alignment down (`wp:align` in `wp:positionV`): `inside`
/// is drawn at the top and `outside` at the bottom, on every page.
const ALIGN_V: &Values<Align> = &Values::new(&[
    own("top", Align::Start),
    own("center", Align::Center),
    own("bottom", Align::End),
    another("inside", Align::Start),
    another("outside", Align::End),
]);

/// A floating drawing with its place, and the text box or the picture that it shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Floating {
    /// The name of the package part that holds the drawing, which a warning of the layout
    /// about the drawing names.
    pub part: Name,
    /// The horizontal position.
    pub h: Position,
    /// The vertical position.
    pub v: Position,
    /// The width of the drawing.
    pub width: Length,
    /// The height of the drawing.
    pub height: Length,
    /// The space between the box edges and its text.
    pub insets: Edges<Length>,
    /// Which edge of the outline the text keeps its insets from.
    pub inset_edge: InsetEdge,
    /// The text rectangle of a VML shape's type, which its text lies in inside the insets, or
    /// `None` for the whole box.
    pub text_rect: Option<TextRect>,
    /// The text rectangle of a DrawingML shape's preset geometry, which its text lies in with
    /// the insets inside it, or `None` for the whole box.
    pub preset_rect: Option<PresetTextRect>,
    /// Whether the shape is as tall as its text (`a:spAutoFit`), whatever height it gives.
    pub fits_text: bool,
    /// Whether the shape is as wide as its text's widest line, whatever width it gives: its
    /// text body does not wrap (`wrap="none"`).
    pub fits_width: bool,
    /// How the text of its text box turns on the page.
    pub text_turn: TextTurn,
    /// The width as a share of an area of the page (`wp14:sizeRelH`), in thousandths of a
    /// percent, which wins over `width`.
    pub relative_width: Option<(PageArea, i64)>,
    /// The height as a share of an area of the page (`wp14:sizeRelV`), unless the shape fits
    /// its height to its text.
    pub relative_height: Option<(PageArea, i64)>,
    /// The content of a text box.
    pub blocks: Vec<Block>,
    /// The color of the text box's text whose own color is automatic or missing: the font
    /// color of the shape's style (`a:fontRef`), `None` when it gives none.
    pub text_color: Option<[u8; 3]>,
    /// The picture, which fills the drawing.
    pub picture: Option<Picture>,
    /// How the text keeps out of the drawing, `None` when it does not: no wrap, `wp:wrapNone`,
    /// a VML wrap without a type, or a shape without height.
    pub wrap: Option<Wrap>,
    /// The points of the polygon of a tight or through wrap that is not a rectangle along the
    /// axes, in order, in 21,600ths of the drawing's width and height from its top left corner;
    /// none for another wrap.
    pub outline: Vec<(i64, i64)>,
    /// How far effects such as a shadow reach out of the edges of the box (`wp:effectExtent`).
    pub effect: Edges<Length>,
    /// The text boxes and pictures of a drawing group, each with its offset from the group's
    /// top left corner. Their own positions and wraps do not apply.
    pub parts: Vec<(Length, Length, Floating)>,
    /// The geometry, fill and line of a shape, with or without a text box.
    pub look: Option<ShapeLook>,
    /// Whether the drawing lies behind the text (`behindDoc`) instead of in front of it.
    pub behind: bool,
    /// Whether a drawing anchored in a table cell is laid out relative to the cell
    /// (`layoutInCell`). Defaults to [`CellLayout::InCell`] when absent; honored in compatibility
    /// modes before 15 and treated as always on from mode 15.
    pub(crate) cell_layout: CellLayout,
    /// The drawing's place among the drawings of its layer, behind or in front of the text: its
    /// `relativeHeight`, or the size of a VML shape's `z-index`. A drawing with a higher one
    /// lies above, and drawings of the same one lie in the order of their anchors.
    pub stack: u64,
    /// Where the text of a text box lies in its box, down the box.
    pub anchor: TextAnchor,
    /// How the text anchor counts the room below the text.
    pub room: Room,
    /// Which rules the lines of the box's text take.
    pub box_text: BoxText,
    /// The parts of a SmartArt graphic, whose saved drawing gives the drawing's parts.
    pub diagram: Option<crate::smartart::Diagram>,
    /// The chart that the drawing shows, which its chart part gives once the parts are read.
    pub chart: Option<crate::chart::Chart>,
    /// The line of text that fills the box, such as a watermark's, instead of a shape.
    pub text_path: Option<TextPath>,
    /// Active single VML drop shadow (`v:shadow on="t"`), if any.
    pub(crate) vml_shadow: Option<VmlShadow>,
}

/// Active single VML drop shadow (`v:shadow`, ECMA-376 Part 4, 14.1.2.18).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct VmlShadow {
    /// Cartesian shadow offset `(across, down)` from the shape.
    pub offset: f_office_drawingml::effect::ShadowOffset,
    /// Shadow color and opacity.
    pub color: f_office_drawingml::effect::ShadowColor,
}

/// Whether a floating drawing anchored in a table cell is laid out inside the cell
/// (`layoutInCell`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum CellLayout {
    /// Laid out relative to the cell (`layoutInCell="1"` or absent).
    #[default]
    InCell,
    /// Laid out relative to the page/column outside the cell (`layoutInCell="0"`).
    OutsideCell,
}

impl CellLayout {
    pub(crate) const fn of(in_cell: bool) -> Self {
        if in_cell {
            Self::InCell
        } else {
            Self::OutsideCell
        }
    }
}

/// A line of text that a VML shape draws to fill its box (a `v:textpath` in a shape of the type
/// 136, plain text), as a watermark is drawn.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextPath {
    /// The text.
    pub string: String,
    /// The family of the face.
    pub face: f_office_fonts::FamilyName,
    /// The fill of the letters, its color already mixed with white by its opacity.
    pub color: f_office_paint::Rgb,
    /// How far the line is turned clockwise about the center of the box, in DrawingML's unit,
    /// 60,000ths of a degree.
    pub rotation: i64,
}

impl Floating {
    /// A drawing of the part `part` with the defaults of every other field: no size, no wrap,
    /// no content and no look, which its reader then sets.
    pub(crate) fn in_part(part: &str) -> Self {
        Self {
            part: Name::new(part),
            h: Position::default(),
            v: Position::default(),
            width: Length::ZERO,
            height: Length::ZERO,
            insets: Edges::default(),
            inset_edge: InsetEdge::default(),
            text_rect: None,
            preset_rect: None,
            fits_text: false,
            fits_width: false,
            text_turn: TextTurn::Upright,
            relative_width: None,
            relative_height: None,
            blocks: Vec::new(),
            text_color: None,
            picture: None,
            wrap: None,
            outline: Vec::new(),
            effect: Edges::default(),
            parts: Vec::new(),
            look: None,
            behind: false,
            cell_layout: CellLayout::InCell,
            stack: 0,
            anchor: TextAnchor::default(),
            room: Room::default(),
            box_text: BoxText::default(),
            diagram: None,
            chart: None,
            text_path: None,
            vml_shadow: None,
        }
    }
}

/// A drawing of the main document part, for a test.
#[cfg(test)]
impl Default for Floating {
    fn default() -> Self {
        Self::in_part(crate::testing::DOCUMENT)
    }
}

/// How the text keeps out of a floating drawing: the one wrap element of DrawingML
/// (`wp:wrapTopAndBottom`, `wp:wrapSquare`, `wp:wrapTight` or `wp:wrapThrough`) or the
/// `w10:wrap` of a VML shape.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Wrap {
    /// The text keeps above and below the drawing (`wp:wrapTopAndBottom`).
    TopAndBottom {
        /// The space to keep above the drawing's box: `distT` and the effect extent above it.
        above: Length,
        /// The space to keep below the drawing's box: `distB` and the effect extent below it.
        below: Length,
    },
    /// The text flows beside the drawing's box: a square wrap (`wp:wrapSquare`), and a tight
    /// or through wrap (`wp:wrapTight`, `wp:wrapThrough`), which keeps the text out of the
    /// bounds of its polygon.
    Beside {
        /// The space to keep at the box's edges (`distL`, `distT`, `distR`, `distB`), with the
        /// effect extents for a square wrap.
        distances: Edges<Length>,
        /// The sides of the drawing that the text of a square wrap flows on (`wrapText`), and
        /// of a tight or through wrap whose polygon is its bounds. `None` for another wrap,
        /// beside which a line takes the widest free piece: Word follows the outline of such a
        /// polygon on each line, where F-Office keeps the text out of the polygon's bounds.
        sides: Option<WrapSides>,
        /// How far the bounds of a tight or through wrap's polygon lie inside the edges of the
        /// box, negative outside them, zero for a tight or through wrap without a polygon;
        /// `None` for a square wrap. Beside a tight or through wrap, a line without room beside
        /// the drawing goes where the quirk `BlockedLines` says.
        polygon: Option<Edges<Length>>,
    },
}

/// Which edge of a box's outline its text keeps its insets from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InsetEdge {
    /// The outline's middle, as in a SmartArt box.
    #[default]
    Middle,
    /// The outline's inner edge, as in a DrawingML text box (`wps:txbx`).
    Inside,
    /// The edge that the target chooses for a VML text box (`v:textbox`).
    Vml,
}

/// Which rules the lines of a box's text take.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BoxText {
    /// The rules of the document's own paragraphs: the text of a text box or of another shape.
    #[default]
    Paragraphs,
    /// The rules of SmartArt text, the text of a shape of a SmartArt graphic's saved drawing
    /// (`dsp:sp`), whose lines below single spacing take the target's SmartArt rule
    /// ([`crate::quirks::SmartArtLowSpacing`]).
    SmartArt,
}

/// How the text anchor of a box counts the room below its text.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Room {
    /// As in a SmartArt box: the text ends at its last line, and text taller than its box
    /// moves up.
    #[default]
    Shape,
    /// As in a DrawingML text box (`wps:txbx`): the text ends below the space after its last
    /// paragraph, and text taller than the box stays at the top.
    TextBox,
}

/// Where the text of a text box lies in its box, down the box (`anchor` of `a:bodyPr`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextAnchor {
    /// At the top.
    #[default]
    Top,
    /// In the middle.
    Center,
    /// At the bottom.
    Bottom,
}

impl TextAnchor {
    /// The anchor that the value of `anchor` names: `ctr` the middle, `b` the bottom, and any
    /// other value, or none, the top (ECMA-376 Part 1, 21.1.2.1.1).
    #[must_use]
    pub fn of(value: Option<&str>) -> Self {
        match value {
            Some("ctr") => Self::Center,
            Some("b") => Self::Bottom,
            _ => Self::Top,
        }
    }
}

/// The size of an inline or floating drawing (`wp:inline` or `wp:anchor`), from its
/// `wp:extent` in EMU, and its effect extent (`wp:effectExtent`) at each edge. A length that is
/// missing or does not read is 0. Each length is read once, so that a value that does not read
/// gives one warning.
pub(crate) fn extents(reader: &mut PartReader, drawing: NodeId) -> ([Length; 2], Edges<Length>) {
    let doc = reader.doc;
    let extent = doc.child(drawing, WP, "extent");
    let effect = doc.child(drawing, WP, "effectExtent");
    let mut length = |node: Option<NodeId>, name: &str| {
        node.and_then(|n| reader.emu_length(n, name))
            .unwrap_or(Length::ZERO)
    };
    (
        ["cx", "cy"].map(|name| length(extent, name)),
        Edges::from(["l", "t", "r", "b"].map(|name| length(effect, name))),
    )
}

/// Reads a floating drawing that holds a text box, a picture, a group, a SmartArt graphic or a
/// chart.
pub(crate) fn read_anchor(reader: &mut PartReader, drawing: NodeId) -> Option<Floating> {
    let doc = reader.doc;
    let anchor = doc.child(drawing, WP, "anchor")?;
    let ([width, height], effects) = extents(reader, anchor);
    let (wrap, outline) = read_wrap(reader, anchor, (width, height), effects);
    // The shown branches of the anchor's alternate content, taken once for both axes, so that
    // each choice that F-Office passes over warns once.
    let shown: Vec<NodeId> = doc
        .child_elements(anchor)
        .filter(|node| doc.is(*node, MC, "AlternateContent"))
        .filter_map(|node| crate::body::shown_branch(reader, node))
        .collect();
    let mut floating = Floating {
        h: position(reader, (anchor, &shown), ("positionH", ALIGN_H)),
        v: position(reader, (anchor, &shown), ("positionV", ALIGN_V)),
        width,
        height,
        wrap,
        outline,
        effect: effects,
        relative_width: relative_size(reader, anchor, "sizeRelH", "pctWidth"),
        relative_height: relative_size(reader, anchor, "sizeRelV", "pctHeight"),
        behind: doc
            .attribute(anchor, None, "behindDoc")
            .is_some_and(f_office_drawingml::boolean),
        cell_layout: CellLayout::of(
            doc.attribute(anchor, None, "layoutInCell")
                .is_none_or(f_office_drawingml::boolean),
        ),
        stack: doc
            .attribute(anchor, None, "relativeHeight")
            .and_then(|value| value.parse().ok())
            .unwrap_or(0),
        ..Floating::in_part(reader.part())
    };
    if let Some(picture) = Picture::read(reader, anchor, Edges::sized(width, height)) {
        let rotation = crate::picture::rotation(doc, anchor);
        let turned = reader
            .turned_pictures()
            .turned_box((width, height), rotation);
        if turned != (width, height) {
            floating.wrap = floating
                .wrap
                .map(|wrap| swapped_wrap(wrap, (width, height)));
        }
        floating.picture = Some(picture);
        return Some(floating);
    }
    let data = doc
        .child(anchor, A, "graphic")
        .and_then(|g| doc.child(g, A, "graphicData"))?;
    // A SmartArt graphic gets its parts from its saved drawing once the parts are read.
    if let Some(diagram) = crate::smartart::diagram(doc, data) {
        floating.diagram = Some(diagram);
        return Some(floating);
    }
    if let Some(group) = shape_child(doc, data, "wgp") {
        read_group(reader, group, &mut floating);
        keep_text_flow_of_shapes(&mut floating);
        return (!floating.parts.is_empty()).then_some(floating);
    }
    if let Some(canvas) = doc.child(data, WPC, "wpc") {
        read_canvas(reader, canvas, &mut floating);
        keep_text_flow_of_shapes(&mut floating);
        return (!floating.parts.is_empty()).then_some(floating);
    }
    // A floating chart takes its place and keeps the text out by its wrap, as any floating
    // drawing does, and shows the chart in its frame as an inline chart does.
    if let Some(chart) = crate::chart::reference(doc, data) {
        floating.chart = Some(chart);
        return Some(floating);
    }
    // A graphic that F-Office draws in no place is left out with a warning.
    let Some(shape) = shape_child(doc, data, "wsp") else {
        skip_graphic(reader, data);
        return None;
    };
    read_shape(reader, shape, &mut floating);
    keep_text_flow_of_shapes(&mut floating);
    Some(floating)
}

/// The wrap `wrap` of a floating picture of `width` by `height` whose box is its frame with
/// its width and height swapped about its centre (`TurnedPictures::turned_box`): square
/// wrapping and top and bottom wrapping keep the text out of that box, half the difference
/// narrower across and taller down, with the effect extent and the wrap distances around it.
/// A tight or through wrap keeps its polygon.
fn swapped_wrap(wrap: Wrap, (width, height): (Length, Length)) -> Wrap {
    let half = (width - height).div_round(2);
    match wrap {
        Wrap::Beside {
            distances,
            sides,
            polygon: None,
        } => Wrap::Beside {
            distances: Edges {
                left: distances.left - half,
                top: distances.top + half,
                right: distances.right - half,
                bottom: distances.bottom + half,
            },
            sides,
            polygon: None,
        },
        Wrap::TopAndBottom { above, below } => Wrap::TopAndBottom {
            above: above + half,
            below: below + half,
        },
        tight @ Wrap::Beside { .. } => tight,
    }
}

/// The graphics of a drawing's graphic data (`a:graphicData`) that F-Office draws in some
/// places and not in others, or in no place, each by its element, with the kind of drawing
/// and the reason that the warning of its skip names: a chart (`c:chart`), which comes here
/// only without a part; a chart of Office 2016 and later (`cx:chart`), such as a
/// waterfall chart; a SmartArt graphic (`dgm:relIds`), which F-Office does not draw in a group;
/// and ink (`w14:contentPart`).
const GRAPHICS: [(&str, &str, Drawing, Reason); 4] = [
    (C, "chart", Drawing::Chart, Reason::Unsupported),
    (
        CX,
        "chart",
        Drawing::Chart,
        Reason::Chart(ChartReason::ChartEx),
    ),
    (DGM, "relIds", Drawing::SmartArt, Reason::Unsupported),
    (W14, "contentPart", Drawing::Shape, Reason::Unsupported),
];

/// The kind of drawing that the graphic data `data` holds, for the warning that it is left
/// out: the kind of its graphic of [`GRAPHICS`], a picture for `pic:pic`, or else a shape.
pub(crate) fn graphic_data_drawing(doc: &Document, data: NodeId) -> Drawing {
    graphic_kind(doc, data).unwrap_or_else(|| {
        if doc.child(data, PIC, "pic").is_some() {
            Drawing::Picture
        } else {
            Drawing::Shape
        }
    })
}

/// The kind of drawing of the graphic of [`GRAPHICS`] that the graphic data `data` holds, or
/// `None` when it holds none of them.
fn graphic_kind(doc: &Document, data: NodeId) -> Option<Drawing> {
    graphic_skip(doc, data).map(|(kind, _)| kind)
}

/// The kind of drawing and the reason of the skip of the graphic of [`GRAPHICS`] that the
/// graphic data `data` holds, or `None` when it holds none of them.
fn graphic_skip(doc: &Document, data: NodeId) -> Option<(Drawing, Reason)> {
    GRAPHICS
        .iter()
        .find(|(namespace, name, _, _)| doc.child(data, namespace, name).is_some())
        .map(|&(_, _, kind, reason)| (kind, reason))
}

/// Keeps the warning that the graphic that the graphic data `data` holds is left out, for a
/// reader that has not drawn it: with its kind and its reason when it is one of [`GRAPHICS`],
/// and as a shape that F-Office does not draw when it is an element of another kind, such as a
/// locked canvas (`lc:lockedCanvas`). A picture (`pic:pic`) gives no warning here, as the
/// picture reader has read it and warns of what it leaves out, such as a missing image part,
/// and graphic data without an element gives none.
fn skip_graphic(reader: &mut PartReader, data: NodeId) {
    let doc = reader.doc;
    if let Some((kind, reason)) = graphic_skip(doc, data) {
        reader.drawing_skipped(kind, reason);
    } else if doc.child(data, PIC, "pic").is_none() && doc.child_elements(data).next().is_some() {
        reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
    }
}

/// Reads the wrap of an anchored drawing of `size` whose effects reach `effects` out of its
/// edges, with the points of a tight or through wrap's polygon that is not a rectangle along
/// the axes. The schema allows one wrap element; of a file with more, a square wrap wins,
/// then a tight or through wrap, then a top and bottom wrap.
fn read_wrap(
    reader: &mut PartReader,
    anchor: NodeId,
    size: (Length, Length),
    effects: Edges<Length>,
) -> (Option<Wrap>, Vec<(i64, i64)>) {
    let doc = reader.doc;
    // Top and bottom wrap and square wrap keep the text away from the box of the drawing with
    // its effect extent, such as a shadow, and the wrap distances around that.
    let distances = Edges::from(
        ["distL", "distT", "distR", "distB"]
            .map(|name| reader.emu_length(anchor, name).unwrap_or(Length::ZERO)),
    );
    let boxed = distances.with(effects, |distance, effect| distance + effect);
    // Tight and through wraps keep the text out of the bounds of their wrap polygon, with the
    // wrap distances around them.
    let tight = ["wrapTight", "wrapThrough"]
        .iter()
        .find_map(|name| doc.child(anchor, WP, name));
    let outline = tight.map_or_else(Vec::new, |wrap| polygon_points(reader, wrap));
    // A polygon whose bounds lie out of range reads as no polygon, with a warning.
    let insets = polygon_insets(&outline, size);
    if insets.is_none() {
        reader.polygon_skipped(Reason::OutOfRange);
    }
    let polygon = insets.unwrap_or_default();
    // The text flows on the sides that a square wrap names, and so does the text of a tight
    // or through wrap whose polygon is its bounds. Beside another polygon, whose outline Word
    // follows on each line where F-Office keeps the text out of its bounds, a line takes the
    // widest free piece.
    if let Some(square) = doc.child(anchor, WP, "wrapSquare") {
        let wrap = Wrap::Beside {
            distances: boxed,
            sides: Some(wrap_sides(reader, square)),
            polygon: None,
        };
        return (Some(wrap), Vec::new());
    }
    if let Some(tight) = tight {
        let bounds = fills_its_bounds(&outline);
        let wrap = Wrap::Beside {
            distances,
            sides: bounds.then(|| wrap_sides(reader, tight)),
            polygon: Some(polygon),
        };
        // The outline of a polygon that is not its bounds, and none of one that reads as no
        // polygon.
        let outline = if bounds || insets.is_none() {
            Vec::new()
        } else {
            outline
        };
        return (Some(wrap), outline);
    }
    let wrap = doc
        .child(anchor, WP, "wrapTopAndBottom")
        .map(|_| Wrap::TopAndBottom {
            above: boxed.top,
            below: boxed.bottom,
        });
    (wrap, Vec::new())
}

/// The sides that the text of a DrawingML wrap flows on (`wrapText`), both when it names none.
fn wrap_sides(reader: &mut PartReader, wrap: NodeId) -> WrapSides {
    reader
        .enumeration_in(wrap, (None, "wrapText"), WRAP_TEXT)
        .unwrap_or_default()
}

/// A size relative to an area of the page (`wp14:sizeRelH` with `wp14:pctWidth`, or
/// `wp14:sizeRelV` with `wp14:pctHeight`), as the area and thousandths of a percent of it.
fn relative_size(
    reader: &mut PartReader,
    anchor: NodeId,
    name: &str,
    share: &str,
) -> Option<(PageArea, i64)> {
    let doc = reader.doc;
    let node = doc.child(anchor, WP14, name)?;
    let from = reader.enumeration_in(node, (None, "relativeFrom"), SIZE_FROM)?;
    let value = doc.text_content(doc.child(node, WP14, share)?);
    // A Strict file writes the share with a percent sign.
    let thousandths = percentage(&value).filter(|v| *v > 0)?;
    Some((from, thousandths))
}

/// How far the bounds of a wrap polygon (`wp:wrapPolygon`) lie inside the left, top, right
/// and bottom edges of a drawing of `size`, negative outside them. The polygon's coordinates
/// run from 0 to 21,600 across the drawing. A wrap without a polygon lies on the edges. The
/// product of a coordinate and a side is taken in `i128`, and a distance beyond
/// [`Length::FILE_LIMIT`] gives `None`.
fn polygon_insets(points: &[(i64, i64)], size: (Length, Length)) -> Option<Edges<Length>> {
    const FULL: i64 = crate::params::WRAP_POLYGON_WHOLE;
    let ((left, right), (top, bottom)) = (bounds(points, |p| p.0), bounds(points, |p| p.1));
    let scale = |value: i64, length: Length| {
        let share = i128::from(value) * i128::from(length.units()) / i128::from(FULL);
        i64::try_from(share)
            .ok()
            .filter(|share| (-Length::FILE_LIMIT..=Length::FILE_LIMIT).contains(share))
            .map(Length::from_units)
    };
    Some(Edges {
        left: scale(left, size.0)?,
        top: scale(top, size.1)?,
        right: scale(FULL - right, size.0)?,
        bottom: scale(FULL - bottom, size.1)?,
    })
}

/// The points of a wrap's polygon (`wp:wrapPolygon`), none when it has none. A point whose
/// coordinate is missing or does not read is left out.
fn polygon_points(reader: &mut PartReader, wrap: NodeId) -> Vec<(i64, i64)> {
    let doc = reader.doc;
    doc.child(wrap, WP, "wrapPolygon")
        .map_or_default(|polygon| {
            doc.child_elements(polygon)
                .filter_map(|point| {
                    let [x, y] = ["x", "y"].map(|name| reader.emus(point, name));
                    x.zip(y)
                })
                .collect()
        })
}

/// The lowest and the highest value of the points along an axis, the whole drawing without
/// points.
fn bounds(points: &[(i64, i64)], axis: fn(&(i64, i64)) -> i64) -> (i64, i64) {
    let low = points.iter().map(axis).min().unwrap_or(0);
    let high = points
        .iter()
        .map(axis)
        .max()
        .unwrap_or(crate::params::WRAP_POLYGON_WHOLE);
    (low, high)
}

/// Whether a wrap's polygon is its own bounds, a rectangle along the axes, as is a wrap without
/// a polygon: every point lies on a corner of the bounds.
fn fills_its_bounds(points: &[(i64, i64)]) -> bool {
    let ((left, right), (top, bottom)) = (bounds(points, |p| p.0), bounds(points, |p| p.1));
    points
        .iter()
        .all(|&(x, y)| (x == left || x == right) && (y == top || y == bottom))
}

/// Takes the wrap away from a shape without height, such as a horizontal line, which keeps no
/// text out.
fn keep_text_flow_of_shapes(floating: &mut Floating) {
    if floating.height == Length::ZERO {
        floating.wrap = None;
    }
}

/// Reads the shape (`wps:wsp`) of an inline drawing (`wp:inline`) as a drawing of `width` by
/// `height` without a place of its own, or gives `None` when the drawing holds no shape.
pub(crate) fn read_inline_shape(
    reader: &mut PartReader,
    inline: NodeId,
    width: Length,
    height: Length,
) -> Option<Floating> {
    let doc = reader.doc;
    let data = doc
        .child(inline, A, "graphic")
        .and_then(|g| doc.child(g, A, "graphicData"))?;
    let mut floating = Floating {
        width,
        height,
        ..Floating::in_part(reader.part())
    };
    if let Some(diagram) = crate::smartart::diagram(doc, data) {
        floating.diagram = Some(diagram);
        return Some(floating);
    }
    // An inline chart takes the room of its frame, and shows the chart in it.
    if let Some(chart) = crate::chart::reference(doc, data) {
        floating.chart = Some(chart);
        return Some(floating);
    }
    // An inline group shows its shapes, text boxes and pictures as a floating group does.
    if let Some(group) = shape_child(doc, data, "wgp") {
        read_group(reader, group, &mut floating);
        return (!floating.parts.is_empty()).then_some(floating);
    }
    // An inline drawing canvas shows its backdrop and children at their offsets from its corner.
    if let Some(canvas) = doc.child(data, WPC, "wpc") {
        read_canvas(reader, canvas, &mut floating);
        return (!floating.parts.is_empty()).then_some(floating);
    }
    // A graphic that F-Office draws in no place keeps its room and is left out with a warning.
    let Some(shape) = shape_child(doc, data, "wsp") else {
        skip_graphic(reader, data);
        return None;
    };
    read_shape(reader, shape, &mut floating);
    Some(floating)
}

/// The namespaces of the elements of shapes and groups. Word writes them in its own two
/// namespaces in a Transitional document and in the namespace of `wp:anchor` in a Strict one,
/// whose schema defines `wsp`, `wgp`, `grpSp`, `txbx` and the others (ECMA-376 Part 1, 20.4.2).
const SHAPE_NAMESPACES: [&str; 3] = [WPS, WPG, WP];

/// The child `name` of `node` among the elements of shapes and groups.
fn shape_child(doc: &Document, node: NodeId, name: &str) -> Option<NodeId> {
    SHAPE_NAMESPACES
        .iter()
        .find_map(|namespace| doc.child(node, namespace, name))
}

/// Whether `node` is the element `name` of shapes and groups.
fn is_shape_element(doc: &Document, node: NodeId, name: &str) -> bool {
    SHAPE_NAMESPACES
        .iter()
        .any(|namespace| doc.is(node, namespace, name))
}

/// Resolves the inherited [`GroupFill`] of `group` (`wpg:wgp` or `wpg:grpSp`) whose box in
/// outermost-group coordinates is `group_box`: takes `group`'s own `wpg:grpSpPr` when it carries
/// an explicit fill (`noFill`, `solidFill`, `gradFill`, `blipFill`, `pattFill`), otherwise
/// inherits from `parent`.
fn resolve_group_fill(
    doc: &Document,
    group: NodeId,
    group_box: Edges<Length>,
    parent: Option<GroupFill>,
) -> GroupFill {
    const EXPLICIT_FILLS: [&str; 5] = ["noFill", "solidFill", "gradFill", "blipFill", "pattFill"];
    if let Some(props) = shape_child(doc, group, "grpSpPr")
        && EXPLICIT_FILLS
            .iter()
            .any(|name| doc.child(props, A, name).is_some())
    {
        return GroupFill {
            props: Some(props),
            frame: group_box,
        };
    }
    parent.unwrap_or(GroupFill {
        props: None,
        frame: group_box,
    })
}

/// Reads the parts of a drawing group (`wpg:wgp`) into `floating`, at their offsets from the
/// group's top left corner.
fn read_group(reader: &mut PartReader, group: NodeId, floating: &mut Floating) {
    let t = xfrm(reader, group);
    let ortho = read_group_ortho(reader, group);
    let Some(map) = Map::root(&t, ortho) else {
        reader.drawing_skipped(Drawing::Shape, Reason::OutOfRange);
        return;
    };
    let group_box = Edges::sized(floating.width, floating.height);
    let group_fill = resolve_group_fill(reader.doc, group, group_box, None);
    group_parts(reader, group, map, Some(group_fill), &mut floating.parts);
}

/// Reads a drawing canvas (`wpc:wpc`) into `floating`: its optional background fill (`wpc:bg`)
/// and whole-canvas outline/effect (`wpc:whole`) painted first as a rectangle filling the canvas,
/// followed by its child shapes, pictures and nested groups at their EMU offsets from the
/// canvas's top left corner without clipping.
fn read_canvas(reader: &mut PartReader, canvas: NodeId, floating: &mut Floating) {
    let doc = reader.doc;
    let bg = doc.child(canvas, WPC, "bg");
    let whole = doc.child(canvas, WPC, "whole");
    let has_backdrop = bg.is_some_and(|n| doc.child_elements(n).next().is_some())
        || whole.is_some_and(|n| doc.child_elements(n).next().is_some());
    if has_backdrop {
        let mut backdrop = Floating {
            width: floating.width,
            height: floating.height,
            look: Some(ShapeLook::read_canvas(
                doc,
                (bg, whole),
                reader.drawing_warnings(),
            )),
            ..Floating::in_part(reader.part())
        };
        if let Some(bg) = bg {
            read_picture_fill(reader, bg, &mut backdrop);
        }
        floating.parts.push((Length::ZERO, Length::ZERO, backdrop));
    }
    group_parts(reader, canvas, Map::IDENTITY, None, &mut floating.parts);
}

/// Reads the picture fill of a shape whose properties are `props` into `floating`, which holds
/// the shape's look and size. The picture is drawn over the shape's whole box, in its own
/// colors: a shape whose outline is not a rectangle, and a color effect of the picture, each
/// warn. A linked image is left out with a warning.
fn read_picture_fill(reader: &mut PartReader, props: NodeId, floating: &mut Floating) {
    let doc = reader.doc;
    let Some(fill) = picture_fill(doc, props) else {
        return;
    };
    let Some(blip) = doc.child(fill, A, "blip") else {
        return;
    };
    if embedded_image(reader, blip, BLIP_IMAGE).is_none() {
        return;
    }
    floating.picture = Picture::from_fill(reader, fill, (floating.width, floating.height));
    let Some(picture) = floating.picture.as_mut() else {
        return;
    };
    let Some(look) = floating.look.as_ref() else {
        return;
    };
    if !look.geometry.is_shaped() {
        return;
    }
    let full_box = picture.left == Length::ZERO
        && picture.top == Length::ZERO
        && picture.width == floating.width
        && picture.height == floating.height;
    let upright = look.is_upright();
    if look.geometry.is_closed_shape() && full_box && upright {
        picture.geometry = look.geometry.clone();
    } else {
        reader.drawingml_feature_not_supported(Feature::ShapedPicture);
    }
}

/// Reads the look of a shape (`wps:wsp`) and its text box, if it has one, into `floating`.
fn read_shape(reader: &mut PartReader, shape: NodeId, floating: &mut Floating) {
    read_shape_with_ortho(reader, shape, Ortho::IDENTITY, None, floating);
}

/// Reads a shape (`wps:wsp`), composing an outer group transform `ortho` onto its look and
/// picture fill before computing its text box turn.
fn read_shape_with_ortho(
    reader: &mut PartReader,
    shape: NodeId,
    ortho: Ortho,
    group_fill: Option<GroupFill>,
    floating: &mut Floating,
) {
    let doc = reader.doc;
    let props = shape_child(doc, shape, "spPr");
    let style = shape_child(doc, shape, "style");
    let look = match group_fill {
        Some(gf) => ShapeLook::read_in_group(doc, (props, style), gf, reader.drawing_warnings()),
        None => ShapeLook::read(doc, (props, style), reader.drawing_warnings()),
    };
    floating.look = Some(look.compose_outer(ortho.0));
    floating.text_color = style
        .and_then(|s| doc.child(s, A, "fontRef"))
        .and_then(|f| DrawColor::read(doc, f, reader.drawing_warnings()))
        .and_then(|color| color.resolve(reader.scheme()))
        .map(|(rgb, _)| [rgb.r, rgb.g, rgb.b]);
    if let Some(props) = props {
        read_picture_fill(reader, props, floating);
        if let Some(picture) = floating.picture.as_mut() {
            picture.compose_outer_turn(ortho.0);
        }
    }
    let Some(content) = shape_child(doc, shape, "txbx").and_then(|t| ns::text_box_content(doc, t))
    else {
        return;
    };
    // Page numbers in a text box count like those around it.
    floating.blocks = read_story(reader, content);
    let body = shape_child(doc, shape, "bodyPr");
    floating.text_turn = text_turn(reader, body, floating.look.as_ref());
    floating.insets = body_insets(reader, body, crate::params::TEXT_BOX_INSETS);
    floating.inset_edge = InsetEdge::Inside;
    floating.preset_rect = props.and_then(|props| text_rect(doc, props));
    floating.fits_width = body
        .and_then(|body| reader.enumeration_in(body, (None, "wrap"), TEXT_WRAPPING))
        == Some(BodyWrap::Unbroken);
    // The text lies at the top, in the middle or at the bottom of the box.
    floating.anchor = TextAnchor::of(body.and_then(|n| doc.attribute(n, None, "anchor")));
    floating.room = Room::TextBox;
    // A shape that fits its height to its text does not take a relative height.
    if body.and_then(|b| doc.child(b, A, "spAutoFit")).is_some() {
        floating.relative_height = None;
        floating.fits_text = true;
    }
}

/// How Word turns the text of a shape's text box, whose body is `body` and whose look is
/// `look`: in a shape that is not turned, the body's `vert` turns it down or up the box, with the
/// East Asian characters of `eaVert` upright; a shape
/// turned by whole quarter turns other than none (ECMA-376 Part 1, 20.1.7.6) turns its text with
/// it, unless the body keeps the text upright (`upright`, Part 1, 21.1.2.1.1), and a shape
/// mirrored down turns it by a half turn more ([`ShapeLook::text_quarter_turns`]). A body that turns
/// its text in another form, or in a turned shape, is laid out upright with the warning of a
/// turned text box. The text of a shape
/// turned by another angle is warned of with the shape's turn.
fn text_turn(reader: &mut PartReader, body: Option<NodeId>, look: Option<&ShapeLook>) -> TextTurn {
    let doc = reader.doc;
    let flow = body.and_then(|body| reader.enumeration_in(body, (None, "vert"), TEXT_VERTICAL));
    let upright = body
        .and_then(|body| doc.attribute(body, None, "upright"))
        .is_some_and(f_office_drawingml::boolean);
    if look.is_some_and(|look| look.quarter_turns().is_none()) && !upright {
        reader.feature_not_supported(crate::Feature::TurnedTextBox);
        return TextTurn::Upright;
    }
    let quarters = look.and_then(ShapeLook::text_quarter_turns).unwrap_or(0);
    match (flow.unwrap_or(TextFlow::Across), quarters) {
        (TextFlow::Across, 0) => TextTurn::Upright,
        (TextFlow::Across, _) if upright => TextTurn::Upright,
        (TextFlow::Across, _) => TextTurn::WithShape,
        (TextFlow::Down, 0) => TextTurn::Down,
        (TextFlow::Up, 0) => TextTurn::Up,
        (TextFlow::EastAsianDown, 0) => TextTurn::EastAsianDown,
        (TextFlow::Down | TextFlow::Up | TextFlow::EastAsianDown | TextFlow::Turned, _) => {
            reader.feature_not_supported(crate::Feature::TurnedTextBox);
            TextTurn::Upright
        }
    }
}

/// The insets of a text body (`a:bodyPr` or `wps:bodyPr`): `lIns`, `tIns`, `rIns` and `bIns`
/// in EMUs, each `defaults` (at the sides, and above and below) when it is missing or does not
/// read: 0.1 inch and 0.05 inch for a text box (ECMA-376 Part 1, 21.1.2.1.1,
/// `params::TEXT_BOX_INSETS`).
pub(crate) fn body_insets(
    reader: &mut PartReader,
    body: Option<NodeId>,
    (side, top): (Length, Length),
) -> Edges<Length> {
    let mut inset = |name: &str, default: Length| {
        body.and_then(|n| reader.emu_length(n, name))
            .unwrap_or(default)
    };
    Edges {
        left: inset("lIns", side),
        top: inset("tIns", top),
        right: inset("rIns", side),
        bottom: inset("bIns", top),
    }
}

/// One axis of the map from a group's child coordinates to EMUs from the top left corner of
/// the outermost group: `origin + (value - child) * num / den`. The fraction `num / den` is
/// kept in its lowest terms, which gives the same places, so that the terms of nested groups do
/// not grow when a group's child range equals its box; a place or a fraction that does not fit
/// gives `None`.
/// An axis-aligned orthogonal 2D transform (element of D4), with entries in `-1..=1`, mapping a
/// local scaled offset `(dx, dy)` to `(m[0][0]*dx + m[0][1]*dy, m[1][0]*dx + m[1][1]*dy)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Ortho([[i32; 2]; 2]);

impl Ortho {
    const IDENTITY: Self = Self([[1, 0], [0, 1]]);

    /// Flip in local space first, then rotate clockwise by `quarters` (`0..=3`) in y-down space.
    fn from_xfrm(quarters: i64, [flip_h, flip_v]: [bool; 2]) -> Self {
        let rot = match quarters {
            0 => Self([[1, 0], [0, 1]]),
            1 => Self([[0, -1], [1, 0]]),
            2 => Self([[-1, 0], [0, -1]]),
            _ => Self([[0, 1], [-1, 0]]),
        };
        let sx = if flip_h { -1 } else { 1 };
        let sy = if flip_v { -1 } else { 1 };
        rot.compose(Self([[sx, 0], [0, sy]]))
    }

    const fn compose(self, inner: Self) -> Self {
        let (a, b) = (self.0, inner.0);
        Self([
            [
                a[0][0] * b[0][0] + a[0][1] * b[1][0],
                a[0][0] * b[0][1] + a[0][1] * b[1][1],
            ],
            [
                a[1][0] * b[0][0] + a[1][1] * b[1][0],
                a[1][0] * b[0][1] + a[1][1] * b[1][1],
            ],
        ])
    }

    fn apply(self, [x, y]: [i128; 2]) -> [i128; 2] {
        [
            i128::from(self.0[0][0]) * x + i128::from(self.0[0][1]) * y,
            i128::from(self.0[1][0]) * x + i128::from(self.0[1][1]) * y,
        ]
    }
}

/// Rational positive scale factor `num / den` for one axis of a group.
#[derive(Clone, Copy, Debug)]
struct Scale {
    num: i128,
    den: i128,
}

impl Scale {
    const ONE: Self = Self { num: 1, den: 1 };

    fn new(num: i128, den: i128) -> Self {
        let (num, den) = lowest_terms(num, den);
        Self { num, den }
    }

    fn scale(self, value: i128) -> Option<i128> {
        Some(value.checked_mul(self.num)? / self.den)
    }

    fn compose(self, ext: i64, child_ext: i64) -> Option<Self> {
        Some(Self::new(
            self.num.checked_mul(i128::from(ext))?,
            self.den.checked_mul(i128::from(child_ext.max(1)))?,
        ))
    }
}

/// The affine map from a group's child coordinates to EMUs from the outermost group's corner,
/// including group flips and quarter-turn rotations.
#[derive(Clone, Copy, Debug)]
struct Map {
    /// Doubled center `[2 * cx, 2 * cy]` of this group in outermost-group EMUs.
    center_out2: [i128; 2],
    /// Doubled center `[2 * chOff + chExt]` of the child coordinate space.
    child_center2: [i128; 2],
    /// Rational scale from child coordinates to local EMUs along each axis.
    scale: [Scale; 2],
    /// Accumulated D4 orthogonal transform from local scaled axes to outermost-group axes.
    ortho: Ortho,
}

fn doubled_center(off: [i64; 2], ext: [i64; 2]) -> Option<[i128; 2]> {
    Some([
        i128::from(off[0])
            .checked_mul(2)?
            .checked_add(i128::from(ext[0]))?,
        i128::from(off[1])
            .checked_mul(2)?
            .checked_add(i128::from(ext[1]))?,
    ])
}

impl Map {
    const IDENTITY: Self = Self {
        center_out2: [0, 0],
        child_center2: [0, 0],
        scale: [Scale::ONE, Scale::ONE],
        ortho: Ortho::IDENTITY,
    };

    fn root(t: &Xfrm, ortho: Ortho) -> Option<Self> {
        Some(Self {
            center_out2: [i128::from(t.ext[0]), i128::from(t.ext[1])],
            child_center2: doubled_center(t.child_off, t.child_ext)?,
            scale: [
                Scale::new(i128::from(t.ext[0]), i128::from(t.child_ext[0].max(1))),
                Scale::new(i128::from(t.ext[1]), i128::from(t.child_ext[1].max(1))),
            ],
            ortho,
        })
    }

    fn mapped_center2(self, off: [i64; 2], ext: [i64; 2]) -> Option<[i128; 2]> {
        let local = doubled_center(off, ext)?;
        let across = local[0].checked_sub(self.child_center2[0])?;
        let down = local[1].checked_sub(self.child_center2[1])?;
        let scaled = [self.scale[0].scale(across)?, self.scale[1].scale(down)?];
        let rotated = self.ortho.apply(scaled);
        Some([
            self.center_out2[0].checked_add(rotated[0])?,
            self.center_out2[1].checked_add(rotated[1])?,
        ])
    }

    /// The unrotated corner and size of a part with the transform `t`, centered at its mapped
    /// position relative to the outermost group's corner, or `None` when out of range.
    fn place(self, t: &Xfrm) -> Option<([Length; 2], [Length; 2])> {
        let center2 = self.mapped_center2(t.off, t.ext)?;
        let sw = self.scale[0].scale(i128::from(t.ext[0]))?;
        let sh = self.scale[1].scale(i128::from(t.ext[1]))?;
        let left = i64::try_from(center2[0].checked_sub(sw)? / 2).ok()?;
        let top = i64::try_from(center2[1].checked_sub(sh)? / 2).ok()?;
        let width = i64::try_from(sw).ok()?;
        let height = i64::try_from(sh).ok()?;
        Some((
            [Length::from_emus(left)?, Length::from_emus(top)?],
            [Length::from_emus(width)?, Length::from_emus(height)?],
        ))
    }

    /// The map of a nested group inside this one with transform `t` and orthogonal transform
    /// `inner_ortho`, or `None` when it does not fit.
    fn inner(self, t: &Xfrm, inner_ortho: Ortho) -> Option<Self> {
        Some(Self {
            center_out2: self.mapped_center2(t.off, t.ext)?,
            child_center2: doubled_center(t.child_off, t.child_ext)?,
            scale: [
                self.scale[0].compose(t.ext[0], t.child_ext[0])?,
                self.scale[1].compose(t.ext[1], t.child_ext[1])?,
            ],
            ortho: self.ortho.compose(inner_ortho),
        })
    }
}

/// The `a:xfrm` of a shape, picture or group, each as x and y.
#[derive(Clone, Copy, Debug)]
struct Xfrm {
    /// `a:off`, the corner of the box.
    off: [i64; 2],
    /// `a:ext`, the size of the box.
    ext: [i64; 2],
    /// `a:chOff`, where the children's coordinates start, which only groups have. It
    /// defaults to `off`.
    child_off: [i64; 2],
    /// `a:chExt`, the length of the children's coordinates, which defaults to `ext`.
    child_ext: [i64; 2],
}

/// Reads the `a:xfrm` of a shape, picture or group.
fn xfrm(reader: &mut PartReader, node: NodeId) -> Xfrm {
    let doc = reader.doc;
    let props = ["grpSpPr", "spPr"]
        .iter()
        .find_map(|name| shape_child(doc, node, name).or_else(|| doc.child(node, PIC, name)))
        .and_then(|props| doc.child(props, A, "xfrm"));
    let mut value = |child: &str, name: &str| {
        props
            .and_then(|x| doc.child(x, A, child))
            .and_then(|n| reader.emus(n, name))
    };
    let [x, y] = [value("off", "x"), value("off", "y")].map(|v| v.unwrap_or(0));
    let [cx, cy] = [value("ext", "cx"), value("ext", "cy")].map(|v| v.unwrap_or(0));
    Xfrm {
        off: [x, y],
        ext: [cx, cy],
        child_off: [
            value("chOff", "x").unwrap_or(x),
            value("chOff", "y").unwrap_or(y),
        ],
        child_ext: [
            value("chExt", "cx").unwrap_or(cx),
            value("chExt", "cy").unwrap_or(cy),
        ],
    }
}

/// Collects the shapes, text boxes and pictures of a drawing group and of the groups inside it, each
/// with its offset from the outermost group's top left corner.
fn group_parts(
    reader: &mut PartReader,
    group: NodeId,
    map: Map,
    inherited_fill: Option<GroupFill>,
    parts: &mut Vec<(Length, Length, Floating)>,
) {
    let doc = reader.doc;
    for child in doc.child_elements(group) {
        let t = xfrm(reader, child);
        // A part whose place, size or map does not fit is left out with a warning.
        if is_shape_element(doc, child, "grpSp") || is_shape_element(doc, child, "wgp") {
            let inner_ortho = read_group_ortho(reader, child);
            let inner_box = map
                .place(&t)
                .and_then(|([l, tp], [w, h])| Edges::placed(l, tp, w, h))
                .unwrap_or_default();
            let inner_fill = resolve_group_fill(doc, child, inner_box, inherited_fill);
            match map.inner(&t, inner_ortho) {
                Some(inner) => group_parts(reader, child, inner, Some(inner_fill), parts),
                None => reader.drawing_skipped(Drawing::Shape, Reason::OutOfRange),
            }
            continue;
        }
        let kind = if is_shape_element(doc, child, "wsp") {
            Drawing::Shape
        } else if doc.is(child, PIC, "pic") {
            Drawing::Picture
        } else {
            // Another drawing in the group is left out with a warning.
            skip_group_child(reader, child);
            continue;
        };
        let Some(([left, top], [width, height])) = map.place(&t) else {
            reader.drawing_skipped(kind, Reason::OutOfRange);
            continue;
        };
        let mut part = Floating {
            width,
            height,
            ..Floating::in_part(reader.part())
        };
        if kind == Drawing::Shape {
            let child_fill = inherited_fill.map(|gf| GroupFill {
                props: gf.props,
                frame: Edges {
                    left: gf.frame.left - left,
                    top: gf.frame.top - top,
                    right: gf.frame.right - left,
                    bottom: gf.frame.bottom - top,
                },
            });
            read_shape_with_ortho(reader, child, map.ortho, child_fill, &mut part);
            parts.push((left, top, part));
        } else {
            let frame = Edges::sized(part.width, part.height);
            if let Some(mut picture) = Picture::from_pic(reader, child, frame) {
                picture.compose_outer_turn(map.ortho.0);
                part.picture = Some(picture);
                parts.push((left, top, part));
            }
        }
    }
}

/// Reads the orthogonal group transform (`flipH`, `flipV`, and whole quarter-turn `rot`) of
/// `group`'s `wpg:grpSpPr/a:xfrm`. Warns on [`crate::Feature::GroupTransform`] when `rot` is not a
/// whole quarter turn (drawn upright while keeping any flip). A `rot` that does not read counts
/// as missing, with a warning.
fn read_group_ortho(reader: &mut PartReader, group: NodeId) -> Ortho {
    let doc = reader.doc;
    let Some(xfrm) =
        shape_child(doc, group, "grpSpPr").and_then(|props| doc.child(props, A, "xfrm"))
    else {
        return Ortho::IDENTITY;
    };
    let rotation = reader
        .or_missing_in(xfrm, (None, "rot"), f_office_drawingml::integer)
        .unwrap_or(0);
    let flip = ["flipH", "flipV"].map(|name| {
        doc.attribute(xfrm, None, name)
            .is_some_and(f_office_drawingml::boolean)
    });
    let quarters = quarter_turns(rotation).unwrap_or_else(|| {
        reader.feature_not_supported(crate::Feature::GroupTransform(GroupTransform::Turn));
        0
    });
    Ortho::from_xfrm(quarters, flip)
}

/// Keeps the warning that the child `child` of a drawing group, which [`group_parts`] does not
/// read, is left out when it is a drawing, of its kind ([`group_drawing_kind`]): a chart
/// because it is in a group ([`ChartReason::InGroup`]), any other drawing as one that F-Office
/// does not draw ([`Reason::Unsupported`]). The group's own properties give no warning.
fn skip_group_child(reader: &mut PartReader, child: NodeId) {
    if let Some(kind) = group_drawing_kind(reader.doc, child) {
        let reason = match kind {
            Drawing::Chart => Reason::Chart(ChartReason::InGroup),
            Drawing::Picture | Drawing::SmartArt | Drawing::Shape => Reason::Unsupported,
        };
        reader.drawing_skipped(kind, reason);
    }
}

/// The kind of drawing of the child `child` of a drawing group, or `None` when it is no
/// drawing, such as the group's properties: a shape (`wps:wsp`) or a group (`wpg:grpSp`) is a
/// shape, a picture (`pic:pic`) a picture, a graphic frame (`wpg:graphicFrame`) the kind of
/// its graphic ([`GRAPHICS`]) or else a shape, ink (`w14:contentPart`) a shape, and alternate
/// content the kind of the first drawing in the branch that the reader takes, else in a choice
/// that it passes over, so that a member with no branch, such as one whose only choice is a
/// chart of Office 2016 and later, still warns.
fn group_drawing_kind(doc: &Document, child: NodeId) -> Option<Drawing> {
    if is_shape_element(doc, child, "wsp")
        || is_shape_element(doc, child, "grpSp")
        || is_shape_element(doc, child, "wgp")
        || doc.is(child, W14, "contentPart")
    {
        return Some(Drawing::Shape);
    }
    if doc.is(child, PIC, "pic") {
        return Some(Drawing::Picture);
    }
    if is_shape_element(doc, child, "graphicFrame") {
        let data = doc
            .child(child, A, "graphic")
            .and_then(|graphic| doc.child(graphic, A, "graphicData"));
        return Some(
            data.and_then(|data| graphic_kind(doc, data))
                .unwrap_or(Drawing::Shape),
        );
    }
    if doc.is(child, MC, "AlternateContent") {
        let kind_in = |node: NodeId| {
            doc.child_elements(node)
                .find_map(|inner| group_drawing_kind(doc, inner))
        };
        return crate::body::alternate_branch(doc, child)
            .and_then(kind_in)
            .or_else(|| crate::body::passed_choices(doc, child).find_map(kind_in));
    }
    None
}

/// One axis of a drawing's place: the position element `name` (`wp:positionH` or
/// `wp:positionV`) of the anchor or of one of the `shown` branches of its alternate content,
/// whose `wp:align` the axis's table `align` reads.
fn position(
    reader: &mut PartReader,
    (anchor, shown): (NodeId, &[NodeId]),
    (name, align): (&str, &'static Values<Align>),
) -> Position {
    let doc = reader.doc;
    // The position may sit in alternate content, as a share of its area (Word 2010) with a
    // plain offset as the fallback; `read_anchor` gave the shown branches and warned of the
    // choices that they pass over.
    let node = doc
        .child(anchor, WP, name)
        .or_else(|| shown.iter().find_map(|branch| doc.child(*branch, WP, name)));
    let Some(node) = node else {
        return Position::default();
    };
    let from = reader
        .enumeration_in(node, (None, "relativeFrom"), POSITION_FROM)
        .unwrap_or_default();
    // Word takes the offset in whole twips, cut toward zero.
    let whole_twips = |offset: Length| offset.toward_zero_whole(Length::UNITS_PER_TWIP);
    let offset = doc
        .child(node, WP, "posOffset")
        .and_then(|n| reader.emu_length_text(n))
        .map_or(Length::ZERO, whole_twips);
    // Only a value of the axis aligns: Word for Windows does not open a document with another
    // value, so such a value gives the offset here, as it does in VML.
    let align = doc
        .child(node, WP, "align")
        .and_then(|n| reader.enumeration_text(n, align));
    let share = ["pctPosHOffset", "pctPosVOffset"]
        .iter()
        .find_map(|tag| doc.child(node, WP14, tag))
        .and_then(|n| percentage(&doc.text_content(n)));
    Position {
        from,
        offset,
        align,
        share,
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Write as _;

    use f_office_units::Length;
    use f_office_xml::{Document, Limits};

    use super::{Wrap, WrapSides, read_anchor};
    use crate::enumerations::assert_names;
    use crate::ns::{A, C, PIC, R, W, WNE, WP, WP14, WPG, WPS};
    use crate::props::Align;
    use crate::reader::PartReader;
    use crate::warnings::{Drawing, ReadAs, Reason};
    use f_office_units::Edges;

    /// A drawing group of 2 by 1 inches whose children count in units of 1000 per inch, with
    /// a text box at (500, 0) and an inner group at (1000, 500) that maps its own 0 to 100 onto
    /// 1000 by 500 units, holding a picture at (50, 0) of 50 by 100 of its units.
    const GROUP: &str = r#"<wp:anchor><wp:extent cx="1828800" cy="914400"/><a:graphic><a:graphicData><wpg:wgp>
        <wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/><a:chOff x="0" y="0"/><a:chExt cx="2000" cy="1000"/></a:xfrm></wpg:grpSpPr>
        <wps:wsp><wps:spPr><a:xfrm><a:off x="500" y="0"/><a:ext cx="500" cy="250"/></a:xfrm></wps:spPr><wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx></wps:wsp>
        <wpg:grpSp><wpg:grpSpPr><a:xfrm><a:off x="1000" y="500"/><a:ext cx="1000" cy="500"/><a:chOff x="0" y="0"/><a:chExt cx="100" cy="100"/></a:xfrm></wpg:grpSpPr>
          <pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="50" y="0"/><a:ext cx="50" cy="100"/></a:xfrm></pic:spPr></pic:pic>
        </wpg:grpSp>
        <wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="10" cy="10"/></a:xfrm></wps:spPr></wps:wsp>
      </wpg:wgp></a:graphicData></a:graphic></wp:anchor>"#;

    fn group() -> super::Floating {
        anchor(GROUP)
    }

    /// Reads a floating drawing from the XML of its `wp:anchor`.
    fn anchor(xml: &str) -> super::Floating {
        anchor_warned(xml).0
    }

    /// The XML of a `w:drawing` that holds the `wp:anchor` `xml`, with the namespaces of its
    /// parts.
    fn drawing_doc(xml: &str) -> Document {
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wpg="{WPG}" xmlns:wps="{WPS}" xmlns:pic="{PIC}" xmlns:r="{R}">{xml}</w:drawing>"#
        );
        Document::parse(xml.as_bytes(), &Limits::default()).unwrap()
    }

    /// [`anchor`], with the element, the attribute and the count of each value that counts as
    /// missing, and the element, the attribute, the name and the count of each name that is
    /// drawn as another.
    #[expect(clippy::type_complexity, reason = "the two lists of a test reading")]
    fn anchor_warned(
        xml: &str,
    ) -> (
        super::Floating,
        Vec<(String, Option<String>, u32)>,
        Vec<(String, Option<String>, &'static str, u32)>,
    ) {
        let doc = drawing_doc(xml);
        let mut reader = PartReader::new(&doc);
        let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
        let mut invalid: Vec<(String, Option<String>, u32)> = reader
            .invalid_values()
            .into_iter()
            .map(|(element, attribute, _, count)| (element, attribute, count))
            .collect();
        invalid.sort();
        (drawing, invalid, reader.unsupported_values())
    }

    #[test]
    fn warns_of_an_alignment_or_a_wrap_side_that_it_does_not_draw() {
        let (drawing, invalid, unsupported) = anchor_warned(
            r#"<wp:anchor><wp:positionH relativeFrom="page"><wp:align> outside </wp:align></wp:positionH><wp:positionV relativeFrom="page"><wp:align>middle</wp:align></wp:positionV><wp:extent cx="914400" cy="914400"/><wp:wrapSquare wrapText="both"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#,
        );
        // Horizontal `outside` is supported directly (`Align::Outside`); text outside the types
        // counts as missing.
        assert_eq!(
            (drawing.h.align, drawing.v.align),
            (Some(Align::Outside), None)
        );
        assert_eq!(drawing.wrap, Some(square(WrapSides::Both)));
        assert_eq!(unsupported, vec![]);
        assert_eq!(
            invalid,
            [
                ("align".to_owned(), None, 1),
                ("wrapSquare".to_owned(), Some("wrapText".to_owned()), 1),
            ]
        );
        let (drawing, invalid, unsupported) = anchor_warned(
            r#"<wp:anchor><wp:extent cx="914400" cy="914400"/><wp:wrapSquare wrapText="largest"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#,
        );
        assert_eq!(drawing.wrap, Some(square(WrapSides::Largest)));
        assert_eq!((invalid, unsupported), (vec![], vec![]));
    }

    #[test]
    fn warns_of_a_place_relative_to_the_character_and_of_area_names_outside_the_types() {
        use super::{PageArea, Relative};
        // A position relative to the character counts from the margins, with a warning that it
        // is drawn as another; a name outside the types counts as missing, with a warning, so
        // that the position counts from the margins and the relative size is left out.
        let (drawing, invalid, unsupported) = anchor_warned(&format!(
            r#"<wp:anchor xmlns:wp14="{WP14}"><wp:positionH relativeFrom="character"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="nowhere"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="914400" cy="914400"/><wp14:sizeRelH relativeFrom="nowhere"><wp14:pctWidth>40000</wp14:pctWidth></wp14:sizeRelH><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
        ));
        let margins = Relative::Area(PageArea::Margin);
        assert_eq!((drawing.h.from, drawing.v.from), (margins, margins));
        assert_eq!(drawing.relative_width, None);
        let from = Some("relativeFrom".to_owned());
        assert_eq!(
            unsupported,
            [("positionH".to_owned(), from.clone(), "character", 1)]
        );
        assert_eq!(
            invalid,
            [
                ("positionV".to_owned(), from.clone(), 1),
                ("sizeRelH".to_owned(), from, 1),
            ]
        );
    }

    #[test]
    fn reads_each_area_name_of_a_position_and_of_a_size_of_either_axis() {
        assert_names(
            super::POSITION_FROM,
            "character column insideMargin leftMargin margin outsideMargin page rightMargin \
             bottomMargin line paragraph topMargin",
        );
        assert_names(
            super::SIZE_FROM,
            "margin page leftMargin rightMargin insideMargin outsideMargin topMargin bottomMargin",
        );
    }

    #[test]
    fn leaves_out_a_graphic_of_another_kind_as_a_shape_with_a_warning() {
        // A graphic of an element that F-Office does not read, such as a locked canvas, is left
        // out with a warning, floating and inline; a picture that does not read, which the
        // picture reader warns of, and graphic data without an element give none here.
        const CANVAS: &str = r#"<lc:lockedCanvas xmlns:lc="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"/>"#;
        let drawing = |kind: &str, graphic: &str| {
            drawing_doc(&format!(
                r#"<wp:{kind}><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData>{graphic}</a:graphicData></a:graphic></wp:{kind}>"#
            ))
        };
        let floating = |graphic: &str| {
            let doc = drawing("anchor", graphic);
            let mut reader = PartReader::new(&doc);
            assert!(read_anchor(&mut reader, doc.root().unwrap()).is_none());
            reader.skipped_drawings()
        };
        let skipped = [(Drawing::Shape, Reason::Unsupported, 1)];
        assert_eq!(floating(CANVAS), skipped);
        assert_eq!(floating("<pic:pic/>"), []);
        assert_eq!(floating(""), []);
        let doc = drawing("inline", CANVAS);
        let mut reader = PartReader::new(&doc);
        let node = doc.child(doc.root().unwrap(), WP, "inline").unwrap();
        let shape = super::read_inline_shape(&mut reader, node, Length::ZERO, Length::ZERO);
        assert!(shape.is_none());
        assert_eq!(reader.skipped_drawings(), skipped);
    }

    /// A square wrap on `sides`, without distances.
    fn square(sides: WrapSides) -> Wrap {
        Wrap::Beside {
            distances: Edges::default(),
            sides: Some(sides),
            polygon: None,
        }
    }

    #[test]
    fn reads_a_floating_chart_with_its_chart_and_its_wrap() {
        let drawing = anchor(&format!(
            r#"<wp:anchor behindDoc="1"><wp:positionH relativeFrom="margin"><wp:posOffset>-635000</wp:posOffset></wp:positionH><wp:extent cx="914400" cy="914400"/><wp:wrapSquare wrapText="bothSides"/><a:graphic><a:graphicData><c:chart xmlns:c="{C}" r:id="rId2"/></a:graphicData></a:graphic></wp:anchor>"#
        ));
        // The chart waits for its part, and its frame keeps the text out on both sides.
        assert_eq!(drawing.chart.map(|chart| chart.id), Some("rId2".to_owned()));
        assert_eq!(drawing.wrap, Some(square(WrapSides::Both)));
        assert_eq!(Some(drawing.h.offset), Length::from_points(-50));
        assert!(drawing.behind);
    }

    #[test]
    fn keeps_the_wrap_of_a_shape_but_not_of_a_shape_without_height() {
        let shape = |cy: i64, wrap: &str| {
            anchor(&format!(
                r#"<wp:anchor distT="0" distB="0"><wp:extent cx="914400" cy="{cy}"/>{wrap}<a:graphic><a:graphicData><wps:wsp><wps:spPr><a:prstGeom prst="line"/></wps:spPr></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
            ))
        };
        // A shape without a text box or a picture keeps its top and bottom wrap.
        let boxed = shape(457_200, "<wp:wrapTopAndBottom/>");
        assert_eq!(
            boxed.wrap,
            Some(Wrap::TopAndBottom {
                above: Length::ZERO,
                below: Length::ZERO
            })
        );
        // A horizontal line without height keeps no text out.
        let line = shape(0, r#"<wp:wrapSquare wrapText="bothSides"/>"#);
        assert_eq!(line.wrap, None);
    }

    #[test]
    fn cuts_an_offset_toward_zero_to_whole_twips() {
        let placed = |x: i64, y: i64| {
            let drawing = anchor(&format!(
                r#"<wp:anchor><wp:positionH relativeFrom="column"><wp:posOffset>{x}</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>{y}</wp:posOffset></wp:positionV><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
            ));
            (drawing.h.offset, drawing.v.offset)
        };
        let twips = |n: i64| Length::from_twips(n).unwrap();
        // 5,935,318 EMU is 9,346.96 twips, and 1,015 EMU 1.6: both go down to whole twips.
        assert_eq!(placed(5_935_318, 1_015), (twips(9_346), twips(1)));
        // -108,144 EMU is -170.31 twips, which goes up to -170, toward zero.
        assert_eq!(placed(-108_144, -634), (twips(-170), Length::ZERO));
        assert_eq!(placed(635, -635), (twips(1), twips(-1)));
    }

    #[test]
    fn reads_a_length_with_a_unit_and_an_offset_with_spaces_as_missing() {
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wps="{WPS}"><wp:anchor distL="0.5in"><wp:positionH relativeFrom="column"><wp:posOffset> 914400 </wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>914400</wp:posOffset></wp:positionV><wp:extent cx="1in" cy="914400"/><wp:effectExtent l="0" t="0" r="0" b="12700.5"/><wp:wrapSquare wrapText="bothSides"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let mut reader = PartReader::new(&doc);
        let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
        let inch = Length::from_emus(914_400).unwrap();
        assert_eq!((drawing.width, drawing.height), (inch, inch));
        assert_eq!((drawing.h.offset, drawing.v.offset), (Length::ZERO, inch));
        let half = Length::from_emus(457_200).unwrap();
        assert_eq!(
            drawing.wrap,
            Some(Wrap::Beside {
                distances: Edges {
                    left: half,
                    ..Edges::default()
                },
                sides: Some(WrapSides::Both),
                polygon: None,
            })
        );
        let mut invalid = reader.invalid_values();
        invalid.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(
            invalid,
            [
                ("effectExtent".into(), Some("b".into()), ReadAs::Missing, 1),
                ("posOffset".into(), None, ReadAs::Missing, 1),
            ]
        );
    }

    #[test]
    fn aligns_only_with_a_value_of_the_axis() {
        let placed = |across: &str, down: &str| {
            let drawing = anchor(&format!(
                r#"<wp:anchor><wp:positionH relativeFrom="page"><wp:align>{across}</wp:align></wp:positionH><wp:positionV relativeFrom="page"><wp:align>{down}</wp:align></wp:positionV><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
            ));
            (drawing.h.align, drawing.v.align)
        };
        assert_eq!(
            placed("right", "bottom"),
            (Some(Align::End), Some(Align::End))
        );
        assert_eq!(
            placed(" center ", "inside"),
            (Some(Align::Center), Some(Align::Start))
        );
        // A value of the other axis, an unknown value or a capital gives no alignment.
        assert_eq!(placed("bottom", "right"), (None, None));
        assert_eq!(placed("top", "left"), (None, None));
        assert_eq!(placed("middle", "Bottom"), (None, None));
    }

    /// A length in thousandths of an inch.
    fn inches(milli: i64) -> Length {
        Length::from_emus(milli * 914_400 / 1000).unwrap()
    }

    #[test]
    fn reads_a_drawing_group_as_one_drawing_with_its_parts() {
        let group = group();
        assert_eq!((group.width, group.height), (inches(2000), inches(1000)));
        assert!(group.blocks.is_empty() && group.picture.is_none());
        // The shape without a text box is a part too, which shows only its look.
        assert_eq!(group.parts.len(), 3);
        let (_, _, shape) = &group.parts[2];
        assert!(shape.blocks.is_empty() && shape.picture.is_none() && shape.look.is_some());
    }

    #[test]
    fn places_the_text_boxes_and_pictures_of_a_drawing_group() {
        let group = group();
        let (left, top, text_box) = &group.parts[0];
        assert_eq!((*left, *top), (inches(500), Length::ZERO));
        assert_eq!(
            (text_box.width, text_box.height),
            (inches(500), inches(250))
        );
        assert_eq!(text_box.blocks.len(), 1);
        // The inner group puts its picture at 1000 + 50 * 10 and 500 + 0 units of the outer
        // group, and makes it 500 by 500 of them.
        let (left, top, picture) = &group.parts[1];
        assert_eq!((*left, *top), (inches(1500), inches(500)));
        assert_eq!((picture.width, picture.height), (inches(500), inches(500)));
        assert_eq!(picture.picture.as_ref().unwrap().embed, "rId1");
    }

    #[test]
    fn places_the_parts_of_an_inline_drawing_group() {
        let inline = GROUP.replace("wp:anchor", "wp:inline");
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wpg="{WPG}" xmlns:wps="{WPS}" xmlns:pic="{PIC}" xmlns:r="{R}">{inline}</w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let node = doc.child(doc.root().unwrap(), WP, "inline").unwrap();
        let group =
            super::read_inline_shape(&mut PartReader::new(&doc), node, inches(2000), inches(1000))
                .unwrap();
        assert_eq!(group.parts.len(), 3);
        let (left, top, text_box) = &group.parts[0];
        assert_eq!((*left, *top), (inches(500), Length::ZERO));
        assert_eq!(text_box.blocks.len(), 1);
        let (left, top, _) = &group.parts[1];
        assert_eq!((*left, *top), (inches(1500), inches(500)));
    }

    #[test]
    fn reads_anchored_and_inline_drawing_canvases_with_backdrop_shapes_group_and_picture() {
        use crate::ns::WPC;
        let canvas = r#"<wpc:wpc><wpc:bg><a:solidFill><a:srgbClr val="E8EEF5"/></a:solidFill></wpc:bg><wpc:whole><a:ln w="12700"><a:solidFill><a:srgbClr val="2F5597"/></a:solidFill></a:ln></wpc:whole><wps:wsp><wps:spPr><a:xfrm><a:off x="91440" y="45720"/><a:ext cx="914400" cy="457200"/></a:xfrm><a:prstGeom prst="rect"/></wps:spPr></wps:wsp><wpg:wgp><wpg:grpSpPr><a:xfrm><a:off x="182880" y="91440"/><a:ext cx="914400" cy="457200"/><a:chOff x="0" y="0"/><a:chExt cx="457200" cy="228600"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="228600" cy="114300"/></a:xfrm><a:prstGeom prst="rect"/></wps:spPr></wps:wsp></wpg:wgp><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="457200" y="228600"/><a:ext cx="457200" cy="228600"/></a:xfrm></pic:spPr></pic:pic></wpc:wpc>"#;
        let anchored = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wpc="{WPC}" xmlns:wpg="{WPG}" xmlns:wps="{WPS}" xmlns:pic="{PIC}" xmlns:r="{R}"><wp:anchor><wp:extent cx="1828800" cy="914400"/><a:graphic><a:graphicData>{canvas}</a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(anchored.as_bytes(), &Limits::default()).unwrap();
        let mut reader = PartReader::new(&doc);
        let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
        let offsets: Vec<(Length, Length)> =
            drawing.parts.iter().map(|(x, y, _)| (*x, *y)).collect();
        assert_eq!(
            (
                reader.skipped_drawings().len(),
                offsets,
                drawing.parts[0].2.width,
                drawing.parts[2].2.width,
                drawing.parts[3]
                    .2
                    .picture
                    .as_ref()
                    .map(|p| p.embed.as_str()),
            ),
            (
                0,
                vec![
                    (Length::ZERO, Length::ZERO),
                    (inches(100), inches(50)),
                    (inches(200), inches(100)),
                    (inches(500), inches(250)),
                ],
                inches(2000),
                inches(500),
                Some("rId1"),
            )
        );

        let inline = anchored.replace("wp:anchor", "wp:inline");
        let doc = Document::parse(inline.as_bytes(), &Limits::default()).unwrap();
        let node = doc.child(doc.root().unwrap(), WP, "inline").unwrap();
        let inline_drawing =
            super::read_inline_shape(&mut PartReader::new(&doc), node, inches(2000), inches(1000))
                .unwrap();
        assert_eq!(inline_drawing.parts.len(), 4);
    }

    /// The size of the range of a coordinate, `ST_Coordinate`, in EMU.
    const MOST: i64 = f_office_drawingml::COORDINATE_LIMIT;

    /// A drawing group of 2 by 1 inches that holds `parts`, whose children count in units of
    /// 1000 per inch, with the kinds, reasons and counts of the drawings left out.
    fn group_of(parts: &str) -> (super::Floating, Vec<(Drawing, Reason, u32)>) {
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wpg="{WPG}" xmlns:wps="{WPS}" xmlns:pic="{PIC}" xmlns:r="{R}"><wp:anchor><wp:extent cx="1828800" cy="914400"/><a:graphic><a:graphicData><wpg:wgp><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/><a:chOff x="0" y="0"/><a:chExt cx="2000" cy="1000"/></a:xfrm></wpg:grpSpPr>{parts}</wpg:wgp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let mut reader = PartReader::new(&doc);
        let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
        (drawing, reader.skipped_drawings())
    }

    /// A group part at `off` with the size `ext` whose children range over `child`, holding
    /// `inner`.
    fn group_part(off: (i64, i64), ext: (i64, i64), child: (i64, i64), inner: &str) -> String {
        format!(
            r#"<wpg:grpSp><wpg:grpSpPr><a:xfrm><a:off x="{}" y="{}"/><a:ext cx="{}" cy="{}"/><a:chOff x="0" y="0"/><a:chExt cx="{}" cy="{}"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:grpSp>"#,
            off.0, off.1, ext.0, ext.1, child.0, child.1
        )
    }

    /// A picture part at `off` with the size `ext`.
    fn picture_part(off: (i64, i64), ext: (i64, i64)) -> String {
        format!(
            r#"<pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill><pic:spPr><a:xfrm><a:off x="{}" y="{}"/><a:ext cx="{}" cy="{}"/></a:xfrm></pic:spPr></pic:pic>"#,
            off.0, off.1, ext.0, ext.1
        )
    }

    /// A shape part at `off` with the size `ext`.
    fn shape_part(off: (i64, i64), ext: (i64, i64)) -> String {
        format!(
            r#"<wps:wsp><wps:spPr><a:xfrm><a:off x="{}" y="{}"/><a:ext cx="{}" cy="{}"/></a:xfrm></wps:spPr></wps:wsp>"#,
            off.0, off.1, ext.0, ext.1
        )
    }

    #[test]
    fn places_the_parts_of_groups_nested_with_large_child_ranges_exactly() {
        // Three groups inside each other, the outer one over 1000 by 1000 units at (1000, 0),
        // each with a child range of the largest coordinate: the terms of their maps would
        // pass `i128` without the lowest terms.
        let picture = picture_part((0, 0), (MOST / 2, MOST));
        let range = (MOST, MOST);
        let inner = group_part((0, 0), range, range, &picture);
        let middle = group_part((0, 0), range, range, &inner);
        let (group, skipped) = group_of(&group_part((1000, 0), (1000, 1000), range, &middle));
        assert_eq!(skipped, []);
        let (left, top, part) = &group.parts[0];
        assert_eq!((*left, *top), (inches(1000), Length::ZERO));
        assert_eq!((part.width, part.height), (inches(500), inches(1000)));
    }

    #[test]
    fn leaves_out_a_group_part_whose_place_or_map_lies_out_of_range_with_a_warning() {
        // A picture at the largest coordinate of the group lies 2.5e16 EMU out, beyond the
        // range of a length; a shape as wide as that is too; three groups that each map one
        // unit to the largest coordinate give a map beyond `i128`. The small shape stays.
        let one = (1, 1);
        let range = (MOST, MOST);
        let shapes = shape_part((0, 0), (10, 10));
        let deep = group_part(
            (0, 0),
            range,
            one,
            &group_part((0, 0), range, one, &group_part((0, 0), range, one, &shapes)),
        );
        let parts = [
            picture_part((MOST, 0), (10, 10)),
            shape_part((0, 0), (MOST, 10)),
            deep,
            shape_part((0, 0), (10, 10)),
        ];
        let (group, mut skipped) = group_of(&parts.concat());
        skipped.sort_by_key(|(drawing, _, _)| *drawing == Drawing::Shape);
        let far = Reason::OutOfRange;
        assert_eq!(
            skipped,
            [(Drawing::Picture, far, 1), (Drawing::Shape, far, 2)]
        );
        assert_eq!(group.parts.len(), 1);
        assert_eq!(group.parts[0].2.width, inches(10));
    }

    #[test]
    fn reads_an_offset_within_the_range_of_a_coordinate_only() {
        let placed = |x: i64| {
            let (drawing, invalid, _) = anchor_warned(&format!(
                r#"<wp:anchor><wp:positionH relativeFrom="page"><wp:posOffset>{x}</wp:posOffset></wp:positionH><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
            ));
            (drawing.h.offset, invalid)
        };
        // The largest coordinate is whole twips.
        assert_eq!(placed(MOST), (Length::from_emus(MOST).unwrap(), vec![]));
        assert_eq!(placed(-MOST), (Length::from_emus(-MOST).unwrap(), vec![]));
        let missing = vec![("posOffset".to_owned(), None, 1)];
        assert_eq!(placed(MOST + 1), (Length::ZERO, missing.clone()));
        assert_eq!(placed(-MOST - 1), (Length::ZERO, missing));
    }

    #[test]
    fn reads_a_wrap_polygon_whose_bounds_lie_out_of_range_as_none_with_a_warning() {
        // A drawing as wide as the largest coordinate with a polygon that reaches as far: the
        // product of the two would pass `i64`, and the bound lies beyond the range of a length.
        let doc = drawing_doc(&format!(
            r#"<wp:anchor><wp:extent cx="{MOST}" cy="914400"/><wp:wrapTight><wp:wrapPolygon><wp:start x="0" y="0"/><wp:lineTo x="{MOST}" y="0"/><wp:lineTo x="{MOST}" y="21600"/><wp:lineTo x="0" y="21600"/></wp:wrapPolygon></wp:wrapTight><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:anchor>"#
        ));
        let mut reader = PartReader::new(&doc);
        let drawing = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
        let Some(Wrap::Beside { polygon, .. }) = drawing.wrap else {
            panic!("{:?}", drawing.wrap);
        };
        assert_eq!(polygon, Some(Edges::default()));
        // The polygon's points read; only its bounds lie out of range, which its own warning
        // says, with the part.
        assert_eq!(reader.invalid_values(), []);
        let mut warnings = crate::Warnings::new();
        reader.finish(&mut warnings);
        let skipped = crate::Warning::WrapPolygonSkipped {
            part: f_office_warnings::Name::new(crate::testing::DOCUMENT),
            reason: crate::Reason::OutOfRange,
        };
        assert_eq!(warnings.into_iter().collect::<Vec<_>>(), [(skipped, 1)]);
    }

    /// A picture of 2 by 1 inches with a through wrap of 0.1 inch to the sides and its polygon
    /// over the middle half of its height.
    fn through(edited: u8) -> super::Floating {
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:pic="{PIC}" xmlns:r="{R}"><wp:anchor distT="91440" distB="91440" distL="91440" distR="91440"><wp:extent cx="1828800" cy="914400"/><wp:wrapThrough><wp:wrapPolygon edited="{edited}"><wp:start x="0" y="5400"/><wp:lineTo x="21600" y="5400"/><wp:lineTo x="21600" y="16200"/><wp:lineTo x="0" y="16200"/></wp:wrapPolygon></wp:wrapThrough><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap()
    }

    #[test]
    fn keeps_the_outline_of_a_wrap_polygon_that_is_not_its_bounds() {
        // A rectangle keeps no outline.
        assert_eq!(through(1).outline, []);
        // A polygon free at the left of its bottom half keeps its points in order.
        let points = [
            (0, 0),
            (0, 10800),
            (10800, 10800),
            (10800, 21600),
            (21600, 21600),
            (21600, 0),
            (0, 0),
        ];
        let mut polygon = String::new();
        for (k, (x, y)) in points.iter().enumerate() {
            let name = if k == 0 { "start" } else { "lineTo" };
            write!(polygon, r#"<wp:{name} x="{x}" y="{y}"/>"#).unwrap();
        }
        let doc = drawing_doc(&format!(
            r#"<wp:anchor><wp:extent cx="914400" cy="914400"/><wp:wrapTight wrapText="bothSides"><wp:wrapPolygon edited="1">{polygon}</wp:wrapPolygon></wp:wrapTight><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:anchor>"#
        ));
        let drawing = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
        assert_eq!(drawing.outline, points);
    }

    #[test]
    fn reads_the_bounds_of_a_wrap_polygon() {
        // The polygon lies 0.25 inch inside the top and the bottom edges, edited or not, and
        // the text keeps 0.1 inch from it.
        for edited in [0, 1] {
            let through = through(edited);
            // The polygon is a rectangle, its own bounds, so the text flows on both sides.
            assert_eq!(
                through.wrap,
                Some(Wrap::Beside {
                    distances: Edges::from([inches(100); 4]),
                    sides: Some(WrapSides::Both),
                    polygon: Some(Edges::from([
                        inches(0),
                        inches(250),
                        inches(0),
                        inches(250)
                    ])),
                })
            );
        }
    }

    /// A text box with a width of 40% of the margins and a height of 20% of the page, and the
    /// body properties `body`.
    fn relative_box(body: &str) -> super::Floating {
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:wp14="{WP14}" xmlns:a="{A}" xmlns:wps="{WPS}"><wp:anchor><wp:extent cx="914400" cy="914400"/><wp14:sizeRelH relativeFrom="margin"><wp14:pctWidth>40000</wp14:pctWidth></wp14:sizeRelH><wp14:sizeRelV relativeFrom="page"><wp14:pctHeight>20000</wp14:pctHeight></wp14:sizeRelV><a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx>{body}</wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap()
    }

    #[test]
    fn reads_relative_sizes_and_keeps_the_height_of_a_box_that_fits_its_text() {
        use super::PageArea;
        let fixed = relative_box("<wps:bodyPr/>");
        assert_eq!(fixed.relative_width, Some((PageArea::Margin, 40_000)));
        assert_eq!(fixed.relative_height, Some((PageArea::Page, 20_000)));
        assert_eq!(fixed.inset_edge, super::InsetEdge::Inside);
        let fitting = relative_box("<wps:bodyPr><a:spAutoFit/></wps:bodyPr>");
        assert_eq!(fitting.relative_width, Some((PageArea::Margin, 40_000)));
        assert_eq!(fitting.relative_height, None);
        // The box that fits its text takes its height from the text when it is drawn.
        assert!(fitting.fits_text);
        assert!(!fixed.fits_text);
    }

    #[test]
    fn reads_the_area_names_of_a_position_and_of_a_relative_size() {
        use super::{PageArea, Relative};
        // A position and a size share the names of the page, the margins and the margin
        // areas; only a position counts from the anchor paragraph or the text column, and a
        // position with an unknown name counts from the margins.
        let read = |from: &str| {
            let xml = format!(
                r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:wp14="{WP14}" xmlns:a="{A}" xmlns:wps="{WPS}"><wp:anchor><wp:positionH relativeFrom="{from}"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:extent cx="914400" cy="914400"/><wp14:sizeRelH relativeFrom="{from}"><wp14:pctWidth>40000</wp14:pctWidth></wp14:sizeRelH><a:graphic><a:graphicData><wps:wsp><wps:spPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
            );
            let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
            let floating = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
            (
                floating.h.from,
                floating.relative_width.map(|(area, _)| area),
            )
        };
        let cases = [
            ("page", Relative::Area(PageArea::Page), Some(PageArea::Page)),
            (
                "margin",
                Relative::Area(PageArea::Margin),
                Some(PageArea::Margin),
            ),
            (
                "leftMargin",
                Relative::Area(PageArea::StartMargin),
                Some(PageArea::StartMargin),
            ),
            (
                "topMargin",
                Relative::Area(PageArea::StartMargin),
                Some(PageArea::StartMargin),
            ),
            (
                "insideMargin",
                Relative::Area(PageArea::StartMargin),
                Some(PageArea::StartMargin),
            ),
            (
                "rightMargin",
                Relative::Area(PageArea::EndMargin),
                Some(PageArea::EndMargin),
            ),
            (
                "bottomMargin",
                Relative::Area(PageArea::EndMargin),
                Some(PageArea::EndMargin),
            ),
            (
                "outsideMargin",
                Relative::Area(PageArea::EndMargin),
                Some(PageArea::EndMargin),
            ),
            ("paragraph", Relative::Paragraph, None),
            ("line", Relative::Line, None),
            ("column", Relative::Column, None),
            ("character", Relative::Area(PageArea::Margin), None),
            ("nowhere", Relative::Area(PageArea::Margin), None),
        ];
        for (from, position, size) in cases {
            assert_eq!(read(from), (position, size), "{from}");
        }
    }

    #[test]
    fn reads_the_content_of_a_text_box_that_word_writes_in_a_strict_document() {
        // Word writes the content of a Strict document's text box as `wne:txbxContent`.
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wne="{WNE}"><wp:anchor><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wp:wsp><wp:spPr/><wp:txbx><wne:txbxContent><w:p/><w:p/></wne:txbxContent></wp:txbx><wp:bodyPr/></wp:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let floating = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
        assert_eq!(floating.blocks.len(), 2);
    }

    #[test]
    fn reads_the_shapes_and_percentages_of_a_strict_document() {
        use super::PageArea;
        // A Strict document has the shape's elements in the namespace of `wp:anchor` and
        // writes a percentage with its sign.
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:wp14="{WP14}" xmlns:a="{A}"><wp:anchor><wp:positionH relativeFrom="page"><wp14:pctPosHOffset>45.5%</wp14:pctPosHOffset></wp:positionH><wp:extent cx="914400" cy="914400"/><wp14:sizeRelH relativeFrom="page"><wp14:pctWidth>37%</wp14:pctWidth></wp14:sizeRelH><a:graphic><a:graphicData><wp:wsp><wp:spPr/><wp:txbx><w:txbxContent><w:p/></w:txbxContent></wp:txbx><wp:bodyPr/></wp:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let floating = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
        assert!(floating.look.is_some());
        assert_eq!(floating.blocks.len(), 1);
        assert_eq!(floating.relative_width, Some((PageArea::Page, 37_000)));
        assert_eq!(floating.h.share, Some(45_500));
        // A group in that namespace gives its shapes as parts.
        let group = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}"><wp:anchor><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wp:wgp><wp:grpSpPr/><wp:wsp><wp:spPr/></wp:wsp></wp:wgp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(group.as_bytes(), &Limits::default()).unwrap();
        assert_eq!(
            read_anchor(&mut PartReader::new(&doc), doc.root().unwrap())
                .unwrap()
                .parts
                .len(),
            1
        );
    }

    #[test]
    fn computes_page_numbers_in_text_boxes() {
        use crate::body::{Block, Content};
        let field = r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>6</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:wps="{WPS}"><wp:anchor><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent>{field}</w:txbxContent></wps:txbx></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let floating = read_anchor(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
        let Some(Block::Paragraph(paragraph)) = floating.blocks.first() else {
            panic!("no paragraph");
        };
        let content: Vec<&Content> = paragraph.runs.iter().flat_map(|r| &r.content).collect();
        // The stored "6" is gone, and layout computes the number. The field's result and its
        // end leave field marks.
        let mark = &Content::FieldMark;
        assert_eq!(content, vec![mark, &Content::PageNumber, mark]);
    }

    #[test]
    fn a_position_in_alternate_content_warns_once_of_each_passed_choice() {
        use crate::ns::MC;
        // The place across sits in alternate content whose choice requires a namespace that
        // F-Office does not take, and the place down in a second alternate content after it.
        // Each axis looks in both, and the passed choice warns once.
        let xml = format!(
            r#"<w:drawing xmlns:w="{W}" xmlns:wp="{WP}" xmlns:wp14="{WP14}" xmlns:a="{A}" xmlns:wps="{WPS}" xmlns:mc="{MC}" xmlns:x="urn:other"><wp:anchor><mc:AlternateContent><mc:Choice Requires="x"><wp:positionH relativeFrom="page"><wp:posOffset>914400</wp:posOffset></wp:positionH></mc:Choice><mc:Fallback><wp:positionH relativeFrom="page"><wp:posOffset>457200</wp:posOffset></wp:positionH></mc:Fallback></mc:AlternateContent><mc:AlternateContent><mc:Choice Requires="wp14"><wp:positionV relativeFrom="page"><wp14:pctPosVOffset>10000</wp14:pctPosVOffset></wp:positionV></mc:Choice><mc:Fallback><wp:positionV relativeFrom="page"><wp:posOffset>0</wp:posOffset></wp:positionV></mc:Fallback></mc:AlternateContent><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let mut reader = PartReader::new(&doc);
        let floating = read_anchor(&mut reader, doc.root().unwrap()).unwrap();
        // The fallback places the drawing across, and the taken choice down.
        assert_eq!(
            (floating.h.offset, floating.h.share, floating.v.share),
            (inches(500), None, Some(10_000))
        );
        let mut warnings = crate::Warnings::default();
        reader.finish(&mut warnings);
        let kinds: Vec<_> = warnings
            .iter()
            .map(|(warning, count)| (warning.kind().to_string(), count))
            .collect();
        assert_eq!(kinds, [("alternate-choice-not-supported".to_string(), 1)]);
    }

    #[test]
    fn gives_a_group_member_in_alternate_content_with_no_branch_the_kind_of_a_passed_choice() {
        use crate::ns::{CX, MC};
        let member = |fallback: &str| {
            format!(
                r#"<mc:AlternateContent xmlns:mc="{MC}" xmlns:wpg="{WPG}" xmlns:a="{A}" xmlns:cx="{CX}" xmlns:pic="{PIC}"><mc:Choice Requires="cx"><wpg:graphicFrame><a:graphic><a:graphicData><cx:chart/></a:graphicData></a:graphic></wpg:graphicFrame></mc:Choice>{fallback}</mc:AlternateContent>"#
            )
        };
        // (fallback, kind): a chart of Office 2016 and later is no taken choice, so with no
        // fallback, or a fallback with no drawing, the passed choice gives the kind; a
        // fallback's drawing gives its own.
        let cases = [
            ("", Some(Drawing::Chart)),
            ("<mc:Fallback/>", Some(Drawing::Chart)),
            (
                "<mc:Fallback><pic:pic/></mc:Fallback>",
                Some(Drawing::Picture),
            ),
        ];
        for (fallback, kind) in cases {
            let xml = member(fallback);
            let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
            assert_eq!(
                super::group_drawing_kind(&doc, doc.root().unwrap()),
                kind,
                "{xml}"
            );
        }
    }

    #[test]
    fn a_text_box_takes_the_font_color_of_its_shape_style() {
        let shape = |style: &str| {
            anchor(&format!(
                r#"<wp:anchor><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><wps:wsp><wps:spPr/><wps:style>{style}</wps:style><wps:txbx><w:txbxContent><w:p/></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor>"#
            ))
            .text_color
        };
        assert_eq!(
            shape(r#"<a:fontRef idx="minor"><a:srgbClr val="ED7D31"/></a:fontRef>"#),
            Some([0xED, 0x7D, 0x31])
        );
        // A scheme color that the reading has no theme for gives none.
        assert_eq!(
            shape(r#"<a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef>"#),
            None
        );
        assert_eq!(shape(r#"<a:fontRef idx="minor"/>"#), None);
    }

    #[test]
    fn composes_group_flips_and_quarter_turns_on_children_and_nested_groups() {
        // flipH composed with (rot=90 * flipV) cancels the two reflections to pure rot=90.
        let flip_h = super::Ortho::from_xfrm(0, [true, false]);
        let inner = super::Ortho::from_xfrm(1, [false, true]);
        assert_eq!(
            flip_h.compose(inner),
            super::Ortho::from_xfrm(1, [false, false])
        );
        // A 120x60 pt group rotated 90 deg CW rotates a child rect at (6, 6, 26, 20) to center
        // (74, -11) with unrotated box (61, -21, 26, 20) and 90 deg CW look rotation.
        let pt = 12_700_i64;
        let group = anchor(&format!(
            concat!(
                r#"<wp:anchor><wp:extent cx="{w}" cy="{h}"/><a:graphic><a:graphicData>"#,
                r#"<wpg:wgp><wpg:grpSpPr><a:xfrm rot="5400000">"#,
                r#"<a:off x="0" y="0"/><a:ext cx="{w}" cy="{h}"/>"#,
                r#"<a:chOff x="0" y="0"/><a:chExt cx="{w}" cy="{h}"/>"#,
                r#"</a:xfrm></wpg:grpSpPr>"#,
                r#"<wps:wsp><wps:spPr><a:xfrm><a:off x="{cx}" y="{cy}"/><a:ext cx="{cw}" cy="{ch}"/></a:xfrm>"#,
                r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></wps:spPr></wps:wsp>"#,
                r#"</wpg:wgp></a:graphicData></a:graphic></wp:anchor>"#,
            ),
            w = 120 * pt,
            h = 60 * pt,
            cx = 6 * pt,
            cy = 6 * pt,
            cw = 26 * pt,
            ch = 20 * pt,
        ));
        assert_eq!(group.parts.len(), 1);
        let (left, top, ref part) = group.parts[0];
        assert_eq!(
            (left, top, part.width, part.height),
            (
                Length::from_points(61).unwrap(),
                Length::from_points(-21).unwrap(),
                Length::from_points(26).unwrap(),
                Length::from_points(20).unwrap(),
            )
        );
        assert_eq!(
            part.look.as_ref().and_then(super::ShapeLook::quarter_turns),
            Some(1)
        );
    }

    #[test]
    fn inherits_group_fill_across_nested_groups_and_preserves_own_fills() {
        let pt = 12_700_i64;
        let group = anchor(&format!(
            concat!(
                r#"<wp:anchor><wp:extent cx="{w}" cy="{h}"/><a:graphic><a:graphicData>"#,
                r#"<wpg:wgp><wpg:grpSpPr><a:xfrm>"#,
                r#"<a:off x="0" y="0"/><a:ext cx="{w}" cy="{h}"/>"#,
                r#"<a:chOff x="0" y="0"/><a:chExt cx="{w}" cy="{h}"/>"#,
                r#"</a:xfrm><a:solidFill><a:srgbClr val="22AA55"/></a:solidFill></wpg:grpSpPr>"#,
                r#"<wpg:grpSp><wpg:grpSpPr><a:xfrm>"#,
                r#"<a:off x="0" y="0"/><a:ext cx="{w}" cy="{h}"/>"#,
                r#"<a:chOff x="0" y="0"/><a:chExt cx="{w}" cy="{h}"/>"#,
                r#"</a:xfrm></wpg:grpSpPr>"#,
                r#"<wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="{cw}" cy="{ch}"/></a:xfrm>"#,
                r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:grpFill/></wps:spPr></wps:wsp>"#,
                r#"<wps:wsp><wps:spPr><a:xfrm><a:off x="{cw}" y="0"/><a:ext cx="{cw}" cy="{ch}"/></a:xfrm>"#,
                r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val="CC3333"/></a:solidFill></wps:spPr></wps:wsp>"#,
                r#"</wpg:grpSp></wpg:wgp></a:graphicData></a:graphic></wp:anchor>"#,
            ),
            w = 200 * pt,
            h = 50 * pt,
            cw = 80 * pt,
            ch = 50 * pt,
        ));
        assert_eq!(group.parts.len(), 2);
        let theme = f_office_drawingml::theme::ShapeTheme::default();
        assert_eq!(
            group.parts[0].2.look.as_ref().and_then(|l| l.fill(&theme)),
            Some((
                f_office_paint::Rgb {
                    r: 0x22,
                    g: 0xAA,
                    b: 0x55
                },
                f_office_paint::Opacity::FULL
            ))
        );
        assert_eq!(
            group.parts[1].2.look.as_ref().and_then(|l| l.fill(&theme)),
            Some((
                f_office_paint::Rgb {
                    r: 0xCC,
                    g: 0x33,
                    b: 0x33
                },
                f_office_paint::Opacity::FULL
            ))
        );
    }
}