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
//! Pages: which header and footer a page takes, where its body starts and ends, how headers,
//! footers and notes are laid out, and how a page is finished.

use f_office_paint::{Item, Page, Rect};
use f_office_units::{Edges, Length};

use std::rc::Rc;

use crate::art_pictures::ArtPictures;
use crate::body::{ArtSide, Block, BorderPages, NoteId, PageAlign, PageBorders, PageSide, Section};
use crate::grid::Device;
use crate::lines::NoteNumber;
use crate::note_setup::NoteLabel;
use crate::numbering::ListCounters;
use crate::props::{ArtStyle, Border};

use super::art_borders;
use super::decisions;
use super::line::height::REST_PARTS;
use super::notes::{Footnote, Separator};
use super::output::{BodyArea, PassOutput};
use super::sections::Parity;
use super::style_refs::StyledPages;
use super::{Kind, Layout, LineStory, PartStory, PlacedLine, Story, StoryKind, StoryNumbers};

/// The height of the page on which a story (a header, a footer, a footnote, a text box) is
/// laid out. It is endless because a story never breaks to a next page: its lines go onto the
/// real page later, as a whole. It is a part of the largest length, not the largest length
/// itself, so that the layout can still add lengths to it without an overflow. The other
/// places that read the page's height during a story read this height too, also a frame or a
/// floating table in a story.
const ENDLESS_STORY_HEIGHT: Length =
    Length::from_units(i64::MAX / crate::params::STORY_HEIGHT_PARTS);

/// The story inputs: what the layout of a story reads from the layout that holds it, besides
/// its blocks, its top, its kind and its numbers, and what can change within a pass. A story
/// laid out again with equal story inputs gives the same items, end, warnings and font notes.
#[derive(Clone, Debug)]
pub(super) struct StoryInputs {
    /// The section with whose margins the story is laid out.
    section: Section,
    /// The section of the page that holds the story.
    page: Section,
    /// The height of the footnotes of the page that holds the story, which its floating
    /// drawings without wrapping keep above the end of the page's margins.
    notes: Length,
    /// The list counters of the flow that holds the story, from which its lists go on.
    counters: ListCounters,
    /// The styled text of the pages, and the page whose styled text the story's `STYLEREF`
    /// fields show.
    style_page: Option<(Rc<StyledPages>, usize)>,
}

impl PartialEq for StoryInputs {
    /// The styled text of the pages is equal when it is the same record: no layout changes a
    /// record once it is made.
    fn eq(&self, other: &Self) -> bool {
        let style_page = match (&self.style_page, &other.style_page) {
            (Some((pages, page)), Some((others, other_page))) => {
                Rc::ptr_eq(pages, others) && page == other_page
            }
            (None, None) => true,
            _ => false,
        };
        self.section == other.section
            && self.page == other.page
            && self.notes == other.notes
            && self.counters == other.counters
            && style_page
    }
}

/// The section that a header or footer is laid out with: its lines keep their own heights,
/// off the section's document grid, and fill the whole width between the margins in one
/// column, whatever the columns of the body.
fn margin_story(section: &Section) -> Section {
    Section {
        line_pitch: None,
        spacing_line_pitch: None,
        char_pitch: None,
        columns: crate::body::Columns::default(),
        ..*section
    }
}

impl<'a> Layout<'a> {
    /// The header and footer kind of a page, from 0.
    fn kind(&self, index: usize) -> Kind {
        let info = self.page_info(index);
        if info.first && self.section_of(info.section).title_page {
            Kind::First
        } else if self.settings.even_and_odd_headers && Parity::of(info.number) == Parity::Even {
            Kind::Even
        } else {
            Kind::Default
        }
    }

    /// Whether a page of the current section can show the header and footer of `kind`: those
    /// of the first page only with a title page (`w:titlePg`), those of even pages only with
    /// even and odd headers (`w:evenAndOddHeaders`), as [`Self::kind`] chooses them.
    fn shows(&self, kind: Kind) -> bool {
        match kind {
            Kind::First => self.section.title_page,
            Kind::Even => self.settings.even_and_odd_headers,
            Kind::Default => true,
        }
    }

    pub(super) fn page_number(&self, index: usize) -> i64 {
        self.page_info(index).number
    }

    pub(super) fn page_top(&self, index: usize) -> Length {
        self.tops
            .get(Self::slot(self.kind(index)))
            .copied()
            .unwrap_or(self.section.top)
    }

    /// Where the body ends on the page being filled, or where balanced columns end.
    pub(super) fn page_bottom(&self) -> Length {
        let bottom = self.body_bottom_of(self.output.pages.len());
        self.balance.map_or(bottom, |b| bottom.min(b.limit))
    }

    /// Where the body ends on the page of `index`, at the bottom margin or above a footer that
    /// reaches past it.
    pub(super) fn body_bottom_of(&self, index: usize) -> Length {
        self.bottoms
            .get(Self::slot(self.kind(index)))
            .copied()
            .unwrap_or(self.section.height - self.section.bottom)
    }

    /// Where the body of the page being filled ends above the footnotes placed on it so far.
    pub(super) fn body_end(&self) -> Length {
        let end = self.page_bottom() - self.notes_height();
        // Below a line whose footnote goes on to the next page, the body has ended.
        if self.body_has_ended() {
            end.min(self.y)
        } else {
            end
        }
    }

    const fn slot(kind: Kind) -> usize {
        match kind {
            Kind::First => 0,
            Kind::Even => 1,
            Kind::Default => 2,
        }
    }

