f-office-docx 0.1.0

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
//! Floating drawings, laid out at their anchored place without moving the text flow.

use std::collections::HashSet;

use f_office_drawingml::color::on_white;
use f_office_drawingml::custom::OutOfRange;
use f_office_drawingml::shape::{CompoundLine, ShapeLook};
use f_office_drawingml::{Feature as DrawingMlFeature, Warning as DrawingMlWarning};
use f_office_paint::{Group, GroupClip, GroupPlaces, Item, Turn};
use f_office_units::scale::DRAWING_WHOLE;
use f_office_units::{Edges, Length};
use f_office_warnings::Name;

use crate::body::{Block, Content, Paragraph, ParagraphId, Section};
use crate::floating::{
    Floating, InsetEdge, PageArea, Position, Relative, Room, TextAnchor, TextPath, TextTurn, Wrap,
    WrapSides,
};
use crate::lines::Line;
use crate::params::NARROWEST_WRAP;
use crate::props::Align;

use super::output::BodyArea;
use super::table::{DOWN, UP, turn_item};
use super::{Layout, PlacedLine, TurnedGlyphs, decisions, text_path};

impl Layout<'_> {
    /// Lays out the floating drawings that a paragraph anchors, with the paragraph's top at
    /// `top`, but those that wait for the line of their anchor mark on one of its `lines` after
    /// the first: each drawing placed down from its line on a target that counts from the line's
    /// top, and each of `later`, drawings placed down from the paragraph whose anchor an earlier
    /// layout of the paragraph found on a later page than its first line. The line that holds
    /// the mark places each of them ([`Self::floating_on_line`]).
    pub(super) fn floating(
        &mut self,
        paragraph: &Paragraph,
        (top, lines): (Length, &[Line]),
        later: &[usize],
    ) -> Waiting {
        let drawings: Vec<usize> = lines
            .iter()
            .skip(1)
            .flat_map(anchor_marks)
            .filter(|&index| {
                later.contains(&index)
                    || floatings(paragraph)
                        .nth(index)
                        .is_some_and(|drawing| self.waits_for_line(drawing))
            })
            .collect();
        for (index, drawing) in floatings(paragraph).enumerate() {
            if !drawings.contains(&index) {
                self.place_floating(drawing, top);
            }
        }
        Waiting {
            top,
            drawings,
            later: later.to_vec(),
            part: (self.output.pages.len(), top),
        }
    }

    /// Lays out the drawings of `waiting` whose anchor mark the line of `lines` with the index
    /// `index` holds, and takes them out of `waiting`. A drawing placed down from its line
    /// counts from the line's top at the cursor, or from the paragraph's top on the first line.
    /// A drawing placed down from its paragraph counts from the top of the paragraph's part on
    /// the page of its line: the paragraph's top on the paragraph's first page, else the top of
    /// the paragraph's first line on that page. A line that is broken again keeps its marks, so
    /// the loop of the paragraph's lines meets each mark.
    pub(super) fn floating_on_line(
        &mut self,
        paragraph: &Paragraph,
        (lines, index): (&[Line], usize),
        waiting: &mut Waiting,
    ) {
        let Some(line) = lines.get(index).filter(|_| !waiting.drawings.is_empty()) else {
            return;
        };
        let page = self.output.pages.len();
        if waiting.part.0 != page {
            waiting.part = (page, self.y);
        }
        let top = if index == 0 { waiting.top } else { self.y };
        for mark in anchor_marks(line) {
            let Some(at) = waiting.drawings.iter().position(|&wait| wait == mark) else {
                continue;
            };
            waiting.drawings.swap_remove(at);
            let from = if waiting.later.contains(&mark) {
                waiting.part.1
            } else {
                top
            };
            if let Some(drawing) = floatings(paragraph).nth(mark) {
                self.place_floating(drawing, from);
            }
        }
    }

    /// Whether a drawing waits for the line that holds its anchor: it is placed down from its
    /// line on a target that counts from the line's top.
    pub(super) fn waits_for_line(&self, drawing: &Floating) -> bool {
        decisions::line_top_drawing(&self.context.quirks, || drawing.v.from == Relative::Line)
            .unwrap_or(false)
    }

    /// Whether a drawing leaves a mark where it is anchored: it waits for the line that holds
    /// its anchor, or it is placed down from its paragraph, whose layout finds the page of its
    /// anchor by the mark.
    pub(super) fn marks_anchor(&self, drawing: &Floating) -> bool {
        self.waits_for_line(drawing) || drawing.v.from == Relative::Paragraph
    }

    /// Whether the anchor of a drawing placed down from a paragraph of the body can stand on a
    /// later page than the paragraph's first line: one of its `lines` after the first holds
    /// the anchor mark of such a drawing.
    pub(super) fn may_anchor_later(&self, paragraph: &Paragraph, lines: &[Line]) -> bool {
        self.story.is_none()
            && self.column.cell.is_none()
            && lines
                .iter()
                .skip(1)
                .flat_map(anchor_marks)
                .any(|index| from_paragraph(paragraph, index))
    }

    /// Whether an earlier pass found that the wrap of one of the paragraph's drawings moved the
    /// paragraph to a page after the one being filled. Then the paragraph starts the next
    /// page: it does not go back to the page that has room for it again without the wrap.
    pub(super) fn held_for_wrap(&self, paragraph: &Paragraph) -> bool {
        let earlier = &self.context.earlier.wraps.held;
        let (mut next_band, mut next_square) = (
            self.output.found.bands.len(),
            self.output.found.squares.len(),
        );
        let mut held = false;
        for drawing in floatings(paragraph).filter(|drawing| early_wrap(drawing)) {
            let (at, pages) = match drawing.wrap {
                Some(Wrap::TopAndBottom { .. }) => (&mut next_band, &earlier.bands),
                Some(Wrap::Beside { .. }) => (&mut next_square, &earlier.squares),
                None => continue,
            };
            held |= pages
                .get(*at)
                .is_some_and(|page| *page > self.output.pages.len());
            *at += 1;
        }
        held
    }

    /// The place down of a drawing whose position down is `position`, and the cell's text top
    /// that it counts from, or none. In a table cell, a drawing placed from the margins by an
    /// offset counts from the cell's text top, and one aligned down from the margins lies at the
    /// cell's text top where the target puts it there, whatever its alignment, as one aligned
    /// to the top of the cell's text.
    fn cell_down(&self, position: Position) -> (Position, Option<Length>) {
        let at_cell_top = self.on_cells_first_page()
            && aligned_from_margin(position)
            && decisions::aligns_at_cell_top(&self.context.quirks);
        let cell_top = self
            .cell_top
            .filter(|_| from_margin_by_offset(position) || at_cell_top);
        let position = if at_cell_top {
            Position {
                align: Some(Align::Start),
                ..position
            }
        } else {
            position
        };
        (position, cell_top)
    }

    /// Where a drawing `width` wide that its place puts at `(x, y)` lies: in a table cell,
    /// inside the cell where the target keeps a drawing that wraps text there.
    fn in_cell(
        &self,
        drawing: &Floating,
        (x, y): (Length, Length),
        width: Length,
    ) -> (Length, Length) {
        let (quirks, wraps) = (&self.context.quirks, drawing.wrap.is_some());
        let x = self.cell_sides.map_or(x, |sides| {
            decisions::cell_drawing_left(quirks, (x, width), (sides, wraps))
        });
        let top = self.cell_top.filter(|_| self.on_cells_first_page());
        let y = top.map_or(y, |top| {
            decisions::cell_drawing_top(quirks, y, (top, wraps))
        });
        (x, y)
    }

    /// Whether the layout is in a table cell, in its part on the row's first page: where the
    /// row splits, the cell's text top bounds no drawing on a later page.
    fn on_cells_first_page(&self) -> bool {
        self.cell_top.is_some() && self.filled_part().is_none_or(|part| part == 0)
    }

    fn place_floating(&mut self, drawing: &Floating, paragraph: Length) {
        let s = self.section;
        // A drawing in a story, such as a header, counts from the page that the story is on;
        // there a drawing without wrapping also ends the margins above the page's footnotes,
        // and one that wraps the text does not.
        let (p, notes) = match self.page {
            Some(page) if drawing.wrap.is_none() => (page, self.story_notes),
            Some(page) => (page, Length::ZERO),
            None => self.body_margins(drawing),
        };
        let horizontal = areas(s.width, s.left, s.right);
        let vertical = areas(p.height, p.top, p.bottom + notes);
        let (size, inset) = sized(drawing, &horizontal, &vertical);
        let size = self.fitted(drawing, size);
        let Edges {
            left,
            top,
            right,
            bottom,
        } = self.aligned_effect(drawing, size);
        let (position, across) = self.across(drawing.h, horizontal);
        let x = place(
            position,
            (size.width, left, right),
            inset.0,
            &across,
            self.column.left,
        );
        let (place_down, cell_top) = self.cell_down(drawing.v);
        let down = match cell_top {
            Some(top) => Areas {
                text: (top, vertical.text.1),
                ..vertical
            },
            None => vertical,
        };
        let y = place(
            place_down,
            (size.height, top, bottom),
            inset.1,
            &down,
            paragraph,
        );
        let (x, y) = self.in_cell(drawing, (x, y), size.width);
        let y = self.below_top_margin(drawing, y, vertical.text.0);
        self.lower_cell_floor(drawing, y + size.height, cell_top.is_some());
        // A drawing placed from the page or its margins lies where it lies whatever the text
        // before its anchor does, so a later pass keeps that text out of its wrap too.
        let early = early_wrap(drawing) && self.column.cell.is_none();
        let page = (self.output.pages.len(), early);
        // A text box that fits its text keeps the text out of its side down to the bottom of
        // the fitted box.
        let height = self.drawn_height(drawing, size, (x, y));
        let earlier = &self.context.earlier.wraps;
        let band = decisions::band_height(&self.context.quirks, height);
        match drawing.wrap {
            Some(Wrap::TopAndBottom { above, below }) => keep_wrap(
                page,
                (y - above, y + band + below),
                &mut self.bands,
                &mut self.output.found.bands,
                &earlier.bands,
            ),
            Some(Wrap::Beside {
                distances,
                sides,
                polygon,
            }) => {
                // Lines flow beside the bounds of a wrap polygon, but a line without room
                // beside the drawing goes below its box, or beside a tight or through wrap
                // where the target puts it.
                let line_steps = polygon
                    .and_then(|polygon| decisions::stepped_lines(&self.context.quirks, polygon))
                    .is_some();
                let polygon = polygon.unwrap_or_default();
                let below = y + band + distances.bottom;
                // A polygon that is not a rectangle keeps the lines out of its outline on each
                // line's band where the target follows the outline.
                let outline = Some(&drawing.outline)
                    .filter(|points| !points.is_empty())
                    .and_then(|points| decisions::wrap_outline(&self.context.quirks, points))
                    .map(|points| {
                        Outline::on_page(points, (x, y), (size.width, size.height), distances)
                    });
                let square = Square {
                    top: y - distances.top + polygon.top,
                    bottom: below - polygon.bottom,
                    left: x - distances.left + polygon.left,
                    right: x + size.width + distances.right - polygon.right,
                    below: below.max(below - polygon.bottom),
                    sides,
                    line_steps,
                    outline,
                    narrowest: NARROWEST_WRAP,
                    start_past: StartPastWrap::FirstLineIndent,
                };
                keep_wrap(
                    page,
                    square,
                    &mut self.squares,
                    &mut self.output.found.squares,
                    &earlier.squares,
                );
            }
            None => {}
        }
        self.show_floating((drawing, size), (x, y), (s.width, p.height));
    }

    /// The size of a text box whose body does not wrap: as wide as its widest line with its
    /// insets and the margins of its preset's text rectangle in a box of `size`, rounded up to
    /// a whole twip; its left edge and height stay. Another drawing keeps `size`.
    fn fitted(&mut self, drawing: &Floating, size: Size) -> Size {
        let body_turned = body_turn(drawing.text_turn).is_some();
        if !drawing.fits_width || drawing.blocks.is_empty() || body_turned {
            return size;
        }
        // The lines are measured in the text box's own story, as the box lays them out.
        let section = decisions::text_box_section(&self.context.quirks, self.section);
        let story = self.text_box_story(drawing, None, None);
        let widest = self.layout_without_warnings(|layout| {
            let mut inner = layout.story_layout(&section, &[], Length::ZERO, story);
            drawing
                .blocks
                .iter()
                .filter_map(|block| match block {
                    Block::Paragraph(paragraph) => {
                        let resolved = inner.resolve(paragraph);
                        Some(inner.unbroken_width(paragraph, &resolved))
                    }
                    Block::Table(_) => None,
                })
                .max()
                .unwrap_or(Length::ZERO)
        });
        let insets = self.text_insets(drawing, size);
        Size {
            width: (widest + insets.left + insets.right).up_to_whole(Length::UNITS_PER_TWIP),
            ..size
        }
    }

    /// The story of the text box `drawing` in this layout, whose automatic text takes the
    /// drawing's text color, whose lines take the SmartArt rule where it is a SmartArt shape,
    /// whose frame `turn` turns onto the page where its body turns its text, and whose text
    /// area on the page is `inside` where it is known: the page numbers of a story inside it
    /// ([`Self::inner_numbers`]) and no footnote number. It copies the behavior from before the
    /// story kinds: a footnote mark in a text box of a footnote shows 1, an open case.
    fn text_box_story(
        &self,
        drawing: &Floating,
        turn: Option<(Turn, TurnedGlyphs)>,
        inside: Option<Edges<Length>>,
    ) -> super::Story {
        super::Story {
            kind: super::StoryKind::TextBox {
                text_color: drawing.text_color,
                turn,
                box_text: drawing.box_text,
                inside,
            },
            numbers: self.inner_numbers(),
        }
    }

    /// Draws a floating drawing with its box of `size`, whose top left corner is at `x` and `y`
    /// on a page of `page` width and height, behind the text, in front of it, or in its table
    /// cell.
    fn show_floating(
        &mut self,
        (drawing, size): (&Floating, Size),
        (x, y): (Length, Length),
        page: (Length, Length),
    ) {
        // A box whose edges lie beyond the range of a length is left out with a warning. No file
        // gives one today: every length that a reader takes lies within `Length::FILE_LIMIT`,
        // and the edges are sums of a few of them.
        let Some(bounds) = Edges::placed(x, y, size.width, size.height) else {
            self.skip_out_of_range(kind_of(drawing), drawing);
            return;
        };
        // A target may leave out a drawing that lies wholly outside the page; one that reaches
        // into the page is drawn.
        if !self.device.draws_object(bounds, page) {
            return;
        }
        // The parts of a drawing group lie at their offsets from the group's corner.
        let items = self.draw_sized((drawing, size), x, y);
        // A floating drawing lies behind the text or in front of it on its page. Only one
        // without a wrap lies behind the text, under the paragraph fills; one that wraps the
        // text lies in front of it, whatever `behindDoc` says. In a table cell it stays among
        // the cell's items, which the cell's row can move or split; one in front of the text
        // still lies above all the page's items.
        let behind = drawing.behind && drawing.wrap.is_none();
        if self.column.cell.is_some() {
            self.cell_drawing(items, !behind);
        } else if behind {
            self.behind
                .extend(items.into_iter().map(|item| (drawing.stack, item)));
        } else {
            self.front
                .extend(items.into_iter().map(|item| (drawing.stack, item)));
        }
    }

    /// Lowers the bottoms that a table cell's content reaches down to, while a cell is laid
    /// out, to the bottom `bottom` of a drawing that is placed from its paragraph, or from the
    /// cell's top (`from_cell`): the bottom of the drawings that wrap text, and that of all of
    /// them.
    fn lower_cell_floor(&mut self, drawing: &Floating, bottom: Length, from_cell: bool) {
        if !drawing.v.from.follows_text() && !from_cell {
            return;
        }
        let wraps = drawing.wrap.is_some();
        self.cell_floor = self.cell_floor.map(|floor| floor.lowered(bottom, wraps));
    }

    /// The margins from which a floating drawing of the body places itself down the page, and
    /// the height of the footnotes that it keeps above their end. A drawing outside a table cell
    /// that counts from the margins or their areas takes, where the target counts from the
    /// body's area, the area of the page being filled, below a header and above a footer that
    /// reach past the margins and above the page's footnotes, whether it wraps the text or not;
    /// every other drawing takes the section's margins. The footnotes are those that the pass
    /// before found on the page, or in a first pass those placed so far, which the pass records
    /// so that a pass that took other footnotes than its page holds asks for one more.
    fn body_margins(&mut self, drawing: &Floating) -> (Section, Length) {
        let s = self.section;
        let from_margins = matches!(
            drawing.v.from,
            Relative::Area(PageArea::Margin | PageArea::StartMargin | PageArea::EndMargin)
        );
        if self.story.is_some() || self.column.cell.is_some() || !from_margins {
            return (s, Length::ZERO);
        }
        let index = self.output.pages.len();
        let notes = self
            .context
            .earlier
            .note_heights
            .of(index)
            .unwrap_or_else(|| self.notes_height());
        let margins = BodyArea {
            top: s.top,
            end: s.height - s.bottom,
            notes: Length::ZERO,
        };
        let body = BodyArea {
            top: self.page_top(index),
            end: self.body_bottom_of(index),
            notes,
        };
        let area = decisions::story_margin_area(&self.context.quirks, margins, body);
        if area == body {
            self.output.margin_notes.push((index, notes));
        }
        let frame = Section {
            top: area.top,
            bottom: s.height - area.end,
            ..s
        };
        (frame, area.notes)
    }

    /// The top of a drawing at `y`, which from Word 2013 stops at the top margin `margin` when
    /// the drawing lies in the body, text wraps around it and it is placed from its paragraph.
    fn below_top_margin(&self, drawing: &Floating, y: Length, margin: Length) -> Length {
        let wraps = drawing.wrap.is_some();
        let modern = self.settings.mode_rules.keeps_drawings_below_top_margin();
        let body = self.page.is_none() && self.column.cell.is_none();
        if wraps && modern && body && drawing.v.from.follows_text() {
            y.max(margin)
        } else {
            y
        }
    }

    /// The horizontal position of a drawing and the areas that it counts from. A drawing
    /// placed from the column counts from the text column that holds its anchor, which in a
    /// table cell is the cell's: it takes the place of the margins. In a table cell, a drawing
    /// placed from the margins counts from the cell's text column too.
    fn across(&self, h: Position, areas: Areas) -> (Position, Areas) {
        let in_cell = self.column.cell.is_some();
        if h.from != Relative::Column && !(in_cell && h.from == Relative::Area(PageArea::Margin)) {
            return (h, areas);
        }
        let column = (self.column.left, self.column.left + self.column.width);
        let position = Position {
            from: Relative::Area(PageArea::Margin),
            ..h
        };
        (
            position,
            Areas {
                text: column,
                ..areas
            },
        )
    }

    /// The items of a floating drawing with its box of `size`, whose top left corner is at `x`
    /// and `y`: its shape, then its picture or the text of its text box. The parts of a group
    /// keep their own sizes, the sizes of their extents.
    pub(super) fn draw_sized(
        &mut self,
        (drawing, size): (&Floating, Size),
        x: Length,
        y: Length,
    ) -> Vec<Item> {
        self.draw_placed((drawing, size), (x, y), false)
    }

    /// [`Self::draw_sized`] for a drawing that is a part of a drawing group when `in_group`.
    fn draw_placed(
        &mut self,
        (drawing, size): (&Floating, Size),
        (x, y): (Length, Length),
        in_group: bool,
    ) -> Vec<Item> {
        let mut items = Vec::new();
        // The parts of a drawing group lie at their offsets from the group's corner.
        for &(left, top, ref part) in &drawing.parts {
            items.extend(self.draw_placed((part, Size::of(part)), (x + left, y + top), true));
        }
        // A chart draws its chart area and then the chart in it. The picture counts in
        // half-EMUs.
        if let Some(chart) = drawing.chart.as_ref().and_then(|c| c.columns.as_deref()) {
            items.extend(self.shape_items(drawing, (x, y), size));
            // A frame beyond the range of a length leaves the columns out with a warning, as
            // `show_floating` leaves out a box, and so do columns that their layout gives no
            // place.
            let Some(frame) = Edges::placed(x, y, size.width, size.height) else {
                self.skip_out_of_range(crate::Drawing::Chart, drawing);
                return items;
            };
            match self.columns(chart, frame) {
                Some((columns, drawn)) => {
                    items.extend(columns);
                    if !drawn.axes_and_legend {
                        self.warn_of_feature(crate::Feature::ChartLabels, drawing.part.as_str());
                    }
                    if !drawn.data_labels {
                        self.warn_of_feature(crate::Feature::DataLabels, drawing.part.as_str());
                    }
                }
                None => self.skip(crate::Drawing::Chart, drawing, crate::Reason::NotPlaced),
            }
            return items;
        }
        if let Some(path) = &drawing.text_path {
            items.extend(self.text_path_items(drawing, path, (x, y), size));
            return items;
        }
        if let Some(picture) = &drawing.picture
            && drawing.blocks.is_empty()
        {
            items.extend(self.shape_items(drawing, (x, y), size));
            items.extend(self.picture_items(picture, x, y));
            return items;
        }
        // quirk: TextBoxContent::LaidOutAsText (src/quirks.rs)
        if drawing.blocks.is_empty() {
            items.extend(self.shape_items(drawing, (x, y), size));
            return items;
        }
        items.extend(self.text_box((drawing, size), (x, y), in_group));
        items
    }

    /// The shape and the text of a text box with its box of `size`, whose top left corner is at
    /// `x` and `y`. A text box that fits its text (`a:spAutoFit`) is as tall as its text and its
    /// insets. The text of a shape turned by quarter turns is laid out in the box before the
    /// turn and turned with the shape about the box's centre; its lines keep no line records.
    /// A body that turns its text lays it out as [`Self::turned_text_box`] says. A text box
    /// that is a part of a drawing group (`in_group`) keeps its last line where its spacing
    /// puts it.
    fn text_box(
        &mut self,
        (drawing, size): (&Floating, Size),
        (x, y): (Length, Length),
        in_group: bool,
    ) -> Vec<Item> {
        if let Some(turn) = body_turn(drawing.text_turn) {
            return self.turned_text_box((drawing, size), (x, y), turn);
        }
        let s = self.section;
        let insets = self.text_insets(drawing, size);
        let Edges { top, bottom, .. } = insets;
        let (section, mut text_top) = self.text_section(drawing, (size, insets), (x, y));
        let paragraphs = crate::body::all_paragraphs(&drawing.blocks);
        self.warn_of_box_note_marks(paragraphs.iter().copied(), false, drawing.part.as_str());
        let mut height = size.height;
        if drawing.anchor != TextAnchor::Top || drawing.fits_text {
            let end = self.text_end(drawing, &section, text_top);
            if drawing.fits_text {
                height = end + bottom - y;
            }
            // Text in the middle or at the bottom of its box moves down by half the room
            // below it, or by all of it. Text taller than a text box stays at the top, and
            // text taller than a SmartArt box moves up.
            let room = y + height - bottom - end;
            let room = match drawing.room {
                Room::TextBox => room.max(Length::ZERO),
                Room::Shape => room,
            };
            text_top += match drawing.anchor {
                TextAnchor::Top => Length::ZERO,
                TextAnchor::Center => room.div_toward_zero(2),
                TextAnchor::Bottom => room,
            };
        }
        let mut items = self.shape_items(drawing, (x, y), size.with_height(height));
        // A shape with a picture fill shows its text over the picture.
        if let Some(picture) = &drawing.picture {
            items.extend(self.picture_items(picture, x, y));
        }
        let area = self.text_area(drawing, (x, y), size, height);
        let story = self.text_box_story(drawing, None, area);
        let drops = drops_last_line(drawing, in_group);
        let device = self.device;
        let quirks = &self.context.quirks;
        let drop = |lines: &[PlacedLine]| {
            if drops {
                decisions::box_last_line_drop(quirks, &device, lines, (y, height, bottom))
            } else {
                Length::ZERO
            }
        };
        let (text, _, lines) =
            self.placed_story_dropping_last(&section, &drawing.blocks, text_top, story, drop);
        // A target that leaves out objects outside the page also leaves out the text of a box
        // that reaches into the page when the box's text area ends above the page, and each
        // line that starts at or below the page's bottom, with the glyphs and the rectangles on
        // them.
        let page_height = self.page.unwrap_or(s).height;
        let band = |line: &PlacedLine| (line.top, line.top + line.height);
        let text_bottom = y + height - bottom;
        let hidden: Vec<(Length, Length)> = lines
            .iter()
            .map(band)
            .filter(|&(top, _)| !self.device.draws_box_line((top, text_bottom), page_height))
            .collect();
        let on_hidden = |at: Length| {
            hidden
                .iter()
                .any(|&(top, bottom)| (top..bottom).contains(&at))
        };
        let shown = without_hidden(text, &on_hidden);
        let mut text = self.cut_text(drawing, shown, (x, size.width), (y + top, text_bottom));
        if let Some(turn) = shape_text_turn(drawing) {
            let centre = (
                x + size.width.div_toward_zero(2),
                y + height.div_toward_zero(2),
            );
            for item in &mut text {
                turn_item(item, (centre, centre), turn, true);
            }
            items.extend(text);
            return items;
        }
        items.extend(text);
        self.output.placed.extend(
            lines
                .into_iter()
                .filter(|line| !hidden.contains(&band(line))),
        );
        items
    }

    /// The section that the text of the text box `drawing` lies in, between the insets
    /// `insets` at the sides of its box of `size` whose top left corner is at `x` and `y`, and
    /// the top of its text, below its top inset.
    fn text_section(
        &self,
        drawing: &Floating,
        (size, insets): (Size, Edges<Length>),
        (x, y): (Length, Length),
    ) -> (Section, Length) {
        let s = self.section;
        // A target that lays out a box's text in one column leaves the section's columns out.
        let mut section = decisions::text_box_section(&self.context.quirks, s);
        section.left = x + insets.left;
        section.right = s.width - (x + size.width - insets.right);
        (section, self.text_origin(drawing, y) + insets.top)
    }

    /// Where the text of the text box `drawing` that starts at `text_top` in `section` ends:
    /// below the space after its last paragraph in a text box, and at its last line in a
    /// SmartArt box.
    fn text_end(&mut self, drawing: &Floating, section: &Section, text_top: Length) -> Length {
        let story = self.text_box_story(drawing, None, None);
        self.layout_without_warnings(|layout| {
            if drawing.room == Room::TextBox {
                layout.story_end(section, &drawing.blocks, text_top, story)
            } else {
                layout.story_in(section, &drawing.blocks, text_top, story).1
            }
        })
    }

    /// The height of the floating drawing `drawing` with its box of `size` whose top left
    /// corner is at `x` and `y`, as [`Self::draw_sized`] draws it: for a text box that fits its
    /// text (`a:spAutoFit`) and whose body does not turn its text, from its top to the end of
    /// its text and its bottom inset; for another drawing, the height of `size`.
    fn drawn_height(&mut self, drawing: &Floating, size: Size, (x, y): (Length, Length)) -> Length {
        let chart = drawing
            .chart
            .as_ref()
            .is_some_and(|chart| chart.columns.is_some());
        let text_box = !chart && drawing.text_path.is_none() && !drawing.blocks.is_empty();
        if !drawing.fits_text || !text_box || body_turn(drawing.text_turn).is_some() {
            return size.height;
        }
        let insets = self.text_insets(drawing, size);
        let (section, text_top) = self.text_section(drawing, (size, insets), (x, y));
        self.text_end(drawing, &section, text_top) + insets.bottom - y
    }

    /// The shape and the text of a text box whose body turns its text by `turn` ([`DOWN`] or
    /// [`UP`]), its glyphs as `glyphs` says, with its box of `size` whose top left corner is at `x` and `y`. The text is laid
    /// out upright in a turned frame ([`super::Within::TurnedFrame`]) as long as the box is high
    /// less the insets before and after its lines, placed across the box from the side of its
    /// first line by its text anchor, and turned onto the box. The insets keep to the box's
    /// sides: for text that runs down, the top inset lies before its lines, the bottom inset
    /// after them and the right inset beside its first line; for text that runs up, the other
    /// way round. The box keeps its size, and the turned lines keep no line records.
    fn turned_text_box(
        &mut self,
        (drawing, size): (&Floating, Size),
        (x, y): (Length, Length),
        (turn, glyphs): (Turn, TurnedGlyphs),
    ) -> Vec<Item> {
        let insets = self.text_insets(drawing, size);
        let (start, end, first, last) = if turn == DOWN {
            (insets.top, insets.bottom, insets.right, insets.left)
        } else {
            (insets.bottom, insets.top, insets.left, insets.right)
        };
        // The frame starts where its lines start down the page, and reaches past the page's
        // width when the box is taller than the page is wide.
        let mut section = decisions::text_box_section(&self.context.quirks, self.section);
        section.left = y + start;
        section.width = section.left + (size.height - start - end).max(Length::ZERO);
        section.right = Length::ZERO;
        let story = self.text_box_story(drawing, Some((turn, glyphs)), None);
        let paragraphs = crate::body::all_paragraphs(&drawing.blocks);
        self.warn_of_box_note_marks(paragraphs.iter().copied(), false, drawing.part.as_str());
        let mut text_top = y;
        if drawing.anchor != TextAnchor::Top {
            let end = self.layout_without_warnings(|layout| {
                layout.story_end(&section, &drawing.blocks, y, story.clone())
            });
            // Text wider than the box across stays at the side of its first line.
            let room = (y + size.width - first - last - end).max(Length::ZERO);
            text_top += match drawing.anchor {
                TextAnchor::Top => Length::ZERO,
                TextAnchor::Center => room.div_toward_zero(2),
                TextAnchor::Bottom => room,
            };
        }
        let mut items = self.shape_items(drawing, (x, y), size);
        if let Some(picture) = &drawing.picture {
            items.extend(self.picture_items(picture, x, y));
        }
        let (mut text, ..) = self.placed_story(&section, &drawing.blocks, text_top, story);
        // The frame's top side turns to the side of the first line, and its start to the start
        // of the lines.
        let origin = if turn == DOWN {
            (x + size.width - first, y + start)
        } else {
            (x + first, y + size.height - start)
        };
        for item in &mut text {
            turn_item(item, ((section.left, y), origin), turn, true);
        }
        let along = (y + insets.top, y + size.height - insets.bottom);
        items.extend(self.cut_text(drawing, text, (x, size.width), along));
        items
    }

    /// The text area of a text box with its box of `size`, whose top left corner is at `x` and
    /// `y`, and which is `height` high once its height is known: inside its insets
    /// ([`Self::text_insets`]) on every side, from where its text starts down to where it ends.
    /// `None` for the text of a SmartArt graphic's shape.
    fn text_area(
        &self,
        drawing: &Floating,
        (x, y): (Length, Length),
        size: Size,
        height: Length,
    ) -> Option<Edges<Length>> {
        let insets = self.text_insets(drawing, size);
        (drawing.box_text == crate::floating::BoxText::Paragraphs).then(|| Edges {
            left: x + insets.left,
            top: self.text_origin(drawing, y) + insets.top,
            right: x + size.width - insets.right,
            bottom: y + height - insets.bottom,
        })
    }

    /// The insets of a text box's text from the edges of its box: from the outline's middle,
    /// from its inner edge in a DrawingML text box, inside the text rectangle of its preset,
    /// and in a VML one as the target says, with the text rectangle of the shape's type inside
    /// them, in a box of `size`.
    fn text_insets(&self, drawing: &Floating, size: Size) -> Edges<Length> {
        let outline = drawing
            .look
            .as_ref()
            .and_then(|look| look.inset_line_width(&self.shaper.theme().shapes))
            .unwrap_or(Length::ZERO);
        match drawing.inset_edge {
            InsetEdge::Middle => drawing.insets,
            InsetEdge::Vml => {
                let insets =
                    decisions::vml_box_insets(&self.context.quirks, drawing.insets, outline);
                // The type's text rectangle lies on the box less its insets.
                let inner = drawing.text_rect.and_then(|rect| {
                    rect.insets_in(
                        drawing.width - insets.left - insets.right,
                        drawing.height - insets.top - insets.bottom,
                    )
                });
                inner.map_or(insets, |inner| insets.with(inner, |a, b| a + b))
            }
            InsetEdge::Inside => {
                let half_line = outline.div_toward_zero(2);
                let mut insets = drawing.insets.map(|inset| inset + half_line);
                insets.left = drawing.insets.left
                    + decisions::box_outline_left(&self.context.quirks, half_line);
                insets.top = drawing.insets.top
                    + decisions::box_outline_top(&self.context.quirks, half_line);
                // The preset's text rectangle lies on the whole box, mirrored with the shape,
                // and the insets inside it.
                let flips = drawing.look.as_ref().map_or([false; 2], ShapeLook::flips);
                let rect = drawing
                    .preset_rect
                    .as_ref()
                    .and_then(|rect| rect.insets_in(size.width, size.height))
                    .map(|rect| mirrored(rect, flips));
                rect.map_or(insets, |rect| insets.with(rect, |a, b| a + b))
            }
        }
    }

    /// The top from which the text of `drawing`, a box whose exact top is at `y`, counts its top
    /// inset: a DrawingML text box's top rounded as the target says, or the exact top of another
    /// box.
    fn text_origin(&self, drawing: &Floating, y: Length) -> Length {
        match drawing.inset_edge {
            InsetEdge::Inside => decisions::box_text_top(&self.context.quirks, y),
            InsetEdge::Middle | InsetEdge::Vml => y,
        }
    }

    /// The items of a text box's `text`, on a target that cuts them at the box's clip: inside
    /// the inner edges of the box's outline, from `left` across `width`, and inside its text
    /// area's `top` and `bottom`. Each run of glyph runs, filled rectangles and cell-clip groups
    /// goes into a group of the page's items under the clip, which the writer places as it places
    /// the page's other text; paths, pictures and other groups stay uncut in their original paint
    /// order (so a text shadow stays under its text). On another target, or for the text of a
    /// SmartArt box, the text stays as it is.
    fn cut_text(
        &self,
        drawing: &Floating,
        text: Vec<Item>,
        (left, width): (Length, Length),
        (top, bottom): (Length, Length),
    ) -> Vec<Item> {
        if drawing.room != Room::TextBox {
            return text;
        }
        decisions::outline_clip(&self.context.quirks, text, |text| {
            let half_outline = drawing
                .look
                .as_ref()
                .and_then(|look| look.inset_line_width(&self.shaper.theme().shapes))
                .map_or(Length::ZERO, |width| width.div_toward_zero(2));
            let clip = GroupClip::rect(
                left + half_outline,
                top,
                width - half_outline - half_outline,
                bottom - top,
            );
            let mut out = Vec::new();
            let mut cut = Vec::new();
            for item in text {
                let clipped = match &item {
                    Item::Glyphs(_) | Item::Rect(_) => true,
                    Item::Group(group) => group.places == GroupPlaces::Cell,
                    Item::Path(_) | Item::Gradient(_) | Item::Image(_) => false,
                };
                if clipped {
                    cut.push(item);
                } else {
                    if !cut.is_empty() {
                        out.push(Item::Group(Group::of_page(
                            std::mem::take(&mut cut),
                            clip.clone(),
                        )));
                    }
                    out.push(item);
                }
            }
            if !cut.is_empty() {
                out.push(Item::Group(Group::of_page(cut, clip)));
            }
            out
        })
    }

    /// The fill and the line of a drawing's shape, in a box of `size` at `x` and `y`. A white
    /// fill or line is drawn as any other color, so that it covers what lies under it, and a
    /// color that lets the page show through is mixed with white. A shape whose custom path gives a place out of range is left out with
    /// a warning. A shape that takes a style of the theme, or a part of one, that F-Office does
    /// not draw warns of it here, where the theme is known. The shape's own outer shadow goes
    /// before it where the target draws shadows ([`decisions::shape_shadow`]); where it does
    /// not, or the shape casts nothing, the shadow warns.
    fn shape_items(
        &mut self,
        drawing: &Floating,
        (x, y): (Length, Length),
        size: Size,
    ) -> Vec<Item> {
        let Some(look) = &drawing.look else {
            return Vec::new();
        };
        let theme = &self.shaper.theme().shapes;
        let fill = look.fill(theme).map(|(rgb, alpha)| on_white(rgb, alpha));
        let line = look
            .line(theme)
            .map(|(rgb, alpha, width)| (on_white(rgb, alpha), width));
        let compound = line
            .is_some()
            .then_some(DrawingMlFeature::CompoundOutline)
            .filter(|_| look.compound_left_out());
        for feature in look.theme_features(theme).into_iter().chain(compound) {
            self.output.warnings.push(crate::Warning::DrawingMl {
                part: drawing.part.clone(),
                warning: DrawingMlWarning::FeatureNotSupported { feature },
            });
        }
        // A box whose right or bottom edge lies beyond the range of a length is left out with
        // the warning of a place out of range, as a point of a custom path beyond it is.
        let Some(frame) = Edges::placed(x, y, size.width, size.height) else {
            self.skip_out_of_range(crate::Drawing::Shape, drawing);
            return Vec::new();
        };
        let thick = crate::params::COMPOUND_LINE_THICK_PARTS;
        let parts: &[i64] = match look.compound {
            CompoundLine::Single => &[1],
            CompoundLine::Double => &[1, 1, 1],
            CompoundLine::ThickThin => &[thick, 1, 1],
            CompoundLine::ThinThick => &[1, 1, thick],
            CompoundLine::Triple => &[1, 1, 2, 1, 1],
        };
        let items = look
            .items_with_theme(theme, frame, fill, line, parts)
            .unwrap_or_else(|OutOfRange| {
                self.skip_out_of_range(crate::Drawing::Shape, drawing);
                Vec::new()
            });
        let Some(shadow) = look.shadow_in(theme) else {
            return items;
        };
        let cast = decisions::shape_shadow(&self.context.quirks, || {
            let color = shadow.color(theme)?;
            super::shadow::items(shadow.blur, shadow.offset(), color, &items)
        })
        .flatten();
        let Some(mut drawn) = cast else {
            self.output.warnings.push(crate::Warning::DrawingMl {
                part: drawing.part.clone(),
                warning: DrawingMlWarning::FeatureNotSupported {
                    feature: DrawingMlFeature::Shadow,
                },
            });
            return items;
        };
        drawn.extend(items);
        drawn
    }

    /// The extents around the box of `drawing`, of `size`, that an alignment of it takes: its
    /// effect extent, or for a line of text that fills its box, the extents of the box that
    /// holds its turned letters and its box turned by the nearest quarter turn
    /// ([`text_path::aligned_extents`]). A line without letters keeps the effect extent.
    fn aligned_effect(&self, drawing: &Floating, size: Size) -> Edges<Length> {
        // quirk: VmlTextPath::InkAligned (src/quirks.rs)
        let Some(path) = &drawing.text_path else {
            return drawing.effect;
        };
        let Ok((letters, em)) = self.text_path_letters(path) else {
            return drawing.effect;
        };
        Edges::placed(Length::ZERO, Length::ZERO, size.width, size.height)
            .and_then(|frame| {
                let items =
                    text_path::letter_items(&letters, em, frame, (path.rotation, path.color))?;
                Some(text_path::aligned_extents(&items, frame, path.rotation))
            })
            .unwrap_or(drawing.effect)
    }

    /// The letters of the line of text `path` and the measures of their face, the face of the
    /// path's family or the face that Word draws in its place.
    fn text_path_letters(
        &self,
        path: &TextPath,
    ) -> Result<(Vec<text_path::Letter>, text_path::Em), NoLetters> {
        let fonts = self.shaper.fonts();
        let face = fonts
            .face(&path.face, false, false)
            .or_else(|| fonts.family_substitute(&path.face, false, false))
            .ok_or(NoLetters::NoFace)?;
        let letters = path
            .string
            .chars()
            .map(|ch| {
                let glyph = fonts.glyph(face.font, ch).unwrap_or(0);
                Some(text_path::Letter {
                    advance: fonts.advance(face.font, glyph).unwrap_or(0),
                    outline: fonts.outline(face.font, glyph).ok()?,
                })
            })
            .collect::<Option<Vec<_>>>()
            .ok_or(NoLetters::NoOutline)?;
        let em = text_path::Em {
            units_per_em: face.metrics.units_per_em,
            descent: face.metrics.descent,
        };
        Ok((letters, em))
    }

    /// The letters of the line of text `path` of `drawing`, which fills its box of `size` at
    /// `x` and `y` ([`text_path::letter_items`]), in the face of the path's family or the face
    /// that Word draws in its place. With no face the line is left out with the warning of text
    /// not drawn, and with a glyph whose outline the caller cannot give, with the warning of a
    /// shape left out.
    fn text_path_items(
        &mut self,
        drawing: &Floating,
        path: &TextPath,
        (x, y): (Length, Length),
        size: Size,
    ) -> Vec<Item> {
        let (letters, em) = match self.text_path_letters(path) {
            Ok(found) => found,
            Err(NoLetters::NoFace) => {
                self.output.warnings.push(crate::Warning::TextNotDrawn {
                    asked: Some(Name::new(path.face.as_str())),
                    tried: vec![Name::new(path.face.as_str())],
                });
                return Vec::new();
            }
            Err(NoLetters::NoOutline) => {
                self.skip(crate::Drawing::Shape, drawing, crate::Reason::Unsupported);
                return Vec::new();
            }
        };
        let items = Edges::placed(x, y, size.width, size.height).and_then(|frame| {
            text_path::letter_items(&letters, em, frame, (path.rotation, path.color))
        });
        items.unwrap_or_else(|| {
            self.skip_out_of_range(crate::Drawing::Shape, drawing);
            Vec::new()
        })
    }

    /// Keeps the warning that the layout leaves out `kind`, the whole of `drawing` or a part of
    /// it, since a place of it lies beyond the range of a length.
    fn skip_out_of_range(&mut self, kind: crate::Drawing, drawing: &Floating) {
        self.skip(kind, drawing, crate::Reason::OutOfRange);
    }

    /// Keeps the warning that the layout leaves out `kind`, the whole of `drawing` or a part of
    /// it, for `reason`.
    fn skip(&mut self, kind: crate::Drawing, drawing: &Floating, reason: crate::Reason) {
        self.output.warnings.push(crate::Warning::DrawingSkipped {
            drawing: kind,
            part: drawing.part.clone(),
            reason,
        });
    }
}

