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
//! Paragraphs and pages.
//!
//! The layout fills the pages of a body in one pass. Its parts live in submodules: `pages`
//! for page geometry, headers and footers, `paragraph` for the flow of paragraphs and the
//! page break rules, `measure` for resolving and measuring paragraphs, `line` for placing and
//! drawing lines, and `table`, `floating`, `frames`, `notes`, `endnotes` and `sections` for
//! those parts of a document.

mod art_borders;
mod bidi;
mod chart;
mod columns;
mod decisions;
mod endnotes;
mod floating;
mod frames;
mod if_fields;
mod incremental_state;
mod line;
mod line_text;
mod markup;
mod measure;
mod metafile;
mod notes;
mod output;
mod page_items;
mod pages;
mod paragraph;
mod sections;
mod shadow;
mod style_refs;
mod table;
#[cfg(test)]
mod testing;
#[cfg(test)]
mod tests;
mod text_path;

pub use floating::{LaterAnchors, NoteHeights};
pub(crate) use incremental_state::{BodyCursor, LayoutState};
pub(crate) use line_text::RunSpan;
pub use line_text::{LineText, LineTextEnd, LineTurn, TextCluster};
pub(crate) use measure::{list_label_props, mark_run_props};
pub use notes::NotePlaces;

use std::borrow::Cow;
use std::rc::Rc;

use f_office_paint::{DisplayList, Item, Rect, Rgb};
use f_office_units::{Length, count_factor};

use crate::body::{Block, Body, NoteId, Notes, ParagraphId, Section, SectionStart, Sections};
use crate::comments::Comments;
use crate::dates::DateTime;
use crate::note_setup::{ByNoteKind, NoteLabel, NoteSetup};
use crate::numbering::{Label, NumberContext, Numbering};
use crate::props::{ParaProps, RunProps};
use crate::styles::{Settings, SideMargins, Styles, TableStyle};
use crate::table::Table;
use crate::text::Shaper;
use paragraph::{HeldBorders, NewPageSpace, Previous};
use sections::SectionIndex;

/// What every flow of a layout pass reads and no flow changes: the document's styles,
/// settings, lists and parts, the target's device and quirks, the date and the custom
/// properties, and what an earlier pass found. It has no `Clone`: a later pass takes what the
/// pass before found in place of `earlier`, and the passes borrow one copy of the document's
/// parts. The sections of the body are not in it: only the body's layout reads them
/// (`Layout::new`), and a story fills one section of its own (`Layout::story`).
pub struct Context<'a> {
    /// The name of the main document's part, which the warning of a setting names where its
    /// default acts and no layer of the cascade sets it (`Layout::setting_part`).
    pub main: &'a str,
    /// The styles.
    pub styles: &'a Styles,
    /// The settings.
    pub settings: &'a Settings,
    /// The HTML divs of the web settings part whose margins or borders change their
    /// paragraphs, of which the layout warns.
    pub html_divs: &'a crate::web_settings::HtmlDivs<'a>,
    /// The list definitions, with their counters at the start of the body.
    pub numbering: Rc<Numbering>,
    /// The footnotes.
    pub notes: Rc<Notes>,
    /// The endnotes.
    pub endnotes: Rc<Notes>,
    /// The comments, which Word prints in balloons beside the pages.
    pub comments: Rc<Comments>,
    /// The target's layout device, from its profile.
    pub device: crate::grid::Device,
    /// The variant of every quirk that the target's profile names, which the layout's rules
    /// of tables, VML shapes and page breaks read; the device reads its own quirks.
    pub quirks: crate::quirks::Quirks,
    /// The local date and time that `DATE` and `TIME` fields show, or none for their stored
    /// results.
    pub now: Option<DateTime>,
    /// The custom properties of the document, which `DOCPROPERTY` fields show.
    pub properties: std::sync::Arc<crate::properties::Properties>,
    /// The time zone of the machine, in minutes east of UTC, in which a target that writes a
    /// date property as its local date writes it (the last layer's that sets one).
    pub zone_minutes: i32,
    /// What an earlier pass found, or nothing in a first pass.
    pub earlier: EarlierPass,
    /// The paragraph ID of the label that the balloon of each deleted table cell shows, which
    /// the layout builds: one ID of the document, as each balloon shows a copy of one label.
    pub deleted_cell_label: ParagraphId,
    /// The pictures of the art page borders that the caller gives.
    pub art: &'a crate::ArtPictures,
}

impl Context<'_> {
    /// The context of the stories that the body's pages hold, such as headers, footers,
    /// footnotes, frames, text boxes and balloons: the same styles, settings, device, date and
    /// properties, with none of the document's parts and nothing of an earlier pass. It holds
    /// no lists either: a story's lists go on from the counters of the flow that holds it,
    /// which its layout takes (`Layout::story`), so a copy here would go unread.
    /// It copies the behavior from before the shared context, in which each story made its own
    /// empty parts: in a story, a footnote, endnote or comment reference finds no note or
    /// comment, and `PAGEREF`, `REF` and `STYLEREF` fields and the wraps of drawings find
    /// nothing of an earlier pass. Each is an open rule question.
    #[must_use]
    pub fn for_stories(&self) -> Self {
        Self {
            numbering: Rc::new(Numbering::default()),
            notes: Rc::new(Notes::default()),
            endnotes: Rc::new(Notes::default()),
            comments: Rc::new(Comments::default()),
            properties: std::sync::Arc::clone(&self.properties),
            earlier: EarlierPass::default(),
            ..*self
        }
    }
}

/// What an earlier pass of the layout found, which the next pass shows.
#[derive(Clone, Default)]
pub struct EarlierPass {
    /// The number of pages, which the body's `NUMPAGES` fields show.
    pub page_count: Option<i64>,
    /// The wraps of the drawings placed from a page or its margins, by page, which apply from
    /// the top of their page.
    pub wraps: PageWraps,
    /// The page number text of each bookmark, which `PAGEREF` fields show, or `None` before a
    /// pass found them.
    pub bookmarks: Option<BookmarkPages>,
    /// The paragraph number contexts of the bookmarks, which `REF` fields show.
    pub bookmark_numbers: BookmarkNumbers,
    /// Whether the `REF` fields keep their stored results, as in the passes that find the pages
    /// of the bookmarks that `PAGEREF` fields show.
    pub stored_number_refs: bool,
    /// The styled text of the pages, which sizes each page's header and footer while the body
    /// fills the pages, so that a `STYLEREF` field there has the text of its page.
    pub header_styles: HeaderStyles,
    /// The place of each footnote among the footnotes whose references stand on its page,
    /// which numbers the footnotes of a section that starts their numbers again on each page.
    pub note_places: NotePlaces,
    /// The drawings placed down from their paragraph whose anchor an earlier pass found on a
    /// later page than the paragraph's first line, which this pass places from the top of the
    /// paragraph's part on that page.
    pub later_anchors: LaterAnchors,
    /// The height of the footnotes of each page, which the floating drawings of the body that
    /// count from the body's area keep above its end.
    pub note_heights: NoteHeights,
}

/// The styled text of the pages of a layout pass, which `STYLEREF` fields in the headers and
/// footers of a later pass show while that pass sizes its pages.
#[derive(Clone, Default)]
pub struct HeaderStyles(Option<std::rc::Rc<style_refs::StyledPages>>);

/// A section with the headers and footers that it uses.
#[derive(Clone, Debug)]
pub struct SectionLayout {
    /// The page size and margins.
    pub section: Section,
    /// How the section starts.
    pub start: SectionStart,
    /// The index after the section's last block.
    pub end: usize,
    /// Whether the section sets its own first page number.
    pub restarts_numbers: bool,
    /// The headers.
    pub headers: Stories,
    /// The footers.
    pub footers: Stories,
    /// The borders around the pages.
    pub borders: Option<crate::body::PageBorders>,
    /// How its footnotes and endnotes are numbered and where they stand: its own elements
    /// over the settings.
    pub notes: ByNoteKind<NoteSetup>,
}

impl SectionLayout {
    /// A section of the page settings `section` that holds the `blocks` blocks of its flow,
    /// starts on a new page, sets no page number of its own, has no headers, footers or
    /// page borders and the notes of a document that sets nothing: the one section of a
    /// story, the area that the story fills.
    #[must_use]
    pub fn plain(section: &Section, blocks: usize) -> Self {
        Self {
            section: *section,
            start: SectionStart::NextPage,
            end: blocks,
            restarts_numbers: false,
            headers: Stories::default(),
            footers: Stories::default(),
            borders: None,
            notes: ByNoteKind::DEFAULT,
        }
    }
}

/// The section and the number of a page.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PageInfo {
    section: SectionIndex,
    number: i64,
    /// Whether the page is the first page of its section.
    first: bool,
}

/// The headers or the footers of a section. A missing one is blank. The sections that name
/// one part share it.
#[derive(Clone, Debug, Default)]
pub struct Stories {
    /// For most pages.
    pub default: Option<PartStory>,
    /// For the first page, when the section has a title page.
    pub first: Option<PartStory>,
    /// For even pages, when the settings ask for even and odd headers.
    pub even: Option<PartStory>,
}