    /// Measures where the body starts and ends on the pages of each kind of the section that
    /// its pages can show ([`Self::shows`]); a kind that they cannot show keeps the margins, and
    /// its header and footer are not laid out, so they give no warnings.
    pub(super) fn measure_body(&mut self) {
        // With the styled text of an earlier pass, the header and footer of the page being
        // started show its `STYLEREF` text, which may take more or fewer lines.
        if self.context.earlier.header_styles.0.is_some() {
            self.story_page = Some(self.output.pages.len());
        }
        let kinds = [Kind::First, Kind::Even, Kind::Default];
        self.tops = kinds.map(|kind| self.body_top(kind));
        self.bottoms = kinds.map(|kind| self.body_bottom(kind));
        self.story_page = None;
    }

    /// The body starts at the top margin, or below the header and the space after its last
    /// paragraph when they reach further down.
    fn body_top(&mut self, kind: Kind) -> Length {
        // A copy of the current section's headers, which share their blocks, so that the
        // header's layout can read them while it writes into this layout; the same holds for
        // the footers below.
        let headers = self.section_layout(self.section_index).headers.clone();
        let top = self.section.top;
        // A fixed top margin keeps the body where it is, over a header that reaches below it.
        let Some(header) = headers.get(kind) else {
            return top;
        };
        if self.section.fixed.0 || !self.shows(kind) {
            return top;
        }
        let section = margin_story(&self.section);
        let layout = self.header_layout(&section, header, section.header, StoryNumbers::PAGE_ONE);
        let end = layout.y + layout.previous.as_ref().map_or(Length::ZERO, |p| p.after);
        top.max(end)
    }

    /// The body ends at the bottom margin, or above the footer when the footer reaches
    /// further up.
    fn body_bottom(&mut self, kind: Kind) -> Length {
        let footers = self.section_layout(self.section_index).footers.clone();
        let height = self.section.height;
        let bottom = height - self.section.bottom;
        let Some(footer) = footers.get(kind) else {
            return bottom;
        };
        if self.section.fixed.1 || !self.shows(kind) {
            return bottom;
        }
        let section = margin_story(&self.section);
        let (footer, _) = self.footer_height(&section, footer, StoryNumbers::PAGE_ONE);
        bottom.min(height - self.section.footer - footer)
    }

    /// The height of a footer, with the space after its last paragraph, which Word keeps
    /// above the footer distance, and the height rest by which the exact sum of its lines'
    /// heights lies past it.
    fn footer_height(
        &mut self,
        section: &Section,
        footer: &PartStory,
        numbers: StoryNumbers,
    ) -> (Length, i64) {
        let layout = self.footer_layout(section, footer, (Length::ZERO, 0), numbers);
        let after = layout.previous.as_ref().map_or(Length::ZERO, |p| p.after);
        (layout.y + after, layout.y_rest)
    }

    /// Lays out the header from the header distance down, and the footer so that it ends at
    /// the footer distance from the bottom edge. Gives their items and the records of their
    /// lines.
    pub(super) fn headers_and_footers(
        &mut self,
        index: usize,
        count: i64,
    ) -> (Vec<Item>, Vec<PlacedLine>) {
        self.story_page = Some(index);
        let kind = self.kind(index);
        let info = self.page_info(index);
        let numbers = StoryNumbers::on_page(info.number, count);
        let section = self.page_section(index);
        let part = self.section_layout(info.section);
        let (headers, footers, borders) =
            (part.headers.clone(), part.footers.clone(), part.borders);
        let margins = margin_story(&section);
        // The floating drawings of the page's header and footer count from the margins of the
        // area that the target chooses: the section's, or the area that the page's body took.
        let between = BodyArea {
            top: section.top,
            end: section.height - section.bottom,
            notes: Length::ZERO,
        };
        let body = self
            .output
            .body_areas
            .get(index)
            .copied()
            .unwrap_or(between);
        let area = decisions::story_margin_area(&self.context.quirks, between, body);
        let frame = Section {
            top: area.top,
            bottom: section.height - area.end,
            ..margins
        };
        let body_page = self.page.replace(frame);
        let body_notes = std::mem::replace(&mut self.story_notes, area.notes);
        let (mut items, mut lines) = (Vec::new(), Vec::new());
        if let Some(header) = headers.get(kind) {
            let mut layout = self.header_layout(&margins, header, section.header, numbers);
            lines.extend(story_lines(&mut layout, index));
            items.extend(layout.page_items());
        }
        if let Some(footer) = footers.get(kind) {
            let height = self.footer_height(&margins, footer, numbers);
            let top = footer_start(section.height - section.footer, height);
            let mut layout = self.footer_layout(&margins, footer, top, numbers);
            lines.extend(story_lines(&mut layout, index));
            items.extend(layout.page_items());
        }
        self.page = body_page;
        self.story_notes = body_notes;
        let shown = borders.filter(|b| match b.pages {
            BorderPages::All => true,
            BorderPages::First => info.first,
            BorderPages::NotFirst => !info.first,
        });
        if let Some(borders) = shown {
            let pictures = self.context.art;
            let missing = page_borders(&borders, (&section, &self.device), pictures, &mut items);
            for (style, size) in missing {
                self.output
                    .warnings
                    .push(crate::Warning::ArtBorderNotDrawn {
                        style: style.name(),
                        size,
                    });
            }
        }
        self.story_page = None;
        (items, lines)
    }

