Skip to main content

fleuron/session/
mod.rs

1//! A retained pipeline: every stage kept, and only what an edit
2//! changed run again.
3//!
4//! `layout_book` is a pure function of its inputs, so every call
5//! rebuilds every stage. A process that renders one book and exits
6//! wants that. A live preview does not, because the common event
7//! there is a small change to one input while the others stand. A
8//! session retains the output of each stage and works out the deepest
9//! stage an edit reaches: a colour serves the display structure back, page
10//! furniture repaints, `@page` geometry re-fragments over cached
11//! lines, and only the measure or the text itself breaks lines
12//! again.
13//!
14//! # Section-local lines
15//!
16//! Line *breaking* is section-local: where the breaks fall depends on
17//! the measure, the face and the text, not on where the section
18//! starts vertically. Line *placement* depends on position and
19//! belongs to fragmentation. So the cache stores breaks, shaped runs
20//! and advances, and no page coordinates at all. An edit to one
21//! chapter re-breaks that chapter and re-fragments the book, which
22//! for a whole novel costs about what tracking the pages that moved
23//! would.
24//!
25//! Two preconditions make that sound, and both are checked rather
26//! than remembered. The first is a uniform measure: masters that
27//! resolve different content widths make breaking depend on which
28//! page a line lands on. The second is that no inline text depends
29//! on pagination, which the parser guarantees: `counter(page)` is
30//! legal only inside a margin box. When either one fails, the session re-breaks
31//! everything instead of serving stale lines.
32//!
33//! A reference that prints a page is the one piece of inline text
34//! that pagination decides, and it is set on a pass of its own. The
35//! first pass sets a placeholder where the number goes, so its lines
36//! are section-local like any others. The second builds again only
37//! the sections whose references print a page, and keys each one by
38//! the folios it prints.
39//!
40//! The parts have a file each: `edit` is what a host changes,
41//! `output` is what it asks for, `inspect` answers what styled one
42//! node and where it landed, `stage` runs the stages, `invalidate`
43//! decides which of them an edit reaches, and `key` fingerprints one
44//! section.
45
46use std::borrow::Cow;
47
48use crate::content::{Book, Names, NodeId, SourceRange};
49use crate::fonts::{FontError, FontRegistry};
50use crate::images::{Assets, Contours};
51use crate::layout::{
52    Fragment, Numbering, PageInfo, Piece, References, UncoveredWarning, no_assets,
53};
54use crate::pages::PageBox;
55use crate::style::{FontLoader, StyleTree, Stylesheets};
56use crate::{LayoutOutput, Warning};
57
58mod edit;
59mod faces;
60mod inspect;
61mod invalidate;
62mod key;
63mod output;
64mod stage;
65
66#[cfg(test)]
67mod testing;
68
69use invalidate::{Prints, section_local};
70
71/// How many times each stage has run since the session was made.
72///
73/// A host reads these to see what an edit cost. The tests read them
74/// to prove what an edit did *not* cost, which a clock cannot show.
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
76pub struct Stages {
77    /// Style compilations: parse, match, cascade.
78    pub style: u32,
79    /// Images decoded to trace a contour. A book whose sheet names no
80    /// contour never decodes one, and a contour already traced is not
81    /// traced again.
82    pub trace: u32,
83    /// Sections broken into lines. One per section, per rebuild.
84    pub lines: u32,
85    /// Fragmentation and page assembly runs.
86    pub flow: u32,
87    /// Furniture paints: numbering and margin boxes.
88    pub paint: u32,
89    /// Second layout passes, which print the pages the references in
90    /// the book name. A book whose sheet prints no page number never
91    /// runs one.
92    pub settle: u32,
93}
94
95/// The deepest stage a change invalidates, which is the shallowest
96/// cache that survives it. Ordered: a deeper stage implies every
97/// stage under it.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
99enum Stale {
100    /// Everything stands; the display structure is served as it is.
101    Nothing,
102    /// Numbering and margin boxes.
103    Paint,
104    /// Fragmentation, over lines that survived.
105    Flow,
106    /// Line breaking, and everything below it.
107    Break,
108    /// Tracing the contours the sheet asks for, which is above line
109    /// breaking because a contour that moved is a measure that moved.
110    Trace,
111}
112
113/// A table a session lays out against: a caller's, or one of its
114/// own.
115///
116/// A host with faces and images to lend keeps lending them. A worker
117/// has nowhere to keep either, since the module is all there is, so
118/// it hands them over once and adds to them through the session.
119enum Table<'a, T> {
120    Borrowed(&'a T),
121    Owned(Box<T>),
122}
123
124impl<T> Table<'_, T> {
125    fn get(&self) -> &T {
126        match self {
127            Table::Borrowed(table) => table,
128            Table::Owned(table) => table,
129        }
130    }
131
132    fn get_mut(&mut self) -> Option<&mut T> {
133        match self {
134            Table::Borrowed(_) => None,
135            Table::Owned(table) => Some(table),
136        }
137    }
138}
139
140/// Why a face did not reach a session's registry.
141#[derive(Debug, thiserror::Error)]
142pub enum AddFontError {
143    /// The session lays out against a registry it borrowed, and the
144    /// caller who owns it is the one who can add to it.
145    #[error("the session borrows its font registry")]
146    Borrowed,
147    /// The bytes are not a face this build can read.
148    #[error(transparent)]
149    Font(#[from] FontError),
150}
151
152/// Why an image did not reach a session's asset table.
153#[derive(Debug, thiserror::Error)]
154pub enum AddImageError {
155    /// The session lays out against an asset table it borrowed, and
156    /// the caller who owns it is the one who can add to it.
157    #[error("the session borrows its asset table")]
158    Borrowed,
159}
160
161/// One section's lines, and what building them had to complain about.
162struct Cached {
163    key: u64,
164    /// The id the section had when its lines were broken.
165    section: NodeId,
166    fragments: Vec<Fragment>,
167    warnings: Vec<Warning>,
168    /// The characters the section set with no glyph.
169    uncovered: Vec<UncoveredWarning>,
170}
171
172impl Cached {
173    /// Whether the lines can be moved onto the ids the book hands out
174    /// now. The notes a line carries were built with ids of their
175    /// own, and moving those is not what `renumber` does, so a
176    /// section that holds one is broken again instead.
177    fn renumbers(&self, section: NodeId) -> bool {
178        section == self.section
179            || !self
180                .fragments
181                .iter()
182                .any(|fragment| fragment.notes.is_some())
183    }
184
185    /// Moves the source ranges onto the ids the book hands out now.
186    /// Ids renumber globally on every edit, so a chapter nothing
187    /// touched comes back out of the cache under a new number; its
188    /// nodes are dense and in document order from the section's own,
189    /// so all of them move by the same step.
190    fn renumber(&mut self, section: NodeId) {
191        let step = section.get() as i64 - self.section.get() as i64;
192        self.section = section;
193        if step == 0 {
194            return;
195        }
196        for fragment in &mut self.fragments {
197            if let Some(marks) = &mut fragment.marks {
198                for node in &mut marks.targets {
199                    *node = node.shifted(step);
200                }
201            }
202            if let Some(decorations) = &mut fragment.decorations {
203                for decoration in &mut decorations.opens {
204                    decoration.node = decoration.node.shifted(step);
205                }
206            }
207            if let Piece::Anchor(node) = &mut fragment.piece {
208                *node = node.shifted(step);
209            }
210            if let Piece::Float(float) = &mut fragment.piece {
211                float.node = float.node.shifted(step);
212            }
213            if let Piece::Row(row) = &mut fragment.piece {
214                for (node, _) in &mut row.boxes {
215                    *node = node.shifted(step);
216                }
217                for item in &mut row.items {
218                    if let crate::pages::DrawItem::Text {
219                        origin,
220                        pseudo_element,
221                        ..
222                    } = item
223                    {
224                        shift_run(origin, pseudo_element, step);
225                    }
226                }
227                continue;
228            }
229            let Piece::Line { line, cap } = &mut fragment.piece else {
230                continue;
231            };
232            let caps = cap.iter_mut().map(|cap| &mut cap.line);
233            for line in std::iter::once(line).chain(caps) {
234                for run in &mut line.runs {
235                    shift_run(&mut run.origin, &mut run.pseudo_element, step);
236                }
237            }
238        }
239    }
240}
241
242/// Moves the ids one run names by `step`.
243fn shift_run(origin: &mut Option<SourceRange>, pseudo_element: &mut Option<NodeId>, step: i64) {
244    if let Some(origin) = origin {
245        origin.node = origin.node.shifted(step);
246    }
247    if let Some(node) = pseudo_element {
248        *node = node.shifted(step);
249    }
250}
251
252/// A retained pipeline: content, styling, and every stage between
253/// them and the page.
254///
255/// ```
256/// # use fleuron::content::Book;
257/// # use fleuron::session::Session;
258/// # use fleuron::style::Stylesheets;
259/// # let registry = fleuron::fonts::bundled_registry().unwrap();
260/// let mut session = Session::new(&registry);
261/// session.set_content(Book::default());
262/// session.set_style(Stylesheets::parse(&[]));
263/// let pages = &session.preview().pages;
264/// ```
265///
266/// A computed style can only resolve to a face already in the
267/// registry. A session over a borrowed registry leaves it as the
268/// host made it, so a sheet that brings its own `@font-face` needs
269/// the host to load that face before the sheet is set. A session
270/// that owns its registry registers the faces the sheet declares from
271/// the files [`add_font_file`](Session::add_font_file) hands over.
272pub struct Session<'a> {
273    registry: Table<'a, FontRegistry>,
274    assets: Table<'a, Assets>,
275    fonts: faces::FontFiles,
276    /// What the trace stage made of the assets the sheet wraps prose
277    /// around. Empty for a sheet that names no contour.
278    contours: Contours,
279    book: Cow<'a, Book>,
280    /// The sources in the order the book holds them, one that has no
281    /// section among them.
282    order: Vec<String>,
283    /// The sheets the tree was compiled from. `None` on the one-shot
284    /// path, where the caller compiled the tree itself and nothing
285    /// will ask for another.
286    sheets: Option<Stylesheets>,
287    styles: Cow<'a, StyleTree>,
288    prints: Prints,
289    /// Whether the preconditions for reusing a section's lines are met.
290    section_local: bool,
291    /// Whether the book places an image, which is what makes the
292    /// page's height an input to breaking.
293    images: bool,
294    /// Whether the stages are kept between calls. This is the only
295    /// difference on the one-shot path, which keeps one section's
296    /// lines at a time and drops each as it is flowed.
297    retain: bool,
298    lines: Vec<Cached>,
299    /// What the book's references resolve against on the pass that
300    /// finds the pages.
301    references: References,
302    /// What the notes of the book are numbered.
303    notes: Numbering,
304    /// Each section's lines on the pass that prints the pages its
305    /// references name. `None` for a section with no such reference,
306    /// whose lines from the pass before stand.
307    settled: Vec<Option<Cached>>,
308    /// What that pass had to complain about: its own sections, and
309    /// every element it set on another page than the pass before.
310    settle_warnings: Vec<Warning>,
311    /// What the links had to complain about: a url that names nothing
312    /// in the book.
313    link_warnings: Vec<Warning>,
314    infos: Vec<PageInfo>,
315    /// The border box of each block, on each page it reaches.
316    boxes: Vec<(NodeId, PageBox)>,
317    output: Option<LayoutOutput>,
318    /// What building lines complained about, deduped in the order the
319    /// sections raised it.
320    flow_warnings: Vec<Warning>,
321    /// What a frontend had to say about the sources it read, which
322    /// happened upstream of every stage here.
323    source_warnings: Vec<Warning>,
324    stale: Stale,
325    stages: Stages,
326}
327
328impl<'a> Session<'a> {
329    /// A session over the faces in `registry`, with no content and
330    /// the built-in sheet alone.
331    pub fn new(registry: &'a FontRegistry) -> Session<'a> {
332        Session::with_assets(registry, no_assets())
333    }
334
335    /// The same, over images the host has already probed.
336    pub fn with_assets(registry: &'a FontRegistry, assets: &'a Assets) -> Session<'a> {
337        Session::over(Table::Borrowed(registry), Table::Borrowed(assets))
338    }
339
340    fn over(registry: Table<'a, FontRegistry>, assets: Table<'a, Assets>) -> Session<'a> {
341        let book = Book::default();
342        let sheets = Stylesheets::parse(&[]);
343        let styles = sheets.compile(&book, registry.get());
344        let fonts = faces::FontFiles::over(registry.get().len());
345        let mut session = Session {
346            registry,
347            assets,
348            fonts,
349            contours: Contours::none(),
350            book: Cow::Owned(book),
351            order: Vec::new(),
352            sheets: Some(sheets),
353            prints: Prints::of(&styles, false),
354            section_local: section_local(&styles),
355            images: false,
356            styles: Cow::Owned(styles),
357            retain: true,
358            lines: Vec::new(),
359            references: References::default(),
360            notes: Numbering::default(),
361            settled: Vec::new(),
362            settle_warnings: Vec::new(),
363            link_warnings: Vec::new(),
364            infos: Vec::new(),
365            boxes: Vec::new(),
366            output: None,
367            flow_warnings: Vec::new(),
368            source_warnings: Vec::new(),
369            stale: Stale::Trace,
370            stages: Stages {
371                style: 1,
372                ..Stages::default()
373            },
374        };
375        session.load_faces();
376        session
377    }
378
379    /// A session that owns the faces it lays out against, and takes
380    /// more through [`add_font`](Session::add_font).
381    ///
382    /// This is the shape a worker needs: font bytes cross the
383    /// boundary once, the module keeps them, and no caller on the
384    /// other side of the wall has a registry to lend.
385    pub fn owning(registry: FontRegistry) -> Session<'static> {
386        Session::over(
387            Table::Owned(Box::new(registry)),
388            Table::Owned(Box::new(Assets::none())),
389        )
390    }
391
392    /// The single run `layout_book` makes, over inputs the caller
393    /// owns and will not edit. Nothing is fingerprinted, because
394    /// nothing will be compared against it.
395    pub(crate) fn once(
396        book: &'a Book,
397        styles: &'a StyleTree,
398        registry: &'a FontRegistry,
399        assets: &'a Assets,
400    ) -> Session<'a> {
401        Session {
402            registry: Table::Borrowed(registry),
403            assets: Table::Borrowed(assets),
404            fonts: faces::FontFiles::over(registry.len()),
405            contours: Contours::none(),
406            book: Cow::Borrowed(book),
407            order: Vec::new(),
408            sheets: None,
409            styles: Cow::Borrowed(styles),
410            prints: Prints::default(),
411            section_local: false,
412            images: false,
413            retain: false,
414            lines: Vec::new(),
415            references: References::default(),
416            notes: Numbering::default(),
417            settled: Vec::new(),
418            settle_warnings: Vec::new(),
419            link_warnings: Vec::new(),
420            infos: Vec::new(),
421            boxes: Vec::new(),
422            output: None,
423            flow_warnings: Vec::new(),
424            source_warnings: Vec::new(),
425            stale: Stale::Trace,
426            stages: Stages::default(),
427        }
428    }
429}
430
431impl Session<'_> {
432    /// The session's own copy of the book, node ids assigned.
433    pub fn book(&self) -> &Book {
434        &self.book
435    }
436
437    /// The classes and the ids the blocks and inlines of one source
438    /// carry, or of the whole book when `source` is `None`, as the
439    /// book holds them now. A section's own names are not in the
440    /// answer.
441    pub fn names(&self, source: Option<&str>) -> Names {
442        self.book.names(source)
443    }
444
445    /// The compiled styling behind the last update.
446    pub fn styles(&self) -> &StyleTree {
447        &self.styles
448    }
449
450    /// The sheets the styling was compiled from, as the host last
451    /// set them.
452    pub fn sheets(&self) -> Option<&Stylesheets> {
453        self.sheets.as_ref()
454    }
455
456    /// The images this session holds, by the url each was registered
457    /// under.
458    pub fn images(&self) -> &Assets {
459        self.assets.get()
460    }
461
462    /// The files [`add_font_file`](Session::add_font_file) handed
463    /// over, by the url a `@font-face` names them by.
464    pub fn font_files(&self) -> &dyn FontLoader {
465        &self.fonts
466    }
467
468    /// The faces this session lays out against.
469    ///
470    /// A painter that has to draw with the same file the shaper used
471    /// reaches the bytes through here; the display structure names
472    /// ids, and the registry is what they index.
473    pub fn fonts(&self) -> &FontRegistry {
474        self.registry.get()
475    }
476
477    /// How many times each stage has run.
478    pub fn stages(&self) -> Stages {
479        self.stages
480    }
481
482    /// Whether a section's lines survive an edit elsewhere in the
483    /// book. This goes false when the styling breaks a precondition,
484    /// either masters of different measures or inline content that
485    /// depends on pagination, and everything is re-broken instead.
486    pub fn reuses_sections(&self) -> bool {
487        self.section_local
488    }
489}