/// Keeps the lines of the page out of `wrap`, the band of a top and bottom wrap or the box of a
/// wrap that the text flows beside, on the page with the index `page`: the wrap goes into
/// `own`, the wraps of the page. The wrap of an `early` drawing, placed from the page or its
/// margins, also goes into `found`, what this pass found, and a wrap that started this page with
/// the wraps of the earlier pass, `earlier`, at the same place is on it already.
fn keep_wrap<T: Clone + PartialEq>(
    (page, early): (usize, bool),
    wrap: T,
    own: &mut Vec<T>,
    found: &mut Vec<(usize, T)>,
    earlier: &[(usize, T)],
) {
    let at = (page, wrap);
    if !early || earlier.get(found.len()) != Some(&at) {
        own.push(at.1.clone());
    }
    if early {
        found.push(at);
    }
}

/// Whether the last line of `drawing`'s text may sit lower than its spacing puts it, by the room
/// below it: in a DrawingML text box outside drawing groups (`in_group` false) whose text starts
/// at its top and that does not fit its text.
fn drops_last_line(drawing: &Floating, in_group: bool) -> bool {
    drawing.anchor == TextAnchor::Top
        && !in_group
        && !drawing.fits_text
        && drawing.room == Room::TextBox
        && drawing.inset_edge == InsetEdge::Inside
}