    /// Lays out a separator of the footnotes from `top` on one endless page, and returns its
    /// items and the position where its room ends, below the space after it that the target
    /// keeps ([`Layout::separator_after`]).
    pub(super) fn separator(&mut self, separator: Separator, top: Length) -> (Vec<Item>, Length) {
        let section = self.note_section();
        let context = self.context;
        let blocks = separator.blocks(&context.notes);
        let mut layout = self.story_layout(&section, blocks, top, note_separator(separator));
        let end = layout.y + layout.separator_after();
        (layout.page_items(), end)
    }

    /// Lays out the endnotes' continuation separator at the cursor, at the top of a page that
    /// the endnotes go on to, and moves the cursor below it and the space after its last
    /// paragraph.
    fn endnote_continuation(&mut self) {
        let section = self.section;
        let context = self.context;
        let blocks = Separator::Continuation.blocks(&context.endnotes);
        let story = Story {
            kind: StoryKind::EndnoteContinuation,
            numbers: StoryNumbers::PAGE_ONE,
        };
        let mut layout = self.story_layout(&section, blocks, self.y, story);
        let after = layout
            .previous
            .as_ref()
            .filter(|last| !last.after_auto)
            .map_or(Length::ZERO, |last| last.after);
        let end = layout.y + after;
        self.items.extend(layout.page_items());
        self.move_to(end);
    }