/// A header or a footer: the blocks of its part, and the part's name, which names the story
/// among the stories of a pass ([`output::StoryKey::Part`]).
#[derive(Clone, Debug)]
pub struct PartStory {
    /// The name of its part, such as `word/header1.xml`.
    pub part: Rc<str>,
    /// Its blocks.
    pub blocks: Rc<[Block]>,
}

/// Which header and footer a page uses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
    First,
    Even,
    Default,
}

impl Stories {
    /// The header or footer of the pages of `kind`, or `None` when it is blank: missing, or
    /// a part without blocks.
    fn get(&self, kind: Kind) -> Option<&PartStory> {
        let story = match kind {
            Kind::First => &self.first,
            Kind::Even => &self.even,
            Kind::Default => &self.default,
        };
        story.as_ref().filter(|story| !story.blocks.is_empty())
    }
}

/// A paragraph's properties after the cascade, and its list label.
struct Resolved {
    props: ParaProps,
    run: RunProps,
    label: Option<Label>,
    /// How far the label starts before the start of the first line: its width when it ends
    /// there, half of it when it is centered there.
    label_shift: Length,
}

/// The page number text of each bookmark, by its name.
pub type BookmarkPages = std::collections::HashMap<String, String>;

/// The number context of each bookmark's paragraph.
pub type BookmarkNumbers = std::collections::HashMap<String, NumberContext>;

/// A band that a `wrapTopAndBottom` floating drawing or `notBeside` frame keeps free of text,
/// with its vertical extent (`top` to `bottom`) and horizontal extent (`left` to `right`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct Band {
    top: Length,
    bottom: Length,
    left: Length,
    right: Length,
}

/// The wrap box or band of a paragraph- or line-anchored drawing whose wrap reaches above its
/// anchor.
#[derive(Clone, Debug, PartialEq, Eq)]
enum UpwardShape {
    Band(Band),
    Square(floating::Square),
}

/// A paragraph- or line-anchored wrapped drawing whose wrap top reached above its anchor on an
/// earlier pass: its page, its floating-drawing ordinal, its pinned vertical position `y`, and
/// its wrap shape.
#[derive(Clone, Debug, PartialEq, Eq)]
struct UpwardWrap {
    page: usize,
    ordinal: usize,
    y: Length,
    wrap: UpwardShape,
}

/// Saved lengths of a [`PageWraps`] accumulator, for rewinding a trial pass.
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct WrapCounts {
    bands: usize,
    squares: usize,
    upward: usize,
    legacy_candidates: usize,
    legacy_reflow_para: usize,
    legacy_para_seq: usize,
}

/// The wraps of floating drawings that are placed from a page or its margins, with the index
/// of the page that each one lies on, plus paragraph- or line-anchored wraps that reach above
/// their anchor.
#[derive(Clone, Debug, Default)]
pub struct PageWraps {
    bands: Vec<(usize, Band)>,
    squares: Vec<(usize, floating::Square)>,
    /// Paragraph- or line-anchored wrapped drawings whose wrap reaches above their anchor, or
    /// (in compatibility modes below 15) whose pass-1 placement is pinned by a later
    /// reflow-causing wrap on the same page.
    upward: Vec<UpwardWrap>,
    /// Non-upward wrapped paragraph- or line-anchored body drawings placed in the current pass
    /// in compatibility modes below 15, paired with their paragraph order. Cleared between passes.
    legacy_candidates: Vec<(usize, UpwardWrap)>,
    /// Pages and paragraph orders that triggered a page reflow in the current pass in
    /// compatibility modes below 15. Cleared between passes.
    legacy_reflow_para: Vec<(usize, usize)>,
    /// Monotonic paragraph order counter within the current pass. Cleared between passes.
    legacy_para_seq: usize,
    /// The pages that the anchor paragraphs of the drawings of the bands and the squares do
    /// not come before.
    held: HeldPages,
}

/// For each band and each square of the page wraps, in their order: the page that the anchor
/// paragraph of its drawing does not come before, or 0.
#[derive(Clone, Debug, Default)]
struct HeldPages {
    /// The pages of the bands.
    bands: Vec<usize>,
    /// The pages of the squares.
    squares: Vec<usize>,
}

impl PageWraps {
    /// The numbers of the bands, squares and upward wraps found so far, which a mark keeps: a
    /// pass only adds to them (`keep_wrap` and upward-wrap recording).
    fn counts(&self) -> WrapCounts {
        WrapCounts {
            bands: self.bands.len(),
            squares: self.squares.len(),
            upward: self.upward.len(),
            legacy_candidates: self.legacy_candidates.len(),
            legacy_reflow_para: self.legacy_reflow_para.len(),
            legacy_para_seq: self.legacy_para_seq,
        }
    }

    /// Takes back the bands, squares and upward wraps found after `counts`.
    fn take_back(&mut self, counts: WrapCounts) {
        self.bands.truncate(counts.bands);
        self.squares.truncate(counts.squares);
        self.upward.truncate(counts.upward);
        self.legacy_candidates.truncate(counts.legacy_candidates);
        self.legacy_reflow_para.truncate(counts.legacy_reflow_para);
        self.legacy_para_seq = counts.legacy_para_seq;
    }

    /// Allocates the next body paragraph order for tracking same-pass reflow pinning in
    /// compatibility modes below 15.
    fn next_legacy_para(&mut self) -> usize {
        self.legacy_para_seq += 1;
        self.legacy_para_seq
    }

    /// Notes that a reflow-causing wrap (a new page/margin early wrap or an upward wrap) was
    /// placed on `page` in paragraph `para_order` in compatibility mode below 15, promoting any
    /// earlier or same-paragraph wrapped body anchor on that page into `upward`.
    fn note_legacy_reflow(&mut self, page: usize, para_order: usize) {
        self.legacy_reflow_para.push((page, para_order));
        for (cand_para, entry) in &self.legacy_candidates {
            if entry.page == page
                && *cand_para <= para_order
                && !self.upward.iter().any(|u| u.ordinal == entry.ordinal)
            {
                self.upward.push(entry.clone());
            }
        }
    }

    /// Records a non-upward wrapped body anchor in compatibility mode below 15: pins it at once
    /// if the same paragraph already triggered a reflow on `entry.page`, or holds it for later
    /// reflows on that page.
    fn note_legacy_candidate(&mut self, para_order: usize, entry: UpwardWrap) {
        if self
            .legacy_reflow_para
            .iter()
            .any(|&(p, o)| p == entry.page && o >= para_order)
        {
            if !self.upward.iter().any(|u| u.ordinal == entry.ordinal) {
                self.upward.push(entry);
            }
        } else {
            self.legacy_candidates.push((para_order, entry));
        }
    }

    /// Whether no drawing placed from a page or its margins, or reaching above its anchor, has a
    /// wrap.
    pub fn is_empty(&self) -> bool {
        self.bands.is_empty() && self.squares.is_empty() && self.upward.is_empty()
    }

    /// The wraps for the pass after one that started its pages with these wraps and found
    /// `found`, or `None` when it found every drawing on the page whose text its wrap moved.
    /// The next pass takes the pages that this one found, and a drawing that came to a later
    /// page than its wrap's page holds its anchor paragraph on that page or after it.
    #[must_use]
    pub fn after(&self, found: &Self) -> Option<Self> {
        let given: Vec<usize> = self.pages().collect();
        let pages: Vec<usize> = found.pages().collect();
        let same_drawings =
            self.bands.len() == found.bands.len() && self.squares.len() == found.squares.len();
        let early_moved = same_drawings && given != pages;
        let upward_moved = self.upward != found.upward;
        if !early_moved && !upward_moved {
            return None;
        }
        let mut next = found.clone();
        next.legacy_candidates.clear();
        next.legacy_reflow_para.clear();
        next.legacy_para_seq = 0;
        if early_moved {
            let (bands, squares) = pages.split_at(self.bands.len());
            let (given_bands, given_squares) = given.split_at(self.bands.len());
            next.held = HeldPages {
                bands: holds(&self.held.bands, given_bands, bands),
                squares: holds(&self.held.squares, given_squares, squares),
            };
        } else {
            next.held = self.held.clone();
        }
        Some(next)
    }

    /// The page of each band and then of each square.
    fn pages(&self) -> impl Iterator<Item = usize> + '_ {
        let bands = self.bands.iter().map(|(page, _)| *page);
        bands.chain(self.squares.iter().map(|(page, _)| *page))
    }
}

/// The pages that the anchors of drawings are held on: for each drawing the page `found` where
/// it lies after its wrap's page `given`, or else the page that `held` it on before.
fn holds(held: &[usize], given: &[usize], found: &[usize]) -> Vec<usize> {
    let before = |at: usize| held.get(at).copied().unwrap_or(0);
    given
        .iter()
        .zip(found)
        .enumerate()
        .map(|(at, (given, found))| {
            if found > given {
                before(at).max(*found)
            } else {
                before(at)
            }
        })
        .collect()
}

/// The story that a placed line belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LineStory {
    /// The main text of the document.
    Body,
    /// A page's header.
    Header,
    /// A page's footer.
    Footer,
    /// A footnote at the bottom of a page.
    Footnote,
    /// The text of a text box or a shape.
    TextBox,
}