/// What a floating drawing is, for a warning, as [`Layout::draw_sized`] draws it: a chart
/// with columns, a picture without text, or else a shape, which a text box and a drawing group
/// are too.
fn kind_of(drawing: &Floating) -> crate::Drawing {
    if drawing
        .chart
        .as_ref()
        .is_some_and(|chart| chart.columns.is_some())
    {
        crate::Drawing::Chart
    } else if drawing.picture.is_some() && drawing.blocks.is_empty() {
        crate::Drawing::Picture
    } else {
        crate::Drawing::Shape
    }
}

/// The floating drawings that a paragraph anchors.
fn floatings(paragraph: &Paragraph) -> impl Iterator<Item = &Floating> {
    let content = paragraph.runs.iter().flat_map(|run| &run.content);
    content.filter_map(|content| match content {
        Content::Floating(floating) => Some(&**floating),
        _ => None,
    })
}

/// The floating drawings of a paragraph that wait for the lines that hold their anchor marks.
pub(super) struct Waiting {
    /// The paragraph's top, which a drawing whose mark the first line holds counts from.
    top: Length,
    /// The indexes of the drawings, in the order of the paragraph's content.
    drawings: Vec<usize>,
    /// The indexes of the drawings placed down from the paragraph that wait for the page of
    /// their anchor.
    later: Vec<usize>,
    /// The page that the paragraph's part being laid out stands on, and its top there.
    part: (usize, Length),
}