    /// Lays out a separator of the footnotes from 0 with the story inputs `inputs`, as
    /// [`Self::story_from`] does.
    pub(super) fn separator_from(&self, inputs: &StoryInputs, separator: Separator) -> Layout<'a> {
        let blocks = separator.blocks(&self.context.notes);
        self.story_from(inputs, blocks, (Length::ZERO, 0), note_separator(separator))
    }

    /// Lays out a footnote, whose `w:footnoteRef` marks show its number, with the margins of
    /// `section`, and gives the records of its lines too.
    pub(super) fn placed_note(
        &mut self,
        section: &Section,
        note: Footnote<'_>,
        top: Length,
        number: NoteNumber,
    ) -> (Vec<Item>, Length, Vec<PlacedLine>) {
        let story = footnote(self.note_label(number), note.id);
        self.placed_story(section, note.blocks, top, story)
    }

    /// Lays out the lines of a footnote from the line `from` to the line `to`, or to its end,
    /// with the margins of `section` and the top of the first of them at `top`: the part of a footnote that stands on one
    /// page when the footnote goes on to the next. Gives the items, the records of the lines,
    /// and the height of the footnote's lines before `from`.
    pub(super) fn note_lines(
        &mut self,
        section: &Section,
        note: Footnote<'_>,
        top: Length,
        number: NoteNumber,
        (from, to): (usize, Option<usize>),
    ) -> (Vec<Item>, Vec<PlacedLine>, Length) {
        let story = footnote(self.note_label(number), note.id);
        let mut layout = self.story_layout(section, note.blocks, Length::ZERO, story);
        let placed = std::mem::take(&mut layout.output.placed);
        let to = to.unwrap_or(placed.len()).min(placed.len());
        let Some(first) = placed.get(from) else {
            return (Vec::new(), Vec::new(), Length::ZERO);
        };
        let cut = first.top;
        // A carried line's items join the page later, so a range from or to one is empty.
        let end = placed
            .get(to)
            .map_or(Some(layout.items.len()), |line| line.item.index());
        let mut items = first
            .item
            .index()
            .zip(end)
            .map_or_default(|(start, end)| layout.items.cloned(start..end));
        super::table::move_items(&mut items, top - cut);
        let page = self.output.pages.len();
        let lines = placed
            .get(from..to)
            .unwrap_or_default()
            .iter()
            .map(|line| {
                let mut line = PlacedLine {
                    page,
                    story: LineStory::Footnote,
                    item: super::FirstItem::Carried,
                    ..line.clone()
                };
                line.move_down(top - cut);
                line
            })
            .collect();
        (items, lines, cut)
    }

    /// Lays out blocks as [`Self::story_in`] does, and gives the records of their lines too,
    /// as lines of this page whose items join the page as a whole, of the story that the kind
    /// of `story` names, or none for a kind whose lines are not recorded.
    pub(super) fn placed_story(
        &mut self,
        section: &Section,
        blocks: &[Block],
        top: Length,
        story: Story,
    ) -> (Vec<Item>, Length, Vec<PlacedLine>) {
        self.placed_story_dropping_last(section, blocks, top, story, |_| Length::ZERO)
    }

    /// [`Self::placed_story`] whose last line moves down by what `drop` gives for the records of
    /// the story's lines: the line's baseline, and its items with the items after them. A story
    /// whose last line lies in a table keeps its lines.
    pub(super) fn placed_story_dropping_last(
        &mut self,
        section: &Section,
        blocks: &[Block],
        top: Length,
        story: Story,
        drop: impl FnOnce(&[PlacedLine]) -> Length,
    ) -> (Vec<Item>, Length, Vec<PlacedLine>) {
        let part = story.kind.part(self.output.story_parts.count);
        if part.is_some() {
            self.output.story_parts.count += 1;
        }
        let mut layout = self.story_layout(section, blocks, top, story);
        let dy = match layout.output.placed.last() {
            Some(line)
                if line.area == super::LineArea::OutsideTables
                    && matches!(line.item, super::FirstItem::At(_)) =>
            {
                drop(&layout.output.placed)
            }
            _ => Length::ZERO,
        };
        if dy != Length::ZERO
            && let Some(line) = layout.output.placed.last_mut()
            && let super::FirstItem::At(first) = line.item
        {
            line.baseline += dy;
            let end = layout.items.len();
            layout.items.move_down(first..end, dy);
        }
        let lines = story_lines(&mut layout, self.output.pages.len())
            .into_iter()
            .map(|line| PlacedLine {
                item: super::FirstItem::Carried,
                part: part.unwrap_or(line.part),
                ..line
            })
            .collect();
        let y = layout.end_of_story();
        (layout.page_items(), y, lines)
    }

    /// Lays out blocks from `top` on one endless page with the margins of `section`, as
    /// `story` says, and returns their items and the position where they end.
    pub(super) fn story_in(
        &mut self,
        section: &Section,
        blocks: &[Block],
        top: Length,
        story: Story,
    ) -> (Vec<Item>, Length) {
        let mut layout = self.story_layout(section, blocks, top, story);
        let y = layout.end_of_story();
        (layout.page_items(), y)
    }

    /// Where the story laid out by this layout ends: below its last line, and for a kind that
    /// ends below the space after of its last paragraph, as [`Self::end_below_space_after`].
    fn end_of_story(&self) -> Length {
        if self
            .story
            .as_ref()
            .is_some_and(|story| story.kind.ends_below_space_after())
        {
            self.end_below_space_after()
        } else {
            self.y
        }
    }

    /// Where the story laid out by this layout ends below the space after its last paragraph,
    /// unless that space is automatic.
    fn end_below_space_after(&self) -> Length {
        let after = self
            .previous
            .as_ref()
            .filter(|p| !p.after_auto)
            .map_or(Length::ZERO, |p| p.after);
        self.y + after
    }

    /// Lays out a header as [`Self::story_layout`] does, with the numbers `numbers`.
    fn header_layout(
        &mut self,
        section: &Section,
        header: &PartStory,
        top: Length,
        numbers: StoryNumbers,
    ) -> Layout<'a> {
        let kind = StoryKind::Header {
            several_blocks: header.blocks.len() > 1,
            part: Rc::clone(&header.part),
        };
        self.story_layout(section, &header.blocks, top, Story { kind, numbers })
    }

    /// Lays out a footer as [`Self::story_layout_with_rest`] does, with the numbers `numbers`.
    /// A footer laid out to end at the footer distance starts with the opposite of the height
    /// rest of its lines' exact sum, so that its last line ends exactly there, without a rest,
    /// as Word places it up from its bottom.
    fn footer_layout(
        &mut self,
        section: &Section,
        footer: &PartStory,
        top: (Length, i64),
        numbers: StoryNumbers,
    ) -> Layout<'a> {
        let kind = StoryKind::Footer {
            part: Rc::clone(&footer.part),
        };
        self.story_layout_with_rest(section, &footer.blocks, top, Story { kind, numbers })
    }

    /// Where a story laid out from `top` ends, below the space after its last paragraph unless
    /// that space is automatic, as in a table cell.
    pub(super) fn story_end(
        &mut self,
        section: &Section,
        blocks: &[Block],
        top: Length,
        story: Story,
    ) -> Length {
        self.story_layout(section, blocks, top, story)
            .end_below_space_after()
    }

    /// Where a SmartArt shape's story laid out from `top` ends: at the bottom of its last line's
    /// text (`unrounded_baseline + descent`) when that line has automatic spacing above single
    /// spacing (dropping the trailing extra line-spacing slack below the last line's descent),
    /// and otherwise at [`Self::end_of_story`].
    pub(super) fn smartart_text_end(
        &mut self,
        section: &Section,
        blocks: &[Block],
        top: Length,
        story: Story,
    ) -> Length {
        let layout = self.story_layout(section, blocks, top, story);
        decisions::SmartArtSpacing::of(&self.context.quirks)
            .text_end(layout.output.placed.last(), layout.end_of_story())
    }

    /// Where the footnote `number` ends when it starts at 0, without the space after its last
    /// paragraph, and that paragraph.
    pub(super) fn note_end(
        &mut self,
        note: Footnote<'_>,
        number: NoteNumber,
    ) -> (Length, Option<super::Previous>) {
        let section = self.note_section();
        let story = footnote(self.note_label(number), note.id);
        let layout = self.story_layout(&section, note.blocks, Length::ZERO, story);
        (layout.y, layout.previous.clone())
    }

    /// Lays out blocks whose warnings another layout of them gives, as `layout` does, and adds
    /// none of its warnings (**Warnings trial**): a layout that only
    /// measures blocks, which the layout lays out again where it places them, and the header
    /// rows that a table repeats at the top of a page, which warned where the table starts.
    pub(super) fn layout_without_warnings<T>(&mut self, layout: impl FnOnce(&mut Self) -> T) -> T {
        let trial = self.output.start_trial();
        let value = layout(self);
        self.output.end_trial(trial, false);
        value
    }

    /// Lays out blocks from `top` with the margins of `section`, as a story of the kind and with
    /// the numbers of `story`. The story's layout has an output and a shaper of its own; when it
    /// ends, its warnings and the notes of its shaper join this layout's, the warnings of a
    /// story that the layout lays out more than once as those of one layout of it, under the
    /// story's key ([`StoryKind::key`]).
    pub(super) fn story_layout(
        &mut self,
        section: &Section,
        blocks: &[Block],
        top: Length,
        story: Story,
    ) -> Layout<'a> {
        self.story_layout_with_rest(section, blocks, (top, 0), story)
    }

    /// Lays out blocks as [`Self::story_layout`] does, from `top` with the height rest `rest`,
    /// which the cursor starts with.
    fn story_layout_with_rest(
        &mut self,
        section: &Section,
        blocks: &[Block],
        (top, rest): (Length, i64),
        story: Story,
    ) -> Layout<'a> {
        let inputs = self.story_inputs(section);
        let key = story.kind.key();
        let mut layout = self.story_from(&inputs, blocks, (top, rest), story);
        if let Some(key) = key {
            let warnings = std::mem::take(&mut layout.output.warnings);
            self.output.join_story_warnings(key, warnings);
        } else {
            self.output.join_warnings_of(&mut layout.output);
        }
        self.shaper.add_notes(layout.shaper.take_notes());
        layout
    }

    /// The story inputs of a story with the margins of `section` in this layout.
    pub(super) fn story_inputs(&self, section: &Section) -> StoryInputs {
        let styles = self
            .output
            .style_pages
            .clone()
            .or_else(|| self.context.earlier.header_styles.0.clone());
        StoryInputs {
            section: *section,
            page: self.page.unwrap_or(*section),
            notes: self.story_notes,
            counters: self.numbering.counters().clone(),
            style_page: styles.zip(self.story_page),
        }
    }

    /// Measures the total height of the endnote separator blocks (including the trailing space
    /// after their last paragraph) on an endless page from 0, dropping the first paragraph's
    /// space before when `drop_before` is set.
    pub(super) fn measure_endnote_separator(&self, blocks: &[Block], drop_before: bool) -> Length {
        let mut section = self.section;
        section.line_numbers = None;
        section.right_to_left = false;
        section.top = Length::ZERO;
        section.height = ENDLESS_STORY_HEIGHT;
        section.bottom = Length::ZERO;
        let mut layout = Layout::story(
            (self.stories, self.stories),
            &section,
            blocks.len(),
            self.shaper.fork(),
            self.numbering
                .with_counters(self.numbering.counters().clone()),
        );
        layout.output = PassOutput::for_story();
        layout.after_break = drop_before;
        layout.blocks(blocks);
        let after = layout
            .previous
            .as_ref()
            .map_or(Length::ZERO, |previous| previous.after);
        layout.y + after
    }

    /// Lays out blocks from `top`, with the height rest `rest` on the cursor, as a story of the
    /// kind and with the numbers of `story`, from the story inputs `inputs`: of this layout it
    /// reads only them, the context of its stories, the list definitions and the fonts. The
    /// warnings and the font notes stay in the story's layout. For a multi-block header or footer
    /// in compatibility mode 15+, runs a second pass when pass 1 finds upward-reaching or
    /// page/margin-relative floating wraps so earlier paragraphs of the story wrap around them.
    fn story_from(
        &self,
        inputs: &StoryInputs,
        blocks: &[Block],
        (top, rest): (Length, i64),
        story: Story,
    ) -> Layout<'a> {
        let mut layout = self.run_story_pass(inputs, blocks, (top, rest), story.clone(), None);
        if blocks.len() > 1
            && layout.is_header_or_footer_story()
            && layout.uses_modern_floating_layout()
            && !layout.output.found.is_empty()
        {
            let found = std::mem::take(&mut layout.output.found);
            return self.run_story_pass(inputs, blocks, (top, rest), story, Some(found));
        }
        layout
    }

    /// Runs one layout pass of a story with `inputs`, pre-loading `earlier` wraps when running
    /// the second pass of a mode-15+ header or footer.
    fn run_story_pass(
        &self,
        inputs: &StoryInputs,
        blocks: &[Block],
        (top, rest): (Length, i64),
        story: Story,
        earlier: Option<super::PageWraps>,
    ) -> Layout<'a> {
        let StoryInputs {
            mut section,
            page,
            notes,
            counters,
            style_page,
        } = inputs.clone();
        // Only body lines have line numbers.
        section.line_numbers = None;
        // The rule for a table in a right-to-left section is the body's.
        section.right_to_left = false;
        section.top = top;
        section.height = ENDLESS_STORY_HEIGHT;
        section.bottom = Length::ZERO;
        // A story goes on from the counters of the lists of the flow that holds it.
        let mut layout = Layout::story(
            (self.stories, self.stories),
            &section,
            blocks.len(),
            self.shaper.fork(),
            self.numbering.with_counters(counters),
        );
        layout.output = PassOutput::for_story();
        if let StoryKind::TextBox {
            turn: Some((turn, glyphs)),
            ..
        } = story.kind
        {
            layout.column.within = super::Within::TurnedFrame(false, turn, glyphs);
        }
        layout.story = Some(story);
        layout.y_rest = rest;
        // The story's lines are written on its page, so the PDF writer offsets their text
        // objects by the steps of the page's size and orientation, not of the story page's
        // endless height.
        layout.device = layout
            .device
            .with_page(page.width, page.height, page.orientation);
        layout.page = Some(page);
        layout.story_notes = notes;
        layout.style_page = style_page;
        if let Some(earlier) = earlier {
            layout
                .squares
                .extend(earlier.squares.iter().map(|(_, s)| s.clone()));
            layout.bands.extend(earlier.bands.iter().map(|(_, b)| *b));
            for upward in &earlier.upward {
                match &upward.wrap {
                    super::UpwardShape::Band(b) => layout.bands.push(*b),
                    super::UpwardShape::Square(s) => layout.squares.push(s.clone()),
                }
            }
            layout.story_earlier_wraps = Some(Box::new(earlier));
        }
        layout.blocks(blocks);
        layout
    }

    /// Starts the wraps of a new page: the body keeps out of the boxes and bands of the
    /// floating drawings in the page's header and footer, as out of those of its own
    /// drawings.
    pub(super) fn start_wraps(&mut self) {
        self.bands.clear();
        self.squares.clear();
        self.frame_boxes.clear();
        let kind = self.kind(self.output.pages.len());
        let number = self.page_number(self.output.pages.len());
        let numbers = StoryNumbers::on_page(number, number);
        let section = margin_story(&self.section);
        let mut squares = Vec::new();
        let mut bands = Vec::new();
        let part = self.section_layout(self.section_index);
        let (headers, footers) = (part.headers.clone(), part.footers.clone());
        if let Some(header) = headers.get(kind) {
            let layout = self.header_layout(&section, header, section.header, numbers);
            squares.extend(layout.squares);
            bands.extend(layout.bands);
        }
        if let Some(footer) = footers.get(kind) {
            let height = self.footer_height(&section, footer, numbers);
            let top = footer_start(section.height - section.footer, height);
            let layout = self.footer_layout(&section, footer, top, numbers);
            squares.extend(layout.squares);
            bands.extend(layout.bands);
        }
        // Drawings placed from the page or its margins keep the text out from the top of their
        // page, also before the paragraph that anchors them.
        let index = self.output.pages.len();
        squares.extend(
            self.context
                .earlier
                .wraps
                .squares
                .iter()
                .filter(|(page, _)| *page == index)
                .map(|(_, s)| s.clone()),
        );
        bands.extend(
            self.context
                .earlier
                .wraps
                .bands
                .iter()
                .filter(|(page, _)| *page == index)
                .map(|(_, b)| *b),
        );
        for upward in self
            .context
            .earlier
            .wraps
            .upward
            .iter()
            .filter(|u| u.page == index)
        {
            match &upward.wrap {
                super::UpwardShape::Band(b) => bands.push(*b),
                super::UpwardShape::Square(s) => squares.push(s.clone()),
            }
        }
        self.squares = squares;
        self.bands = bands;
    }

    /// Takes the items of the page being filled, with the drawings behind the text first and
    /// the drawings in front of it last, each layer from the bottom of its stack up.
    fn page_items(&mut self) -> Vec<Item> {
        let stacked = |mut layer: Vec<(u64, Item)>| {
            layer.sort_by_key(|(stack, _)| *stack);
            layer.into_iter().map(|(_, item)| item)
        };
        let mut items: Vec<Item> = stacked(std::mem::take(&mut self.behind)).collect();
        items.append(&mut self.items.take());
        items.extend(stacked(std::mem::take(&mut self.front)));
        items
    }

    /// Moves the body of the page being filled down by half the room below it, or by all of
    /// it, when its section centers the body or puts it at the bottom margin. Drawings that
    /// float and the notes stay where they are.
    fn align_page(&mut self) {
        // The body ends below the space after its last paragraph.
        let after = self.previous.as_ref().map_or(Length::ZERO, |p| p.after);
        let notes = self.notes_height();
        let room = self.page_bottom() - notes - self.y - after;
        let Some(room) = decisions::aligned_room(&self.context.quirks, notes > Length::ZERO, room)
        else {
            return;
        };
        let dy = match self.section.vertical {
            PageAlign::Top => return,
            PageAlign::Center => room.div_toward_zero(2),
            PageAlign::Bottom => room,
        };
        if dy > Length::ZERO && self.column.cell.is_none() {
            self.shift(0..self.items.len(), dy);
        }
    }

    /// Whether nothing has been laid out on the page being filled yet, a floating drawing
    /// included.
    pub(super) fn page_is_empty(&self) -> bool {
        self.items.is_empty() && self.behind.is_empty() && self.front.is_empty()
    }

    /// Whether the page being filled has no line yet: nothing is laid out on it, and the
    /// first column is at the top of the page. An empty paragraph draws nothing and takes its
    /// line, so a page that holds only empty paragraphs is full at its foot as any other.
    pub(super) fn page_has_no_line(&self) -> bool {
        self.page_is_empty()
            && self.column_index == 0
            && self.y <= self.page_top(self.output.pages.len())
    }

    pub(super) fn new_page(&mut self) {
        // Before the page's alignment, which moves the lines with the text.
        self.paint_column_separators();
        self.align_page();
        let index = self.output.pages.len();
        let area = BodyArea {
            top: self.page_top(index),
            end: self.body_bottom_of(index),
            notes: self.notes_height(),
        };
        self.place_notes();
        let info = self.page_info(index);
        self.output.page_infos.push(info);
        self.output.body_areas.push(area);
        let items = self.page_items();
        // A page keeps its exact size; the target's PDF writer rounds it in the output stage.
        // The page carries its section's orientation to the PDF writer's page offsets.
        let section = &self.section;
        self.output.pages.push(Page::new(
            section.width,
            section.height,
            section.orientation,
            items,
        ));
        if let Some(index) = self.pending.take() {
            let saved = self.output.line_count;
            self.adopt(index);
            if self
                .section
                .line_numbers
                .is_some_and(|n| n.restart == crate::body::LineNumberRestart::NewSection)
            {
                self.output.line_count = saved;
            }
            // A continuous section started on the page before, so this page is not its first.
            self.section_title_page = None;
        } else if self.settings.side_margins != crate::styles::SideMargins::Section {
            // The new page takes the side margins of its side.
            let section = self.section_of(self.section_index);
            self.take_side_margins(&section);
            self.set_columns();
        }
        if self.context.earlier.header_styles.0.is_some() {
            self.measure_body();
        }
        self.start_wraps();
        self.move_to_body_top(self.output.pages.len());
        self.first_column();
        if self.endnote.is_some() {
            self.endnote_continuation();
        }
    }

    /// Moves the cursor to the body's top on the page of `index`. The body's top at the top
    /// margin, a length of whole twips from the page's top, starts the cursor's twips rest; a
    /// body below its header starts none.
    pub(super) fn move_to_body_top(&mut self, index: usize) {
        let top = self.page_top(index);
        self.move_to(top);
        // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
        if top == self.section.top {
            self.start_twips(top);
        }
    }
}

