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