Skip to main content

fleuron/session/
output.rs

1//! What a host asks for: the pages, a PDF, and the folios one node
2//! was set on.
3
4use std::ops::Range;
5
6use crate::LayoutOutput;
7use crate::content::NodeId;
8use crate::fonts::FontRegistry;
9use crate::images::Assets;
10use crate::layout::font_table;
11use crate::pages::{DrawItem, Folios, Navigation};
12use crate::pdf::{self, PadTo, PdfError};
13
14use super::Session;
15
16impl Session<'_> {
17    /// The display structure, brought up to date.
18    pub fn preview(&mut self) -> &LayoutOutput {
19        self.update();
20        self.output.as_ref().expect("an update leaves an output")
21    }
22
23    /// The same, as PDF bytes. The stages above the painter are the
24    /// ones the preview used, so an export cannot contradict it.
25    pub fn export(&mut self) -> Result<Vec<u8>, PdfError> {
26        self.export_padded(None)
27    }
28
29    /// The same, with blank pages after the last page until the
30    /// book has the count `pad` names. The blank pages are in the
31    /// PDF only. No stage runs to add them, and
32    /// [`Session::preview`] returns the same pages as before.
33    pub fn export_padded(&mut self, pad: Option<PadTo>) -> Result<Vec<u8>, PdfError> {
34        self.update();
35        let output = self.output.as_ref().expect("an update leaves an output");
36        pdf::write_padded(
37            output,
38            self.registry.get(),
39            self.assets.get(),
40            &self.book.metadata,
41            pad,
42        )
43    }
44
45    /// How many pages [`Session::export_padded`] writes with the
46    /// same `pad`, answered without writing them.
47    pub fn exported_pages(&mut self, pad: Option<PadTo>) -> usize {
48        self.update();
49        let output = self.output.as_ref().expect("an update leaves an output");
50        pdf::page_count(output, pad)
51    }
52
53    /// Where each of these nodes' content is set, answered in the
54    /// order they were asked about: the folios it runs between, and
55    /// the pages of the book those folios are.
56    ///
57    /// A node covers itself and everything under it, so a heading
58    /// answers with the page its own text is on, and a chapter with
59    /// the pages it runs across. Nothing for a node the book does
60    /// not hold, and nothing for one whose content reaches no page:
61    /// a node the engine synthesized, or a scene break, whose
62    /// ornament the engine wrote itself.
63    ///
64    /// The answer is a walk over the pages the session already
65    /// holds. It runs a stage only when an edit has left one to run.
66    pub fn folios(&mut self, nodes: &[NodeId]) -> Vec<Option<Folios>> {
67        let held: Vec<Option<Range<u32>>> =
68            nodes.iter().map(|node| self.book.subtree(*node)).collect();
69        self.update();
70        let output = self.output.as_ref().expect("an update leaves an output");
71        let mut answers: Vec<Option<Folios>> = vec![None; nodes.len()];
72        for (at, page) in output.pages.iter().enumerate() {
73            let at = at as u32;
74            let mut reached = |node: NodeId| {
75                for (answer, held) in answers.iter_mut().zip(&held) {
76                    if !held.as_ref().is_some_and(|held| held.contains(&node.get())) {
77                        continue;
78                    }
79                    *answer = Some(match *answer {
80                        Some(folios) => Folios {
81                            last: page.number,
82                            count: at - folios.at + 1,
83                            ..folios
84                        },
85                        None => Folios {
86                            first: page.number,
87                            last: page.number,
88                            at,
89                            count: 1,
90                        },
91                    });
92                }
93            };
94            // A page names the sections it carries, and each run of
95            // text names the node it was shaped from. Between them
96            // they name every node the page took content from.
97            for section in &page.sections {
98                reached(*section);
99            }
100            for item in &page.items {
101                if let DrawItem::Text {
102                    origin: Some(origin),
103                    ..
104                } = item
105                {
106                    reached(origin.node.element());
107                }
108            }
109        }
110        answers
111    }
112
113    /// The display structure by value, consuming the session.
114    pub fn into_output(mut self) -> LayoutOutput {
115        self.update();
116        self.output.take().expect("an update leaves an output")
117    }
118}
119
120/// An output with the font and asset tables filled in and nothing
121/// painted yet.
122pub(super) fn blank_output(registry: &FontRegistry, assets: &Assets) -> LayoutOutput {
123    LayoutOutput {
124        pages: Vec::new(),
125        fonts: font_table(registry),
126        assets: assets.assets().to_vec(),
127        warnings: Vec::new(),
128        navigation: Navigation::default(),
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use crate::content::NodeId;
136    use crate::session::Session;
137    use crate::session::testing::{
138        book, heading, named_on, prose, registry, section, sheets, three_chapters,
139    };
140
141    /// A chapter's content runs across pages, and the question
142    /// answers the folio it opens on and the folio it ends on.
143    #[test]
144    fn a_node_answers_the_first_and_last_folio_it_is_set_on() {
145        let mut session = three_chapters();
146        let chapters: Vec<NodeId> = session.book().sections.iter().map(|s| s.id).collect();
147        let settled = session.stages();
148        let folios = session.folios(&chapters);
149        assert_eq!(
150            session.stages(),
151            settled,
152            "answering ran a stage over pages that were already placed"
153        );
154        let output = session.preview();
155
156        for (chapter, folios) in chapters.iter().zip(&folios) {
157            let named = named_on(output, *chapter);
158            let at = *named.first().expect("a chapter of prose reaches a page");
159            let last = *named.last().expect("a chapter of prose reaches a page");
160            assert_eq!(
161                *folios,
162                Some(Folios {
163                    first: output.pages[at].number,
164                    last: output.pages[last].number,
165                    at: at as u32,
166                    count: (last - at + 1) as u32,
167                }),
168                "chapter {} is set on the pages {named:?}",
169                chapter.get()
170            );
171        }
172        assert!(
173            folios
174                .iter()
175                .any(|folios| folios.is_some_and(|folios| folios.first < folios.last)),
176            "no chapter of {} pages ran across two of them",
177            output.pages.len()
178        );
179    }
180
181    /// A folio is what a page has printed on it, and a book whose
182    /// counter restarts prints a number that is not the page's place
183    /// in the book. Both are answered, so a host names one and
184    /// fetches by the other.
185    #[test]
186    fn a_restarted_counter_leaves_the_folio_and_the_page_apart() {
187        let mut session = Session::new(registry());
188        session.set_content(book(vec![
189            section("front.md", prose("alpha", 4)),
190            section("body.md", prose("beta", 8)),
191        ]));
192        session.set_style(sheets("section:last-child { counter-reset: page 1 }"));
193        let body = session.book().sections[1].id;
194        let folios = session.folios(&[body])[0].expect("the chapter reaches a page");
195        let output = session.preview();
196
197        assert_eq!(folios.first, 1, "the restarted chapter opens at folio 1");
198        assert!(
199            folios.at > 0,
200            "the restarted chapter is not the first page of the book"
201        );
202        assert_eq!(
203            output.pages[folios.at as usize].number, folios.first,
204            "`at` is not the page the folio is printed on"
205        );
206        assert_eq!(
207            output.pages[(folios.at + folios.count - 1) as usize].number,
208            folios.last,
209            "`at` and `count` do not reach the folio it ends on"
210        );
211    }
212
213    /// One call, one answer per node asked about, in the order they
214    /// were asked about.
215    #[test]
216    fn several_nodes_are_answered_in_one_call() {
217        let mut session = three_chapters();
218        let mut asked: Vec<NodeId> = session.book().sections.iter().map(|s| s.id).collect();
219        asked.reverse();
220        asked.push(NodeId::new(u32::MAX));
221
222        let together = session.folios(&asked);
223        let apart: Vec<Option<Folios>> = asked
224            .iter()
225            .map(|node| session.folios(std::slice::from_ref(node))[0])
226            .collect();
227        assert_eq!(together, apart);
228        assert_eq!(together.len(), asked.len());
229    }
230
231    /// A node the book does not hold, and the id the engine writes
232    /// its own text under, are both answered with nothing rather
233    /// than with a folio or an error.
234    #[test]
235    fn a_node_the_book_does_not_hold_answers_with_nothing() {
236        let mut session = three_chapters();
237        let past = NodeId::new(u32::MAX);
238        assert_eq!(
239            session.folios(&[past, NodeId::UNASSIGNED, past]),
240            vec![None, None, None]
241        );
242    }
243
244    /// A heading's runs are shaped from the text inside it, so no run
245    /// names the heading itself. It answers with the page that text
246    /// is on all the same.
247    #[test]
248    fn a_node_no_run_names_answers_with_the_page_its_content_is_on() {
249        let mut session = Session::new(registry());
250        session.set_content(book(vec![section(
251            "one.md",
252            [vec![heading("Chapter One")], prose("alpha", 8)].concat(),
253        )]));
254        let node = crate::content::block_id(&session.book().sections[0].blocks[0]);
255        let folios = session.folios(&[node]);
256        let output = session.preview();
257
258        assert!(
259            named_on(output, node).is_empty(),
260            "a run named the heading, so this proves nothing"
261        );
262        let first = output.pages.first().expect("the book has pages").number;
263        assert_eq!(
264            folios,
265            vec![Some(Folios {
266                first,
267                last: first,
268                at: 0,
269                count: 1,
270            })]
271        );
272    }
273
274    /// An export costs nothing the preview has not already paid: the
275    /// stages above the painter are the same ones.
276    #[test]
277    fn export_paints_from_the_stages_the_preview_used() {
278        let mut session = three_chapters();
279        let before = session.stages();
280        let bytes = session.export().expect("the fixture book writes PDF");
281        assert_eq!(session.stages(), before, "an export re-ran a stage");
282        assert!(bytes.starts_with(b"%PDF"), "that is not a PDF");
283    }
284
285    /// Acceptance: the session's export takes the count to pad to,
286    /// and says how many pages the file holds.
287    #[test]
288    fn the_export_takes_a_count_and_says_how_many_pages_it_writes() {
289        let mut session = three_chapters();
290        let laid_out = session.preview().pages.len();
291        assert_eq!(session.exported_pages(None), laid_out);
292        for (pad, multiple) in [(PadTo::Even, 2), (PadTo::MultipleOfFour, 4)] {
293            let pages = session.exported_pages(Some(pad));
294            assert_eq!(pages, laid_out.next_multiple_of(multiple));
295            let bytes = session
296                .export_padded(Some(pad))
297                .expect("the fixture book writes PDF");
298            let pdf = String::from_utf8_lossy(&bytes);
299            assert!(
300                pdf.contains(&format!("/Type /Pages\n  /Count {pages}")),
301                "the file does not hold the {pages} pages the session answered with"
302            );
303        }
304    }
305
306    /// Acceptance: the padding lays nothing out again, and the pages
307    /// the preview answers with are the ones it answered with before.
308    #[test]
309    fn padding_runs_no_stage_and_leaves_the_preview_as_it_was() {
310        let mut session = Session::new(registry());
311        session.set_content(book(vec![section("one.md", prose("alpha", 1))]));
312        let encoded = |output: &LayoutOutput| crate::wire::encode(output).expect("it encodes");
313        let before = encoded(session.preview());
314        let laid_out = session.preview().pages.len();
315        assert_eq!(laid_out % 4, 1, "the book needs no padding");
316        let settled = session.stages();
317
318        let pages = session.exported_pages(Some(PadTo::MultipleOfFour));
319        session
320            .export_padded(Some(PadTo::MultipleOfFour))
321            .expect("the fixture book writes PDF");
322        assert_eq!(pages, laid_out + 3);
323        assert_eq!(session.stages(), settled, "padding re-ran a stage");
324        assert!(
325            encoded(session.preview()) == before,
326            "padding changed the preview"
327        );
328        assert_eq!(session.stages(), settled, "the preview after it re-ran one");
329    }
330}