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