1use std::borrow::Cow;
5
6use crate::Warning;
7use crate::content::{Attributes, Book, Metadata, Section};
8use crate::fonts::FontSource;
9use crate::images::Added;
10use crate::style::Stylesheets;
11
12use super::invalidate::{has_images, hyphenation};
13use super::{AddFontError, AddImageError, Session, Stale};
14
15impl Session<'_> {
16 pub fn set_content(&mut self, mut book: Book) {
22 book.assign_node_ids();
23 self.order.clear();
24 for section in &book.sections {
25 if let Some(source) = §ion.source
26 && !self.order.contains(source)
27 {
28 self.order.push(source.clone());
29 }
30 }
31 self.book = Cow::Owned(book);
32 self.images = has_images(&self.book);
33 self.recompile();
34 self.stale = Stale::Trace;
35 }
36
37 pub fn set_source_order(&mut self, names: Vec<String>) {
43 self.order = names;
44 }
45
46 pub fn replace_source(&mut self, name: &str, sections: Vec<Section>) {
53 let place = self.order.iter().position(|source| source == name);
54 if place.is_none() {
55 self.order.push(name.to_string());
56 }
57 let order = &self.order;
58 let book = self.book.to_mut();
59 let own = |section: &Section| section.source.as_deref() == Some(name);
60 let follows = |section: &Section| {
61 let at = section
62 .source
63 .as_ref()
64 .and_then(|source| order.iter().position(|known| known == source));
65 matches!((at, place), (Some(at), Some(place)) if at > place)
66 };
67 let at = book
68 .sections
69 .iter()
70 .position(own)
71 .or_else(|| book.sections.iter().position(follows))
72 .unwrap_or(book.sections.len());
73 book.sections.retain(|section| !own(section));
76 book.sections.splice(at..at, sections);
77 book.assign_node_ids();
78 self.images = has_images(&self.book);
79 self.recompile();
80 self.stale = Stale::Trace;
81 }
82
83 pub fn remove_source(&mut self, name: &str) {
86 self.replace_source(name, Vec::new());
87 self.order.retain(|source| source != name);
88 }
89
90 pub fn set_source_attributes(&mut self, name: &str, attributes: &Attributes) {
97 let book = self.book.to_mut();
98 for section in &mut book.sections {
99 if section.source.as_deref() == Some(name) {
100 section.attributes = attributes.clone();
101 }
102 }
103 self.recompile();
104 }
105
106 pub fn set_source_warnings(&mut self, warnings: Vec<Warning>) {
116 self.source_warnings = warnings;
117 }
118
119 pub fn set_style(&mut self, sheets: Stylesheets) {
122 self.sheets = Some(sheets);
123 self.load_faces();
124 self.recompile();
125 }
126
127 pub fn set_metadata(&mut self, metadata: Metadata) {
135 if hyphenation(&metadata) != hyphenation(&self.book.metadata) {
136 self.stale = self.stale.max(Stale::Break);
137 }
138 self.book.to_mut().metadata = metadata;
139 }
140
141 pub fn add_font(&mut self, source: FontSource) -> Result<Vec<u16>, AddFontError> {
151 let added = self.register_font(source);
152 self.output = None;
155 self.stale = Stale::Break;
156 self.recompile();
157 added
158 }
159
160 pub fn add_image(&mut self, url: &str, bytes: Vec<u8>) -> Result<Option<u32>, AddImageError> {
175 let added = self
176 .assets
177 .get_mut()
178 .ok_or(AddImageError::Borrowed)?
179 .add(url, bytes);
180 Ok(match added {
181 Added::Unchanged(index) => Some(index),
182 Added::Replaced {
183 index,
184 previous,
185 current,
186 } => {
187 if previous != Some(current) {
188 self.output = None;
196 self.lines.clear();
197 self.settled.clear();
198 self.stale = Stale::Trace;
199 } else if self.contours.traces(index) {
200 self.stale = self.stale.max(Stale::Trace);
201 }
202 Some(index)
203 }
204 Added::Refused => None,
205 })
206 }
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212 use crate::content::{Attributes, Block, Book, NodeId, Section};
213 use crate::pages::DrawItem;
214 use crate::session::Session;
215 use crate::session::testing::{
216 MAP, book, book_with_image, gif, heading, paragraph, placed, placed_image_size, prose,
217 registry, runs, section, sheets, spelled, three_chapters,
218 };
219 use crate::style::{Source, Stylesheets};
220
221 #[test]
225 fn an_image_pushed_after_the_book_is_placed_and_indexed() {
226 let mut book = Book {
227 sections: vec![Section {
228 attributes: Default::default(),
229 blocks: vec![Block::Image {
230 id: NodeId::UNASSIGNED,
231 url: "plate.jpg".into(),
232 alt: "a map".into(),
233 attributes: Attributes::default(),
234 position: None,
235 span: None,
236 }],
237 ..Default::default()
238 }],
239 ..Default::default()
240 };
241 book.assign_node_ids();
242 let mut session =
243 Session::owning(crate::fonts::bundled_registry().expect("bundled font parses"));
244 session.set_content(book);
245 assert!(
246 session.preview().assets.is_empty(),
247 "a book whose images nobody supplied has no assets",
248 );
249
250 assert_eq!(
251 session.add_image("plate.jpg", MAP.to_vec()).unwrap(),
252 Some(0),
253 );
254 let output = session.preview();
255 assert_eq!(output.assets.len(), 1);
256 assert_eq!(output.assets[0].url, "plate.jpg");
257 let placed: Vec<&DrawItem> = output
258 .pages
259 .iter()
260 .flat_map(|page| &page.items)
261 .filter(|item| matches!(item, DrawItem::Image { .. }))
262 .collect();
263 assert_eq!(placed.len(), 1, "the map was not placed");
264 assert!(
265 output.warnings.is_empty(),
266 "a supplied image still complains: {:?}",
267 output.warnings,
268 );
269 }
270
271 #[test]
275 fn identical_bytes_at_a_registered_url_cost_nothing() {
276 let mut session = Session::owning(crate::fonts::bundled_registry().unwrap());
277 session.set_content(book_with_image("pic.gif"));
278 session.add_image("pic.gif", gif(64, 32, 0)).unwrap();
279 session.preview();
280 let before = session.stages();
281
282 assert_eq!(
283 session.add_image("pic.gif", gif(64, 32, 0)).unwrap(),
284 Some(0)
285 );
286 session.preview();
287 assert_eq!(session.stages(), before, "identical bytes cost a stage");
288 }
289
290 #[test]
294 fn a_same_size_replacement_breaks_nothing() {
295 let mut session = Session::owning(crate::fonts::bundled_registry().unwrap());
296 session.set_content(book_with_image("pic.gif"));
297 session.add_image("pic.gif", gif(64, 32, 0)).unwrap();
298 session.preview();
299 let before = session.stages();
300
301 assert_eq!(
302 session.add_image("pic.gif", gif(64, 32, 1)).unwrap(),
303 Some(0)
304 );
305 session.preview();
306 assert_eq!(
307 session.stages().lines,
308 before.lines,
309 "a same-size replacement broke lines it did not need to"
310 );
311 }
312
313 #[test]
316 fn a_resized_replacement_re_breaks_and_reaches_the_page() {
317 let mut session = Session::owning(crate::fonts::bundled_registry().unwrap());
318 session.set_content(book_with_image("pic.gif"));
319 session.add_image("pic.gif", gif(64, 32, 0)).unwrap();
320 let before_size = placed_image_size(session.preview());
321 let before_stages = session.stages();
322
323 assert_eq!(
324 session.add_image("pic.gif", gif(640, 320, 0)).unwrap(),
325 Some(0)
326 );
327 let after_size = placed_image_size(session.preview());
328 assert!(
329 session.stages().lines > before_stages.lines,
330 "a resize did not re-break the lines around it"
331 );
332 assert_ne!(
333 after_size, before_size,
334 "the new size did not reach the page"
335 );
336 }
337
338 #[test]
341 fn a_borrowed_asset_table_refuses_an_image() {
342 let mut session = Session::new(registry());
343 assert!(matches!(
344 session.add_image("plate.jpg", MAP.to_vec()),
345 Err(AddImageError::Borrowed),
346 ));
347 }
348
349 #[test]
352 fn replacing_a_source_re_breaks_only_its_own_sections() {
353 let mut session = three_chapters();
354 assert_eq!(
355 session.stages().lines,
356 3,
357 "the first pass broke every section"
358 );
359 session.replace_source("two.md", vec![section("two.md", prose("delta", 9))]);
360 session.preview();
361 assert_eq!(
362 session.stages().lines,
363 4,
364 "a section other than two.md was broken again"
365 );
366 }
367
368 #[test]
371 fn a_source_that_split_into_several_sections_is_replaced_whole() {
372 let mut session = Session::new(registry());
373 session.set_content(book(vec![
374 section("one.md", vec![heading("One"), paragraph("first")]),
375 section("one.md", vec![heading("Two"), paragraph("second")]),
376 section("two.md", vec![heading("Three"), paragraph("third")]),
377 ]));
378 session.preview();
379 session.replace_source("one.md", vec![section("one.md", vec![heading("Only")])]);
380 session.preview();
381 let sources: Vec<Option<&str>> = session
382 .book()
383 .sections
384 .iter()
385 .map(|section| section.source.as_deref())
386 .collect();
387 assert_eq!(sources, vec![Some("one.md"), Some("two.md")]);
388 assert_eq!(session.book().sections.len(), 2);
389 }
390
391 fn page_of(session: &Session, source: &str) -> Option<String> {
394 let at = session
395 .book()
396 .sections
397 .iter()
398 .position(|section| section.source.as_deref() == Some(source))
399 .expect("the book carries the source");
400 let tree = session.styles();
401 let node = tree
402 .nodes()
403 .iter()
404 .filter(|node| node.element == "section")
405 .nth(at)
406 .expect("every section is styled");
407 tree.styles()[node.style as usize].page.clone()
408 }
409
410 #[test]
413 fn a_host_names_a_section_beside_its_source() {
414 let mut session = three_chapters();
415 session.set_style(sheets(
416 "section.front { page: front } section#closing { page: back }",
417 ));
418 session.preview();
419 let before = session.book().sections.clone();
420
421 session.set_source_attributes(
422 "one.md",
423 &Attributes {
424 id: None,
425 classes: vec!["front".into()],
426 },
427 );
428 session.set_source_attributes(
429 "three.md",
430 &Attributes {
431 id: Some("closing".into()),
432 classes: Vec::new(),
433 },
434 );
435 session.preview();
436
437 assert_eq!(page_of(&session, "one.md").as_deref(), Some("front"));
438 assert_eq!(page_of(&session, "two.md").as_deref(), Some("chapter"));
439 assert_eq!(page_of(&session, "three.md").as_deref(), Some("back"));
440 for (was, is) in before.iter().zip(&session.book().sections) {
441 assert_eq!(was.blocks, is.blocks, "naming a section changed its text");
442 assert_eq!(was.span, is.span);
443 }
444
445 session.set_source_attributes("one.md", &Attributes::default());
446 assert_eq!(page_of(&session, "one.md").as_deref(), Some("chapter"));
447 }
448
449 #[test]
451 fn a_source_the_book_does_not_carry_is_appended() {
452 let mut session = Session::new(registry());
453 session.set_content(book(vec![section("one.md", vec![paragraph("first")])]));
454 session.replace_source("two.md", vec![section("two.md", vec![paragraph("second")])]);
455 session.preview();
456 assert_eq!(session.book().sections.len(), 2);
457 }
458
459 fn sources(session: &Session) -> Vec<String> {
460 session
461 .book()
462 .sections
463 .iter()
464 .filter_map(|section| section.source.clone())
465 .collect()
466 }
467
468 #[test]
471 fn a_source_emptied_and_filled_again_keeps_its_place() {
472 let mut session = three_chapters();
473 session.replace_source("one.md", Vec::new());
474 session.preview();
475 assert_eq!(sources(&session), ["two.md", "three.md"]);
476
477 session.replace_source("one.md", vec![section("one.md", prose("alpha", 8))]);
478 session.preview();
479 assert_eq!(sources(&session), ["one.md", "two.md", "three.md"]);
480
481 session.replace_source("two.md", Vec::new());
482 session.replace_source("three.md", Vec::new());
483 session.replace_source("three.md", vec![section("three.md", prose("gamma", 8))]);
484 session.replace_source("two.md", vec![section("two.md", prose("beta", 8))]);
485 assert_eq!(sources(&session), ["one.md", "two.md", "three.md"]);
486 }
487
488 #[test]
491 fn a_source_empty_when_the_book_arrives_is_set_at_its_place() {
492 let mut session = Session::new(registry());
493 session.set_content(book(vec![
494 section("one.md", prose("alpha", 8)),
495 section("three.md", prose("gamma", 8)),
496 ]));
497 session.set_source_order(vec!["one.md".into(), "two.md".into(), "three.md".into()]);
498 session.replace_source("two.md", vec![section("two.md", prose("beta", 8))]);
499 session.preview();
500 assert_eq!(sources(&session), ["one.md", "two.md", "three.md"]);
501 }
502
503 #[test]
505 fn a_removed_source_comes_back_at_the_end() {
506 let mut session = three_chapters();
507 session.remove_source("one.md");
508 session.replace_source("one.md", vec![section("one.md", prose("alpha", 8))]);
509 assert_eq!(sources(&session), ["two.md", "three.md", "one.md"]);
510 }
511
512 #[test]
515 fn a_moved_section_keeps_its_breaks_and_takes_new_coordinates() {
516 let mut session = Session::new(registry());
517 session.set_style(sheets("section { break-before: auto }"));
521 session.set_content(book(vec![
522 section("one.md", prose("alpha", 2)),
523 section("two.md", prose("beta", 12)),
524 ]));
525 let before = runs(session.preview(), "beta");
526 let broke = session.stages().lines;
527
528 session.replace_source("one.md", vec![section("one.md", prose("alpha", 24))]);
529 let after = runs(session.preview(), "beta");
530
531 assert_eq!(
532 session.stages().lines,
533 broke + 1,
534 "the untouched section was broken again"
535 );
536 assert!(!before.is_empty(), "the section painted nothing");
537 assert_eq!(spelled(&before), spelled(&after), "the breaks moved");
538 assert_ne!(placed(&before), placed(&after), "nothing moved");
539 }
540
541 #[test]
545 fn identical_content_set_again_breaks_nothing() {
546 let mut session = three_chapters();
547 let before = session.stages();
548 session.set_content(book(vec![
549 section("one.md", prose("alpha", 8)),
550 section("two.md", prose("beta", 8)),
551 section("three.md", prose("gamma", 8)),
552 ]));
553 session.preview();
554 assert_eq!(
555 session.stages().lines,
556 before.lines,
557 "renumbering alone cost a re-break"
558 );
559 }
560
561 #[test]
565 fn an_owning_session_takes_a_face_and_uses_it() {
566 let mut session = Session::owning(crate::fonts::bundled_registry().unwrap());
567 session.set_content(book(vec![section("one.md", prose("alpha", 2))]));
568 let faces = session.preview().fonts.len();
569
570 let mut source = crate::fonts::FontSource::from_bytes(crate::fonts::BUNDLED_FONT.to_vec())
571 .expect("the bundled face parses");
572 source.family = "borrowed garamond".into();
573 source.declared = Some(crate::fonts::FaceAttributes::REGULAR);
574 let ids = session
575 .add_font(source)
576 .expect("an owning session registers");
577 assert_eq!(ids.len(), 1);
578
579 let css = "book { font-family: 'borrowed garamond' }";
580 session.set_style(Stylesheets::parse(&[Source::author("faces.css", css)]));
581 let output = session.preview();
582 assert_eq!(
583 output.fonts.len(),
584 faces + 1,
585 "the font table did not grow with the registry"
586 );
587 assert!(
588 output
589 .pages
590 .iter()
591 .flat_map(|page| &page.items)
592 .any(|item| matches!(
593 item,
594 DrawItem::Text { font_id, .. } if *font_id == ids[0]
595 )),
596 "the face that was registered set nothing"
597 );
598 }
599
600 #[test]
604 fn a_borrowed_registry_refuses_a_face() {
605 let mut session = Session::new(registry());
606 let source = crate::fonts::FontSource::from_bytes(crate::fonts::BUNDLED_FONT.to_vec())
607 .expect("the bundled face parses");
608 assert!(matches!(
609 session.add_font(source),
610 Err(AddFontError::Borrowed)
611 ));
612 }
613
614 #[test]
617 fn reordering_the_book_breaks_nothing() {
618 let mut session = three_chapters();
619 let before = session.stages();
620 session.set_content(book(vec![
621 section("three.md", prose("gamma", 8)),
622 section("one.md", prose("alpha", 8)),
623 section("two.md", prose("beta", 8)),
624 ]));
625 session.preview();
626 assert_eq!(
627 session.stages().lines,
628 before.lines,
629 "a section that only moved was broken again"
630 );
631 }
632}