/// Where a footer starts so that it ends at `bottom` without a height rest, from the height and
/// the height rest of its first pass from 0: the bottom less that height, and the opposite of
/// that rest, carried into whole half-EMUs as the cursor carries a rest, so that the place and
/// its rest together are the exact top.
fn footer_start(bottom: Length, (height, rest): (Length, i64)) -> (Length, i64) {
    let carry = f_office_units::div_round(-rest, REST_PARTS);
    (
        bottom - height + Length::from_units(carry),
        -rest - carry * REST_PARTS,
    )
}

/// Takes the records of the lines of a story laid out on its own, for the page `index` and
/// the story that the kind of the layout's story names; none for a kind whose lines are not
/// recorded.
fn story_lines(layout: &mut Layout<'_>, index: usize) -> Vec<PlacedLine> {
    let mut lines = std::mem::take(&mut layout.output.placed);
    let Some(story) = layout
        .story
        .as_ref()
        .and_then(|story| story.kind.line_story())
    else {
        return Vec::new();
    };
    for line in &mut lines {
        line.page = index;
        line.story = story;
    }
    lines
}

/// The story of the footnote `id`, whose mark shows `label`.
fn footnote(label: NoteLabel, id: NoteId) -> Story {
    Story {
        kind: StoryKind::Footnote { id },
        numbers: StoryNumbers::of_note(label),
    }
}