/// The height of the footnotes of each page of a layout pass (**Note heights**), which the
/// next pass gives the floating drawings of the body that count down the page from the
/// margins of the body's area, before it knows the footnotes of their page.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NoteHeights(Vec<Length>);

impl NoteHeights {
    /// The note heights of the pages of `areas`, in the order of the pages.
    pub(super) fn of_areas(areas: &[BodyArea]) -> Self {
        Self(areas.iter().map(|area| area.notes).collect())
    }

    /// The height of the footnotes of the page `page`, or `None` for a page that the pass did
    /// not fill.
    pub(super) fn of(&self, page: usize) -> Option<Length> {
        self.0.get(page).copied()
    }
}

/// The drawings placed down from their paragraph whose anchor a pass found on a later page
/// than the paragraph's first line (**Later anchors**), each by its paragraph and its index
/// among the paragraph's drawings, in the order of its content. The next pass places them from
/// the top of the paragraph's part on the page of their anchor.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LaterAnchors(HashSet<(ParagraphId, usize)>);

impl LaterAnchors {
    /// The later anchors that a pass found, in the order of finding.
    pub(super) fn found(found: &[(ParagraphId, usize)]) -> Self {
        Self(found.iter().copied().collect())
    }

    /// The indexes of the drawings of the paragraph `paragraph` among them, in order.
    pub(super) fn of(&self, paragraph: ParagraphId) -> Vec<usize> {
        let mut drawings: Vec<usize> = self
            .0
            .iter()
            .filter(|(id, _)| *id == paragraph)
            .map(|&(_, drawing)| drawing)
            .collect();
        drawings.sort_unstable();
        drawings
    }