/// The part of its story that a placed line belongs to, for the text map, which reads each part
/// as a story of its own (**Story part**). The layout does not read it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StoryPart {
    /// The story's own text.
    #[default]
    Own,
    /// The endnotes, which flow in the body after its text.
    Endnotes,
    /// The content of a frame of the body, by the number of its layout in the pass.
    Frame(u32),
    /// The text of one text box or shape, by the number of its layout in the pass.
    TextBox(u32),
}

/// Where in its story a placed line lies.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LineArea {
    /// Outside tables.
    OutsideTables,
    /// In a table cell. A row moves its cells' lines with their items.
    TableCell,
}

impl LineArea {
    /// The area of a line that the page breaks (`paginate`), outside tables, or else in a
    /// table cell.
    pub(crate) const fn of(paginate: bool) -> Self {
        if paginate {
            Self::OutsideTables
        } else {
            Self::TableCell
        }
    }
}

/// Which places and parts of a line the page rounds to the device's dots to put its baseline
/// (**Baseline form**). The parts that round are lengths of the line's box: its height, the
/// paragraph's own space before that it holds, its ascent and its descent, and the parts above
/// and below its baseline.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BaselineForm {
    /// Single spacing whose box's height rounds up: the exact bottom rounds, and the baseline
    /// sits the rounded descent above it.
    SingleBottom,
    /// Single spacing whose box's height rounds down: the box's top rounds, and the baseline
    /// sits below it where the device's quirk `SingleBaseline` puts it in the rounded height.
    SingleTop,
    /// A line whose at-least minimum sets its height and whose box rounds down: the box's top
    /// and its height round, and the baseline sits the rounded part below the baseline above
    /// that bottom.
    AtLeastBox,
    /// A line of exact spacing whose box rounds down, under the quirk `ExactBaseline::BoxForms`:
    /// the box's top rounds, and the baseline sits below it as in the rounded-down box of a
    /// single line.
    ExactBox,
    /// A line of exact spacing, or one whose at-least minimum sets its height: the exact bottom
    /// rounds, and the baseline sits the rounded part below the baseline above it.
    Bottom,
    /// A line of exact spacing that ends its paragraph outside table cells, with the space
    /// after following it, under `ExactSpacedBottom::PartsRounded`: the exact top and the
    /// exact height round each on their own, and the baseline sits the rounded part below the
    /// baseline above their sum.
    SpacedBottom,
    /// A box that holds its paragraph's spaces where the descent goes above the extra spacing,
    /// or that holds the space after of a line whose at-least minimum sets its height: the
    /// box's top rounds, and the baseline sits the larger of the rounded part above it and the
    /// rounded descent part below that top.
    HeldSpaces,
    /// Multiple spacing below the paragraph's own space before: the box's top, the space before
    /// and the baseline's offset each round.
    SpaceAndAscent,
    /// A baseline whole dots below the top: the top rounds.
    WholeDotsBelowTop,
    /// A single line in the steps of a line grid under `GridSingleLine::PartsRounded`: the top
    /// rounds, a half up the page, and the baseline lies whole dots below it.
    GridSteps,
    /// A centered line of multiple spacing whose middle rounds
    /// (`CenteredMultiple::MiddleRounded`): the box's top, the space before and the line's
    /// ascent less the middle of its face's win line, or the box's height, the part below its
    /// single line and half the win line, each round, and the baseline lies half the face's
    /// pixel line below that middle.
    CenteredMiddle,
    /// A line below single spacing under `LowMultipleBaseline::HeightFraction`: the top rounds,
    /// and the baseline less half the part of a dot of the line's height rounds below it, where
    /// that part is less than half a dot; otherwise the exact bottom rounds, and the part below
    /// the baseline rounds above it.
    HeightFraction,
    /// The exact baseline rounds once.
    Baseline,
}

/// Whether the block `next` is a table that goes on the floating table `table` as more rows
/// of it: Word joins floating tables with the same properties and grid that follow each
/// other directly.
fn goes_on(table: &Table, next: Option<&Block>) -> bool {
    let floats = table.props.placement.is_some();
    matches!(next, Some(Block::Table(next)) if floats && next.props.lays_out_as(&table.props) && next.grid == table.grid)
}

/// The blocks of a story after a point, as the chunks of [`Layout::blocks`]: runs of
/// paragraphs, and tables, each a chunk of its own. A chain of kept paragraphs or table rows
/// looks into them.
#[derive(Clone, Copy, Default)]
pub(super) struct Rest<'b>(&'b [&'b [Block]]);

impl<'b> Rest<'b> {
    /// Whether no block comes after the point: the point is the end of the story.
    pub(super) const fn is_end(self) -> bool {
        self.0.is_empty()
    }

    /// The table that comes first, and the blocks after it.
    pub(super) fn table(self) -> Option<(&'b Table, Self)> {
        let (first, rest) = self.0.split_first()?;
        match first.first() {
            Some(Block::Table(table)) => Some((table, Self(rest))),
            _ => None,
        }
    }

    /// The paragraphs that come first, none when a table comes first, and the blocks after
    /// them.
    pub(super) fn paragraphs(self) -> (Vec<&'b crate::body::Paragraph>, Self) {
        let paragraph = |block: &'b Block| match block {
            Block::Paragraph(paragraph) => Some(paragraph),
            Block::Table(_) => None,
        };
        match self.0.split_first() {
            Some((first, rest)) if self.table().is_none() => {
                (first.iter().filter_map(paragraph).collect(), Self(rest))
            }
            _ => (Vec::new(), self),
        }
    }
}

/// The parts of the left edge of an upright table cell's text, from which its lines count
/// their start: the x of the table's leftmost grid line, the x of the grid line on the cell's
/// left, and the part of the text edge that lies inside the cell's edge, its left margin.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CellEdgeParts {
    /// The x of the table's leftmost grid line.
    pub table: Length,
    /// The x of the grid line on the cell's left.
    pub grid: Length,
    /// The part of the text edge inside the cell's edge: the cell's left margin.
    pub inner: Length,
    /// The outer edge of a centered table that a target keeps in fixed-point points
    /// (`CenteredTablePlace::FixedPointHalf`), from which the text edge then counts its parts.
    pub outer: Option<crate::grid::FixedPlace>,
}

/// How a centered or a right-aligned line that starts on a dot found its start: the dot of its
/// start at its indent, the dot where its written text ends from there, the dot of its space's
/// right edge, and the space's exact place, its indent past the column's left edge and its
/// width.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AlignedParts {
    /// The dot of the line's start at its indent.
    pub start: Length,
    /// The dot where its written text ends when it is drawn from `start`.
    pub end: Length,
    /// The dot of its space's right edge.
    pub edge: Length,
    /// The space's indent past the column's left edge.
    pub indent: Length,
    /// The space's width.
    pub width: Length,
}

/// The table cell that a placed line lies in, each number from 1.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CellPlace {
    /// The table, in the order in which the layout of its story starts its tables, nested
    /// tables too. A header or a footer counts its tables on each page anew.
    pub table: usize,
    /// The row of the table.
    pub row: usize,
    /// The first grid column that the cell covers.
    pub column: usize,
}

/// The widths of the grid columns that the layout gave one table of the body, nested tables
/// too, for a tool that compares them with the grid that the file saved.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TableColumns {
    /// The table's number, as [`CellPlace::table`] counts it.
    pub table: usize,
    /// The widths of its grid columns, from its leading edge.
    pub widths: Vec<Length>,
}

/// Where the items of a placed line lie among the items of its page while the layout runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FirstItem {
    /// Its first item has this index among the items of its page.
    At(usize),
    /// A carried line: its items join the page later as a whole. It is a line that a row that
    /// splits carries to the next column or page, or a line of a footnote or a text box. No
    /// move of the page's items applies to it.
    Carried,
}

impl FirstItem {
    /// The index of the first item, or `None` for a carried line.
    #[must_use]
    pub const fn index(self) -> Option<usize> {
        match self {
            Self::At(index) => Some(index),
            Self::Carried => None,
        }
    }
}

/// What a line records of a glyph that it draws: not a space, which it places but draws
/// nothing for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DrawnGlyph {
    /// The length that the run's character spacing adds to the glyph's advance.
    pub spacing: Length,
    /// The unrounded place from which the device's steps place the glyph, on the page.
    pub x: Length,
    /// The place on the page that the line's steps give the glyph, before the PDF writer
    /// moves it with its text object to that object's written start.
    pub place: Length,
    /// The spaces, stretched or not, that the line places between the drawn glyph before and
    /// this one.
    pub spaces: u32,
    /// Where the device's steps started again since the drawn glyph before.
    pub started: StepsStart,
    /// What the edge check of the device's steps found at the glyph, when the steps placed it
    /// from the glyph before (`EdgeSteps::take_checked`). The steps of right-to-left text run
    /// in reading order, from the right, and their check counts edges and moves in that order.
    pub checked: Option<crate::grid::EdgeCheck>,
    /// Why the PDF writer started its first text object since the drawn glyph before, at a
    /// space before this glyph or at the glyph, if it started one. Only the tests read it.
    pub object_start: Option<crate::grid::ObjectStart>,
    /// The place that the device's steps rounded to the glyph's dot, when they started again at
    /// the glyph (`EdgeSteps::take_start_place`): its exact place, or for a glyph that starts a
    /// segment the place that the segment rule counts. Only the tests read it.
    pub start_place: Option<Length>,
}

