Skip to main content

fleuron/layout/
mod.rs

1//! Layout: box construction, inline layout, fragmentation.
2//!
3//! ```text
4//! content + style ─► box tree ─► line layout ─► fragmentation ─► pages
5//! ```
6//!
7//! v0.2 folds the middle of the pipeline into one pass: each section
8//! becomes fragments (each block with the style the tree computed for
9//! it, via `lines::LineLayout`), and the paginator flows those
10//! fragments into page content boxes. Nothing here decides what
11//! anything looks like — the style tree was told, and this asks it.
12//!
13//! A fragment is what the flow can move: one line, one image, one
14//! ornament. Where a page may end is decided when the fragments are
15//! built — orphans, widows, `break-inside`, an ornament that must
16//! keep the prose around it — and the flow only stacks and, when
17//! something does not fit, walks back to the last place a break was
18//! allowed.
19//!
20//! The stages have a file each: `fragment` is what the flow moves,
21//! `build` turns blocks into fragments, `cap` sets the initial letter
22//! beside them, `list` sets a list an item at a time with the marker
23//! of each, `table` sets a table a row at a time, `flow` stacks
24//! fragments into pages, `exclusion` places the images and blocks the
25//! sheet anchored and wraps prose around them, `float` keeps the room
26//! a floated image takes in its column, `background` puts art
27//! behind a box, `inline` paints the box an inline element takes on a
28//! line, `furniture` paints the margin boxes, and `text` turns a
29//! shaped line into paint ops.
30
31mod background;
32mod build;
33mod cap;
34mod exclusion;
35mod float;
36mod flow;
37mod fragment;
38mod furniture;
39mod image;
40mod inline;
41mod list;
42mod navigation;
43mod note;
44mod reference;
45mod sheet;
46mod table;
47mod text;
48
49#[cfg(test)]
50mod testing;
51
52pub use build::Reflow;
53pub use fragment::{
54    BreakPoint, Decoration, Decorations, DropCap, Floated, Fragment, Marker, Marks, Piece, TableRow,
55};
56pub use furniture::margin_band;
57pub use note::Note;
58
59use background::Backdrop;
60
61pub(crate) use exclusion::AnchoredBoxes;
62pub(crate) use flow::{PageInfo, Paged};
63pub(crate) use navigation::{navigation, run_area};
64pub(crate) use note::{Numbering, UNSETTLED};
65pub(crate) use reference::{Named, References, landed, moved};
66
67use std::borrow::Cow;
68use std::cell::{Cell, OnceCell, RefCell};
69use std::collections::{BTreeSet, HashSet};
70
71use crate::content::{Book, Metadata, origin};
72use crate::fonts::{FeatureSetting, FontRegistry};
73use crate::images::{Assets, Contours};
74use crate::lines::{LineLayout, ParagraphStyle, Patterns};
75use crate::pages::{DrawItem, Page, Side};
76use crate::session::Session;
77use crate::style::{Background, Float, PageGeometry, PageStyle, Position, StyleTree};
78use crate::{LayoutOutput, Warning};
79
80use flow::{Flow, PageSlot};
81
82/// How many times a book whose notes are numbered by page is laid
83/// out again for them. Each pass numbers the notes of the pass
84/// before, and a book that has not settled by the last of them keeps
85/// the numbers it has.
86pub(crate) const NOTE_PASSES: u32 = 4;
87
88/// One book through the whole pipeline: lines laid out, flowed into
89/// pages, everything the output needs assembled.
90///
91/// A single run over a session that retains nothing. It keeps one
92/// section's lines at a time, which is what a process that renders a
93/// book once and exits wants. A live preview uses `Session` instead.
94///
95/// `assets` is the images the host probed. A book with none of them
96/// passes [`Assets::none`].
97pub fn layout_book(
98    book: &Book,
99    styles: &StyleTree,
100    registry: &FontRegistry,
101    assets: &Assets,
102) -> LayoutOutput {
103    Session::once(book, styles, registry, assets).into_output()
104}
105
106/// The asset table of a host that supplied none.
107pub(crate) fn no_assets() -> &'static Assets {
108    static EMPTY: std::sync::OnceLock<Assets> = std::sync::OnceLock::new();
109    EMPTY.get_or_init(Assets::none)
110}
111
112/// The contours of a book whose sheet asked for none.
113pub(crate) fn no_contours() -> &'static Contours {
114    static EMPTY: std::sync::OnceLock<Contours> = std::sync::OnceLock::new();
115    EMPTY.get_or_init(Contours::none)
116}
117
118/// The fonts a run used, in the order the output indexes them.
119pub(crate) fn font_table(registry: &FontRegistry) -> Vec<crate::fonts::FontRefEntry> {
120    (0..registry.len() as u16)
121        .filter_map(|id| registry.font_ref(id).cloned())
122        .collect()
123}
124
125/// The pagination pass: content in, `Page`s of `DrawItem`s out.
126///
127/// Fragments stack from the top of the content box. One that does not
128/// fit ends the page — at the last point a break was allowed, which
129/// may be several fragments back — and a fragment taller than a whole
130/// page overflows it.
131pub struct Paginator<'a> {
132    registry: &'a FontRegistry,
133    styles: &'a StyleTree,
134    assets: &'a Assets,
135    /// What the trace stage made of the assets the sheet asked to
136    /// wrap around.
137    contours: &'a Contours,
138    lines: LineLayout<'a>,
139    /// The syllable patterns `hyphens: auto` breaks by.
140    patterns: Cell<Patterns>,
141    /// The declared language there are no patterns for, which the
142    /// first paragraph that asks to be hyphenated complains about.
143    unknown: RefCell<Option<String>>,
144    /// What fragmentation had to complain about. Recorded once per
145    /// message: a book that scales the same image twice has one
146    /// problem, not two.
147    warnings: RefCell<Vec<Warning>>,
148    /// The characters set with no glyph. Recorded once for each
149    /// character and source, so the same message stands once under
150    /// every file that has the character.
151    uncovered: RefCell<Vec<UncoveredWarning>>,
152    /// Whether the sheet anchors anything to the page or floats
153    /// anything, answered once.
154    wraps: OnceCell<bool>,
155    /// Whether the sheet floats anything, answered once.
156    floats: OnceCell<bool>,
157    /// How many times the flow set a paragraph again beside an image.
158    rebreaks: Cell<u32>,
159    /// What the references in the book resolve against.
160    references: RefCell<References>,
161    /// What the notes of the book are numbered.
162    notes: RefCell<Numbering>,
163    /// How many times the book was laid out again to print the pages
164    /// its references name.
165    settles: Cell<u32>,
166}
167
168/// A character set with no glyph, and what the run says about it.
169///
170/// Kept apart from the other warnings, which are recorded once for
171/// each message. This one is recorded once for each character and
172/// source.
173#[derive(Debug, Clone, PartialEq)]
174pub(crate) struct UncoveredWarning {
175    pub(crate) character: char,
176    /// The file the character was written in.
177    pub(crate) source: Option<String>,
178    pub(crate) warning: Warning,
179}
180
181impl UncoveredWarning {
182    /// The warnings of `found`, in order, once for each character
183    /// and source.
184    pub(crate) fn warnings<'f>(
185        found: impl IntoIterator<Item = &'f UncoveredWarning>,
186    ) -> Vec<Warning> {
187        let mut seen = HashSet::new();
188        found
189            .into_iter()
190            .filter(|found| seen.insert((found.source.as_deref(), found.character)))
191            .map(|found| found.warning.clone())
192            .collect()
193    }
194}
195
196impl<'a> Paginator<'a> {
197    /// A paginator over one book's styling and the faces it shapes
198    /// with, for a book with no images in it.
199    pub fn new(registry: &'a FontRegistry, styles: &'a StyleTree) -> Self {
200        Paginator::with_assets(registry, styles, no_assets())
201    }
202
203    /// The same, over images the host has already probed. A book
204    /// whose sheet names a traced contour also passes what the trace
205    /// stage made of it, through
206    /// [`with_contours`](Paginator::with_contours).
207    pub fn with_assets(
208        registry: &'a FontRegistry,
209        styles: &'a StyleTree,
210        assets: &'a Assets,
211    ) -> Self {
212        Paginator::with_contours(registry, styles, assets, no_contours())
213    }
214
215    /// The same, over the contours the trace stage left.
216    pub fn with_contours(
217        registry: &'a FontRegistry,
218        styles: &'a StyleTree,
219        assets: &'a Assets,
220        contours: &'a Contours,
221    ) -> Self {
222        Paginator {
223            registry,
224            styles,
225            assets,
226            contours,
227            lines: LineLayout::new(registry),
228            patterns: Cell::new(Patterns::default()),
229            unknown: RefCell::new(None),
230            warnings: RefCell::new(Vec::new()),
231            uncovered: RefCell::new(Vec::new()),
232            wraps: OnceCell::new(),
233            floats: OnceCell::new(),
234            rebreaks: Cell::new(0),
235            references: RefCell::new(References::default()),
236            notes: RefCell::new(Numbering::default()),
237            settles: Cell::new(0),
238        }
239    }
240}
241
242impl Paginator<'_> {
243    /// Takes the hyphenation patterns from the language the book
244    /// declares. `paginate` reads them from the book it is handed. A
245    /// caller that builds one section's fragments on its own sets
246    /// them here.
247    ///
248    /// A language with no patterns leaves every word whole, rather
249    /// than breaking one language's words at another's syllables,
250    /// and the first paragraph that asks for hyphenation says so.
251    pub fn language(&self, metadata: &Metadata) {
252        let patterns = Patterns::of(metadata);
253        self.patterns.set(patterns);
254        *self.unknown.borrow_mut() = metadata
255            .language()
256            .filter(|_| patterns == Patterns::NONE)
257            .map(str::to_string);
258    }
259
260    /// What `hyphens: auto` has to break with, complaining the first
261    /// time it is asked for and there is nothing behind the language
262    /// the book declares.
263    fn patterns(&self) -> Patterns {
264        if let Some(tag) = self.unknown.borrow().as_deref() {
265            self.warn(
266                format!(
267                    "No hyphenation patterns for `{tag}`. Hyphenation is skipped for that \
268                     language."
269                ),
270                None,
271            );
272        }
273        self.patterns.get()
274    }
275
276    /// What fragmentation had to complain about.
277    pub fn warnings(&self) -> Vec<Warning> {
278        let mut warnings = self.flow_warnings();
279        let uncovered = self.uncovered.borrow();
280        warnings.extend(uncovered.iter().map(|found| found.warning.clone()));
281        warnings
282    }
283
284    /// The same, without the characters set with no glyph.
285    pub(crate) fn flow_warnings(&self) -> Vec<Warning> {
286        self.warnings.borrow().clone()
287    }
288
289    /// The characters set with no glyph, once for each character and
290    /// source.
291    pub(crate) fn uncovered(&self) -> Vec<UncoveredWarning> {
292        self.uncovered.borrow().clone()
293    }
294
295    /// Files the characters shaping found no glyph for under
296    /// `source`, the file they were written in.
297    fn uncover(&self, source: Option<&str>) {
298        let mut uncovered = self.uncovered.borrow_mut();
299        for found in self.lines.take_uncovered() {
300            let seen = uncovered
301                .iter()
302                .any(|seen| seen.character == found.character && seen.source.as_deref() == source);
303            if seen {
304                continue;
305            }
306            let face = self
307                .registry
308                .font_ref(found.font_id)
309                .map(|entry| entry.name.clone())
310                .unwrap_or_default();
311            let at = origin(source, found.position);
312            uncovered.push(UncoveredWarning {
313                character: found.character,
314                source: source.map(str::to_string),
315                warning: Warning {
316                    message: format!(
317                        "{face} has no glyph for `{}` (U+{:04X}).",
318                        found.character, found.character as u32,
319                    ),
320                    origin: (!at.is_empty()).then_some(at),
321                },
322            });
323        }
324    }
325
326    /// How many times the flow that paints set a paragraph again
327    /// beside an image. A book that anchors nothing never does.
328    pub fn rebreaks(&self) -> u32 {
329        self.rebreaks.get()
330    }
331
332    /// How many times the book was laid out a second time, to print
333    /// the pages its references name. A book whose sheet prints no
334    /// page number is laid out once.
335    pub fn settles(&self) -> u32 {
336        self.settles.get()
337    }
338
339    /// Takes what the book's references resolve against. `paginate`
340    /// reads it from the book it is handed. A caller that builds one
341    /// section's fragments on its own sets it here.
342    pub(crate) fn refer(&self, references: References) {
343        *self.references.borrow_mut() = references;
344    }
345
346    /// Whether the sheet takes anything out of the flow: against the
347    /// page, or to one side of a column.
348    ///
349    /// A book that anchors nothing and floats nothing never sets a
350    /// paragraph twice, so its fragments keep nothing to set one from.
351    fn wraps(&self) -> bool {
352        *self.wraps.get_or_init(|| {
353            self.floats()
354                || self
355                    .styles
356                    .styles()
357                    .iter()
358                    .any(|style| style.position == Position::Absolute)
359        })
360    }
361
362    /// Whether the sheet floats anything.
363    pub(super) fn floats(&self) -> bool {
364        *self.floats.get_or_init(|| {
365            self.styles
366                .styles()
367                .iter()
368                .any(|style| style.float != Float::None)
369        })
370    }
371
372    /// Records one diagnostic, once. A book that hits the same
373    /// problem on every page has one problem.
374    fn warn(&self, message: String, origin: Option<String>) {
375        let mut warnings = self.warnings.borrow_mut();
376        if !warnings.iter().any(|seen| seen.message == message) {
377            warnings.push(Warning { message, origin });
378        }
379    }
380
381    /// The style a note's reference is set in: the style of the
382    /// note, and the face's superior figures over it. The engine
383    /// asks for them, the way it asks for small capitals, because
384    /// `font-feature-settings` inherits and a rule on the note would
385    /// set the prose of the note in superiors as well.
386    ///
387    /// A face with no superior figures sets the reference on the
388    /// baseline at the size the note gives it, and says so once.
389    fn superior(&self, mut style: ParagraphStyle) -> ParagraphStyle {
390        const SUPS: [u8; 4] = *b"sups";
391        if self.registry.has_feature(style.font_id, SUPS) {
392            style.features.push(FeatureSetting::new(SUPS, 1));
393            return style;
394        }
395        let family = self
396            .registry
397            .font_ref(style.font_id)
398            .map(|entry| entry.family.clone())
399            .unwrap_or_default();
400        self.warn(
401            format!(
402                "{family} has no superior figures. The reference of a note stands on the \
403                 baseline."
404            ),
405            None,
406        );
407        style
408    }
409
410    /// Says so where the host supplied no image for a url. The table
411    /// complains about a url it probed and refused. A url the table
412    /// was never offered means the host supplied nothing at all.
413    /// What one box paints behind its content, complaining where the
414    /// sheet named an image nothing answers for.
415    fn backdrop(&self, background: &Background) -> Backdrop {
416        let found = background.image.as_ref().and_then(|url| {
417            let found = self.assets.lookup(&url.value);
418            if found.is_none() {
419                self.missing(&url.value, url.origin.clone().unwrap_or_default());
420            }
421            found
422        });
423        Backdrop::of(background, found)
424    }
425
426    fn missing(&self, url: &str, origin: String) {
427        if !self.assets.probed(url) {
428            self.warn(
429                format!("No image was supplied for {url}. The image is skipped."),
430                (!origin.is_empty()).then_some(origin),
431            );
432        }
433    }
434
435    /// Flows one book into numbered, side-tagged pages.
436    ///
437    /// A section's fragments are built, flowed, and released before
438    /// the next one is measured: what exists at once is the book's
439    /// pages, not every line it was ever broken into.
440    ///
441    /// A book whose references print pages is laid out twice: once to
442    /// find the page each element lands on, and once to print it.
443    pub fn paginate(&self, book: &Book) -> Vec<Page> {
444        self.paginated(book).pages
445    }
446
447    /// The same, with where each id landed and the box of each block.
448    pub(crate) fn paginated(&self, book: &Book) -> Paged {
449        self.language(&book.metadata);
450        if self.styles.refers() {
451            self.refer(References::of(book));
452        }
453        self.number(Numbering::of(book, self.styles));
454        let mut paged = self.pass(book);
455        if self.styles.numbers_notes_per_page() {
456            paged = self.settle_notes(book, paged);
457        }
458        if self.styles.counts_pages() {
459            let found = landed(&paged);
460            let resolved = self.references.borrow().landed(found.clone());
461            self.refer(resolved);
462            self.settles.set(self.settles.get() + 1);
463            paged = self.pass(book);
464            let references = self.references.borrow();
465            let printed: BTreeSet<_> = book
466                .sections
467                .iter()
468                .flat_map(|section| Named::in_section(section, self.styles, &references).pages)
469                .collect();
470            for warning in moved(&found, &landed(&paged), &printed, &references) {
471                self.warn(warning.message, warning.origin);
472            }
473        }
474        self.paint(&mut paged.pages, &paged.infos);
475        paged
476    }
477
478    /// Numbers the notes by the page their references were set on,
479    /// and lays the book out again to print those numbers.
480    ///
481    /// A number of another width moves the line its reference is on,
482    /// which can move a note onto another page and number it again.
483    /// So the book is laid out until the numbering stops changing,
484    /// and the numbering of the last pass stands where it does not.
485    fn settle_notes(&self, book: &Book, mut paged: Paged) -> Paged {
486        let start = self.styles.first_note_number();
487        for _ in 0..NOTE_PASSES {
488            let numbered = self.notes.borrow().on_pages(&paged.notes, start);
489            if numbered == *self.notes.borrow() {
490                return paged;
491            }
492            self.number(numbered);
493            self.settles.set(self.settles.get() + 1);
494            paged = self.pass(book);
495        }
496        self.warn(note::UNSETTLED.to_string(), None);
497        paged
498    }
499
500    /// One pass over the whole book, stopping short of the furniture.
501    fn pass(&self, book: &Book) -> Paged {
502        let anchored = self.anchored(book, |index| {
503            Cow::Owned(self.section_fragments(&book.sections[index]))
504        });
505        let mut flow = Flow::new(self, anchored);
506        for section in &book.sections {
507            let fragments = self.section_fragments(section);
508            flow.section(section, &fragments);
509        }
510        flow.finish()
511    }
512
513    /// The boxes the sheet anchors, each on the page its anchor
514    /// landed on and against the block its insets measure from.
515    ///
516    /// A box inside a positioned block is laid out a second time: the
517    /// first layout breaks its lines to what the page area leaves it,
518    /// and the settling pass answers which block they measure from and
519    /// how wide that block is.
520    fn anchored<'f>(
521        &self,
522        book: &Book,
523        mut fragments: impl FnMut(usize) -> Cow<'f, [Fragment]>,
524    ) -> AnchoredBoxes {
525        let boxes = self.anchored_boxes(book, &[]);
526        if boxes.is_empty() {
527            return AnchoredBoxes::default();
528        }
529        let mut settled = self.settle(book, boxes, &mut fragments);
530        if let Some(within) = settled.narrowed() {
531            let boxes = self.anchored_boxes(book, &within);
532            settled.relaid(boxes, within);
533        }
534        settled
535    }
536
537    /// Fragments in, numbered pages out: fragmentation and page
538    /// assembly, one `Vec<Fragment>` per section of `book`. Nothing
539    /// here measures — every fragment arrives with its box decided.
540    pub fn flow(&self, book: &Book, sections: &[Vec<Fragment>]) -> Vec<Page> {
541        let mut paged = self.fragment(book, sections.iter().map(Vec::as_slice));
542        self.paint(&mut paged.pages, &paged.infos);
543        paged.pages
544    }
545
546    /// The same, stopping short of the furniture: pages as the flow
547    /// settled them, and what each one needs to paint its own.
548    pub(crate) fn fragment<'f>(
549        &self,
550        book: &Book,
551        sections: impl IntoIterator<Item = &'f [Fragment]>,
552    ) -> Paged {
553        let sections: Vec<&[Fragment]> = sections.into_iter().collect();
554        let anchored = self.anchored(book, |index| Cow::Borrowed(sections[index]));
555        let mut flow = Flow::new(self, anchored);
556        for (section, fragments) in book.sections.iter().zip(&sections) {
557            flow.section(section, fragments);
558        }
559        flow.finish()
560    }
561
562    /// The master of the page that will sit at `index`.
563    fn master(&self, index: usize, slot: &PageSlot) -> &PageStyle {
564        self.styles
565            .page(slot.query(Side::of_number(index as u32 + 1)))
566    }
567
568    /// A page of the master's trim size with nothing on it. Numbering
569    /// and side are settled once the whole flow is assembled.
570    fn blank_page(&self, slot: &PageSlot) -> Page {
571        let geometry = self.sheet(slot);
572        Page {
573            number: 0,
574            side: Side::Verso,
575            width: geometry.width,
576            height: geometry.height,
577            bleed: geometry.bleed(),
578            slug: geometry.slug(),
579            sections: Vec::new(),
580            items: Vec::new(),
581            links: Vec::new(),
582        }
583    }
584
585    /// The printer's marks around a page of the master's trim size.
586    fn marks(&self, slot: &PageSlot) -> Vec<DrawItem> {
587        sheet::marks(self.sheet(slot))
588    }
589
590    /// The geometry a page's trim, bleed and marks are read from.
591    fn sheet(&self, slot: &PageSlot) -> PageGeometry {
592        self.styles.page(slot.query(Side::Verso)).geometry
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599    use crate::layout::testing::{book_of, heading, long_prose, registry, section};
600
601    /// Pagination is line layout then flow, and splitting it that way
602    /// changes nothing: the harness times the two halves separately,
603    /// which is only worth doing while their composition is the whole.
604    #[test]
605    fn the_stages_compose_into_what_paginate_does() {
606        let book = book_of(vec![
607            section(long_prose(30)),
608            section([vec![heading("Two")], long_prose(24)].concat()),
609        ]);
610        let styles = crate::style::defaults(&book, registry());
611        let paginator = Paginator::new(registry(), &styles);
612
613        let staged: Vec<Vec<Fragment>> = book
614            .sections
615            .iter()
616            .map(|section| paginator.section_fragments(section))
617            .collect();
618        let by_stage = paginator.flow(&book, &staged);
619        let in_one = paginator.paginate(&book);
620
621        assert!(in_one.len() > 2, "a book worth splitting");
622        assert_eq!(by_stage.len(), in_one.len());
623        for (staged, whole) in by_stage.iter().zip(&in_one) {
624            assert_eq!(staged.number, whole.number);
625            assert_eq!(staged.side, whole.side);
626            assert_eq!(format!("{:?}", staged.items), format!("{:?}", whole.items));
627        }
628    }
629}