    /// Whether a pass found none.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Adds the later anchors of `other`, and says whether it added any. The passes keep each
    /// drawing that one of them found, so that a drawing that waits for its page and lets its
    /// anchor back onto the paragraph's first page does not go back and forth.
    pub fn join(&mut self, other: &Self) -> bool {
        let before = self.0.len();
        self.0.extend(other.0.iter().copied());
        self.0.len() != before
    }
}

/// The pages of the lines of a paragraph's layout that hold the anchor marks of drawings placed
/// down from the paragraph, beside the page of its first line.
#[derive(Default)]
pub(super) struct AnchorPages {
    /// The page of the paragraph's first line.
    first: Option<usize>,
    /// The index of each such drawing, in the order of the paragraph's content, with the page
    /// of the line that holds its mark.
    marks: Vec<(usize, usize)>,
}

impl AnchorPages {
    /// Notes that `line` of `paragraph` stands on `page`.
    pub(super) fn note(&mut self, paragraph: &Paragraph, line: &Line, page: usize) {
        self.first.get_or_insert(page);
        for mark in anchor_marks(line).filter(|&mark| from_paragraph(paragraph, mark)) {
            self.marks.push((mark, page));
        }
    }

    /// The drawings whose anchor stands on a later page than the paragraph's first line.
    pub(super) fn later(&self) -> Vec<usize> {
        let first = self.first.unwrap_or(0);
        let later = self.marks.iter().filter(|&&(_, page)| page > first);
        later.map(|&(drawing, _)| drawing).collect()
    }
}