/// Where the device's steps started again between the drawn glyph before and a drawn glyph, as
/// they do at a line's start, after a tab or a gap, and at the end of a segment
/// (`EdgeSteps::started`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StepsStart {
    /// They did not, or the target keeps the PDF writer's steps.
    #[default]
    Stepped,
    /// At the drawn glyph.
    Glyph,
    /// At one of the spaces before it: the n-th, from 1 for the first after the drawn glyph
    /// before.
    Space(u32),
}

/// A line of the body, a header, a footer, a footnote or a text box that the layout placed,
/// outside tables or in a table cell, with the exact values before the page rounds its
/// baseline. Every line keeps one, which table rows move with its items.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlacedLine {
    /// The paragraph whose line it is, which a text block finds its pages by.
    pub paragraph: ParagraphId,
    /// The index of its page.
    pub page: usize,
    /// The story that it belongs to.
    pub story: LineStory,
    /// The part of its story that it belongs to.
    pub part: StoryPart,
    /// Whether it lies outside tables or in a table cell.
    pub area: LineArea,
    /// The table cell that it lies in, when it lies in one.
    pub cell: Option<CellPlace>,
    /// Where its items lie among the items of its page, while the layout runs.
    pub item: FirstItem,
    /// Its exact top on the page.
    pub top: Length,
    /// What its exact top lies past `top`, in 1/512 of a half-EMU: the height rest that the
    /// layout's cursor carried there, and the twips rest where the cursor keeps one there. A
    /// table cell that moves its lines for its vertical alignment keeps the rests of their place
    /// before the move.
    pub top_rests: (i64, Option<i64>),
    /// The height that the next line starts below its top.
    pub height: Length,
    /// What its exact height lies past `height`, in 1/512 of a half-EMU, and its twips rest
    /// where its height is a length of whole twips or of whole 1/4096 pt.
    pub height_rests: (i64, Option<i64>),
    /// The offset of its baseline from its top.
    pub baseline: Length,
    /// The exact offset of its baseline from its top, before the page rounds its places and
    /// parts to the device's dots.
    pub unrounded_baseline: Length,
    /// Which places and parts of the line the page rounded to put its baseline on the device's
    /// dots.
    pub baseline_form: BaselineForm,
    /// How far its text goes above the baseline.
    pub ascent: Length,
    /// How far its text goes below the baseline.
    pub descent: Length,
    /// The line spacing of its paragraph.
    pub spacing: crate::props::LineSpacing,
    /// The index of the line in its paragraph, 0 for the first.
    pub index: usize,
    /// Whether it is the last line of its paragraph.
    pub last: bool,
    /// Whether its paragraph's space after follows it: a last line whose space after the next
    /// paragraph does not remove.
    pub spaced: bool,
    /// The paragraph's own space before above it, on a first line that keeps it.
    pub before: Length,
    /// The decision that kept its last word on it.
    pub kept: Option<crate::lines::Fit>,
    /// For a line that ends before a word that does not fit, the decision that moved the word
    /// to the next line.
    pub wrapped: Option<crate::lines::Fit>,
    /// Whether its paragraph is justified.
    pub justified: bool,
    /// How the line itself is aligned, after the last line of a justified paragraph and
    /// right-to-left text change its paragraph's alignment.
    pub alignment: crate::props::Alignment,
    /// What lies before each glyph that the line draws, in the order of drawing.
    pub steps: Vec<crate::lines::Step>,
    /// What the line records of each glyph that it draws, in the order of drawing.
    pub drawn: Vec<DrawnGlyph>,
    /// How much each space that stretches gains on the line, below 0 when the spaces shrink.
    pub spread: Length,
    /// The free space that the line spreads over its stretched spaces, before each space's
    /// share of it goes toward zero to a whole half-EMU ([`Self::spread`]); 0 when its spaces
    /// neither stretch nor shrink.
    pub free_space: Length,
    /// What rounding to whole half-EMUs took from the advances of the line's glyphs from its
    /// last tab to its last visible piece, in thousandths of a half-EMU to the nearest one: the
    /// part of the free space that the rounded advances leave out. 0 when its spaces neither
    /// stretch nor shrink.
    pub free_rounding_thousandths: i64,
    /// The dot of the edge that the line counts its start from: its column's left edge on the
    /// nearest dot, or the wrap edge of a drawing on its left.
    pub edge: Length,
    /// The exact left edge of the line's column before it goes to a dot: the left edge of the
    /// page's column, or for a line of a table cell the left edge of the cell's text, its left
    /// margin and the table's place past the column included.
    pub column_left: Length,
    /// The left edge of the page's column that holds the line's column.
    pub column_origin: Length,
    /// For a line of an upright table cell, the parts of the cell's text edge.
    pub cell_edge: Option<CellEdgeParts>,
    /// For a centered or a right-aligned line that starts on a dot, how it found its start.
    pub aligned: Option<AlignedParts>,
    /// When its page prints with the markup area, the scale of that print in steps of 1/300
    /// (`MARKUP_SCALE_STEPS`). Its top and baseline are then those of the printed page, and
    /// its heights those of the layout.
    pub markup_scale: Option<i64>,
    /// The text that it shows, with the edges of its clusters on the page.
    pub text: LineText,
}

impl PlacedLine {
    /// Moves the line `dy` down the page: its top, or for a turned line the place of its frame
    /// on the page, whose own places stay.
    pub(crate) fn move_down(&mut self, dy: Length) {
        match &mut self.text.turn {
            Some(turn) => turn.to.1 += dy,
            None => self.top += dy,
        }
    }

    /// Moves the line `dx` right across the page: its column edges and clusters, or for a turned
    /// line the place of its frame on the page.
    pub(crate) fn move_right(&mut self, dx: Length) {
        if dx == Length::ZERO {
            return;
        }
        self.edge += dx;
        self.column_left += dx;
        self.column_origin += dx;
        if let Some(turn) = &mut self.text.turn {
            turn.to.0 += dx;
        } else {
            self.text.left += dx;
            for cluster in &mut self.text.clusters {
                cluster.left += dx;
                cluster.right += dx;
            }
        }
    }

    /// Whether the line lies upright on the page, and not in a frame that turned onto it.
    pub(crate) const fn upright(&self) -> bool {
        self.text.turn.is_none()
    }
}

/// The last widths of each table number of `starts`, in the order of the numbers.
fn last_columns(starts: Vec<TableColumns>) -> Vec<TableColumns> {
    let mut last = std::collections::BTreeMap::new();
    for columns in starts {
        last.insert(columns.table, columns);
    }
    last.into_values().collect()
}

/// What a layout pass gives: the pages, and what a later pass needs from them.
pub struct Pass {
    /// The pages.
    pub list: DisplayList,
    /// The wraps of the drawings placed from a page or its margins.
    pub wraps: PageWraps,
    /// The page number text of the bookmarks.
    pub bookmarks: BookmarkPages,
    /// The paragraph numbers of the bookmarks.
    pub bookmark_numbers: BookmarkNumbers,
    /// The styled text of the pages.
    pub styles: HeaderStyles,
    /// The place of each footnote on its page.
    pub note_places: NotePlaces,
    /// The drawings placed down from their paragraph whose anchor stood on a later page than
    /// the paragraph's first line.
    pub later_anchors: LaterAnchors,
    /// The height of the footnotes of each page.
    pub note_heights: NoteHeights,
    /// Whether a floating drawing of the body that counts from the body's area took other
    /// footnotes than its page holds, so that a next pass places it with those of this pass.
    pub notes_missed: bool,
    /// The lines outside tables, in the order of placing.
    pub lines: Vec<PlacedLine>,
    /// The widths of the grid columns of the body's tables, the last that the pass gave each.
    pub tables: Vec<TableColumns>,
    /// The warnings of the pass and of its stories.
    pub warnings: crate::Warnings,
    /// The fonts that the pass and its stories drew in another way than the runs ask.
    pub font_notes: crate::text::FontNotes,
}

/// How a line that holds nothing meets the floating drawings of its story.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EmptyLines {
    /// It goes below or beside them, as other lines do.
    Wrap,
    /// It stays where it is, as in a header of more than one paragraph.
    Stay,
}

/// The kind of a story that a layout fills on the body's pages. It decides how the story's
/// lines meet the drawings, which way they round, whether frames apply in it and how its line
/// records are named. The kinds whose warnings count once hold the name of their story
/// ([`Self::key`]). The body is no story.
#[derive(Clone, Debug, PartialEq, Eq)]
enum StoryKind {
    /// A page's header.
    Header {
        /// Whether the header holds more than one block.
        several_blocks: bool,
        /// The name of its part.
        part: Rc<str>,
    },
    /// A page's footer.
    Footer {
        /// The name of its part.
        part: Rc<str>,
    },
    /// A footnote.
    Footnote {
        /// Its ID in the footnotes part.
        id: NoteId,
    },
    /// A separator of the footnotes: above a page's footnotes, or above the part of a
    /// footnote that goes on.
    NoteSeparator(notes::Separator),
    /// The endnotes' continuation separator, at the top of a page that the endnotes go on to.
    EndnoteContinuation,
    /// The content of a frame.
    Frame {
        /// The frame's box on the page, outside which its inline pictures show nothing on a
        /// target that cuts them; `None` while the frame is measured.
        inside: Option<f_office_units::Edges<Length>>,
    },
    /// The text of a text box or a shape.
    TextBox {
        /// The color of its text whose own color is automatic or missing, from the shape's
        /// style, `None` when the style gives none.
        text_color: Option<[u8; 3]>,
        /// The turn that takes the frame of a text box whose body turns its text onto the
        /// page, whose lines are then a turned frame's, with how its glyphs lie there, or
        /// `None` for upright text.
        turn: Option<(f_office_paint::Turn, TurnedGlyphs)>,
        /// Which rules its lines take.
        box_text: crate::floating::BoxText,
        /// The box's text area on the page, inside its insets and its line, outside which its
        /// inline pictures show nothing on a target that cuts them; `None` while the text is
        /// measured, for the text of a SmartArt graphic's shape, and for text turned onto the
        /// page.
        inside: Option<f_office_units::Edges<Length>>,
    },
    /// The text of a comment balloon.
    Balloon,
}

