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