/// The indexes of the drawings whose anchor marks a line holds.
fn anchor_marks(line: &Line) -> impl Iterator<Item = usize> + '_ {
    line.anchors.iter().map(|mark| mark.drawing)
}

/// Whether the drawing with the index `index` of a paragraph's content is placed down from the
/// paragraph.
fn from_paragraph(paragraph: &Paragraph, index: usize) -> bool {
    floatings(paragraph)
        .nth(index)
        .is_some_and(|drawing| drawing.v.from == Relative::Paragraph)
}

/// Whether a line holds the anchor mark of one of the drawings `later`.
pub(super) fn holds_later(line: &Line, later: &[usize]) -> bool {
    anchor_marks(line).any(|mark| later.contains(&mark))
}

/// Whether a drawing is placed from the page or its margins, so that its wrap starts with its
/// page in a later pass.
fn early_wrap(drawing: &Floating) -> bool {
    !drawing.v.from.follows_text()
}

/// The box of a drawing that text flows beside, with its distances, on the page.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Square {
    pub(super) top: Length,
    pub(super) bottom: Length,
    pub(super) left: Length,
    pub(super) right: Length,
    /// Where a line that has no room beside the drawing goes below it.
    pub(super) below: Length,
    /// The sides that the text flows on, or `None` for a drawing whose wrap polygon is not its
    /// bounds, beside which a line takes the widest free piece.
    pub(super) sides: Option<WrapSides>,
    /// Where a line that has no room beside the drawing goes: to [`Self::below`], or with
    /// `line_steps` down in steps of its height past [`Self::bottom`].
    pub(super) line_steps: bool,
    /// The outline of a tight or through wrap's polygon that is not a rectangle, which a line
    /// meets on its band; `None` where the line meets the bounds above.
    pub(super) outline: Option<Outline>,
    /// The narrowest piece of a line on either side of it that takes text.
    pub(super) narrowest: Length,
    /// What a line on its right keeps of its own start past its wrap edge.
    pub(super) start_past: StartPastWrap,
}

/// What a line keeps of its own start past the wrap edge of a wrap on its left, which moves
/// the line's start there.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum StartPastWrap {
    /// Beside a drawing: the part that the line's paragraph gives, on a left-to-right line
    /// the paragraph's first line's first-line indent and nothing on a later line.
    FirstLineIndent,
    /// Beside a frame or a floating table: the line's whole start past its column's edge.
    Whole,
}

/// A piece of a line that the wraps of the page narrow: its start and width from the column's
/// left edge, and the wrap edge from that edge where a wrap on its left moved its start.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct NarrowedPiece {
    pub(super) start: Length,
    pub(super) width: Length,
    pub(super) edge: Option<Length>,
}

/// The outline of a wrap polygon on the page, with the wrap distances around it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Outline {
    /// The polygon's points on the page, in order.
    points: Vec<(Length, Length)>,
    /// The wrap distances (`distL`, `distT`, `distR`, `distB`).
    distances: Edges<Length>,
}

impl Outline {
    /// The outline of the polygon `points`, in 21,600ths of a drawing of `size` whose top left
    /// corner lies at `corner` on the page, with the wrap distances `distances`.
    fn on_page(
        points: &[(i64, i64)],
        corner: (Length, Length),
        size: (Length, Length),
        distances: Edges<Length>,
    ) -> Self {
        let whole = i128::from(crate::params::WRAP_POLYGON_WHOLE);
        let scale = |value: i64, side: Length| {
            let share = i128::from(value) * i128::from(side.units()) / whole;
            Length::from_units(i64::try_from(share).unwrap_or_default())
        };
        let points = points
            .iter()
            .map(|&(x, y)| (corner.0 + scale(x, size.0), corner.1 + scale(y, size.1)))
            .collect();
        Self { points, distances }
    }

    /// The leftmost and the rightmost points of the outline on the band of a line from `top`
    /// to `bottom`, with the wrap distances: the outline's parts that lie strictly inside the
    /// band, widened by the distance below the polygon above the band and the distance above it
    /// below the band. `None` where no part of the outline lies in the band.
    fn across(&self, (top, bottom): (Length, Length)) -> Option<(Length, Length)> {
        let (low, high) = (top - self.distances.bottom, bottom + self.distances.top);
        let closing = self.points.last().zip(self.points.first());
        let edges = self
            .points
            .windows(2)
            .filter_map(|pair| pair.first().zip(pair.get(1)))
            .chain(closing);
        let mut xs = edges
            .filter_map(|(&a, &b)| inside_band(a, b, (low, high)))
            .flatten();
        let first = xs.next()?;
        let (left, right) = xs.fold((first, first), |(l, r), x| (l.min(x), r.max(x)));
        Some((left - self.distances.left, right + self.distances.right))
    }
}