impl StoryKind {
    /// How a line that holds nothing meets the floating drawings: in a header of more than
    /// one block it stays where it is.
    const fn empty_lines(&self) -> EmptyLines {
        match self {
            Self::Header {
                several_blocks: true,
                ..
            } => EmptyLines::Stay,
            _ => EmptyLines::Wrap,
        }
    }

    /// Which way a position of a line halfway between two device dots rounds: up the page in
    /// a header, and in a footer down the page except a line's bottom, which the device's quirk
    /// `FooterHalves` decides.
    const fn ties(&self) -> line::height::Ties {
        match self {
            Self::Header { .. } => line::height::Ties::TowardTop,
            Self::Footer { .. } => line::height::Ties::Footer,
            _ => line::height::Ties::AwayFromTop,
        }
    }

    /// The name of the story among the stories of a pass, for the kinds whose warnings count
    /// as those of one layout of the story, whatever the number of its layouts
    /// ([`output::PassOutput::join_story_warnings`]): a header or a footer, which the layout
    /// lays out on each page that shows it and to measure it, by its part; a footnote, laid
    /// out to measure it, to find its breaks and to place it, whole or in parts, by its ID; and
    /// a separator, laid out on each page with footnotes, whose height each line that brings a
    /// page's first footnotes asks, by its kind. `None` for the endnotes' continuation
    /// separator, laid out once on each page that it starts, a frame, a text box and a
    /// balloon, whose layouts each add their warnings.
    fn key(&self) -> Option<output::StoryKey> {
        match self {
            Self::Header { part, .. } | Self::Footer { part } => {
                Some(output::StoryKey::Part(Rc::clone(part)))
            }
            Self::Footnote { id } => Some(output::StoryKey::Footnote(*id)),
            Self::NoteSeparator(separator) => Some(output::StoryKey::Separator(*separator)),
            Self::EndnoteContinuation
            | Self::Frame { .. }
            | Self::TextBox { .. }
            | Self::Balloon => None,
        }
    }

    /// The part of its story that a layout of the story numbered `number` gives the lines that
    /// it places: a frame and a text box are each a part of their own; `None` for the kinds
    /// whose lines keep their own part.
    const fn part(&self, number: u32) -> Option<StoryPart> {
        match self {
            Self::Frame { .. } => Some(StoryPart::Frame(number)),
            Self::TextBox { .. } => Some(StoryPart::TextBox(number)),
            _ => None,
        }
    }

    /// Whether the story ends below the space after of its last paragraph: a frame is as tall
    /// as its lines and that space.
    const fn ends_below_space_after(&self) -> bool {
        matches!(self, Self::Frame { .. })
    }

    /// Whether frames apply in the story: not inside a frame or a text box.
    const fn holds_frames(&self) -> bool {
        !matches!(self, Self::Frame { .. } | Self::TextBox { .. })
    }

    /// The story of the records of the story's lines, for the kinds whose lines are recorded.
    /// The lines of a frame are recorded as lines of the body; a header, a footer
    /// or a footnote that holds the frame takes them as its own lines.
    const fn line_story(&self) -> Option<LineStory> {
        match self {
            Self::Header { .. } => Some(LineStory::Header),
            Self::Footer { .. } => Some(LineStory::Footer),
            Self::Footnote { .. } => Some(LineStory::Footnote),
            Self::TextBox { .. } => Some(LineStory::TextBox),
            Self::Frame { .. } => Some(LineStory::Body),
            Self::NoteSeparator(_) | Self::EndnoteContinuation | Self::Balloon => None,
        }
    }
}

/// The numbers that the fields of a story show.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct StoryNumbers {
    /// The page number, which `PAGE` shows.
    page: i64,
    /// The page count, which `NUMPAGES` shows.
    pages: i64,
    /// The label of the footnote that the story belongs to, which a footnote mark shows.
    note: Option<NoteLabel>,
}

impl StoryNumbers {
    /// Page 1 of 1 and no footnote: the numbers of a story laid out apart from the page
    /// count, such as a footnote's separator, a balloon, or a header measured for its height.
    const PAGE_ONE: Self = Self::on_page(1, 1);

    /// Page `page` of `pages`, and no footnote.
    const fn on_page(page: i64, pages: i64) -> Self {
        Self {
            page,
            pages,
            note: None,
        }
    }

    /// The numbers of the footnote whose mark shows `label`, on page 1 of 1.
    const fn of_note(label: NoteLabel) -> Self {
        Self {
            note: Some(label),
            ..Self::PAGE_ONE
        }
    }
}

/// A story that a layout fills: its kind and the numbers that its fields show.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Story {
    kind: StoryKind,
    numbers: StoryNumbers,
}

/// The twips rest of the cursor: the part of a half-EMU, in 1/512 of one, by which the lengths
/// of whole twips from the body's top on the page down to the place `at`, each in the target's
/// unit (`TwipLengthUnit`), lie past their exact sum (`line::height::twips_rest`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct TwipsRest {
    at: Length,
    rest: i64,
}

/// The rests of a table cell laid out in a row: the twips rest at its bottom where it is known
/// (`end`), the twips rest at its text top (`top`) and the height rest there (`top_height`),
/// and, where its content sets its bottom, the height rest there (`end_height`) and the sum of
/// the height rest and the twips rest there (`bottom`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct CellRests {
    end: Option<TwipsRest>,
    top: Option<i64>,
    top_height: i64,
    end_height: Option<i64>,
    bottom: Option<i64>,
}

/// The rests of a place of a table row that the rows carry, `at`: its twips rest (`twips`)
/// and its height rest (`height`). At a row's end, the height rest is that of the cell whose
/// content sets the end, and 0 where the row's height rule sets it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct RowRests {
    at: Length,
    twips: i64,
    height: i64,
}

/// The rests that the text top of a table cell takes where the cell moves down for its
/// vertical alignment: the twips rest that it had there before the move (`twips`), and the
/// height rest of the move (`rest`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct MovedTop {
    twips: Option<i64>,
    rest: i64,
}

/// The twips rests of the table row being laid out, each with the place that it belongs to:
/// the text top of its cells below its top border, the rests of the cell laid out last
/// (`cell`), and the row's end, with their height rests; the rests that the cell being laid out takes at a text top
/// that its vertical alignment moved (`moved`); and whether the cell being laid out carries
/// its text top's rest from its row (`carried`), where a cell that starts its rest anew leaves
/// it `false`.
#[derive(Clone, Copy, Default)]
struct TableTwips {
    row: Option<RowRests>,
    cell: CellRests,
    row_end: Option<RowRests>,
    moved: Option<MovedTop>,
    carried: bool,
}

impl Layout<'_> {
    /// Moves the cursor to the place `y`, where a new exact sum of line heights starts: its
    /// height rest is 0, and it has no twips rest.
    fn move_to(&mut self, y: Length) {
        self.y = y;
        self.y_rest = 0;
        self.y_twips = None;
    }

    /// How a line that holds nothing meets the floating drawings: as the story's kind says
    /// ([`StoryKind::empty_lines`]), and in the body as other lines.
    fn empty_lines(&self) -> EmptyLines {
        self.story
            .as_ref()
            .map_or(EmptyLines::Wrap, |story| story.kind.empty_lines())
    }

    /// Which way a position of a line halfway between two device dots rounds: down the frame of
    /// a turned cell whose lines lie on the page's dots, else as
    /// the story's kind says ([`StoryKind::ties`]), and down the page in the body, with the
    /// rule of a single line's top of a table cell there whose text top starts its twips rest
    /// anew.
    fn ties(&self) -> line::height::Ties {
        if matches!(self.column.within, Within::TurnedFrame(true, ..)) {
            return line::height::Ties::TurnedFrame;
        }
        let ties = self
            .story
            .as_ref()
            .map_or(line::height::Ties::AwayFromTop, |story| story.kind.ties());
        if ties == line::height::Ties::AwayFromTop
            && self.column.cell.is_some()
            && !self.table_twips.carried
        {
            return line::height::Ties::Cell;
        }
        ties
    }

    /// Where the box of a line whose top is `top`, with `space` above it in its box, lies on
    /// its page: at the body's top on the page, which a line of the body or of a table row at
    /// the page's top reaches, or lower. A line of another story is never there.
    fn box_top(&self, (top, space): (Length, line::height::SpaceBefore)) -> line::height::BoxTop {
        if self.story.is_none() && top - space.length() == self.page_top(self.output.pages.len()) {
            line::height::BoxTop::PageTop
        } else {
            line::height::BoxTop::Lower
        }
    }

    /// Whether frames apply in this layout: in the body, and in a story whose kind holds them
    /// ([`StoryKind::holds_frames`]).
    fn holds_frames(&self) -> bool {
        self.story
            .as_ref()
            .is_none_or(|story| story.kind.holds_frames())
    }

    /// The page number and the page count that the fields of a story show; `None` in the
    /// body, which counts its own pages.
    fn story_pages(&self) -> Option<(i64, i64)> {
        self.story
            .as_ref()
            .map(|story| (story.numbers.page, story.numbers.pages))
    }

    /// The label of the footnote that this layout fills, if it fills one.
    fn footnote_label(&self) -> Option<NoteLabel> {
        self.story.as_ref().and_then(|story| story.numbers.note)
    }

    /// The page number and the page count of this layout, which a story inside it, such as a
    /// frame or a text box, shows: those of this story, or in the body the page's number as
    /// both the number and the count. They hold no footnote number.
    fn inner_numbers(&self) -> StoryNumbers {
        let (page, pages) = self.story_pages().unwrap_or_else(|| {
            let number = self.page_number(self.output.pages.len());
            (number, number)
        });
        StoryNumbers::on_page(page, pages)
    }

    /// Warns that F-Office does not apply `feature` where the part `part` sets it
    /// (**Feature not supported**): the one place where the layout gives such a warning.
    fn warn_of_feature(&mut self, feature: crate::Feature, part: &str) {
        self.output
            .warnings
            .push(crate::Warning::FeatureNotSupported {
                part: f_office_warnings::Name::new(part),
                feature,
            });
    }
}