/// The story of a footnote separator, whose fields show page 1 of 1.
const fn note_separator(separator: Separator) -> Story {
    Story {
        kind: StoryKind::NoteSeparator(separator),
        numbers: StoryNumbers::PAGE_ONE,
    }
}

/// The outer edges of a section's page borders, before they go to the device's dots, with each
/// side `width` wide: each side's space from the page's edge, or, measured from the text, its
/// space and width outside the margins.
fn outer_edges(borders: &PageBorders, section: &Section, width: &Edges<Length>) -> Edges<Length> {
    let space = borders.sides.map(|side| match side {
        Some(PageSide::Line(border)) => border.space,
        Some(PageSide::Art(art)) => art.space,
        None => Length::ZERO,
    });
    let (page_w, page_h) = (section.width, section.height);
    if borders.from_page {
        Edges {
            left: space.left,
            top: space.top,
            right: page_w - space.right,
            bottom: page_h - space.bottom,
        }
    } else {
        Edges {
            left: section.left - space.left - width.left,
            top: section.top - space.top - width.top,
            right: page_w - section.right + space.right + width.right,
            bottom: page_h - section.bottom + space.bottom + width.bottom,
        }
    }
}

/// The lines of a section's page borders, as filled rectangles. A line's outer edge lies its
/// space from the page edge, or, measured from the text, its space and width outside the
/// margins. The top and bottom lines run across the whole box, and the side lines down it.
/// Word puts each outer edge on the nearest device dot of the page, and each line on the
/// device as the quirk `PageBorderLines` says ([`Device::page_border_lines`]).
/// The bands of a 3-D style touch, and where two sides of 3-D styles meet, their bands nest
/// ([`band_ends`]). A side of an art style is as wide as its corner square, and its pictures
/// come from `pictures` ([`art_borders::art_items`]); this adds the items to `items` and gives
/// the style and size of each art side whose picture `pictures` lacks.
fn page_borders(
    borders: &PageBorders,
    (section, device): (&Section, &Device),
    pictures: &ArtPictures,
    items: &mut Vec<Item>,
) -> Vec<(ArtStyle, u32)> {
    let thick = |width: Length| device.page_border_line(width);
    let sides = borders.sides.map(|side| {
        side.and_then(PageSide::line)
            .map(|b| device.drawn_border(b))
    });
    let arts = borders.sides.map(|side| side.and_then(PageSide::art));
    let art_width = |art: Option<ArtSide>| {
        art.map(|art| device.dots(art_borders::corner_dots(art.size, device)))
    };
    // Each side's lines as their offset from its top or left edge and their thickness; the
    // outer edge of the top and the left sides is their top or left.
    let lines_of = |side: Option<Border>, outer_first: bool| {
        side.map_or_else(Vec::new, |b| {
            if b.touches() {
                b.touching_lines(thick)
            } else {
                device.page_border_lines(b, thick(b.width), outer_first)
            }
        })
    };
    let drawn = Edges {
        left: lines_of(sides.left, true),
        top: lines_of(sides.top, true),
        right: lines_of(sides.right, false),
        bottom: lines_of(sides.bottom, false),
    };
    let width = Edges {
        left: art_width(arts.left).unwrap_or_else(|| side_width(sides.left, &drawn.left, thick)),
        top: art_width(arts.top).unwrap_or_else(|| side_width(sides.top, &drawn.top, thick)),
        right: art_width(arts.right)
            .unwrap_or_else(|| side_width(sides.right, &drawn.right, thick)),
        bottom: art_width(arts.bottom)
            .unwrap_or_else(|| side_width(sides.bottom, &drawn.bottom, thick)),
    };
    let Edges {
        left,
        top,
        right,
        bottom,
    } = outer_edges(borders, section, &width).map(|edge| device.snap(edge));
    let depth = band_depths(&sides, &drawn);
    // The lines in the order top, left, bottom and right, each with its box, whether it runs
    // across, whether its outer edge is its top or left, and the depths of the sides at its
    // ends: the top and bottom lines run across, and the side lines down.
    let lines = [
        (
            (sides.top, &drawn.top),
            [left, top, right - left, width.top],
            true,
            true,
            (depth.left.as_slice(), depth.right.as_slice()),
        ),
        (
            (sides.left, &drawn.left),
            [left, top, width.left, bottom - top],
            false,
            true,
            (depth.top.as_slice(), depth.bottom.as_slice()),
        ),
        (
            (sides.bottom, &drawn.bottom),
            [left, bottom - width.bottom, right - left, width.bottom],
            true,
            false,
            (depth.left.as_slice(), depth.right.as_slice()),
        ),
        (
            (sides.right, &drawn.right),
            [right - width.right, top, width.right, bottom - top],
            false,
            false,
            (depth.top.as_slice(), depth.bottom.as_slice()),
        ),
    ];
    for ((side, drawn), bounds, across, outer_first, ends) in lines {
        if let Some(border) = side {
            side_rects(items, (border, drawn), bounds, (across, outer_first), ends);
        }
    }
    let box_edges = Edges {
        left,
        top,
        right,
        bottom,
    };
    art_borders::art_items(&arts, box_edges, device, pictures, items)
}