/// The horizontal places of the ends of the part of the edge from `a` to `b` that lies
/// strictly between `low` and `high` down the page, none where no part does.
fn inside_band(
    (ax, ay): (Length, Length),
    (bx, by): (Length, Length),
    (low, high): (Length, Length),
) -> Option<[Length; 2]> {
    if ay == by {
        return (low < ay && ay < high).then_some([ax, bx]);
    }
    let (top, bottom) = (ay.min(by), ay.max(by));
    if bottom <= low || top >= high {
        return None;
    }
    let at = |y: Length| {
        let part = i128::from((y - ay).units()) * i128::from((bx - ax).units())
            / i128::from((by - ay).units());
        ax + Length::from_units(i64::try_from(part).unwrap_or_default())
    };
    Some([at(low.max(top)), at(high.min(bottom))])
}

impl Square {
    /// The left and right edges that a line from `top` to `bottom` keeps out of: the bounds
    /// with the wrap distances, or the outline's on the line's band. `None` where the line
    /// does not meet the outline.
    fn across(&self, band: (Length, Length)) -> Option<(Length, Length)> {
        match &self.outline {
            Some(outline) => outline.across(band),
            None => Some((self.left, self.right)),
        }
    }

    /// Where a line of `height` with its top at `top`, which meets this drawing's wrap and has
    /// no room beside it in the piece from `left` to `right`, goes: to [`Self::below`], or with
    /// [`Self::line_steps`] down from its own top, one `step` at a time, until it no longer
    /// meets the wrap, where the target's steps end (`decisions::step_end`), or beside an
    /// outline until the outline leaves it a piece at least [`NARROWEST_WRAP`] wide. The step
    /// is the line's single line under multiple spacing, and its height otherwise
    /// (`LineBox::step`).
    fn line_end(
        &self,
        (top, height, step): (Length, Length, Length),
        (left, right): (Length, Length),
        quirks: &crate::quirks::Quirks,
    ) -> Length {
        if !self.line_steps || step <= Length::ZERO {
            return self.below;
        }
        let end = top + decisions::step_end(quirks, self.bottom - top, step);
        if self.outline.is_none() {
            return end;
        }
        // A step at the wrap's bottom or below it ends where the target's steps end.
        let mut at = top + step;
        while at < end.min(self.bottom) {
            let free = self.across((at, at + height)).is_none_or(|(a, b)| {
                right.min(a) - left >= NARROWEST_WRAP || right - left.max(b) >= NARROWEST_WRAP
            });
            if free {
                return at;
            }
            at += step;
        }
        end
    }
}

impl Layout<'_> {
    /// Where a line of `height` with its top at `top`, which starts at `start` from the column
    /// edge with `width`, may go beside the drawings of the page, as narrowed pieces, when a
    /// drawing is in its way. A drawing on the line's left moves its start to the wrap edge
    /// plus `kept`, the part of its start that it keeps beside a drawing; a frame or a floating
    /// table moves it to the wrap edge plus its whole start ([`StartPastWrap`]). `None` means
    /// that no drawing is in the way. A start of `None` means that the line does not fit
    /// beside the drawing and must go below it, to the returned top, which a tight or through
    /// wrap can give in steps of `step` (`Square::line_end`). The line meets the bounds of the
    /// wraps over its `height`, and the outline of a tight or through wrap over `band` from its
    /// top (`Layout::wrap_band`).
    pub(super) fn beside(
        &self,
        (top, (height, band), step): (Length, (Length, Length), Length),
        (start, width): (Length, Length),
        kept: Length,
    ) -> Option<Beside> {
        let band_height = band;
        let band = (top, top + band_height);
        let (meeting, across): (Vec<&Square>, Vec<(Length, Length)>) = self
            .squares
            .iter()
            .filter(|s| top < s.bottom && top + height > s.top)
            .filter_map(|s| s.across(band).map(|edges| (s, edges)))
            .unzip();
        let column_left = self.column.left;
        let left = column_left + start;
        let right = left + width;
        let quirks = &self.context.quirks;
        let first_end = meeting
            .iter()
            .map(|s| s.line_end((top, band_height, step), (left, right), quirks))
            .min()?;
        let mut pieces = vec![(left, right)];
        for &(square_left, square_right) in &across {
            pieces = pieces
                .into_iter()
                .flat_map(|(a, b)| [(a, b.min(square_left)), (a.max(square_right), b)])
                .filter(|(a, b)| b > a)
                .collect();
        }
        let chosen = chosen_pieces(&meeting, pieces);
        let Some(&(a, b)) = chosen.first() else {
            // Beside an outline, the line meets the wraps again where its steps end.
            if meeting.iter().any(|s| s.outline.is_some()) {
                return Some(Beside::Step(first_end));
            }
            return Some(Beside::Below(first_end));
        };
        // Beside a wrap on its left, the line starts at the wrap edge and keeps part of its
        // start past it.
        let past = |edge: Length| {
            let whole = meeting.iter().zip(&across).any(|(square, &(_, right))| {
                right == edge && square.start_past == StartPastWrap::Whole
            });
            if whole { start } else { kept }
        };
        let place = |(a, b): (Length, Length)| {
            let edge = (a > left).then(|| a - column_left);
            let from = edge.map_or(start, |edge| edge + past(a));
            NarrowedPiece {
                start: from,
                width: (b - column_left - from).min(width),
                edge,
            }
        };
        Some(Beside::Line(
            place((a, b)),
            first_end,
            chosen.iter().skip(1).map(|&piece| place(piece)).collect(),
        ))
    }

    /// The heights over which the line `size` meets the wraps of the page from its top: its
    /// height, which meets the wraps' bounds, and the band that meets the outline of a tight or
    /// through wrap, its height or its single line where the target tests that
    /// (`decisions::line_wrap_band`).
    pub(super) fn wrap_band(&self, size: &super::line::height::LineBox) -> (Length, Length) {
        let band = decisions::line_wrap_band(&self.context.quirks, (size.height, size.step()));
        (size.height, band)
    }

    /// Moves the current position below every drawing that starts above it and reaches
    /// below it, after a clearing line break.
    pub(super) fn clear_floats(&mut self) {
        while let Some(below) = self
            .squares
            .iter()
            .filter(|s| s.top <= self.y && self.y < s.below)
            .map(|s| s.below)
            .max()
        {
            self.move_to(below);
        }
    }
}

/// How a line goes past a drawing in its way.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Beside {
    /// On the first free piece that the wraps let the text flow on, where the first of the
    /// drawings in the way ends, for a line that does not fit there after all, and each
    /// further piece that the line goes on in, on the same baseline.
    Line(NarrowedPiece, Length, Vec<NarrowedPiece>),
    /// Below the drawing, which ends here.
    Below(Length),
    /// Down to this top, where the steps of a line beside the outline of a wrap polygon end,
    /// and there beside the wraps that the line meets again.
    Step(Length),
}

/// The areas that a position counts from on one axis, each as its start and end.
#[derive(Clone, Copy, Debug)]
struct Areas {
    /// The page.
    page: (Length, Length),
    /// The space between the margins, or the text column that takes its place.
    text: (Length, Length),
    /// The start margin.
    start_margin: (Length, Length),
    /// The end margin.
    end_margin: (Length, Length),
}

impl Areas {
    /// The start and the end of the area `area` on this axis, which a position and a relative
    /// size count from alike.
    const fn of(&self, area: PageArea) -> (Length, Length) {
        match area {
            PageArea::Page => self.page,
            PageArea::Margin => self.text,
            PageArea::StartMargin => self.start_margin,
            PageArea::EndMargin => self.end_margin,
        }
    }
}

/// Whether a drawing is aligned from the margins, to their start, center or end.
fn aligned_from_margin(position: Position) -> bool {
    position.from == Relative::Area(PageArea::Margin) && position.align.is_some()
}

/// Whether a drawing is placed from the margins by an offset, without an alignment or a share
/// of the area: in a table cell it counts from the cell's text top.
fn from_margin_by_offset(position: Position) -> bool {
    position.from == Relative::Area(PageArea::Margin)
        && position.align.is_none()
        && position.share.is_none()
}

/// Why the layout has no letters of a line of text that fills its box.
enum NoLetters {
    /// The caller has no face of the line's family, nor the face that Word draws in its place.
    NoFace,
    /// The caller cannot give the outline of one of the letters.
    NoOutline,
}