impl<'a> Layout<'a> {
    /// The name of the part that sets a setting, which acts also where no layer of the cascade
    /// sets it: `part`, the part of the layer that sets it ([`crate::props::SetIn`]), or the
    /// main document's where its default acts, such as hanging punctuation
    /// (`w:overflowPunct`, on by default).
    fn setting_part<'p>(&self, part: Option<&'p str>) -> &'p str
    where
        'a: 'p,
    {
        part.unwrap_or(self.context.main)
    }
}

/// Whether the chain of kept blocks of the block before the paragraphs about to be laid out
/// goes on into the first of them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum TableChain {
    /// The block before is not a table of the body whose last row is kept.
    #[default]
    Ends,
    /// The block before is a table of the body whose last row is kept, so the first
    /// paragraph after it goes on that table's chain.
    GoesOn,
}

/// Lays out a body into pages.
pub struct Layout<'a> {
    /// The context of the pass, which this layout reads.
    context: &'a Context<'a>,
    /// The context of the stories that this layout makes ([`Context::for_stories`]).
    stories: &'a Context<'a>,
    styles: &'a Styles,
    settings: &'a Settings,
    numbering: Numbering,
    /// The target's layout device, on which page sizes, column edges, baselines and drawn
    /// lines land.
    device: crate::grid::Device,
    /// The sections of the flow: the body's, which it borrows from its pass, or the one section
    /// of a story, its own area. `section_index` names the current one.
    sections: Cow<'a, Sections<SectionLayout>>,
    /// The page settings of the current section, with the side margins of the page being
    /// filled.
    section: Section,
    shaper: Shaper<'a>,
    /// The items of the page being filled, with the table border lines and the cell clips
    /// among them ([`page_items::PageItems`]).
    items: page_items::PageItems,
    /// The places among `items` at which the fills of cells that continue merged regions went
    /// under the content of earlier rows, in order, so that going back to a row mark takes
    /// them out again.
    y: Length,
    /// The height rest of the cursor: the part of a half-EMU, in 1/`REST_PARTS` of one, by
    /// which the exact sum of the heights of lines held in whole 1/4096 pt lies past `y`
    /// (`line::height::LineBox::rest`). A move to a new place starts a new sum
    /// ([`Self::move_to`]).
    y_rest: i64,
    /// The cursor's twips rest and the place that it belongs to (`line::Layout::twips_here`).
    /// A move to a new place ends it ([`Self::move_to`]).
    y_twips: Option<TwipsRest>,
    /// The twips rests that a body table carries from row to row (`table::rows`).
    table_twips: TableTwips,
    previous: Option<Previous>,
    /// Where the body starts on a page of each kind: first, even, default.
    tops: [Length; 3],
    /// Where the body ends on a page of each kind.
    bottoms: [Length; 3],
    /// The story that this layout fills, or `None` for the body.
    story: Option<Story>,
    /// The part that holds the body, which the warnings of the body's sections name: set when
    /// the body's layout runs ([`Self::run_with_wraps`]), and empty in a story's layout.
    body_part: std::rc::Rc<f_office_warnings::Name>,
    /// What this layout adds to its pass and gives back.
    output: output::PassOutput,
    /// The footnotes of the page being filled.
    page_notes: notes::PageNotes,
    /// The label of the endnote being laid out. Endnotes flow in the body, after its text.
    endnote: Option<NoteLabel>,
    /// The comments, and where the body's lines put their anchors.
    comment_markup: markup::CommentMarkup<'a>,
    /// For a story, such as a header or a text box, the section of the page that it is on,
    /// whose height and margins place its floating drawings. A story itself runs on an
    /// endless page.
    page: Option<Section>,
    /// For a story on a page, the height of the page's footnotes, which its floating drawings
    /// without wrapping keep above the end of the page's margins.
    story_notes: Length,
    /// The page whose header or footer is being laid out.
    story_page: Option<usize>,
    /// The styled text of the body's pages and the page of the header or footer that this
    /// layout fills, for its `STYLEREF` fields.
    style_page: Option<(std::rc::Rc<style_refs::StyledPages>, usize)>,
    /// The paragraph being measured, for relative number references.
    number_context: Option<NumberContext>,
    /// The bands of the page being filled that floating drawings keep free of text, with their
    /// vertical and horizontal extents.
    bands: Vec<Band>,
    /// The measured texts whose words may take automatic hyphenation points, while a paragraph
    /// that the document's automatic hyphenation applies to is measured; else `None`.
    hyphen_runs: Option<Vec<measure::HyphenRun>>,
    /// Whether the paragraph currently being measured is right to left (`w:bidi`), saved and
    /// restored around nested text-box paragraphs.
    paragraph_bidi: measure::ParagraphDirection,
    /// The boxes of the page being filled that text flows beside.
    squares: Vec<floating::Square>,
    /// The boxes of the frames of the body on the page being filled.
    frame_boxes: Vec<frames::FrameBox>,
    /// The places in the text of the frames of the paragraphs at the indexes that they name,
    /// which the paragraph before them, laid out again below the frames' bands, no longer gives.
    frame_places: Vec<(usize, Length)>,
    /// The further free pieces of the line being placed, on its baseline, beside drawings
    /// with room on both sides.
    same_baseline: Vec<floating::NarrowedPiece>,
    /// The bottom of the first piece of such a line, below which the next line starts.
    line_floor: Option<Length>,
    /// The items of the floating drawings of the page being filled that lie behind the text,
    /// each with its drawing's place in the stack ([`crate::floating::Floating::stack`]).
    behind: Vec<(u64, Item)>,
    /// The items of the floating drawings of the page being filled that lie in front of the
    /// text, each with its drawing's place in the stack.
    front: Vec<(u64, Item)>,
    column: Column,
    /// The left edge and the width of each text column of the section.
    columns: Vec<(Length, Length)>,
    /// The column being filled.
    column_index: usize,
    /// Where the columns start on the page being filled.
    column_top: Length,
    /// How far down each column of the page has been filled.
    column_ends: Vec<Length>,
    /// The paragraph that ends the section being laid out, when a later section follows: its
    /// lines that draw nothing do not reach the line between the columns.
    section_end_paragraph: Option<ParagraphId>,
    /// While the columns of a section are balanced, how far down they may go.
    balance: Option<columns::Balance>,
    /// Whether the next paragraph is the first one of a section whose columns are balanced.
    section_top: columns::SectionTop,
    /// While the first layout of a section of balanced columns keeps them, the mark of the
    /// first paragraph of the section that starts on the newest page.
    page_marks: Option<columns::PageMarks>,
    /// While a cell of a row that splits is laid out: its parts on this page and the pages
    /// after it. A floating table in the cell keeps it, so that its cells' lines stop against
    /// the cell's limit; another table in the cell takes it for its rows.
    fragment: Option<table::Fragment>,
    /// Whether a cell that holds the cell being laid out, in a row that splits, has moved on
    /// to a later part, so that the lines of this cell are carried lines: part of the state
    /// that a table cell starts afresh, which its table passes down to the cell's content.
    /// `false` outside a cell.
    cell_carried: bool,
    /// While a table cell is laid out, the lowest bottoms of the drawings anchored in it that
    /// are placed from their paragraph; `None` outside a cell.
    cell_floor: Option<table::CellFloor>,
    /// While a table cell is laid out, the top of its text below its top margin, which a
    /// drawing anchored in it and placed down from the margins counts from; `None` outside a
    /// cell.
    cell_top: Option<Length>,
    /// While a table cell is laid out, the inner edges of its side lines across, between which
    /// a drawing anchored in it that wraps text lies on a target that keeps it inside the cell;
    /// `None` outside a cell.
    cell_sides: Option<(Length, Length)>,
    /// While a table cell is laid out, the effective paragraph style ID of the paragraph
    /// immediately before the cell in document stream order (the previous cell's last paragraph,
    /// the previous row's end-of-row mark as the default style, or the paragraph before the table
    /// for the first cell of its first row); `None` outside a cell.
    cell_prev_style: Option<String>,
    /// While a table is laid out, the effective paragraph style ID of the paragraph immediately
    /// before the table (or the enclosing cell's predecessor style for a nested table at cell
    /// top); `None` when none preceded it.
    table_prev_style: Option<String>,
    /// Number of wrapped paragraph- or line-anchored body floating drawings placed so far in this
    /// pass, used to match upward-reaching wraps across passes.
    body_floatings: usize,
    /// Number of wrapped paragraph- or line-anchored floating drawings placed so far in the
    /// current table cell.
    cell_floatings: usize,
    /// Upward-reaching wraps found on pass 1 of the current table cell, active on pass 2.
    cell_upward_earlier: Vec<UpwardWrap>,
    /// Upward-reaching wraps found during pass 1 of the current table cell.
    cell_upward_found: Vec<UpwardWrap>,
    /// Wraps found on pass 1 of a mode-15+ header or footer story, active on pass 2.
    story_earlier_wraps: Option<Box<PageWraps>>,
    /// Whether a paragraph has been laid out, so that the next one is not the first of the
    /// document.
    started: bool,
    /// Whether the last line ended with a page break, so that the next paragraph starts the
    /// new page.
    after_break: bool,
    /// The paragraph without text whose page break ended the last page, until the next
    /// paragraph starts the new page: the part of that paragraph's space before that is larger
    /// than this one's space after is a space that the new page dropped.
    alone_break: Option<Previous>,
    /// The last paragraph of the previous section, while a section that starts on a new page
    /// has no block yet. Its space after stays on its page.
    section_previous: Option<Previous>,
    /// Whether the chain of kept blocks of the table before the paragraphs about to be laid
    /// out goes on into them.
    table_chain: TableChain,
    /// The index of the last page that a page break started.
    page_from_break: Option<usize>,
    /// The number of items that line numbers and the fills of empty paragraphs have put on the
    /// page that a page break began, while nothing else has come onto it, and the count of
    /// numbered lines at the break.
    break_numbers: (usize, (i64, usize)),
    /// The pitch of the document grid that the paragraph being laid out follows, if any.
    grid_pitch: Option<Length>,
    /// The space after the paragraph being laid out that the next paragraph leaves below its
    /// last line: none when the next paragraph removes it by contextual spacing or by
    /// automatic spacing in one list. `None` where no next paragraph is known, and the
    /// paragraph's own space after follows.
    following_after: Option<Length>,
    /// The last lines of the kept paragraph being laid out that go to the next page with the
    /// paragraph after it, when all its lines fit on this page but what follows them does not
    /// (`KEPT_SPLIT_MODE`); `None` for every other paragraph.
    kept_tail: Option<usize>,
    /// What the pieces of the line being drawn share, where its paragraph's text alignment
    /// puts the middles of their win lines on one line (`Self::centered_line`); `None` for
    /// every other line, and between lines.
    centered_middle: Option<line::centered::CenteredMiddle>,
    /// The box of the line being drawn, its top and its bottom down the page, with its space
    /// before on a paragraph's first line and the space after that it keeps on its last line,
    /// for the clip of its inline pictures (`decisions::inline_picture_cut`); `None` between
    /// lines.
    line_band: Option<(Length, Length)>,
    /// The axis above the baseline of the line being drawn in a turned frame whose glyphs of the
    /// East Asian font side stand upright ([`TurnedGlyphs::EastAsianUpright`]); `None` for
    /// every other line, and between lines.
    east_asian_axis: Option<Length>,
    /// How the centered or right-aligned line being drawn found its start on a dot, for its
    /// record; `None` for every other line, and between lines.
    aligned_parts: Option<AlignedParts>,
    /// For each glyph of the line being drawn whose run is written, the index of its piece
    /// and its drawn place; empty between lines.
    glyph_places: Vec<(usize, Length)>,
    /// The own space before of the paragraph being laid out, until its first line is placed:
    /// a drawing that moves that line down keeps this space above it.
    own_space_before: Length,
    /// The own space before of the paragraph being laid out as the paragraph starts, until its
    /// first line is placed: when it is more than 0, the box of that line takes the form of a
    /// box below space before, even where a new page leaves the space out.
    first_space_before: Length,
    /// The rooms (width and space) of the top and the bottom border of the paragraph being
    /// laid out that the boxes of its first and its last line hold, under
    /// `BorderSpace::Held`: the first until its first line is placed. Both are 0 otherwise.
    held_borders: HeldBorders,
    /// The drawings entry of the shaded paragraph of a table cell being laid out, which takes
    /// the drawings behind the text that the paragraph anchors, under its fill
    /// ([`page_items::PageItems::open_drawings`]); none otherwise.
    drawings_under_fill: Option<page_items::FillsEntry>,
    /// What the own space before of the paragraph being laid out does at the top of the next
    /// page: it stays for the first paragraph after a continuous section end.
    new_page_space: NewPageSpace,
    /// The page and the index in its items of the change bar beside the last line of the
    /// paragraph being laid out, which reaches down past the paragraph's bottom border.
    last_bar: Option<(usize, usize)>,
    /// The page and the column of the paragraph being laid out, and where its part there
    /// starts in its text, in UTF-16 code units: Word counts the pieces of the text again from
    /// the paragraph's first character on each page.
    text_part: ((usize, usize), u32),
    /// The section of the page being filled.
    section_index: SectionIndex,
    /// The index of the first page of that section.
    section_first_page: usize,
    /// The index of the page of that section that takes its first-page header and footer:
    /// `section_first_page`, or none when the section started with a continuous break on the
    /// page before it.
    section_title_page: Option<usize>,
    /// The number of that page.
    number_start: i64,
    /// A section that started on this page and takes over its size from the next page on.
    pending: Option<usize>,
    /// The number of the table whose rows the layout places, or 0 outside tables.
    table_number: usize,
    /// The table cell whose content the layout places, for the line records.
    cell_place: Option<CellPlace>,
}