/// The thicknesses of each side's lines from its outer edge in, for a side whose lines touch,
/// where its bands nest with those of the sides that it meets; none for another side.
fn band_depths(
    sides: &Edges<Option<Border>>,
    drawn: &Edges<Vec<(Length, Length)>>,
) -> Edges<Vec<Length>> {
    let depths = |side: Option<Border>, lines: &[(Length, Length)], outer_first: bool| {
        let mut depths: Vec<Length> = lines.iter().map(|(_, thickness)| *thickness).collect();
        if !outer_first {
            depths.reverse();
        }
        if side.is_some_and(|b| b.touches()) {
            depths
        } else {
            Vec::new()
        }
    };
    Edges {
        left: depths(sides.left, &drawn.left, true),
        top: depths(sides.top, &drawn.top, true),
        right: depths(sides.right, &drawn.right, false),
        bottom: depths(sides.bottom, &drawn.bottom, false),
    }
}

/// Adds to `items` the lines `drawn` of the page border's side `border` in the box `[x, y, w,
/// h]`: across it from the left when `across`, else down it from the top, at their offsets
/// and thicknesses. With `outer_first` the first line lies at the side's outer edge. The bands
/// of a side whose lines touch end where they nest with the sides at its ends, whose depths
/// are `ends` ([`band_ends`]).
fn side_rects(
    items: &mut Vec<Item>,
    (border, drawn): (Border, &[(Length, Length)]),
    [x, y, w, h]: [Length; 4],
    (across, outer_first): (bool, bool),
    ends: (&[Length], &[Length]),
) {
    let count = drawn.len();
    for (index, (&(offset, thickness), color)) in drawn.iter().zip(border.line_colors()).enumerate()
    {
        let depth = if outer_first {
            index
        } else {
            count - 1 - index
        };
        let nested = if border.touches() {
            band_ends(depth, across, ends)
        } else {
            (Length::ZERO, Length::ZERO)
        };
        let [x, y, width, height] = if across {
            [x + nested.0, y + offset, w - nested.0 - nested.1, thickness]
        } else {
            [x + offset, y + nested.0, thickness, h - nested.0 - nested.1]
        };
        items.push(Item::Rect(Rect {
            x,
            y,
            width,
            height,
            color,
        }));
    }
}

