1use 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 pub fn preview(&mut self) -> &LayoutOutput {
19 self.update();
20 self.output.as_ref().expect("an update leaves an output")
21 }
22
23 pub fn export(&mut self) -> Result<Vec<u8>, PdfError> {
26 self.export_padded(None)
27 }
28
29 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 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 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 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 pub fn into_output(mut self) -> LayoutOutput {
115 self.update();
116 self.output.take().expect("an update leaves an output")
117 }
118}
119
120pub(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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}