/// The start of a drawing on one axis, from its `areas`; `paragraph` is where the anchor
/// paragraph starts. A position by offset or by share places the drawing's box, and the drawing
/// starts `inset` inside it.
fn place(
    position: Position,
    (size, lead, trail): (Length, Length, Length),
    inset: Length,
    areas: &Areas,
    paragraph: Length,
) -> Length {
    let (start, end) = match position.from {
        Relative::Area(area) => areas.of(area),
        Relative::Column => areas.text,
        // A drawing placed from its line counts from the top that its caller gives: the line's,
        // or the paragraph's where the target counts from it.
        Relative::Paragraph | Relative::Line => (paragraph, paragraph + size),
    };
    // An aligned drawing aligns its box together with the effect extent around it, such as a
    // shadow.
    match (position.align, position.share) {
        (Some(Align::Start), _) => start + lead,
        (Some(Align::Center), _) => {
            start + lead + (end - start - size - lead - trail).div_toward_zero(2)
        }
        (Some(Align::End), _) => end - size - trail,
        // The file gives the share without a bound: a share whose part of the area does not
        // fit in a length places the drawing by its offset.
        (None, Some(share)) => {
            (end - start)
                .checked_mul(share)
                // The part rounds to the nearest half-EMU, a half up, where the part of a relative
                // size rounds toward zero (`sized`). The two differ by at most one half-EMU, and no
                // Word page has shown which rounding Word takes for either.
                .and_then(|part| part.checked_div_round(DRAWING_WHOLE))
                .map_or(start + position.offset, |part| start + part)
                + inset
        }
        (None, None) => start + position.offset + inset,
    }
}

/// The width and the height of a drawing's box where the layout places it, which a size
/// relative to an area of the page changes, so that a placed drawing needs no copy with
/// another size.
#[derive(Clone, Copy, Debug)]
pub(super) struct Size {
    /// The width.
    width: Length,
    /// The height.
    height: Length,
}

impl Size {
    /// The size of the drawing's own extent.
    pub(super) const fn of(drawing: &Floating) -> Self {
        Self {
            width: drawing.width,
            height: drawing.height,
        }
    }

    /// This size with the height `height`.
    pub(super) const fn with_height(self, height: Length) -> Self {
        Self { height, ..self }
    }
}

/// The size of a drawing on the page: that of its extent, or for a shape or text box with a
/// size relative to an area of the page, that size less the drawing's effect extent at both
/// ends, since the relative size is that of the box with the effect extent around the drawing.
/// A picture keeps the size of its frame. The second value is how far the drawing starts inside
/// its box across and down: the effect extent at the left and at the top where the size on that
/// axis is relative, and zero where it is not.
fn sized(drawing: &Floating, horizontal: &Areas, vertical: &Areas) -> (Size, (Length, Length)) {
    let mut size = Size::of(drawing);
    let mut inset = (Length::ZERO, Length::ZERO);
    if drawing.picture.is_some() {
        return (size, inset);
    }
    let effect = drawing.effect;
    // The file gives the share without a bound: a share whose part of the area does not fit
    // in a length keeps the size of the drawing's extent.
    let span = |(from, share): (PageArea, i64), areas: &Areas| {
        let (start, end) = areas.of(from);
        (end - start)
            .checked_mul(share)
            // The part rounds toward zero, where the part of a relative position rounds to the
            // nearest half-EMU, a half up (`place`). The two differ by at most one half-EMU, and
            // no Word page has shown which rounding Word takes for either.
            .map(|part| part.div_toward_zero(DRAWING_WHOLE))
    };
    if let Some(width) = drawing.relative_width.and_then(|w| span(w, horizontal)) {
        size.width = width - effect.left - effect.right;
        inset.0 = effect.left;
    }
    if let Some(height) = drawing.relative_height.and_then(|h| span(h, vertical)) {
        size.height = height - effect.top - effect.bottom;
        inset.1 = effect.top;
    }
    (size, inset)
}

/// The items of a text box's `text` without the glyph runs and the filled rectangles that
/// start on a line that `on_hidden` leaves out, also inside the group of a table cell's clip,
/// which holds the cell's glyph runs and rectangles. A cell's group that keeps no item is left
/// out.
fn without_hidden(text: Vec<Item>, on_hidden: &dyn Fn(Length) -> bool) -> Vec<Item> {
    text.into_iter()
        .filter_map(|item| match item {
            Item::Glyphs(run) if run.glyphs.first().is_some_and(|g| on_hidden(g.y)) => None,
            Item::Rect(rect) if on_hidden(rect.y) => None,
            Item::Group(mut group) if group.places == GroupPlaces::Cell => {
                group.items = without_hidden(group.items, on_hidden);
                (!group.items.is_empty()).then_some(Item::Group(group))
            }
            item => Some(item),
        })
        .collect()
}

/// The areas that a position counts from on one axis of a page of `length` with the margins
/// `start` and `end`.
fn areas(length: Length, start: Length, end: Length) -> Areas {
    Areas {
        page: (Length::ZERO, length),
        text: (start, length - end),
        start_margin: (Length::ZERO, start),
        end_margin: (length - end, length),
    }
}

/// The free pieces of a line, as left and right edges on the page in reading order, that the
/// wraps of the drawings in its way let it flow on, each at least [`NARROWEST_WRAP`] wide, or as
/// wide as the drawing beside it asks for ([`Square::narrowest`]). Beside
/// drawings whose text flows on both sides, the line fills every piece from left to right.
/// Beside one drawing whose text flows on one side, it fills that side, or the wider one, the
/// left one of equal ones. Beside wrap polygons that are not their bounds and mixed wraps, it
/// takes the widest piece, the rightmost of equal ones. Frames and floating tables flow on both
/// sides.
fn chosen_pieces(meeting: &[&Square], pieces: Vec<(Length, Length)>) -> Vec<(Length, Length)> {
    let usable: Vec<(Length, Length)> = pieces
        .into_iter()
        .filter(|&piece| piece.1 - piece.0 >= narrowest(meeting, piece))
        .collect();
    let widest = |usable: Vec<(Length, Length)>, rightmost: bool| -> Vec<(Length, Length)> {
        let best = if rightmost {
            usable.iter().copied().max_by_key(|&(a, b)| b - a)
        } else {
            usable.iter().copied().rev().max_by_key(|&(a, b)| b - a)
        };
        best.into_iter().collect()
    };
    if meeting.iter().all(|s| s.sides == Some(WrapSides::Both)) {
        return usable;
    }
    match meeting {
        [square] => match square.sides {
            Some(WrapSides::Left) => usable
                .into_iter()
                .filter(|(_, b)| *b <= square.left)
                .collect(),
            Some(WrapSides::Right) => usable
                .into_iter()
                .filter(|(a, _)| *a >= square.right)
                .collect(),
            Some(WrapSides::Largest) => widest(usable, false),
            _ => widest(usable, true),
        },
        _ => widest(usable, true),
    }
}

/// The narrowest that the piece from `a` to `b` may be to take text: [`NARROWEST_WRAP`], or more
/// where a drawing of `meeting` that it ends at or starts from asks for more.
fn narrowest(meeting: &[&Square], (a, b): (Length, Length)) -> Length {
    meeting
        .iter()
        .filter(|square| b == square.left || a == square.right)
        .fold(NARROWEST_WRAP, |least, square| least.max(square.narrowest))
}

/// The distances `rect` of a preset's text rectangle from the edges of its box, mirrored with a
/// shape mirrored across or down (`flips`): Word lays the text out upright in the rectangle that
/// the mirrored outline shows, before it turns the text of a shape mirrored down.
const fn mirrored(rect: Edges<Length>, [across, down]: [bool; 2]) -> Edges<Length> {
    let (left, right) = if across {
        (rect.right, rect.left)
    } else {
        (rect.left, rect.right)
    };
    let (top, bottom) = if down {
        (rect.bottom, rect.top)
    } else {
        (rect.top, rect.bottom)
    };
    Edges {
        left,
        top,
        right,
        bottom,
    }
}

/// The turn of the frame of a text box whose body turns its text, with how its glyphs lie on the
/// page, or `None` for upright text and for text that turns with its shape.
const fn body_turn(turn: TextTurn) -> Option<(Turn, TurnedGlyphs)> {
    match turn {
        TextTurn::Down => Some((DOWN, TurnedGlyphs::WithLine)),
        TextTurn::Up => Some((UP, TurnedGlyphs::WithLine)),
        TextTurn::EastAsianDown => Some((DOWN, TurnedGlyphs::EastAsianUpright)),
        TextTurn::Upright | TextTurn::WithShape => None,
    }
}

/// The turn of a shape's text that turns with the shape by quarter turns, about the box's
/// centre, or `None` for text that does not turn with it.
fn shape_text_turn(drawing: &Floating) -> Option<Turn> {
    (drawing.text_turn == TextTurn::WithShape)
        .then(|| {
            drawing
                .look
                .as_ref()
                .and_then(ShapeLook::text_quarter_turns)
        })
        .flatten()
        .and_then(|quarters| crate::picture::turn(quarters, [false, false]))
}

#[cfg(test)]
mod tests;