/// What holds a column of text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Within {
    /// The page, or a story such as a header or a note.
    Page,
    /// An upright table cell, with the parts of the column's left edge: the table's leftmost
    /// grid line, the cell's grid line, and the part that lies inside the cell's edge, the
    /// cell's left margin.
    Cell(CellEdgeParts),
    /// The frame of a turned cell, or of a text box whose body turns its text, whose lines run
    /// along the page's other axis, with whether its lines lie on the page's dots across the
    /// page, else on the frame's, the turn that takes the frame onto the page, and how its
    /// glyphs lie there.
    TurnedFrame(bool, f_office_paint::Turn, TurnedGlyphs),
}

/// How the glyphs of a turned frame's lines lie on the page.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TurnedGlyphs {
    /// Every glyph turns with its line.
    WithLine,
    /// A glyph of a character of the East Asian font side stands upright: it is turned back
    /// about the centre of its em box in the line, half an em along the line from its origin
    /// and half the face's ascent less its descent above the baseline. The other glyphs turn
    /// with their line.
    EastAsianUpright,
}

impl Within {
    /// The parts of the column's left edge in an upright table cell, or none outside one.
    const fn cell_edge(self) -> Option<CellEdgeParts> {
        match self {
            Self::Cell(parts) => Some(parts),
            Self::Page | Self::TurnedFrame(..) => None,
        }
    }
}

/// The column that paragraphs fill: the text column of the page, or the text area of a table
/// cell.
#[derive(Clone, Debug)]
struct Column {
    left: Length,
    width: Length,
    /// What holds the column.
    within: Within,
    /// The left edge of the column of the page that holds this column.
    origin: Length,
    /// Inside a table cell, what the table style gives the cell. A line in a cell never starts
    /// a new page itself. Its row moves or splits instead. The copies of the column, such as
    /// the one that a mark of the layout keeps, share it, since the layout only reads it.
    cell: Option<Rc<TableStyle>>,
}

impl Column {
    /// A top-level page column starting at `left` with width `width`.
    const fn page(left: Length, width: Length) -> Self {
        Self {
            left,
            width,
            within: Within::Page,
            origin: left,
            cell: None,
        }
    }
}

impl<'a> Layout<'a> {
    /// Makes the layout of a body with the sections `sections`, which reads `context` and
    /// makes its stories with `stories`. It starts in the first section.
    #[must_use]
    pub fn new(
        contexts: (&'a Context<'a>, &'a Context<'a>),
        sections: &'a Sections<SectionLayout>,
        shaper: Shaper<'a>,
    ) -> Self {
        let numbering = (*contexts.0.numbering).clone();
        Self::with_sections(contexts, Cow::Borrowed(sections), shaper, numbering)
    }

    /// Makes the layout of a story of `blocks` blocks, which fills the one section `section`
    /// and whose lists go on from the counters of `numbering` in place of a copy of the
    /// context's, so that a story copies the lists of the flow that holds it once.
    fn story(
        contexts: (&'a Context<'a>, &'a Context<'a>),
        section: &Section,
        blocks: usize,
        shaper: Shaper<'a>,
        numbering: Numbering,
    ) -> Self {
        let sections = Sections::one(SectionLayout::plain(section, blocks));
        Self::with_sections(contexts, Cow::Owned(sections), shaper, numbering)
    }

