Skip to main content

fleuron/session/
edit.rs

1//! What a host changes: the book, a source, the sheet, a face, an
2//! image, the metadata.
3
4use 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    /// Sets the book, and with it every stage below box
17    /// construction.
18    ///
19    /// Node identity is the engine's: the tree is renumbered on the
20    /// way in, so a host may hand over sections it built by hand.
21    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) = &section.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    /// Sets the order of the book's sources, one that has no section
38    /// among them.
39    ///
40    /// [`set_content`](Session::set_content) resets the order to the
41    /// sources the book carries, so this follows it.
42    pub fn set_source_order(&mut self, names: Vec<String>) {
43        self.order = names;
44    }
45
46    /// Replaces every section that came from one source file.
47    ///
48    /// The source is the replaceable unit because a host names files
49    /// and one file may split into several sections. A name the book
50    /// does not already have appends instead, which is how a file it
51    /// has not seen before arrives.
52    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        // Nothing above the first of its sections is its own, so the
74        // index outlives the rest of them going.
75        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    /// Drops every section that came from one source file, and its
84    /// place in the book with them.
85    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    /// Names every section that came from one source by these classes
91    /// and this id, and styles the book again.
92    ///
93    /// The names sit beside the source rather than in it, so every
94    /// node keeps the bytes it was read from. A name the book does
95    /// not carry changes nothing.
96    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    /// Adds a frontend's complaints to the run's diagnostics.
107    ///
108    /// A construct the content vocabulary cannot express is reported
109    /// where the source was read, which is upstream of every stage a
110    /// session runs. The output's warnings are the whole run's, so
111    /// they belong in the same channel rather than in a second one
112    /// the host has to remember to read. Which of them still apply
113    /// after an edit is the caller's to decide; this replaces the
114    /// lot.
115    pub fn set_source_warnings(&mut self, warnings: Vec<Warning>) {
116        self.source_warnings = warnings;
117    }
118
119    /// Sets the styling, and with it whichever stage the change
120    /// reaches, which is usually far short of everything.
121    pub fn set_style(&mut self, sheets: Stylesheets) {
122        self.sheets = Some(sheets);
123        self.load_faces();
124        self.recompile();
125    }
126
127    /// Names the book: title, author, and whatever else a frontend
128    /// read.
129    ///
130    /// The declared language is the one field a stage below reads,
131    /// and a book that changes it is hyphenated again. The pages
132    /// already laid out are otherwise the pages the export writes
133    /// under the new name.
134    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    /// Registers a face, and re-runs everything a face can change.
142    ///
143    /// A family the registry did not have is a family the cascade
144    /// resolved to something else, so the styling is compiled again
145    /// and the lines are broken again. The output's font table is
146    /// rebuilt with them.
147    ///
148    /// Only a session that owns its registry has one to add to; one
149    /// that borrowed it says so instead.
150    pub fn add_font(&mut self, source: FontSource) -> Result<Vec<u16>, AddFontError> {
151        let added = self.register_font(source);
152        // The table is built with the output and never patched, so
153        // the output goes rather than outlive the ids it indexes.
154        self.output = None;
155        self.stale = Stale::Break;
156        self.recompile();
157        added
158    }
159
160    /// Registers one image, and the index `DrawItem::Image.asset`
161    /// gets for it. `None` for bytes no probe recognises,
162    /// which is a diagnostic on the next display structure and no asset.
163    ///
164    /// A url registered again with the bytes it already answers for
165    /// costs nothing. Registered again with different bytes, it
166    /// replaces them in place: the box the image takes is re-broken
167    /// only if the header now reports a different size, since the
168    /// PDF writer reads the asset table fresh on every export and
169    /// needs no invalidation to see new pixels at an unchanged size.
170    /// An image whose contour was traced is the exception, because
171    /// the pixels are what the contour came from.
172    /// Only a session that owns its asset table has one to add to;
173    /// one that borrowed it says so instead.
174    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                    // The table is built with the output and never
189                    // patched, so the output goes rather than
190                    // outlive the indexes it names. A size that
191                    // moved is a box line-breaking reserved
192                    // differently, so the section-local cache — keyed
193                    // on the url and not on what it resolves to — is
194                    // dropped rather than trusted to notice.
195                    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    /// An image the host pushes reaches the display structure: the box is
222    /// placed, the asset table names the url, and the pages are
223    /// broken again around the room it takes.
224    #[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    /// Registering the same url with the same bytes again costs
272    /// nothing: no stage runs again, since neither the asset nor the
273    /// box it takes changed.
274    #[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    /// Different bytes at a registered url that probe to the same
291    /// size replace the asset without re-breaking anything: the box
292    /// an image takes did not move.
293    #[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    /// A different size at a registered url re-breaks the lines
314    /// around it, and the new size reaches the page.
315    #[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    /// A session that borrowed its asset table says so rather than
339    /// adding to somebody else's.
340    #[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    /// The replaceable unit is the file: a host names one, and only
350    /// the sections that came from it are broken again.
351    #[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    /// One file may split into several sections, and all of them go
369    /// when it is replaced.
370    #[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    /// The page name the computed style of one source's section
392    /// carries.
393    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    /// Acceptance: a host sets a section's class and id without
411    /// changing the section's text, and the sheet reaches it by them.
412    #[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    /// A file the book has not seen before arrives at the end.
450    #[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    /// Acceptance: a source replaced with no sections keeps its place,
469    /// and is set there again when it is given some.
470    #[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    /// Acceptance: a source with no sections when the book arrives is
489    /// set at the place the host named for it.
490    #[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    /// A source that was removed has no place to come back to.
504    #[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    /// The cache stores breaks and no positions, so a section the
513    /// flow moved paints at new coordinates with the same lines.
514    #[test]
515    fn a_moved_section_keeps_its_breaks_and_takes_new_coordinates() {
516        let mut session = Session::new(registry());
517        // Chapters that open where the last one ended, so an edit
518        // above moves what follows instead of leaving it on its own
519        // opening page.
520        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    /// Setting the same content twice re-keys every section and
542    /// breaks none of them: the key is what the section says, not
543    /// which node ids it was given this time.
544    #[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    /// A session that owns its registry takes a face after it was
562    /// made, and lays out against it: bytes cross once, and the
563    /// session they crossed into is the one that keeps them.
564    #[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    /// A session laying out against someone else's registry has none
601    /// of its own to add to, and says so rather than laying out
602    /// against a face that is not there.
603    #[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    /// A section that moves in the book keeps its lines: the key
615    /// travels with the content, and nothing in it is positional.
616    #[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}