Skip to main content

f_office_docx/
layout.rs

1//! Paragraphs and pages.
2//!
3//! The layout fills the pages of a body in one pass. Its parts live in submodules: `pages`
4//! for page geometry, headers and footers, `paragraph` for the flow of paragraphs and the
5//! page break rules, `measure` for resolving and measuring paragraphs, `line` for placing and
6//! drawing lines, and `table`, `floating`, `frames`, `notes`, `endnotes` and `sections` for
7//! those parts of a document.
8
9mod art_borders;
10mod bidi;
11mod chart;
12mod columns;
13mod decisions;
14mod endnotes;
15mod floating;
16mod frames;
17mod if_fields;
18mod line;
19mod line_text;
20mod markup;
21mod measure;
22mod metafile;
23mod notes;
24mod output;
25mod page_items;
26mod pages;
27mod paragraph;
28mod sections;
29mod shadow;
30mod style_refs;
31mod table;
32#[cfg(test)]
33mod testing;
34#[cfg(test)]
35mod tests;
36mod text_path;
37
38pub use floating::{LaterAnchors, NoteHeights};
39pub(crate) use line_text::RunSpan;
40pub use line_text::{LineText, LineTextEnd, LineTurn, TextCluster};
41pub use notes::NotePlaces;
42
43use std::borrow::Cow;
44use std::rc::Rc;
45
46use f_office_paint::{DisplayList, Item, Rect, Rgb};
47use f_office_units::{Length, count_factor};
48
49use crate::body::{Block, Body, NoteId, Notes, ParagraphId, Section, SectionStart, Sections};
50use crate::comments::Comments;
51use crate::dates::DateTime;
52use crate::note_setup::{ByNoteKind, NoteLabel, NoteSetup};
53use crate::numbering::{Label, NumberContext, Numbering};
54use crate::props::{ParaProps, RunProps};
55use crate::styles::{Settings, SideMargins, Styles, TableStyle};
56use crate::table::Table;
57use crate::text::Shaper;
58use paragraph::{HeldBorders, NewPageSpace, Previous};
59use sections::SectionIndex;
60
61/// What every flow of a layout pass reads and no flow changes: the document's styles,
62/// settings, lists and parts, the target's device and quirks, the date and the custom
63/// properties, and what an earlier pass found. It has no `Clone`: a later pass takes what the
64/// pass before found in place of `earlier`, and the passes borrow one copy of the document's
65/// parts. The sections of the body are not in it: only the body's layout reads them
66/// (`Layout::new`), and a story fills one section of its own (`Layout::story`).
67pub struct Context<'a> {
68    /// The name of the main document's part, which the warning of a setting names where its
69    /// default acts and no layer of the cascade sets it (`Layout::setting_part`).
70    pub main: &'a str,
71    /// The styles.
72    pub styles: &'a Styles,
73    /// The settings.
74    pub settings: &'a Settings,
75    /// The HTML divs of the web settings part whose margins or borders change their
76    /// paragraphs, of which the layout warns.
77    pub html_divs: &'a crate::web_settings::HtmlDivs<'a>,
78    /// The list definitions, with their counters at the start of the body.
79    pub numbering: Numbering,
80    /// The footnotes.
81    pub notes: Notes,
82    /// The endnotes.
83    pub endnotes: Notes,
84    /// The comments, which Word prints in balloons beside the pages.
85    pub comments: Comments,
86    /// The target's layout device, from its profile.
87    pub device: crate::grid::Device,
88    /// The variant of every quirk that the target's profile names, which the layout's rules
89    /// of tables, VML shapes and page breaks read; the device reads its own quirks.
90    pub quirks: crate::quirks::Quirks,
91    /// The local date and time that `DATE` and `TIME` fields show, or none for their stored
92    /// results.
93    pub now: Option<DateTime>,
94    /// The custom properties of the document, which `DOCPROPERTY` fields show.
95    pub properties: std::sync::Arc<crate::properties::Properties>,
96    /// The time zone of the machine, in minutes east of UTC, in which a target that writes a
97    /// date property as its local date writes it (the last layer's that sets one).
98    pub zone_minutes: i32,
99    /// What an earlier pass found, or nothing in a first pass.
100    pub earlier: EarlierPass,
101    /// The paragraph ID of the label that the balloon of each deleted table cell shows, which
102    /// the layout builds: one ID of the document, as each balloon shows a copy of one label.
103    pub deleted_cell_label: ParagraphId,
104    /// The pictures of the art page borders that the caller gives.
105    pub art: &'a crate::ArtPictures,
106}
107
108impl Context<'_> {
109    /// The context of the stories that the body's pages hold, such as headers, footers,
110    /// footnotes, frames, text boxes and balloons: the same styles, settings, device, date and
111    /// properties, with none of the document's parts and nothing of an earlier pass. It holds
112    /// no lists either: a story's lists go on from the counters of the flow that holds it,
113    /// which its layout takes (`Layout::story`), so a copy here would go unread.
114    /// It copies the behavior from before the shared context, in which each story made its own
115    /// empty parts: in a story, a footnote, endnote or comment reference finds no note or
116    /// comment, and `PAGEREF`, `REF` and `STYLEREF` fields and the wraps of drawings find
117    /// nothing of an earlier pass. Each is an open rule question.
118    #[must_use]
119    pub fn for_stories(&self) -> Self {
120        Self {
121            numbering: Numbering::default(),
122            notes: Notes::default(),
123            endnotes: Notes::default(),
124            comments: Comments::default(),
125            properties: std::sync::Arc::clone(&self.properties),
126            earlier: EarlierPass::default(),
127            ..*self
128        }
129    }
130}
131
132/// What an earlier pass of the layout found, which the next pass shows.
133#[derive(Clone, Default)]
134pub struct EarlierPass {
135    /// The number of pages, which the body's `NUMPAGES` fields show.
136    pub page_count: Option<i64>,
137    /// The wraps of the drawings placed from a page or its margins, by page, which apply from
138    /// the top of their page.
139    pub wraps: PageWraps,
140    /// The page number text of each bookmark, which `PAGEREF` fields show, or `None` before a
141    /// pass found them.
142    pub bookmarks: Option<BookmarkPages>,
143    /// The paragraph number contexts of the bookmarks, which `REF` fields show.
144    pub bookmark_numbers: BookmarkNumbers,
145    /// Whether the `REF` fields keep their stored results, as in the passes that find the pages
146    /// of the bookmarks that `PAGEREF` fields show.
147    pub stored_number_refs: bool,
148    /// The styled text of the pages, which sizes each page's header and footer while the body
149    /// fills the pages, so that a `STYLEREF` field there has the text of its page.
150    pub header_styles: HeaderStyles,
151    /// The place of each footnote among the footnotes whose references stand on its page,
152    /// which numbers the footnotes of a section that starts their numbers again on each page.
153    pub note_places: NotePlaces,
154    /// The drawings placed down from their paragraph whose anchor an earlier pass found on a
155    /// later page than the paragraph's first line, which this pass places from the top of the
156    /// paragraph's part on that page.
157    pub later_anchors: LaterAnchors,
158    /// The height of the footnotes of each page, which the floating drawings of the body that
159    /// count from the body's area keep above its end.
160    pub note_heights: NoteHeights,
161}
162
163/// The styled text of the pages of a layout pass, which `STYLEREF` fields in the headers and
164/// footers of a later pass show while that pass sizes its pages.
165#[derive(Clone, Default)]
166pub struct HeaderStyles(Option<std::rc::Rc<style_refs::StyledPages>>);
167
168/// A section with the headers and footers that it uses.
169#[derive(Clone, Debug)]
170pub struct SectionLayout {
171    /// The page size and margins.
172    pub section: Section,
173    /// How the section starts.
174    pub start: SectionStart,
175    /// The index after the section's last block.
176    pub end: usize,
177    /// Whether the section sets its own first page number.
178    pub restarts_numbers: bool,
179    /// The headers.
180    pub headers: Stories,
181    /// The footers.
182    pub footers: Stories,
183    /// The borders around the pages.
184    pub borders: Option<crate::body::PageBorders>,
185    /// How its footnotes and endnotes are numbered and where they stand: its own elements
186    /// over the settings.
187    pub notes: ByNoteKind<NoteSetup>,
188}
189
190impl SectionLayout {
191    /// A section of the page settings `section` that holds the `blocks` blocks of its flow,
192    /// starts on a new page, sets no page number of its own, has no headers, footers or
193    /// page borders and the notes of a document that sets nothing: the one section of a
194    /// story, the area that the story fills.
195    #[must_use]
196    pub fn plain(section: &Section, blocks: usize) -> Self {
197        Self {
198            section: *section,
199            start: SectionStart::NextPage,
200            end: blocks,
201            restarts_numbers: false,
202            headers: Stories::default(),
203            footers: Stories::default(),
204            borders: None,
205            notes: ByNoteKind::DEFAULT,
206        }
207    }
208}
209
210/// The section and the number of a page.
211#[derive(Clone, Copy, Debug, PartialEq, Eq)]
212struct PageInfo {
213    section: SectionIndex,
214    number: i64,
215    /// Whether the page is the first page of its section.
216    first: bool,
217}
218
219/// The headers or the footers of a section. A missing one is blank. The sections that name
220/// one part share it.
221#[derive(Clone, Debug, Default)]
222pub struct Stories {
223    /// For most pages.
224    pub default: Option<PartStory>,
225    /// For the first page, when the section has a title page.
226    pub first: Option<PartStory>,
227    /// For even pages, when the settings ask for even and odd headers.
228    pub even: Option<PartStory>,
229}
230
231/// A header or a footer: the blocks of its part, and the part's name, which names the story
232/// among the stories of a pass ([`output::StoryKey::Part`]).
233#[derive(Clone, Debug)]
234pub struct PartStory {
235    /// The name of its part, such as `word/header1.xml`.
236    pub part: Rc<str>,
237    /// Its blocks.
238    pub blocks: Rc<[Block]>,
239}
240
241/// Which header and footer a page uses.
242#[derive(Clone, Copy, Debug, PartialEq, Eq)]
243enum Kind {
244    First,
245    Even,
246    Default,
247}
248
249impl Stories {
250    /// The header or footer of the pages of `kind`, or `None` when it is blank: missing, or
251    /// a part without blocks.
252    fn get(&self, kind: Kind) -> Option<&PartStory> {
253        let story = match kind {
254            Kind::First => &self.first,
255            Kind::Even => &self.even,
256            Kind::Default => &self.default,
257        };
258        story.as_ref().filter(|story| !story.blocks.is_empty())
259    }
260}
261
262/// A paragraph's properties after the cascade, and its list label.
263struct Resolved {
264    props: ParaProps,
265    run: RunProps,
266    label: Option<Label>,
267    /// How far the label starts before the start of the first line: its width when it ends
268    /// there, half of it when it is centered there.
269    label_shift: Length,
270}
271
272/// The page number text of each bookmark, by its name.
273pub type BookmarkPages = std::collections::HashMap<String, String>;
274
275/// The number context of each bookmark's paragraph.
276pub type BookmarkNumbers = std::collections::HashMap<String, NumberContext>;
277
278/// A band that a `wrapTopAndBottom` floating drawing or `notBeside` frame keeps free of text,
279/// with its vertical extent (`top` to `bottom`) and horizontal extent (`left` to `right`).
280#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
281pub(super) struct Band {
282    top: Length,
283    bottom: Length,
284    left: Length,
285    right: Length,
286}
287
288/// The wrap box or band of a paragraph- or line-anchored drawing whose wrap reaches above its
289/// anchor.
290#[derive(Clone, Debug, PartialEq, Eq)]
291enum UpwardShape {
292    Band(Band),
293    Square(floating::Square),
294}
295
296/// A paragraph- or line-anchored wrapped drawing whose wrap top reached above its anchor on an
297/// earlier pass: its page, its floating-drawing ordinal, its pinned vertical position `y`, and
298/// its wrap shape.
299#[derive(Clone, Debug, PartialEq, Eq)]
300struct UpwardWrap {
301    page: usize,
302    ordinal: usize,
303    y: Length,
304    wrap: UpwardShape,
305}
306
307/// The wraps of floating drawings that are placed from a page or its margins, with the index
308/// of the page that each one lies on, plus paragraph- or line-anchored wraps that reach above
309/// their anchor.
310#[derive(Clone, Debug, Default)]
311pub struct PageWraps {
312    bands: Vec<(usize, Band)>,
313    squares: Vec<(usize, floating::Square)>,
314    /// Paragraph- or line-anchored wrapped drawings whose wrap reaches above their anchor.
315    upward: Vec<UpwardWrap>,
316    /// The pages that the anchor paragraphs of the drawings of the bands and the squares do
317    /// not come before.
318    held: HeldPages,
319}
320
321/// For each band and each square of the page wraps, in their order: the page that the anchor
322/// paragraph of its drawing does not come before, or 0.
323#[derive(Clone, Debug, Default)]
324struct HeldPages {
325    /// The pages of the bands.
326    bands: Vec<usize>,
327    /// The pages of the squares.
328    squares: Vec<usize>,
329}
330
331impl PageWraps {
332    /// The numbers of the bands, squares and upward wraps found so far, which a mark keeps: a
333    /// pass only adds to them (`keep_wrap` and upward-wrap recording).
334    fn counts(&self) -> (usize, usize, usize) {
335        (self.bands.len(), self.squares.len(), self.upward.len())
336    }
337
338    /// Takes back the bands, squares and upward wraps found after `counts`.
339    fn take_back(&mut self, (bands, squares, upward): (usize, usize, usize)) {
340        self.bands.truncate(bands);
341        self.squares.truncate(squares);
342        self.upward.truncate(upward);
343    }
344
345    /// Whether no drawing placed from a page or its margins, or reaching above its anchor, has a
346    /// wrap.
347    pub fn is_empty(&self) -> bool {
348        self.bands.is_empty() && self.squares.is_empty() && self.upward.is_empty()
349    }
350
351    /// The wraps for the pass after one that started its pages with these wraps and found
352    /// `found`, or `None` when it found every drawing on the page whose text its wrap moved.
353    /// The next pass takes the pages that this one found, and a drawing that came to a later
354    /// page than its wrap's page holds its anchor paragraph on that page or after it.
355    #[must_use]
356    pub fn after(&self, found: &Self) -> Option<Self> {
357        let given: Vec<usize> = self.pages().collect();
358        let pages: Vec<usize> = found.pages().collect();
359        let same_drawings =
360            self.bands.len() == found.bands.len() && self.squares.len() == found.squares.len();
361        let early_moved = same_drawings && given != pages;
362        let upward_moved = self.upward != found.upward;
363        if !early_moved && !upward_moved {
364            return None;
365        }
366        let mut next = found.clone();
367        if early_moved {
368            let (bands, squares) = pages.split_at(self.bands.len());
369            let (given_bands, given_squares) = given.split_at(self.bands.len());
370            next.held = HeldPages {
371                bands: holds(&self.held.bands, given_bands, bands),
372                squares: holds(&self.held.squares, given_squares, squares),
373            };
374        } else {
375            next.held = self.held.clone();
376        }
377        Some(next)
378    }
379
380    /// The page of each band and then of each square.
381    fn pages(&self) -> impl Iterator<Item = usize> + '_ {
382        let bands = self.bands.iter().map(|(page, _)| *page);
383        bands.chain(self.squares.iter().map(|(page, _)| *page))
384    }
385}
386
387/// The pages that the anchors of drawings are held on: for each drawing the page `found` where
388/// it lies after its wrap's page `given`, or else the page that `held` it on before.
389fn holds(held: &[usize], given: &[usize], found: &[usize]) -> Vec<usize> {
390    let before = |at: usize| held.get(at).copied().unwrap_or(0);
391    given
392        .iter()
393        .zip(found)
394        .enumerate()
395        .map(|(at, (given, found))| {
396            if found > given {
397                before(at).max(*found)
398            } else {
399                before(at)
400            }
401        })
402        .collect()
403}
404
405/// The story that a placed line belongs to.
406#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
407pub enum LineStory {
408    /// The main text of the document.
409    Body,
410    /// A page's header.
411    Header,
412    /// A page's footer.
413    Footer,
414    /// A footnote at the bottom of a page.
415    Footnote,
416    /// The text of a text box or a shape.
417    TextBox,
418}
419
420/// The part of its story that a placed line belongs to, for the text map, which reads each part
421/// as a story of its own (**Story part**). The layout does not read it.
422#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
423pub enum StoryPart {
424    /// The story's own text.
425    #[default]
426    Own,
427    /// The endnotes, which flow in the body after its text.
428    Endnotes,
429    /// The content of a frame of the body, by the number of its layout in the pass.
430    Frame(u32),
431    /// The text of one text box or shape, by the number of its layout in the pass.
432    TextBox(u32),
433}
434
435/// Where in its story a placed line lies.
436#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
437pub enum LineArea {
438    /// Outside tables.
439    OutsideTables,
440    /// In a table cell. A row moves its cells' lines with their items.
441    TableCell,
442}
443
444impl LineArea {
445    /// The area of a line that the page breaks (`paginate`), outside tables, or else in a
446    /// table cell.
447    pub(crate) const fn of(paginate: bool) -> Self {
448        if paginate {
449            Self::OutsideTables
450        } else {
451            Self::TableCell
452        }
453    }
454}
455
456/// Which places and parts of a line the page rounds to the device's dots to put its baseline
457/// (**Baseline form**). The parts that round are lengths of the line's box: its height, the
458/// paragraph's own space before that it holds, its ascent and its descent, and the parts above
459/// and below its baseline.
460#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
461pub enum BaselineForm {
462    /// Single spacing whose box's height rounds up: the exact bottom rounds, and the baseline
463    /// sits the rounded descent above it.
464    SingleBottom,
465    /// Single spacing whose box's height rounds down: the box's top rounds, and the baseline
466    /// sits below it where the device's quirk `SingleBaseline` puts it in the rounded height.
467    SingleTop,
468    /// A line whose at-least minimum sets its height and whose box rounds down: the box's top
469    /// and its height round, and the baseline sits the rounded part below the baseline above
470    /// that bottom.
471    AtLeastBox,
472    /// A line of exact spacing whose box rounds down, under the quirk `ExactBaseline::BoxForms`:
473    /// the box's top rounds, and the baseline sits below it as in the rounded-down box of a
474    /// single line.
475    ExactBox,
476    /// A line of exact spacing, or one whose at-least minimum sets its height: the exact bottom
477    /// rounds, and the baseline sits the rounded part below the baseline above it.
478    Bottom,
479    /// A line of exact spacing that ends its paragraph outside table cells, with the space
480    /// after following it, under `ExactSpacedBottom::PartsRounded`: the exact top and the
481    /// exact height round each on their own, and the baseline sits the rounded part below the
482    /// baseline above their sum.
483    SpacedBottom,
484    /// A box that holds its paragraph's spaces where the descent goes above the extra spacing,
485    /// or that holds the space after of a line whose at-least minimum sets its height: the
486    /// box's top rounds, and the baseline sits the larger of the rounded part above it and the
487    /// rounded descent part below that top.
488    HeldSpaces,
489    /// Multiple spacing below the paragraph's own space before: the box's top, the space before
490    /// and the baseline's offset each round.
491    SpaceAndAscent,
492    /// A baseline whole dots below the top: the top rounds.
493    WholeDotsBelowTop,
494    /// A single line in the steps of a line grid under `GridSingleLine::PartsRounded`: the top
495    /// rounds, a half up the page, and the baseline lies whole dots below it.
496    GridSteps,
497    /// A centered line of multiple spacing whose middle rounds
498    /// (`CenteredMultiple::MiddleRounded`): the box's top, the space before and the line's
499    /// ascent less the middle of its face's win line, or the box's height, the part below its
500    /// single line and half the win line, each round, and the baseline lies half the face's
501    /// pixel line below that middle.
502    CenteredMiddle,
503    /// A line below single spacing under `LowMultipleBaseline::HeightFraction`: the top rounds,
504    /// and the baseline less half the part of a dot of the line's height rounds below it, where
505    /// that part is less than half a dot; otherwise the exact bottom rounds, and the part below
506    /// the baseline rounds above it.
507    HeightFraction,
508    /// The exact baseline rounds once.
509    Baseline,
510}
511
512/// Whether the block `next` is a table that goes on the floating table `table` as more rows
513/// of it: Word joins floating tables with the same properties and grid that follow each
514/// other directly.
515fn goes_on(table: &Table, next: Option<&Block>) -> bool {
516    let floats = table.props.placement.is_some();
517    matches!(next, Some(Block::Table(next)) if floats && next.props.lays_out_as(&table.props) && next.grid == table.grid)
518}
519
520/// The blocks of a story after a point, as the chunks of [`Layout::blocks`]: runs of
521/// paragraphs, and tables, each a chunk of its own. A chain of kept paragraphs or table rows
522/// looks into them.
523#[derive(Clone, Copy, Default)]
524pub(super) struct Rest<'b>(&'b [&'b [Block]]);
525
526impl<'b> Rest<'b> {
527    /// Whether no block comes after the point: the point is the end of the story.
528    pub(super) const fn is_end(self) -> bool {
529        self.0.is_empty()
530    }
531
532    /// The table that comes first, and the blocks after it.
533    pub(super) fn table(self) -> Option<(&'b Table, Self)> {
534        let (first, rest) = self.0.split_first()?;
535        match first.first() {
536            Some(Block::Table(table)) => Some((table, Self(rest))),
537            _ => None,
538        }
539    }
540
541    /// The paragraphs that come first, none when a table comes first, and the blocks after
542    /// them.
543    pub(super) fn paragraphs(self) -> (Vec<&'b crate::body::Paragraph>, Self) {
544        let paragraph = |block: &'b Block| match block {
545            Block::Paragraph(paragraph) => Some(paragraph),
546            Block::Table(_) => None,
547        };
548        match self.0.split_first() {
549            Some((first, rest)) if self.table().is_none() => {
550                (first.iter().filter_map(paragraph).collect(), Self(rest))
551            }
552            _ => (Vec::new(), self),
553        }
554    }
555}
556
557/// The parts of the left edge of an upright table cell's text, from which its lines count
558/// their start: the x of the table's leftmost grid line, the x of the grid line on the cell's
559/// left, and the part of the text edge that lies inside the cell's edge, its left margin.
560#[derive(Clone, Copy, Debug, PartialEq, Eq)]
561pub struct CellEdgeParts {
562    /// The x of the table's leftmost grid line.
563    pub table: Length,
564    /// The x of the grid line on the cell's left.
565    pub grid: Length,
566    /// The part of the text edge inside the cell's edge: the cell's left margin.
567    pub inner: Length,
568    /// The outer edge of a centered table that a target keeps in fixed-point points
569    /// (`CenteredTablePlace::FixedPointHalf`), from which the text edge then counts its parts.
570    pub outer: Option<crate::grid::FixedPlace>,
571}
572
573/// How a centered or a right-aligned line that starts on a dot found its start: the dot of its
574/// start at its indent, the dot where its written text ends from there, the dot of its space's
575/// right edge, and the space's exact place, its indent past the column's left edge and its
576/// width.
577#[derive(Clone, Copy, Debug, PartialEq, Eq)]
578pub struct AlignedParts {
579    /// The dot of the line's start at its indent.
580    pub start: Length,
581    /// The dot where its written text ends when it is drawn from `start`.
582    pub end: Length,
583    /// The dot of its space's right edge.
584    pub edge: Length,
585    /// The space's indent past the column's left edge.
586    pub indent: Length,
587    /// The space's width.
588    pub width: Length,
589}
590
591/// The table cell that a placed line lies in, each number from 1.
592#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
593pub struct CellPlace {
594    /// The table, in the order in which the layout of its story starts its tables, nested
595    /// tables too. A header or a footer counts its tables on each page anew.
596    pub table: usize,
597    /// The row of the table.
598    pub row: usize,
599    /// The first grid column that the cell covers.
600    pub column: usize,
601}
602
603/// The widths of the grid columns that the layout gave one table of the body, nested tables
604/// too, for a tool that compares them with the grid that the file saved.
605#[derive(Clone, Debug, PartialEq, Eq)]
606pub struct TableColumns {
607    /// The table's number, as [`CellPlace::table`] counts it.
608    pub table: usize,
609    /// The widths of its grid columns, from its leading edge.
610    pub widths: Vec<Length>,
611}
612
613/// Where the items of a placed line lie among the items of its page while the layout runs.
614#[derive(Clone, Copy, Debug, PartialEq, Eq)]
615pub enum FirstItem {
616    /// Its first item has this index among the items of its page.
617    At(usize),
618    /// A carried line: its items join the page later as a whole. It is a line that a row that
619    /// splits carries to the next column or page, or a line of a footnote or a text box. No
620    /// move of the page's items applies to it.
621    Carried,
622}
623
624impl FirstItem {
625    /// The index of the first item, or `None` for a carried line.
626    #[must_use]
627    pub const fn index(self) -> Option<usize> {
628        match self {
629            Self::At(index) => Some(index),
630            Self::Carried => None,
631        }
632    }
633}
634
635/// What a line records of a glyph that it draws: not a space, which it places but draws
636/// nothing for.
637#[derive(Clone, Copy, Debug, PartialEq, Eq)]
638pub struct DrawnGlyph {
639    /// The length that the run's character spacing adds to the glyph's advance.
640    pub spacing: Length,
641    /// The unrounded place from which the device's steps place the glyph, on the page.
642    pub x: Length,
643    /// The place on the page that the line's steps give the glyph, before the PDF writer
644    /// moves it with its text object to that object's written start.
645    pub place: Length,
646    /// The spaces, stretched or not, that the line places between the drawn glyph before and
647    /// this one.
648    pub spaces: u32,
649    /// Where the device's steps started again since the drawn glyph before.
650    pub started: StepsStart,
651    /// What the edge check of the device's steps found at the glyph, when the steps placed it
652    /// from the glyph before (`EdgeSteps::take_checked`). The steps of right-to-left text run
653    /// in reading order, from the right, and their check counts edges and moves in that order.
654    pub checked: Option<crate::grid::EdgeCheck>,
655    /// Why the PDF writer started its first text object since the drawn glyph before, at a
656    /// space before this glyph or at the glyph, if it started one. Only the tests read it.
657    pub object_start: Option<crate::grid::ObjectStart>,
658    /// The place that the device's steps rounded to the glyph's dot, when they started again at
659    /// the glyph (`EdgeSteps::take_start_place`): its exact place, or for a glyph that starts a
660    /// segment the place that the segment rule counts. Only the tests read it.
661    pub start_place: Option<Length>,
662}
663
664/// Where the device's steps started again between the drawn glyph before and a drawn glyph, as
665/// they do at a line's start, after a tab or a gap, and at the end of a segment
666/// (`EdgeSteps::started`).
667#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
668pub enum StepsStart {
669    /// They did not, or the target keeps the PDF writer's steps.
670    #[default]
671    Stepped,
672    /// At the drawn glyph.
673    Glyph,
674    /// At one of the spaces before it: the n-th, from 1 for the first after the drawn glyph
675    /// before.
676    Space(u32),
677}
678
679/// A line of the body, a header, a footer, a footnote or a text box that the layout placed,
680/// outside tables or in a table cell, with the exact values before the page rounds its
681/// baseline. Every line keeps one, which table rows move with its items.
682#[derive(Clone, Debug, PartialEq, Eq)]
683pub struct PlacedLine {
684    /// The paragraph whose line it is, which a text block finds its pages by.
685    pub paragraph: ParagraphId,
686    /// The index of its page.
687    pub page: usize,
688    /// The story that it belongs to.
689    pub story: LineStory,
690    /// The part of its story that it belongs to.
691    pub part: StoryPart,
692    /// Whether it lies outside tables or in a table cell.
693    pub area: LineArea,
694    /// The table cell that it lies in, when it lies in one.
695    pub cell: Option<CellPlace>,
696    /// Where its items lie among the items of its page, while the layout runs.
697    pub item: FirstItem,
698    /// Its exact top on the page.
699    pub top: Length,
700    /// What its exact top lies past `top`, in 1/512 of a half-EMU: the height rest that the
701    /// layout's cursor carried there, and the twips rest where the cursor keeps one there. A
702    /// table cell that moves its lines for its vertical alignment keeps the rests of their place
703    /// before the move.
704    pub top_rests: (i64, Option<i64>),
705    /// The height that the next line starts below its top.
706    pub height: Length,
707    /// What its exact height lies past `height`, in 1/512 of a half-EMU, and its twips rest
708    /// where its height is a length of whole twips or of whole 1/4096 pt.
709    pub height_rests: (i64, Option<i64>),
710    /// The offset of its baseline from its top.
711    pub baseline: Length,
712    /// The exact offset of its baseline from its top, before the page rounds its places and
713    /// parts to the device's dots.
714    pub unrounded_baseline: Length,
715    /// Which places and parts of the line the page rounded to put its baseline on the device's
716    /// dots.
717    pub baseline_form: BaselineForm,
718    /// How far its text goes above the baseline.
719    pub ascent: Length,
720    /// How far its text goes below the baseline.
721    pub descent: Length,
722    /// The line spacing of its paragraph.
723    pub spacing: crate::props::LineSpacing,
724    /// The index of the line in its paragraph, 0 for the first.
725    pub index: usize,
726    /// Whether it is the last line of its paragraph.
727    pub last: bool,
728    /// Whether its paragraph's space after follows it: a last line whose space after the next
729    /// paragraph does not remove.
730    pub spaced: bool,
731    /// The paragraph's own space before above it, on a first line that keeps it.
732    pub before: Length,
733    /// The decision that kept its last word on it.
734    pub kept: Option<crate::lines::Fit>,
735    /// For a line that ends before a word that does not fit, the decision that moved the word
736    /// to the next line.
737    pub wrapped: Option<crate::lines::Fit>,
738    /// Whether its paragraph is justified.
739    pub justified: bool,
740    /// How the line itself is aligned, after the last line of a justified paragraph and
741    /// right-to-left text change its paragraph's alignment.
742    pub alignment: crate::props::Alignment,
743    /// What lies before each glyph that the line draws, in the order of drawing.
744    pub steps: Vec<crate::lines::Step>,
745    /// What the line records of each glyph that it draws, in the order of drawing.
746    pub drawn: Vec<DrawnGlyph>,
747    /// How much each space that stretches gains on the line, below 0 when the spaces shrink.
748    pub spread: Length,
749    /// The free space that the line spreads over its stretched spaces, before each space's
750    /// share of it goes toward zero to a whole half-EMU ([`Self::spread`]); 0 when its spaces
751    /// neither stretch nor shrink.
752    pub free_space: Length,
753    /// What rounding to whole half-EMUs took from the advances of the line's glyphs from its
754    /// last tab to its last visible piece, in thousandths of a half-EMU to the nearest one: the
755    /// part of the free space that the rounded advances leave out. 0 when its spaces neither
756    /// stretch nor shrink.
757    pub free_rounding_thousandths: i64,
758    /// The dot of the edge that the line counts its start from: its column's left edge on the
759    /// nearest dot, or the wrap edge of a drawing on its left.
760    pub edge: Length,
761    /// The exact left edge of the line's column before it goes to a dot: the left edge of the
762    /// page's column, or for a line of a table cell the left edge of the cell's text, its left
763    /// margin and the table's place past the column included.
764    pub column_left: Length,
765    /// The left edge of the page's column that holds the line's column.
766    pub column_origin: Length,
767    /// For a line of an upright table cell, the parts of the cell's text edge.
768    pub cell_edge: Option<CellEdgeParts>,
769    /// For a centered or a right-aligned line that starts on a dot, how it found its start.
770    pub aligned: Option<AlignedParts>,
771    /// When its page prints with the markup area, the scale of that print in steps of 1/300
772    /// (`MARKUP_SCALE_STEPS`). Its top and baseline are then those of the printed page, and
773    /// its heights those of the layout.
774    pub markup_scale: Option<i64>,
775    /// The text that it shows, with the edges of its clusters on the page.
776    pub text: LineText,
777}
778
779impl PlacedLine {
780    /// Moves the line `dy` down the page: its top, or for a turned line the place of its frame
781    /// on the page, whose own places stay.
782    pub(crate) fn move_down(&mut self, dy: Length) {
783        match &mut self.text.turn {
784            Some(turn) => turn.to.1 += dy,
785            None => self.top += dy,
786        }
787    }
788
789    /// Moves the line `dx` right across the page: its column edges and clusters, or for a turned
790    /// line the place of its frame on the page.
791    pub(crate) fn move_right(&mut self, dx: Length) {
792        if dx == Length::ZERO {
793            return;
794        }
795        self.edge += dx;
796        self.column_left += dx;
797        self.column_origin += dx;
798        if let Some(turn) = &mut self.text.turn {
799            turn.to.0 += dx;
800        } else {
801            self.text.left += dx;
802            for cluster in &mut self.text.clusters {
803                cluster.left += dx;
804                cluster.right += dx;
805            }
806        }
807    }
808
809    /// Whether the line lies upright on the page, and not in a frame that turned onto it.
810    pub(crate) const fn upright(&self) -> bool {
811        self.text.turn.is_none()
812    }
813}
814
815/// The last widths of each table number of `starts`, in the order of the numbers.
816fn last_columns(starts: Vec<TableColumns>) -> Vec<TableColumns> {
817    let mut last = std::collections::BTreeMap::new();
818    for columns in starts {
819        last.insert(columns.table, columns);
820    }
821    last.into_values().collect()
822}
823
824/// What a layout pass gives: the pages, and what a later pass needs from them.
825pub struct Pass {
826    /// The pages.
827    pub list: DisplayList,
828    /// The wraps of the drawings placed from a page or its margins.
829    pub wraps: PageWraps,
830    /// The page number text of the bookmarks.
831    pub bookmarks: BookmarkPages,
832    /// The paragraph numbers of the bookmarks.
833    pub bookmark_numbers: BookmarkNumbers,
834    /// The styled text of the pages.
835    pub styles: HeaderStyles,
836    /// The place of each footnote on its page.
837    pub note_places: NotePlaces,
838    /// The drawings placed down from their paragraph whose anchor stood on a later page than
839    /// the paragraph's first line.
840    pub later_anchors: LaterAnchors,
841    /// The height of the footnotes of each page.
842    pub note_heights: NoteHeights,
843    /// Whether a floating drawing of the body that counts from the body's area took other
844    /// footnotes than its page holds, so that a next pass places it with those of this pass.
845    pub notes_missed: bool,
846    /// The lines outside tables, in the order of placing.
847    pub lines: Vec<PlacedLine>,
848    /// The widths of the grid columns of the body's tables, the last that the pass gave each.
849    pub tables: Vec<TableColumns>,
850    /// The warnings of the pass and of its stories.
851    pub warnings: crate::Warnings,
852    /// The fonts that the pass and its stories drew in another way than the runs ask.
853    pub font_notes: crate::text::FontNotes,
854}
855
856/// How a line that holds nothing meets the floating drawings of its story.
857#[derive(Clone, Copy, Debug, PartialEq, Eq)]
858enum EmptyLines {
859    /// It goes below or beside them, as other lines do.
860    Wrap,
861    /// It stays where it is, as in a header of more than one paragraph.
862    Stay,
863}
864
865/// The kind of a story that a layout fills on the body's pages. It decides how the story's
866/// lines meet the drawings, which way they round, whether frames apply in it and how its line
867/// records are named. The kinds whose warnings count once hold the name of their story
868/// ([`Self::key`]). The body is no story.
869#[derive(Clone, Debug, PartialEq, Eq)]
870enum StoryKind {
871    /// A page's header.
872    Header {
873        /// Whether the header holds more than one block.
874        several_blocks: bool,
875        /// The name of its part.
876        part: Rc<str>,
877    },
878    /// A page's footer.
879    Footer {
880        /// The name of its part.
881        part: Rc<str>,
882    },
883    /// A footnote.
884    Footnote {
885        /// Its ID in the footnotes part.
886        id: NoteId,
887    },
888    /// A separator of the footnotes: above a page's footnotes, or above the part of a
889    /// footnote that goes on.
890    NoteSeparator(notes::Separator),
891    /// The endnotes' continuation separator, at the top of a page that the endnotes go on to.
892    EndnoteContinuation,
893    /// The content of a frame.
894    Frame {
895        /// The frame's box on the page, outside which its inline pictures show nothing on a
896        /// target that cuts them; `None` while the frame is measured.
897        inside: Option<f_office_units::Edges<Length>>,
898    },
899    /// The text of a text box or a shape.
900    TextBox {
901        /// The color of its text whose own color is automatic or missing, from the shape's
902        /// style, `None` when the style gives none.
903        text_color: Option<[u8; 3]>,
904        /// The turn that takes the frame of a text box whose body turns its text onto the
905        /// page, whose lines are then a turned frame's, with how its glyphs lie there, or
906        /// `None` for upright text.
907        turn: Option<(f_office_paint::Turn, TurnedGlyphs)>,
908        /// Which rules its lines take.
909        box_text: crate::floating::BoxText,
910        /// The box's text area on the page, inside its insets and its line, outside which its
911        /// inline pictures show nothing on a target that cuts them; `None` while the text is
912        /// measured, for the text of a SmartArt graphic's shape, and for text turned onto the
913        /// page.
914        inside: Option<f_office_units::Edges<Length>>,
915    },
916    /// The text of a comment balloon.
917    Balloon,
918}
919
920impl StoryKind {
921    /// How a line that holds nothing meets the floating drawings: in a header of more than
922    /// one block it stays where it is.
923    const fn empty_lines(&self) -> EmptyLines {
924        match self {
925            Self::Header {
926                several_blocks: true,
927                ..
928            } => EmptyLines::Stay,
929            _ => EmptyLines::Wrap,
930        }
931    }
932
933    /// Which way a position of a line halfway between two device dots rounds: up the page in
934    /// a header, and in a footer down the page except a line's bottom, which the device's quirk
935    /// `FooterHalves` decides.
936    const fn ties(&self) -> line::height::Ties {
937        match self {
938            Self::Header { .. } => line::height::Ties::TowardTop,
939            Self::Footer { .. } => line::height::Ties::Footer,
940            _ => line::height::Ties::AwayFromTop,
941        }
942    }
943
944    /// The name of the story among the stories of a pass, for the kinds whose warnings count
945    /// as those of one layout of the story, whatever the number of its layouts
946    /// ([`output::PassOutput::join_story_warnings`]): a header or a footer, which the layout
947    /// lays out on each page that shows it and to measure it, by its part; a footnote, laid
948    /// out to measure it, to find its breaks and to place it, whole or in parts, by its ID; and
949    /// a separator, laid out on each page with footnotes, whose height each line that brings a
950    /// page's first footnotes asks, by its kind. `None` for the endnotes' continuation
951    /// separator, laid out once on each page that it starts, a frame, a text box and a
952    /// balloon, whose layouts each add their warnings.
953    fn key(&self) -> Option<output::StoryKey> {
954        match self {
955            Self::Header { part, .. } | Self::Footer { part } => {
956                Some(output::StoryKey::Part(Rc::clone(part)))
957            }
958            Self::Footnote { id } => Some(output::StoryKey::Footnote(*id)),
959            Self::NoteSeparator(separator) => Some(output::StoryKey::Separator(*separator)),
960            Self::EndnoteContinuation
961            | Self::Frame { .. }
962            | Self::TextBox { .. }
963            | Self::Balloon => None,
964        }
965    }
966
967    /// The part of its story that a layout of the story numbered `number` gives the lines that
968    /// it places: a frame and a text box are each a part of their own; `None` for the kinds
969    /// whose lines keep their own part.
970    const fn part(&self, number: u32) -> Option<StoryPart> {
971        match self {
972            Self::Frame { .. } => Some(StoryPart::Frame(number)),
973            Self::TextBox { .. } => Some(StoryPart::TextBox(number)),
974            _ => None,
975        }
976    }
977
978    /// Whether the story ends below the space after of its last paragraph: a frame is as tall
979    /// as its lines and that space.
980    const fn ends_below_space_after(&self) -> bool {
981        matches!(self, Self::Frame { .. })
982    }
983
984    /// Whether frames apply in the story: not inside a frame or a text box.
985    const fn holds_frames(&self) -> bool {
986        !matches!(self, Self::Frame { .. } | Self::TextBox { .. })
987    }
988
989    /// The story of the records of the story's lines, for the kinds whose lines are recorded.
990    /// The lines of a frame are recorded as lines of the body; a header, a footer
991    /// or a footnote that holds the frame takes them as its own lines.
992    const fn line_story(&self) -> Option<LineStory> {
993        match self {
994            Self::Header { .. } => Some(LineStory::Header),
995            Self::Footer { .. } => Some(LineStory::Footer),
996            Self::Footnote { .. } => Some(LineStory::Footnote),
997            Self::TextBox { .. } => Some(LineStory::TextBox),
998            Self::Frame { .. } => Some(LineStory::Body),
999            Self::NoteSeparator(_) | Self::EndnoteContinuation | Self::Balloon => None,
1000        }
1001    }
1002}
1003
1004/// The numbers that the fields of a story show.
1005#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1006struct StoryNumbers {
1007    /// The page number, which `PAGE` shows.
1008    page: i64,
1009    /// The page count, which `NUMPAGES` shows.
1010    pages: i64,
1011    /// The label of the footnote that the story belongs to, which a footnote mark shows.
1012    note: Option<NoteLabel>,
1013}
1014
1015impl StoryNumbers {
1016    /// Page 1 of 1 and no footnote: the numbers of a story laid out apart from the page
1017    /// count, such as a footnote's separator, a balloon, or a header measured for its height.
1018    const PAGE_ONE: Self = Self::on_page(1, 1);
1019
1020    /// Page `page` of `pages`, and no footnote.
1021    const fn on_page(page: i64, pages: i64) -> Self {
1022        Self {
1023            page,
1024            pages,
1025            note: None,
1026        }
1027    }
1028
1029    /// The numbers of the footnote whose mark shows `label`, on page 1 of 1.
1030    const fn of_note(label: NoteLabel) -> Self {
1031        Self {
1032            note: Some(label),
1033            ..Self::PAGE_ONE
1034        }
1035    }
1036}
1037
1038/// A story that a layout fills: its kind and the numbers that its fields show.
1039#[derive(Clone, Debug, PartialEq, Eq)]
1040struct Story {
1041    kind: StoryKind,
1042    numbers: StoryNumbers,
1043}
1044
1045/// The twips rest of the cursor: the part of a half-EMU, in 1/512 of one, by which the lengths
1046/// of whole twips from the body's top on the page down to the place `at`, each in the target's
1047/// unit (`TwipLengthUnit`), lie past their exact sum (`line::height::twips_rest`).
1048#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1049struct TwipsRest {
1050    at: Length,
1051    rest: i64,
1052}
1053
1054/// The rests of a table cell laid out in a row: the twips rest at its bottom where it is known
1055/// (`end`), the twips rest at its text top (`top`) and the height rest there (`top_height`),
1056/// and, where its content sets its bottom, the height rest there (`end_height`) and the sum of
1057/// the height rest and the twips rest there (`bottom`).
1058#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1059struct CellRests {
1060    end: Option<TwipsRest>,
1061    top: Option<i64>,
1062    top_height: i64,
1063    end_height: Option<i64>,
1064    bottom: Option<i64>,
1065}
1066
1067/// The rests of a place of a table row that the rows carry, `at`: its twips rest (`twips`)
1068/// and its height rest (`height`). At a row's end, the height rest is that of the cell whose
1069/// content sets the end, and 0 where the row's height rule sets it.
1070#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1071struct RowRests {
1072    at: Length,
1073    twips: i64,
1074    height: i64,
1075}
1076
1077/// The rests that the text top of a table cell takes where the cell moves down for its
1078/// vertical alignment: the twips rest that it had there before the move (`twips`), and the
1079/// height rest of the move (`rest`).
1080#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1081struct MovedTop {
1082    twips: Option<i64>,
1083    rest: i64,
1084}
1085
1086/// The twips rests of the table row being laid out, each with the place that it belongs to:
1087/// the text top of its cells below its top border, the rests of the cell laid out last
1088/// (`cell`), and the row's end, with their height rests; the rests that the cell being laid out takes at a text top
1089/// that its vertical alignment moved (`moved`); and whether the cell being laid out carries
1090/// its text top's rest from its row (`carried`), where a cell that starts its rest anew leaves
1091/// it `false`.
1092#[derive(Clone, Copy, Default)]
1093struct TableTwips {
1094    row: Option<RowRests>,
1095    cell: CellRests,
1096    row_end: Option<RowRests>,
1097    moved: Option<MovedTop>,
1098    carried: bool,
1099}
1100
1101impl Layout<'_> {
1102    /// Moves the cursor to the place `y`, where a new exact sum of line heights starts: its
1103    /// height rest is 0, and it has no twips rest.
1104    fn move_to(&mut self, y: Length) {
1105        self.y = y;
1106        self.y_rest = 0;
1107        self.y_twips = None;
1108    }
1109
1110    /// How a line that holds nothing meets the floating drawings: as the story's kind says
1111    /// ([`StoryKind::empty_lines`]), and in the body as other lines.
1112    fn empty_lines(&self) -> EmptyLines {
1113        self.story
1114            .as_ref()
1115            .map_or(EmptyLines::Wrap, |story| story.kind.empty_lines())
1116    }
1117
1118    /// Which way a position of a line halfway between two device dots rounds: down the frame of
1119    /// a turned cell whose lines lie on the page's dots, else as
1120    /// the story's kind says ([`StoryKind::ties`]), and down the page in the body, with the
1121    /// rule of a single line's top of a table cell there whose text top starts its twips rest
1122    /// anew.
1123    fn ties(&self) -> line::height::Ties {
1124        if matches!(self.column.within, Within::TurnedFrame(true, ..)) {
1125            return line::height::Ties::TurnedFrame;
1126        }
1127        let ties = self
1128            .story
1129            .as_ref()
1130            .map_or(line::height::Ties::AwayFromTop, |story| story.kind.ties());
1131        if ties == line::height::Ties::AwayFromTop
1132            && self.column.cell.is_some()
1133            && !self.table_twips.carried
1134        {
1135            return line::height::Ties::Cell;
1136        }
1137        ties
1138    }
1139
1140    /// Where the box of a line whose top is `top`, with `space` above it in its box, lies on
1141    /// its page: at the body's top on the page, which a line of the body or of a table row at
1142    /// the page's top reaches, or lower. A line of another story is never there.
1143    fn box_top(&self, (top, space): (Length, line::height::SpaceBefore)) -> line::height::BoxTop {
1144        if self.story.is_none() && top - space.length() == self.page_top(self.output.pages.len()) {
1145            line::height::BoxTop::PageTop
1146        } else {
1147            line::height::BoxTop::Lower
1148        }
1149    }
1150
1151    /// Whether frames apply in this layout: in the body, and in a story whose kind holds them
1152    /// ([`StoryKind::holds_frames`]).
1153    fn holds_frames(&self) -> bool {
1154        self.story
1155            .as_ref()
1156            .is_none_or(|story| story.kind.holds_frames())
1157    }
1158
1159    /// The page number and the page count that the fields of a story show; `None` in the
1160    /// body, which counts its own pages.
1161    fn story_pages(&self) -> Option<(i64, i64)> {
1162        self.story
1163            .as_ref()
1164            .map(|story| (story.numbers.page, story.numbers.pages))
1165    }
1166
1167    /// The label of the footnote that this layout fills, if it fills one.
1168    fn footnote_label(&self) -> Option<NoteLabel> {
1169        self.story.as_ref().and_then(|story| story.numbers.note)
1170    }
1171
1172    /// The page number and the page count of this layout, which a story inside it, such as a
1173    /// frame or a text box, shows: those of this story, or in the body the page's number as
1174    /// both the number and the count. They hold no footnote number.
1175    fn inner_numbers(&self) -> StoryNumbers {
1176        let (page, pages) = self.story_pages().unwrap_or_else(|| {
1177            let number = self.page_number(self.output.pages.len());
1178            (number, number)
1179        });
1180        StoryNumbers::on_page(page, pages)
1181    }
1182
1183    /// Warns that F-Office does not apply `feature` where the part `part` sets it
1184    /// (**Feature not supported**): the one place where the layout gives such a warning.
1185    fn warn_of_feature(&mut self, feature: crate::Feature, part: &str) {
1186        self.output
1187            .warnings
1188            .push(crate::Warning::FeatureNotSupported {
1189                part: f_office_warnings::Name::new(part),
1190                feature,
1191            });
1192    }
1193}
1194
1195impl<'a> Layout<'a> {
1196    /// The name of the part that sets a setting, which acts also where no layer of the cascade
1197    /// sets it: `part`, the part of the layer that sets it ([`crate::props::SetIn`]), or the
1198    /// main document's where its default acts, such as hanging punctuation
1199    /// (`w:overflowPunct`, on by default).
1200    fn setting_part<'p>(&self, part: Option<&'p str>) -> &'p str
1201    where
1202        'a: 'p,
1203    {
1204        part.unwrap_or(self.context.main)
1205    }
1206}
1207
1208/// Whether the chain of kept blocks of the block before the paragraphs about to be laid out
1209/// goes on into the first of them.
1210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1211enum TableChain {
1212    /// The block before is not a table of the body whose last row is kept.
1213    #[default]
1214    Ends,
1215    /// The block before is a table of the body whose last row is kept, so the first
1216    /// paragraph after it goes on that table's chain.
1217    GoesOn,
1218}
1219
1220/// Lays out a body into pages.
1221pub struct Layout<'a> {
1222    /// The context of the pass, which this layout reads.
1223    context: &'a Context<'a>,
1224    /// The context of the stories that this layout makes ([`Context::for_stories`]).
1225    stories: &'a Context<'a>,
1226    styles: &'a Styles,
1227    settings: &'a Settings,
1228    numbering: Numbering,
1229    /// The target's layout device, on which page sizes, column edges, baselines and drawn
1230    /// lines land.
1231    device: crate::grid::Device,
1232    /// The sections of the flow: the body's, which it borrows from its pass, or the one section
1233    /// of a story, its own area. `section_index` names the current one.
1234    sections: Cow<'a, Sections<SectionLayout>>,
1235    /// The page settings of the current section, with the side margins of the page being
1236    /// filled.
1237    section: Section,
1238    shaper: Shaper<'a>,
1239    /// The items of the page being filled, with the table border lines and the cell clips
1240    /// among them ([`page_items::PageItems`]).
1241    items: page_items::PageItems,
1242    /// The places among `items` at which the fills of cells that continue merged regions went
1243    /// under the content of earlier rows, in order, so that going back to a row mark takes
1244    /// them out again.
1245    y: Length,
1246    /// The height rest of the cursor: the part of a half-EMU, in 1/`REST_PARTS` of one, by
1247    /// which the exact sum of the heights of lines held in whole 1/4096 pt lies past `y`
1248    /// (`line::height::LineBox::rest`). A move to a new place starts a new sum
1249    /// ([`Self::move_to`]).
1250    y_rest: i64,
1251    /// The cursor's twips rest and the place that it belongs to (`line::Layout::twips_here`).
1252    /// A move to a new place ends it ([`Self::move_to`]).
1253    y_twips: Option<TwipsRest>,
1254    /// The twips rests that a body table carries from row to row (`table::rows`).
1255    table_twips: TableTwips,
1256    previous: Option<Previous>,
1257    /// Where the body starts on a page of each kind: first, even, default.
1258    tops: [Length; 3],
1259    /// Where the body ends on a page of each kind.
1260    bottoms: [Length; 3],
1261    /// The story that this layout fills, or `None` for the body.
1262    story: Option<Story>,
1263    /// The part that holds the body, which the warnings of the body's sections name: set when
1264    /// the body's layout runs ([`Self::run_with_wraps`]), and empty in a story's layout.
1265    body_part: std::rc::Rc<f_office_warnings::Name>,
1266    /// What this layout adds to its pass and gives back.
1267    output: output::PassOutput,
1268    /// The footnotes of the page being filled.
1269    page_notes: notes::PageNotes,
1270    /// The label of the endnote being laid out. Endnotes flow in the body, after its text.
1271    endnote: Option<NoteLabel>,
1272    /// The comments, and where the body's lines put their anchors.
1273    comment_markup: markup::CommentMarkup<'a>,
1274    /// For a story, such as a header or a text box, the section of the page that it is on,
1275    /// whose height and margins place its floating drawings. A story itself runs on an
1276    /// endless page.
1277    page: Option<Section>,
1278    /// For a story on a page, the height of the page's footnotes, which its floating drawings
1279    /// without wrapping keep above the end of the page's margins.
1280    story_notes: Length,
1281    /// The page whose header or footer is being laid out.
1282    story_page: Option<usize>,
1283    /// The styled text of the body's pages and the page of the header or footer that this
1284    /// layout fills, for its `STYLEREF` fields.
1285    style_page: Option<(std::rc::Rc<style_refs::StyledPages>, usize)>,
1286    /// The paragraph being measured, for relative number references.
1287    number_context: Option<NumberContext>,
1288    /// The bands of the page being filled that floating drawings keep free of text, with their
1289    /// vertical and horizontal extents.
1290    bands: Vec<Band>,
1291    /// The measured texts whose words may take automatic hyphenation points, while a paragraph
1292    /// that the document's automatic hyphenation applies to is measured; else `None`.
1293    hyphen_runs: Option<Vec<measure::HyphenRun>>,
1294    /// The boxes of the page being filled that text flows beside.
1295    squares: Vec<floating::Square>,
1296    /// The boxes of the frames of the body on the page being filled.
1297    frame_boxes: Vec<frames::FrameBox>,
1298    /// The places in the text of the frames of the paragraphs at the indexes that they name,
1299    /// which the paragraph before them, laid out again below the frames' bands, no longer gives.
1300    frame_places: Vec<(usize, Length)>,
1301    /// The further free pieces of the line being placed, on its baseline, beside drawings
1302    /// with room on both sides.
1303    same_baseline: Vec<floating::NarrowedPiece>,
1304    /// The bottom of the first piece of such a line, below which the next line starts.
1305    line_floor: Option<Length>,
1306    /// The items of the floating drawings of the page being filled that lie behind the text,
1307    /// each with its drawing's place in the stack ([`crate::floating::Floating::stack`]).
1308    behind: Vec<(u64, Item)>,
1309    /// The items of the floating drawings of the page being filled that lie in front of the
1310    /// text, each with its drawing's place in the stack.
1311    front: Vec<(u64, Item)>,
1312    column: Column,
1313    /// The left edge and the width of each text column of the section.
1314    columns: Vec<(Length, Length)>,
1315    /// The column being filled.
1316    column_index: usize,
1317    /// Where the columns start on the page being filled.
1318    column_top: Length,
1319    /// How far down each column of the page has been filled.
1320    column_ends: Vec<Length>,
1321    /// The paragraph that ends the section being laid out, when a later section follows: its
1322    /// lines that draw nothing do not reach the line between the columns.
1323    section_end_paragraph: Option<ParagraphId>,
1324    /// While the columns of a section are balanced, how far down they may go.
1325    balance: Option<columns::Balance>,
1326    /// Whether the next paragraph is the first one of a section whose columns are balanced.
1327    section_top: columns::SectionTop,
1328    /// While the first layout of a section of balanced columns keeps them, the mark of the
1329    /// first paragraph of the section that starts on the newest page.
1330    page_marks: Option<columns::PageMarks>,
1331    /// While a cell of a row that splits is laid out: its parts on this page and the pages
1332    /// after it. A floating table in the cell keeps it, so that its cells' lines stop against
1333    /// the cell's limit; another table in the cell takes it for its rows.
1334    fragment: Option<table::Fragment>,
1335    /// Whether a cell that holds the cell being laid out, in a row that splits, has moved on
1336    /// to a later part, so that the lines of this cell are carried lines: part of the state
1337    /// that a table cell starts afresh, which its table passes down to the cell's content.
1338    /// `false` outside a cell.
1339    cell_carried: bool,
1340    /// While a table cell is laid out, the lowest bottoms of the drawings anchored in it that
1341    /// are placed from their paragraph; `None` outside a cell.
1342    cell_floor: Option<table::CellFloor>,
1343    /// While a table cell is laid out, the top of its text below its top margin, which a
1344    /// drawing anchored in it and placed down from the margins counts from; `None` outside a
1345    /// cell.
1346    cell_top: Option<Length>,
1347    /// While a table cell is laid out, the inner edges of its side lines across, between which
1348    /// a drawing anchored in it that wraps text lies on a target that keeps it inside the cell;
1349    /// `None` outside a cell.
1350    cell_sides: Option<(Length, Length)>,
1351    /// While a table cell is laid out, the effective paragraph style ID of the paragraph
1352    /// immediately before the cell in document stream order (the previous cell's last paragraph,
1353    /// the previous row's end-of-row mark as the default style, or the paragraph before the table
1354    /// for the first cell of its first row); `None` outside a cell.
1355    cell_prev_style: Option<String>,
1356    /// While a table is laid out, the effective paragraph style ID of the paragraph immediately
1357    /// before the table (or the enclosing cell's predecessor style for a nested table at cell
1358    /// top); `None` when none preceded it.
1359    table_prev_style: Option<String>,
1360    /// Number of wrapped paragraph- or line-anchored body floating drawings placed so far in this
1361    /// pass, used to match upward-reaching wraps across passes.
1362    body_floatings: usize,
1363    /// Number of wrapped paragraph- or line-anchored floating drawings placed so far in the
1364    /// current table cell.
1365    cell_floatings: usize,
1366    /// Upward-reaching wraps found on pass 1 of the current table cell, active on pass 2.
1367    cell_upward_earlier: Vec<UpwardWrap>,
1368    /// Upward-reaching wraps found during pass 1 of the current table cell.
1369    cell_upward_found: Vec<UpwardWrap>,
1370    /// Wraps found on pass 1 of a mode-15+ header or footer story, active on pass 2.
1371    story_earlier_wraps: Option<Box<PageWraps>>,
1372    /// Whether a paragraph has been laid out, so that the next one is not the first of the
1373    /// document.
1374    started: bool,
1375    /// Whether the last line ended with a page break, so that the next paragraph starts the
1376    /// new page.
1377    after_break: bool,
1378    /// The paragraph without text whose page break ended the last page, until the next
1379    /// paragraph starts the new page: the part of that paragraph's space before that is larger
1380    /// than this one's space after is a space that the new page dropped.
1381    alone_break: Option<Previous>,
1382    /// The last paragraph of the previous section, while a section that starts on a new page
1383    /// has no block yet. Its space after stays on its page.
1384    section_previous: Option<Previous>,
1385    /// Whether the chain of kept blocks of the table before the paragraphs about to be laid
1386    /// out goes on into them.
1387    table_chain: TableChain,
1388    /// The index of the last page that a page break started.
1389    page_from_break: Option<usize>,
1390    /// The number of items that line numbers and the fills of empty paragraphs have put on the
1391    /// page that a page break began, while nothing else has come onto it, and the count of
1392    /// numbered lines at the break.
1393    break_numbers: (usize, (i64, usize)),
1394    /// The pitch of the document grid that the paragraph being laid out follows, if any.
1395    grid_pitch: Option<Length>,
1396    /// The space after the paragraph being laid out that the next paragraph leaves below its
1397    /// last line: none when the next paragraph removes it by contextual spacing or by
1398    /// automatic spacing in one list. `None` where no next paragraph is known, and the
1399    /// paragraph's own space after follows.
1400    following_after: Option<Length>,
1401    /// The last lines of the kept paragraph being laid out that go to the next page with the
1402    /// paragraph after it, when all its lines fit on this page but what follows them does not
1403    /// (`KEPT_SPLIT_MODE`); `None` for every other paragraph.
1404    kept_tail: Option<usize>,
1405    /// What the pieces of the line being drawn share, where its paragraph's text alignment
1406    /// puts the middles of their win lines on one line (`Self::centered_line`); `None` for
1407    /// every other line, and between lines.
1408    centered_middle: Option<line::centered::CenteredMiddle>,
1409    /// The box of the line being drawn, its top and its bottom down the page, with its space
1410    /// before on a paragraph's first line and the space after that it keeps on its last line,
1411    /// for the clip of its inline pictures (`decisions::inline_picture_cut`); `None` between
1412    /// lines.
1413    line_band: Option<(Length, Length)>,
1414    /// The axis above the baseline of the line being drawn in a turned frame whose glyphs of the
1415    /// East Asian font side stand upright ([`TurnedGlyphs::EastAsianUpright`]); `None` for
1416    /// every other line, and between lines.
1417    east_asian_axis: Option<Length>,
1418    /// How the centered or right-aligned line being drawn found its start on a dot, for its
1419    /// record; `None` for every other line, and between lines.
1420    aligned_parts: Option<AlignedParts>,
1421    /// For each glyph of the line being drawn whose run is written, the index of its piece
1422    /// and its drawn place; empty between lines.
1423    glyph_places: Vec<(usize, Length)>,
1424    /// The own space before of the paragraph being laid out, until its first line is placed:
1425    /// a drawing that moves that line down keeps this space above it.
1426    own_space_before: Length,
1427    /// The own space before of the paragraph being laid out as the paragraph starts, until its
1428    /// first line is placed: when it is more than 0, the box of that line takes the form of a
1429    /// box below space before, even where a new page leaves the space out.
1430    first_space_before: Length,
1431    /// The rooms (width and space) of the top and the bottom border of the paragraph being
1432    /// laid out that the boxes of its first and its last line hold, under
1433    /// `BorderSpace::Held`: the first until its first line is placed. Both are 0 otherwise.
1434    held_borders: HeldBorders,
1435    /// The drawings entry of the shaded paragraph of a table cell being laid out, which takes
1436    /// the drawings behind the text that the paragraph anchors, under its fill
1437    /// ([`page_items::PageItems::open_drawings`]); none otherwise.
1438    drawings_under_fill: Option<page_items::FillsEntry>,
1439    /// What the own space before of the paragraph being laid out does at the top of the next
1440    /// page: it stays for the first paragraph after a continuous section end.
1441    new_page_space: NewPageSpace,
1442    /// The page and the index in its items of the change bar beside the last line of the
1443    /// paragraph being laid out, which reaches down past the paragraph's bottom border.
1444    last_bar: Option<(usize, usize)>,
1445    /// The page and the column of the paragraph being laid out, and where its part there
1446    /// starts in its text, in UTF-16 code units: Word counts the pieces of the text again from
1447    /// the paragraph's first character on each page.
1448    text_part: ((usize, usize), u32),
1449    /// The section of the page being filled.
1450    section_index: SectionIndex,
1451    /// The index of the first page of that section.
1452    section_first_page: usize,
1453    /// The index of the page of that section that takes its first-page header and footer:
1454    /// `section_first_page`, or none when the section started with a continuous break on the
1455    /// page before it.
1456    section_title_page: Option<usize>,
1457    /// The number of that page.
1458    number_start: i64,
1459    /// A section that started on this page and takes over its size from the next page on.
1460    pending: Option<usize>,
1461    /// The number of the table whose rows the layout places, or 0 outside tables.
1462    table_number: usize,
1463    /// The table cell whose content the layout places, for the line records.
1464    cell_place: Option<CellPlace>,
1465}
1466
1467/// What holds a column of text.
1468#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1469enum Within {
1470    /// The page, or a story such as a header or a note.
1471    Page,
1472    /// An upright table cell, with the parts of the column's left edge: the table's leftmost
1473    /// grid line, the cell's grid line, and the part that lies inside the cell's edge, the
1474    /// cell's left margin.
1475    Cell(CellEdgeParts),
1476    /// The frame of a turned cell, or of a text box whose body turns its text, whose lines run
1477    /// along the page's other axis, with whether its lines lie on the page's dots across the
1478    /// page, else on the frame's, the turn that takes the frame onto the page, and how its
1479    /// glyphs lie there.
1480    TurnedFrame(bool, f_office_paint::Turn, TurnedGlyphs),
1481}
1482
1483/// How the glyphs of a turned frame's lines lie on the page.
1484#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1485enum TurnedGlyphs {
1486    /// Every glyph turns with its line.
1487    WithLine,
1488    /// A glyph of a character of the East Asian font side stands upright: it is turned back
1489    /// about the centre of its em box in the line, half an em along the line from its origin
1490    /// and half the face's ascent less its descent above the baseline. The other glyphs turn
1491    /// with their line.
1492    EastAsianUpright,
1493}
1494
1495impl Within {
1496    /// The parts of the column's left edge in an upright table cell, or none outside one.
1497    const fn cell_edge(self) -> Option<CellEdgeParts> {
1498        match self {
1499            Self::Cell(parts) => Some(parts),
1500            Self::Page | Self::TurnedFrame(..) => None,
1501        }
1502    }
1503}
1504
1505/// The column that paragraphs fill: the text column of the page, or the text area of a table
1506/// cell.
1507#[derive(Clone, Debug)]
1508struct Column {
1509    left: Length,
1510    width: Length,
1511    /// What holds the column.
1512    within: Within,
1513    /// The left edge of the column of the page that holds this column.
1514    origin: Length,
1515    /// Inside a table cell, what the table style gives the cell. A line in a cell never starts
1516    /// a new page itself. Its row moves or splits instead. The copies of the column, such as
1517    /// the one that a mark of the layout keeps, share it, since the layout only reads it.
1518    cell: Option<Rc<TableStyle>>,
1519}
1520
1521impl Column {
1522    /// A top-level page column starting at `left` with width `width`.
1523    const fn page(left: Length, width: Length) -> Self {
1524        Self {
1525            left,
1526            width,
1527            within: Within::Page,
1528            origin: left,
1529            cell: None,
1530        }
1531    }
1532}
1533
1534impl<'a> Layout<'a> {
1535    /// Makes the layout of a body with the sections `sections`, which reads `context` and
1536    /// makes its stories with `stories`. It starts in the first section.
1537    #[must_use]
1538    pub fn new(
1539        contexts: (&'a Context<'a>, &'a Context<'a>),
1540        sections: &'a Sections<SectionLayout>,
1541        shaper: Shaper<'a>,
1542    ) -> Self {
1543        let numbering = contexts.0.numbering.clone();
1544        Self::with_sections(contexts, Cow::Borrowed(sections), shaper, numbering)
1545    }
1546
1547    /// Makes the layout of a story of `blocks` blocks, which fills the one section `section`
1548    /// and whose lists go on from the counters of `numbering` in place of a copy of the
1549    /// context's, so that a story copies the lists of the flow that holds it once.
1550    fn story(
1551        contexts: (&'a Context<'a>, &'a Context<'a>),
1552        section: &Section,
1553        blocks: usize,
1554        shaper: Shaper<'a>,
1555        numbering: Numbering,
1556    ) -> Self {
1557        let sections = Sections::one(SectionLayout::plain(section, blocks));
1558        Self::with_sections(contexts, Cow::Owned(sections), shaper, numbering)
1559    }
1560
1561    /// Makes a layout that fills `sections` from the first, with the lists of `numbering`.
1562    fn with_sections(
1563        (context, stories): (&'a Context<'a>, &'a Context<'a>),
1564        sections: Cow<'a, Sections<SectionLayout>>,
1565        shaper: Shaper<'a>,
1566        numbering: Numbering,
1567    ) -> Self {
1568        let section = sections.first().section;
1569        let top = section.top;
1570        let columns = columns::areas(&section, &context.quirks);
1571        let (left, width) = columns.first().copied().unwrap_or_default();
1572        Self {
1573            context,
1574            stories,
1575            styles: context.styles,
1576            settings: context.settings,
1577            numbering,
1578            device: context
1579                .device
1580                .with_page(section.width, section.height, section.orientation),
1581            sections,
1582            section,
1583            shaper,
1584            items: page_items::PageItems::new(),
1585            y: top,
1586            y_rest: 0,
1587            y_twips: None,
1588            table_twips: TableTwips::default(),
1589            previous: None,
1590            tops: [top; 3],
1591            bottoms: [section.height - section.bottom; 3],
1592            story: None,
1593            body_part: std::rc::Rc::default(),
1594            output: output::PassOutput::default(),
1595            page_notes: notes::PageNotes::default(),
1596            endnote: None,
1597            comment_markup: markup::CommentMarkup::new(&context.comments),
1598            page: None,
1599            story_notes: Length::ZERO,
1600            story_page: None,
1601            style_page: None,
1602            number_context: None,
1603            bands: Vec::new(),
1604            hyphen_runs: None,
1605            squares: Vec::new(),
1606            frame_boxes: Vec::new(),
1607            frame_places: Vec::new(),
1608            same_baseline: Vec::new(),
1609            line_floor: None,
1610            behind: Vec::new(),
1611            front: Vec::new(),
1612            column: Column::page(left, width),
1613            columns,
1614            column_index: 0,
1615            column_top: top,
1616            column_ends: Vec::new(),
1617            section_end_paragraph: None,
1618            balance: None,
1619            section_top: columns::SectionTop::Placed,
1620            page_marks: None,
1621            fragment: None,
1622            cell_carried: false,
1623            cell_floor: None,
1624            cell_top: None,
1625            cell_sides: None,
1626            cell_prev_style: None,
1627            table_prev_style: None,
1628            body_floatings: 0,
1629            cell_floatings: 0,
1630            cell_upward_earlier: Vec::new(),
1631            cell_upward_found: Vec::new(),
1632            story_earlier_wraps: None,
1633            started: false,
1634            after_break: false,
1635            alone_break: None,
1636            section_previous: None,
1637            table_chain: TableChain::Ends,
1638            page_from_break: None,
1639            break_numbers: (0, (0, 0)),
1640            grid_pitch: None,
1641            following_after: None,
1642            kept_tail: None,
1643            centered_middle: None,
1644            line_band: None,
1645            east_asian_axis: None,
1646            aligned_parts: None,
1647            glyph_places: Vec::new(),
1648            own_space_before: Length::ZERO,
1649            first_space_before: Length::ZERO,
1650            held_borders: HeldBorders::NONE,
1651            drawings_under_fill: None,
1652            new_page_space: NewPageSpace::Goes,
1653            last_bar: None,
1654            text_part: ((0, 0), 0),
1655            section_index: SectionIndex::FIRST,
1656            section_first_page: 0,
1657            section_title_page: Some(0),
1658            number_start: section.first_page_number,
1659            pending: None,
1660            table_number: 0,
1661            cell_place: None,
1662        }
1663    }
1664
1665    /// Lays out a whole body, then the header and footer of each page. Gives the pages with
1666    /// the wraps of the drawings that it placed from a page or its margins, the page number
1667    /// text of its bookmarks, the styled text of its pages and its placed lines.
1668    #[must_use]
1669    pub fn run_with_wraps(mut self, body: &Body) -> Pass {
1670        self.body_part = std::rc::Rc::clone(&body.part);
1671        self.output.styled = Some(style_refs::Record::default());
1672        if self.settings.side_margins != SideMargins::Section {
1673            // The first page takes the side margins of its side.
1674            let section = self.section_of(SectionIndex::FIRST);
1675            self.take_side_margins(&section);
1676            self.set_columns();
1677        }
1678        self.measure_body();
1679        self.start_wraps();
1680        self.move_to_body_top(0);
1681        self.column_top = self.y;
1682        self.sections_flow(&body.blocks);
1683        self.endnotes_flow();
1684        // A page break at the end of the document starts no page when nothing, not even an
1685        // empty paragraph, comes after it.
1686        let trailing = !self.output.pages.is_empty()
1687            && self.page_from_break == Some(self.output.pages.len())
1688            && self.page_is_empty()
1689            && self.y == self.page_top(self.output.pages.len());
1690        if !trailing {
1691            self.new_page();
1692        }
1693        // The rest of a footnote that goes on after the last page of the body has a page.
1694        if self.rest_waits() {
1695            self.new_page();
1696        }
1697        self.output.style_pages = self.output.styled.take().map(style_refs::Record::finish);
1698        let count = count_factor(self.output.pages.len());
1699        // Headers and footers lie behind the body, so that their drawings behind the text do
1700        // not cover it.
1701        let mut behind = Vec::with_capacity(self.output.pages.len());
1702        for index in 0..self.output.pages.len() {
1703            if self.output.blank_pages.contains(&index) {
1704                behind.push(Vec::new());
1705                continue;
1706            }
1707            let (items, lines) = self.headers_and_footers(index, count);
1708            behind.push(items);
1709            self.output.placed.extend(lines);
1710        }
1711        let pages = std::mem::take(&mut self.output.pages);
1712        let page_color = self.settings.page_color;
1713        self.output.pages = pages
1714            .into_iter()
1715            .zip(behind)
1716            .map(|(page, items)| {
1717                // The page color fills the whole page under the headers, the footers and the
1718                // body.
1719                let color = page_color.map(|[r, g, b]| {
1720                    Item::Rect(Rect {
1721                        x: Length::ZERO,
1722                        y: Length::ZERO,
1723                        width: page.width(),
1724                        height: page.height(),
1725                        color: Rgb { r, g, b },
1726                    })
1727                });
1728                page.map_items(|mut body| {
1729                    body.splice(0..0, color.into_iter().chain(items));
1730                    body
1731                })
1732            })
1733            .collect();
1734        self.print_markup();
1735        let styles = HeaderStyles(self.output.style_pages.clone());
1736        let note_places = self.output.notes.take_places();
1737        let areas = &self.output.body_areas;
1738        let notes_missed = self
1739            .output
1740            .margin_notes
1741            .iter()
1742            .any(|&(page, notes)| areas.get(page).is_some_and(|area| area.notes != notes));
1743        let note_heights = NoteHeights::of_areas(areas);
1744        Pass {
1745            list: DisplayList::new(self.output.pages),
1746            wraps: self.output.found,
1747            bookmarks: self.output.found_bookmarks.into_values(),
1748            bookmark_numbers: self.output.found_numbers.into_values(),
1749            styles,
1750            note_places,
1751            later_anchors: LaterAnchors::found(&self.output.found_later),
1752            note_heights,
1753            notes_missed,
1754            lines: self.output.placed,
1755            tables: last_columns(self.output.table_columns),
1756            warnings: self.output.warnings,
1757            font_notes: self.shaper.take_notes(),
1758        }
1759    }
1760
1761    /// Lays out paragraphs and tables in order. The paragraphs between two tables flow
1762    /// together, so that neighbors with equal borders form a group.
1763    fn blocks(&mut self, blocks: &[Block]) {
1764        self.blocks_from(blocks, columns::BlockStart::default());
1765    }
1766
1767    /// Lays out `blocks` from `start`, as [`Self::blocks`] does, when the blocks before it are
1768    /// laid out already and the layout stands at the mark of `start`'s paragraph.
1769    fn blocks_from(&mut self, blocks: &[Block], start: columns::BlockStart) {
1770        let paragraphs =
1771            |a: &Block, b: &Block| matches!((a, b), (Block::Paragraph(_), Block::Paragraph(_)));
1772        let chunks: Vec<&[Block]> = blocks.chunk_by(paragraphs).collect();
1773        // A floating table that the tables after it go on, as rows of one table.
1774        let mut joined: Option<Table> = None;
1775        self.enter_blocks();
1776        for (index, chunk) in chunks.iter().enumerate().skip(start.chunk) {
1777            self.note_chunk(index);
1778            let mut group = Vec::new();
1779            // A table is a chunk of its own, so the block after it starts the next chunk.
1780            let rest = Rest(chunks.get(index + 1..).unwrap_or_default());
1781            let next = chunks.get(index + 1).and_then(|next| next.first());
1782            for block in *chunk {
1783                match block {
1784                    Block::Paragraph(paragraph) => group.push(paragraph),
1785                    Block::Table(table) => {
1786                        let more = goes_on(table, next);
1787                        match joined.as_mut() {
1788                            Some(whole) => whole.rows.extend(table.rows.iter().cloned()),
1789                            None if more => joined = Some(table.clone()),
1790                            None => self.table(table, rest),
1791                        }
1792                        if let Some(whole) = joined.take_if(|_| !more) {
1793                            self.table(&whole, rest);
1794                        }
1795                    }
1796                }
1797            }
1798            let first = if index == start.chunk {
1799                start.paragraph
1800            } else {
1801                0
1802            };
1803            self.flow(&group, rest, first);
1804        }
1805        self.leave_blocks();
1806    }
1807}