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