/// How wide a page border's side `side` is on the device, whose lines are `lines`: a side of
/// a 3-D style as wide as its bands as drawn, and any other its width rounded by `thick`.
fn side_width(
    side: Option<Border>,
    lines: &[(Length, Length)],
    thick: impl Fn(Length) -> Length,
) -> Length {
    side.map_or(Length::ZERO, |b| {
        if b.touches() {
            lines.iter().map(|(_, thickness)| *thickness).sum()
        } else {
            thick(b.width)
        }
    })
}

/// How far the band of a page border's 3-D side at `depth` from its outer edge stops short of
/// each end of the side, where it meets the sides `ends` of 3-D styles, given as the
/// thicknesses of their bands from their outer edges in (none for a side of another style).
/// The bands nest: a band of the top or the bottom (`across`) runs to the outer edge of the
/// side's band of the same depth and covers the corner square that they share, and a band of
/// the left or the right side stops at the inner edge of the top's or the bottom's band of the
/// same depth.
fn band_ends(depth: usize, across: bool, (start, end): (&[Length], &[Length])) -> (Length, Length) {
    let reach = |depths: &[Length]| {
        if depths.is_empty() {
            return Length::ZERO;
        }
        let count = if across { depth } else { depth + 1 };
        depths.iter().take(count).copied().sum()
    };
    (reach(start), reach(end))
}

#[cfg(test)]
mod tests;