    /// Makes a layout that fills `sections` from the first, with the lists of `numbering`.
    fn with_sections(
        (context, stories): (&'a Context<'a>, &'a Context<'a>),
        sections: Cow<'a, Sections<SectionLayout>>,
        shaper: Shaper<'a>,
        numbering: Numbering,
    ) -> Self {
        let section = sections.first().section;
        let top = section.top;
        let columns = columns::areas(&section, &context.quirks);
        let (left, width) = columns.first().copied().unwrap_or_default();
        Self {
            context,
            stories,
            styles: context.styles,
            settings: context.settings,
            numbering,
            device: context
                .device
                .with_page(section.width, section.height, section.orientation),
            sections,
            section,
            shaper,
            items: page_items::PageItems::new(),
            y: top,
            y_rest: 0,
            y_twips: None,
            table_twips: TableTwips::default(),
            previous: None,
            tops: [top; 3],
            bottoms: [section.height - section.bottom; 3],
            story: None,
            body_part: std::rc::Rc::default(),
            output: output::PassOutput::default(),
            page_notes: notes::PageNotes::default(),
            endnote: None,
            comment_markup: markup::CommentMarkup::new(&context.comments),
            page: None,
            story_notes: Length::ZERO,
            story_page: None,
            style_page: None,
            number_context: None,
            bands: Vec::new(),
            hyphen_runs: None,
            paragraph_bidi: measure::ParagraphDirection::LeftToRight,
            squares: Vec::new(),
            frame_boxes: Vec::new(),
            frame_places: Vec::new(),
            same_baseline: Vec::new(),
            line_floor: None,
            behind: Vec::new(),
            front: Vec::new(),
            column: Column::page(left, width),
            columns,
            column_index: 0,
            column_top: top,
            column_ends: Vec::new(),
            section_end_paragraph: None,
            balance: None,
            section_top: columns::SectionTop::Placed,
            page_marks: None,
            fragment: None,
            cell_carried: false,
            cell_floor: None,
            cell_top: None,
            cell_sides: None,
            cell_prev_style: None,
            table_prev_style: None,
            body_floatings: 0,
            cell_floatings: 0,
            cell_upward_earlier: Vec::new(),
            cell_upward_found: Vec::new(),
            story_earlier_wraps: None,
            started: false,
            after_break: false,
            alone_break: None,
            section_previous: None,
            table_chain: TableChain::Ends,
            page_from_break: None,
            break_numbers: (0, (0, 0)),
            grid_pitch: None,
            following_after: None,
            kept_tail: None,
            centered_middle: None,
            line_band: None,
            east_asian_axis: None,
            aligned_parts: None,
            glyph_places: Vec::new(),
            own_space_before: Length::ZERO,
            first_space_before: Length::ZERO,
            held_borders: HeldBorders::NONE,
            drawings_under_fill: None,
            new_page_space: NewPageSpace::Goes,
            last_bar: None,
            text_part: ((0, 0), 0),
            section_index: SectionIndex::FIRST,
            section_first_page: 0,
            section_title_page: Some(0),
            number_start: section.first_page_number,
            pending: None,
            table_number: 0,
            cell_place: None,
        }
    }

    /// Prepares the layout for stepping or running through `body`.
    pub(crate) fn begin_body(&mut self, body: &Body) {
        self.body_part = std::rc::Rc::clone(&body.part);
        self.output.styled = Some(style_refs::Record::default());
        if self.settings.side_margins != SideMargins::Section {
            // The first page takes the side margins of its side.
            let section = self.section_of(SectionIndex::FIRST);
            self.take_side_margins(&section);
            self.set_columns();
        }
        self.measure_body();
        self.start_wraps();
        self.move_to_body_top(0);
        self.column_top = self.y;
    }

    /// Finalizes a body pass after all sections have flowed: lays out endnotes, flushes any
    /// trailing page, stamps final headers/footers and page color, and builds [`Pass`].
    #[must_use]
    pub(crate) fn finish_body_pass(mut self) -> Pass {
        self.endnotes_flow();
        // A page break at the end of the document starts no page when nothing, not even an
        // empty paragraph, comes after it.
        let trailing = !self.output.pages.is_empty()
            && self.page_from_break == Some(self.output.pages.len())
            && self.page_is_empty()
            && self.y == self.page_top(self.output.pages.len());
        if !trailing {
            self.new_page();
        }
        // The rest of a footnote that goes on after the last page of the body has a page.
        if self.rest_waits() {
            self.new_page();
        }
        self.output.style_pages = self.output.styled.take().map(style_refs::Record::finish);
        let count = count_factor(self.output.pages.len());
        // Headers and footers lie behind the body, so that their drawings behind the text do
        // not cover it.
        let mut behind = Vec::with_capacity(self.output.pages.len());
        for index in 0..self.output.pages.len() {
            if self.output.blank_pages.contains(&index) {
                behind.push(Vec::new());
                continue;
            }
            let (items, lines) = self.headers_and_footers(index, count);
            behind.push(items);
            self.output.placed.extend(lines);
        }
        let pages = std::mem::take(&mut self.output.pages);
        let page_color = self.settings.page_color;
        self.output.pages = pages
            .into_iter()
            .zip(behind)
            .map(|(page, items)| {
                // The page color fills the whole page under the headers, the footers and the
                // body.
                let color = page_color.map(|[r, g, b]| {
                    Item::Rect(Rect {
                        x: Length::ZERO,
                        y: Length::ZERO,
                        width: page.width(),
                        height: page.height(),
                        color: Rgb { r, g, b },
                    })
                });
                page.map_items(|mut body| {
                    body.splice(0..0, color.into_iter().chain(items));
                    body
                })
            })
            .collect();
        self.print_markup();
        let styles = HeaderStyles(self.output.style_pages.clone());
        let note_places = self.output.notes.take_places();
        let areas = &self.output.body_areas;
        let notes_missed = self
            .output
            .margin_notes
            .iter()
            .any(|&(page, notes)| areas.get(page).is_some_and(|area| area.notes != notes));
        let note_heights = NoteHeights::of_areas(areas);
        Pass {
            list: DisplayList::new(self.output.pages),
            wraps: self.output.found,
            bookmarks: self.output.found_bookmarks.into_values(),
            bookmark_numbers: self.output.found_numbers.into_values(),
            styles,
            note_places,
            later_anchors: LaterAnchors::found(&self.output.found_later),
            note_heights,
            notes_missed,
            lines: self.output.placed,
            tables: last_columns(self.output.table_columns),
            warnings: self.output.warnings,
            font_notes: self.shaper.take_notes(),
        }
    }

    /// Lays out a whole body, then the header and footer of each page. Gives the pages with
    /// the wraps of the drawings that it placed from a page or its margins, the page number
    /// text of its bookmarks, the styled text of its pages and its placed lines.
    #[must_use]
    pub fn run_with_wraps(mut self, body: &Body) -> Pass {
        self.begin_body(body);
        self.sections_flow(&body.blocks);
        self.finish_body_pass()
    }

    /// Lays out paragraphs and tables in order. The paragraphs between two tables flow
    /// together, so that neighbors with equal borders form a group.
    fn blocks(&mut self, blocks: &[Block]) {
        self.blocks_from(blocks, columns::BlockStart::default());
    }

    /// Lays out `blocks` from `start`, as [`Self::blocks`] does, when the blocks before it are
    /// laid out already and the layout stands at the mark of `start`'s paragraph.
    fn blocks_from(&mut self, blocks: &[Block], start: columns::BlockStart) {
        let chunks = paragraph_chunks(blocks);
        // A floating table that the tables after it go on, as rows of one table.
        let mut joined: Option<Table> = None;
        self.enter_blocks();
        for (index, chunk) in chunks.iter().enumerate().skip(start.chunk) {
            self.note_chunk(index);
            let mut group = Vec::new();
            // A table is a chunk of its own, so the block after it starts the next chunk.
            let rest = Rest(chunks.get(index + 1..).unwrap_or_default());
            let next = chunks.get(index + 1).and_then(|next| next.first());
            for block in *chunk {
                match block {
                    Block::Paragraph(paragraph) => group.push(paragraph),
                    Block::Table(table) => {
                        let more = goes_on(table, next);
                        match joined.as_mut() {
                            Some(whole) => whole.rows.extend(table.rows.iter().cloned()),
                            None if more => joined = Some(table.clone()),
                            None => self.table(table, rest),
                        }
                        if let Some(whole) = joined.take_if(|_| !more) {
                            self.table(&whole, rest);
                        }
                    }
                }
            }
            let first = if index == start.chunk {
                start.paragraph
            } else {
                0
            };
            self.flow(&group, rest, first);
        }
        self.leave_blocks();
    }
}

/// Groups consecutive paragraphs into chunks while keeping each table in a chunk of its own.
fn paragraph_chunks(blocks: &[Block]) -> Vec<&[Block]> {
    blocks
        .chunk_by(|a, b| matches!((a, b), (Block::Paragraph(_), Block::Paragraph(_))))
        .collect()
}