Skip to main content

devpage_design/scene/
edit.rs

1//! Edits: how one scene becomes the next. Each names its nodes by id — a
2//! node's own attributes changed, a subtree inserted after a sibling, a
3//! subtree removed, a subtree moved — and applying them to a scene is all or
4//! nothing, at the cost of the edits alone.
5
6use std::collections::{HashMap, HashSet};
7
8use super::{Ids, ImageFiles, ImageId, Node, Scene};
9use crate::fonts::{FontFiles, FontId};
10use crate::tree::{NodeId, Order, OrderKey};
11
12/// One step from a scene to the next, naming its nodes by id.
13#[derive(Debug, Clone, PartialEq)]
14pub enum Edit {
15    /// The node of this id takes these own attributes; its children stay.
16    Change(Node),
17    /// This subtree goes under the node `parent`, after its child `after`
18    /// or first — or, with no parent, replaces the scene.
19    Insert {
20        parent: Option<NodeId>,
21        after: Option<NodeId>,
22        node: Node,
23    },
24    /// The subtree of this id goes.
25    Remove(NodeId),
26    /// The subtree of this id moves under `parent`, after `after` or first.
27    Move {
28        id: NodeId,
29        parent: NodeId,
30        after: Option<NodeId>,
31    },
32}
33
34/// Edits with the image and font files they bring: everything that takes a
35/// scene to the next. Of the files, only those the scene before didn't hold
36/// — each travels once.
37#[derive(Debug, Clone, PartialEq, Default)]
38pub struct Edits {
39    /// The edits, in the order they apply.
40    pub list: Vec<Edit>,
41    /// The image files they bring that the scene before didn't hold.
42    pub images: ImageFiles,
43    /// The font files they bring that the scene before didn't hold.
44    pub fonts: FontFiles,
45    /// Whether the scene they make is themed.
46    pub themed: bool,
47}
48
49impl Edits {
50    /// The edits that turn `old` into `new`, by their nodes' ids: an insert
51    /// before the first of 100,000 siblings is one insert. It compares the
52    /// two scenes whole; a design resolved again finds most edits without
53    /// one, from what a save reached.
54    pub fn between(old: &Scene, new: &Scene) -> Edits {
55        Edits::onto(old, diff(old, new), &new.images, &new.fonts, new.themed)
56    }
57
58    /// `list` to apply to `scene`, with of `images` and `fonts` — the files
59    /// the scene they make may use — those `scene` doesn't hold.
60    pub fn onto(
61        scene: &Scene,
62        list: Vec<Edit>,
63        images: &ImageFiles,
64        fonts: &FontFiles,
65        themed: bool,
66    ) -> Edits {
67        Edits {
68            list,
69            images: images
70                .iter()
71                .filter(|(id, _)| !scene.images.contains_key(id))
72                .map(|(id, f)| (*id, f.clone()))
73                .collect(),
74            fonts: fonts
75                .iter()
76                .filter(|(id, _)| !scene.fonts.contains_key(id))
77                .map(|(id, f)| (*id, f.clone()))
78                .collect(),
79            themed,
80        }
81    }
82
83    /// `scene` whole, as edits from nothing: its root, and every file.
84    pub fn whole(scene: &Scene) -> Edits {
85        Edits {
86            list: vec![Edit::Insert {
87                parent: None,
88                after: None,
89                node: scene.root.clone(),
90            }],
91            images: scene.images.clone(),
92            fonts: scene.fonts.clone(),
93            themed: scene.themed,
94        }
95    }
96}
97
98/// The edits from `old` to `new`. Each node of `new` that `old` has is
99/// kept — moved if it has another parent or falls out of the longest run of
100/// siblings still in their order, and changed if its own attributes did;
101/// each one `old` hasn't is inserted, whole where nothing under it is kept,
102/// alone where something is, which is then moved into it. Last, what `old`
103/// has and `new` doesn't goes: by then nothing kept is under it.
104fn diff(old: &Scene, new: &Scene) -> Vec<Edit> {
105    if old.root.id != new.root.id {
106        return vec![Edit::Insert {
107            parent: None,
108            after: None,
109            node: new.root.clone(),
110        }];
111    }
112    subtree(old, &[], &new.root)
113}
114
115/// The edits that turn the subtree of `old` at `at` — whose root has the id
116/// `new`'s root has — into `new`: what a part of a scene resolved again is
117/// brought across by, costing that part alone.
118pub fn subtree(old: &Scene, at: &[OrderKey], new: &Node) -> Vec<Edit> {
119    let within = |id: &NodeId| old.ids.get(id).is_some_and(|o| o.starts_with(at));
120    let mut out = Vec::new();
121    // Under each node of `new`, whether something `old` has is.
122    fn kept_below(n: &Node, within: &dyn Fn(&NodeId) -> bool, out: &mut HashSet<NodeId>) -> bool {
123        let mut any = false;
124        for c in &n.children {
125            any |= kept_below(c, within, out) | within(&c.id);
126        }
127        if any {
128            out.insert(n.id.clone());
129        }
130        any
131    }
132    let mut holds = HashSet::new();
133    kept_below(new, &within, &mut holds);
134    let Some(was) = old.at(at) else {
135        return out;
136    };
137    if !was.same_own(new) {
138        out.push(Edit::Change(new.own()));
139    }
140    let mut todo = vec![new];
141    while let Some(p) = todo.pop() {
142        // The children `old` had under this same parent, by their places
143        // there: those in the longest run still in order stay.
144        let old_parent = old
145            .ids
146            .get(&p.id)
147            .filter(|o| o.starts_with(at))
148            .and_then(|o| old.at(o));
149        let rank: HashMap<&NodeId, usize> = old_parent
150            .map(|op| {
151                op.children
152                    .iter()
153                    .enumerate()
154                    .map(|(i, c)| (&c.id, i))
155                    .collect()
156            })
157            .unwrap_or_default();
158        let ranks: Vec<Option<usize>> = p
159            .children
160            .iter()
161            .map(|c| rank.get(&c.id).copied())
162            .collect();
163        let stay = longest_run(&ranks);
164        let mut prev: Option<&NodeId> = None;
165        for (i, c) in p.children.iter().enumerate() {
166            match old.node(&c.id).filter(|_| within(&c.id)) {
167                Some(was) => {
168                    if !stay[i] {
169                        out.push(Edit::Move {
170                            id: c.id.clone(),
171                            parent: p.id.clone(),
172                            after: prev.cloned(),
173                        });
174                    }
175                    if !was.same_own(c) {
176                        out.push(Edit::Change(c.own()));
177                    }
178                    todo.push(c);
179                }
180                None => {
181                    let node = if holds.contains(&c.id) {
182                        todo.push(c);
183                        c.own()
184                    } else {
185                        c.clone()
186                    };
187                    out.push(Edit::Insert {
188                        parent: Some(p.id.clone()),
189                        after: prev.cloned(),
190                        node,
191                    });
192                }
193            }
194            prev = Some(&c.id);
195        }
196    }
197    let kept: HashSet<&NodeId> = {
198        fn ids<'a>(n: &'a Node, out: &mut HashSet<&'a NodeId>) {
199            out.insert(&n.id);
200            for c in &n.children {
201                ids(c, out);
202            }
203        }
204        let mut out = HashSet::new();
205        ids(new, &mut out);
206        out
207    };
208    fn gone(n: &Node, kept: &HashSet<&NodeId>, out: &mut Vec<Edit>) {
209        for c in &n.children {
210            if kept.contains(&c.id) {
211                gone(c, kept, out);
212            } else {
213                out.push(Edit::Remove(c.id.clone()));
214            }
215        }
216    }
217    gone(was, &kept, &mut out);
218    out
219}
220
221/// Which of a list stay where they are: the longest increasing run of their
222/// places before, `None` for those that weren't there.
223fn longest_run(ranks: &[Option<usize>]) -> Vec<bool> {
224    // Patience sorting: the smallest last place of a run of each length,
225    // and each element's predecessor in its run.
226    let mut tails: Vec<usize> = Vec::new();
227    let mut before: Vec<Option<usize>> = vec![None; ranks.len()];
228    for (i, r) in ranks.iter().enumerate() {
229        let Some(r) = r else { continue };
230        let at = tails.partition_point(|&t| ranks[t].expect("ranked") < *r);
231        before[i] = at.checked_sub(1).map(|a| tails[a]);
232        if at == tails.len() {
233            tails.push(i);
234        } else {
235            tails[at] = i;
236        }
237    }
238    let mut stay = vec![false; ranks.len()];
239    let mut at = tails.last().copied();
240    while let Some(i) = at {
241        stay[i] = true;
242        at = before[i];
243    }
244    stay
245}
246
247/// What edits did, by id, for a drawing kept beside the scene to follow:
248/// the subtrees that left their place — removed, or moved away — the
249/// subtrees placed — inserted, or moved here — and the nodes that kept their
250/// place and took new own attributes, with the ones they had.
251#[derive(Debug, Default, Clone, PartialEq)]
252pub struct Applied {
253    /// The roots of the subtrees that left their place: removed, or moved away.
254    pub removed: Vec<NodeId>,
255    /// The roots of the subtrees placed: inserted, or moved here.
256    pub placed: Vec<NodeId>,
257    /// The nodes that kept their place and took new own attributes, each with
258    /// the node it was.
259    pub changed: Vec<(NodeId, Node)>,
260}
261
262/// One operation done, and how to undo it.
263enum Step {
264    /// Put back these own attributes at this order.
265    Own(Order, Node),
266    /// Take out the subtree at this order.
267    Take(Order),
268    /// Put this subtree back under the parent at this order, under this key.
269    Put(Order, OrderKey, Node),
270    /// Move the subtree now at this order back under this parent and key.
271    Back(Order, Order, OrderKey),
272    /// Put this root back.
273    Root(Node),
274}
275
276/// Applies `edits` to `scene`, whose files `uses` counts, or says why it
277/// can't — leaving both as they were. The work is the edits': each finds its
278/// nodes by id, and the files no node uses any more are dropped by count,
279/// never by a walk of the scene.
280pub fn apply(scene: &mut Scene, uses: &mut Uses, edits: &Edits) -> Result<Applied, String> {
281    applied(scene, uses, edits).map(|(applied, _)| applied)
282}
283
284/// [`apply`], and what puts the scene back as it was before them, at their
285/// cost again: for a holder that finds only after applying them that the
286/// scene they made can't be drawn, and draws the one before.
287pub fn applied(
288    scene: &mut Scene,
289    uses: &mut Uses,
290    edits: &Edits,
291) -> Result<(Applied, Undo), String> {
292    let (images, fonts) = (&edits.images, &edits.fonts);
293    let mut undo = Vec::new();
294    let mut applied = Applied::default();
295    let done =
296        run(scene, uses, &edits.list, &mut undo, &mut applied).and_then(|()| {
297            // Every file a node uses is held or arrives with the patch.
298            if let Some(missing) = uses.images.iter().find(|(id, c)| {
299                **c > 0 && !scene.images.contains_key(id) && !images.contains_key(id)
300            }) {
301                return Err(format!(
302                    "the stream never sent the image file {:?}",
303                    missing.0
304                ));
305            }
306            if let Some(missing) = uses
307                .fonts
308                .iter()
309                .find(|(id, c)| **c > 0 && !scene.fonts.contains_key(id) && !fonts.contains_key(id))
310            {
311                return Err(format!(
312                    "the stream never sent the font file {:?}",
313                    missing.0
314                ));
315            }
316            Ok(())
317        });
318    if let Err(e) = done {
319        for u in undo.into_iter().rev() {
320            revert(scene, uses, u);
321        }
322        uses.settle();
323        return Err(e);
324    }
325    scene
326        .images
327        .extend(images.iter().map(|(id, f)| (*id, f.clone())));
328    scene
329        .fonts
330        .extend(fonts.iter().map(|(id, f)| (*id, f.clone())));
331    uses.settle();
332    let mut back = Undo {
333        steps: undo,
334        images: ImageFiles::new(),
335        fonts: FontFiles::new(),
336        themed: scene.themed,
337    };
338    scene.images.retain(|id, f| {
339        let kept = uses.images.contains_key(id);
340        if !kept {
341            back.images.insert(*id, f.clone());
342        }
343        kept
344    });
345    scene.fonts.retain(|id, f| {
346        let kept = uses.fonts.contains_key(id);
347        if !kept {
348            back.fonts.insert(*id, f.clone());
349        }
350        kept
351    });
352    scene.themed = edits.themed;
353    Ok((applied, back))
354}
355
356/// What puts a scene back as it was before edits applied to it: each step
357/// undone, last first, the files they let go held again, and whether it was
358/// themed.
359pub struct Undo {
360    /// Each operation done, in the order it was done.
361    steps: Vec<Step>,
362    /// The image files the edits let go.
363    images: ImageFiles,
364    /// The font files the edits let go.
365    fonts: FontFiles,
366    /// Whether the scene was themed before the edits.
367    themed: bool,
368}
369
370impl Undo {
371    /// Puts `scene`, whose files `uses` counts, back as it was before the
372    /// edits this undoes — which must be the last applied to it.
373    pub fn undo(self, scene: &mut Scene, uses: &mut Uses) {
374        for step in self.steps.into_iter().rev() {
375            revert(scene, uses, step);
376        }
377        uses.settle();
378        scene.images.extend(self.images);
379        scene.fonts.extend(self.fonts);
380        scene.images.retain(|id, _| uses.images.contains_key(id));
381        scene.fonts.retain(|id, _| uses.fonts.contains_key(id));
382        scene.themed = self.themed;
383    }
384}
385
386/// Where a design's one scene is held: what resolving it again reads the
387/// scene from, and brings it across by — by edits applied to it there,
388/// once, and to whatever is kept beside it, like a drawing.
389pub trait Holder {
390    /// The scene as it is now.
391    fn scene(&self) -> &Scene;
392
393    /// Applies `edits` to the scene, or says why they don't apply, leaving
394    /// it as it was.
395    fn apply(&mut self, edits: &Edits) -> Result<Applied, String>;
396}
397
398/// A scene held with nothing beside it, counting the edits applied to it:
399/// what the engine's tests resolve again into.
400#[cfg(test)]
401pub(crate) struct Bare {
402    pub scene: Scene,
403    pub uses: Uses,
404    /// How many times edits were applied to it.
405    pub applies: usize,
406}
407
408#[cfg(test)]
409impl Bare {
410    pub fn new(scene: Scene) -> Bare {
411        Bare {
412            uses: Uses::of(&scene.root),
413            scene,
414            applies: 0,
415        }
416    }
417}
418
419#[cfg(test)]
420impl Holder for Bare {
421    fn scene(&self) -> &Scene {
422        &self.scene
423    }
424
425    fn apply(&mut self, edits: &Edits) -> Result<Applied, String> {
426        self.applies += 1;
427        apply(&mut self.scene, &mut self.uses, edits)
428    }
429}
430
431/// Applies `ops` to `scene` in order, counting their files in `uses` and
432/// recording each step in `undo` and what it did in `applied`; stops at the
433/// first that doesn't apply, saying why.
434fn run(
435    scene: &mut Scene,
436    uses: &mut Uses,
437    ops: &[Edit],
438    undo: &mut Vec<Step>,
439    applied: &mut Applied,
440) -> Result<(), String> {
441    for o in ops {
442        match o {
443            Edit::Change(new) => {
444                let order = order_of(scene, &new.id)?;
445                let new = new.clone();
446                let place = scene.at_mut(&order).expect("indexed");
447                let mut own = std::mem::replace(place, new);
448                std::mem::swap(&mut place.children, &mut own.children);
449                uses.take_own(&own);
450                uses.add_own(place);
451                applied.changed.push((own.id.clone(), own.clone()));
452                undo.push(Step::Own(order, own));
453            }
454            Edit::Insert {
455                parent,
456                after,
457                node,
458            } => {
459                let node = node.clone();
460                let Some(parent) = parent.as_ref() else {
461                    // A new root: the scene, replaced.
462                    if Ids::of(&node).len() != count(&node) {
463                        return Err(format!("{} holds a node twice", node.id));
464                    }
465                    let old = std::mem::replace(&mut scene.root, node);
466                    uses.take(&old);
467                    uses.add(&scene.root);
468                    scene.ids = Ids::of(&scene.root);
469                    applied.removed.push(old.id.clone());
470                    applied.placed.push(scene.root.id.clone());
471                    undo.push(Step::Root(old));
472                    continue;
473                };
474                let parent = order_of(scene, parent)?;
475                let after = after_key(scene, &parent, after.as_ref())?;
476                check_unique(scene, &node, None)?;
477                uses.add(&node);
478                let id = node.id.clone();
479                let order = place(scene, &parent, after.as_ref(), node);
480                applied.placed.push(id);
481                undo.push(Step::Take(order));
482            }
483            Edit::Remove(id) => {
484                let order = order_of(scene, id)?;
485                if order.is_empty() {
486                    return Err("the root can't be removed".into());
487                }
488                let (parent, key) = (
489                    order[..order.len() - 1].to_vec(),
490                    order[order.len() - 1].clone(),
491                );
492                let node = take(scene, &order);
493                uses.take(&node);
494                applied.removed.push(id.clone());
495                undo.push(Step::Put(parent, key, node));
496            }
497            Edit::Move { id, parent, after } => {
498                let from = order_of(scene, id)?;
499                if from.is_empty() {
500                    return Err("the root can't be moved".into());
501                }
502                let parent = order_of(scene, parent)?;
503                if parent.starts_with(&from) {
504                    return Err(format!("{id} can't move under itself"));
505                }
506                let key = from[from.len() - 1].clone();
507                let old_parent = from[..from.len() - 1].to_vec();
508                let after = after_key(scene, &parent, after.as_ref())?;
509                if after.as_ref() == Some(&key) && parent == old_parent {
510                    return Err(format!("{id} can't move after itself"));
511                }
512                let node = take(scene, &from);
513                let to = place(scene, &parent, after.as_ref(), node);
514                applied.removed.push(id.clone());
515                applied.placed.push(id.clone());
516                undo.push(Step::Back(to, old_parent, key));
517            }
518        }
519    }
520    Ok(())
521}
522
523/// How many nodes the subtree of `n` holds, `n` included.
524fn count(n: &Node) -> usize {
525    1 + n.children.iter().map(count).sum::<usize>()
526}
527
528/// Where in `scene` the node `id` is, or that there is none.
529fn order_of(scene: &Scene, id: &NodeId) -> Result<Order, String> {
530    scene
531        .ids
532        .get(id)
533        .cloned()
534        .ok_or_else(|| format!("no node {id}"))
535}
536
537/// The key, under the parent at `parent`, of its child `after`.
538fn after_key(
539    scene: &Scene,
540    parent: &Order,
541    after: Option<&NodeId>,
542) -> Result<Option<OrderKey>, String> {
543    let Some(id) = after else { return Ok(None) };
544    let o = order_of(scene, id)?;
545    if o.len() != parent.len() + 1 || !o.starts_with(parent) {
546        return Err(format!("{id} isn't a child of the node it is placed under"));
547    }
548    Ok(o.last().cloned())
549}
550
551/// Says if `node`'s subtree names a node the scene has, but for `but`.
552fn check_unique(scene: &Scene, node: &Node, but: Option<&NodeId>) -> Result<(), String> {
553    if Some(&node.id) != but && scene.ids.contains(&node.id) {
554        return Err(format!("{} is in the scene already", node.id));
555    }
556    let mut seen = HashSet::new();
557    fn walk<'a>(n: &'a Node, scene: &Scene, seen: &mut HashSet<&'a NodeId>) -> Result<(), String> {
558        if !seen.insert(&n.id) {
559            return Err(format!("{} is in the subtree twice", n.id));
560        }
561        for c in &n.children {
562            if scene.ids.contains(&c.id) {
563                return Err(format!("{} is in the scene already", c.id));
564            }
565            walk(c, scene, seen)?;
566        }
567        Ok(())
568    }
569    walk(node, scene, &mut seen)
570}
571
572/// Places `node` under the parent at `parent`, after its child `after` or
573/// first, indexing its subtree; returns where it is.
574fn place(scene: &mut Scene, parent: &Order, after: Option<&OrderKey>, node: Node) -> Order {
575    let p = scene.at_mut(parent).expect("indexed");
576    let key = p.children.insert_after(after, node);
577    let mut order = parent.clone();
578    order.push(key.clone());
579    index(scene, &order);
580    order
581}
582
583/// Indexes the subtree at `order`.
584fn index(scene: &mut Scene, order: &Order) {
585    let mut at = &scene.root;
586    for k in order {
587        at = at.children.get(k).expect("placed");
588    }
589    scene.ids.add(at, order.clone());
590}
591
592/// Takes the subtree at `order` out of the scene and its index.
593fn take(scene: &mut Scene, order: &Order) -> Node {
594    let (parent, key) = (&order[..order.len() - 1], &order[order.len() - 1]);
595    let node = scene
596        .at_mut(parent)
597        .expect("indexed")
598        .children
599        .remove(key)
600        .expect("indexed");
601    scene.ids.remove(&node);
602    node
603}
604
605/// Undoes the step `u` on `scene`, counting the files it changes in `uses`.
606fn revert(scene: &mut Scene, uses: &mut Uses, u: Step) {
607    match u {
608        Step::Own(order, mut own) => {
609            let place = scene.at_mut(&order).expect("done");
610            std::mem::swap(&mut place.children, &mut own.children);
611            let new = std::mem::replace(place, own);
612            uses.take_own(&new);
613            uses.add_own(scene.at(&order).expect("done"));
614        }
615        Step::Take(order) => {
616            let node = take(scene, &order);
617            uses.take(&node);
618        }
619        Step::Put(parent, key, node) => {
620            uses.add(&node);
621            let p = scene.at_mut(&parent).expect("done");
622            p.children.put(key.clone(), node);
623            let mut order = parent;
624            order.push(key);
625            index(scene, &order);
626        }
627        Step::Back(now, parent, key) => {
628            let node = take(scene, &now);
629            let p = scene.at_mut(&parent).expect("done");
630            p.children.put(key.clone(), node);
631            let mut order = parent;
632            order.push(key);
633            index(scene, &order);
634        }
635        Step::Root(old) => {
636            let new = std::mem::replace(&mut scene.root, old);
637            uses.take(&new);
638            uses.add(&scene.root);
639            scene.ids = Ids::of(&scene.root);
640        }
641    }
642}
643
644/// How many nodes of a scene show each image file and are set in each font
645/// file: what lets edits drop the files no node uses any more without
646/// walking the scene.
647#[derive(Debug, Default, Clone, PartialEq)]
648pub struct Uses {
649    /// How many nodes show each image file.
650    images: std::collections::HashMap<ImageId, usize>,
651    /// How many nodes are set in each font file.
652    fonts: std::collections::HashMap<FontId, usize>,
653}
654
655impl Uses {
656    /// The files `root` and every node under it use.
657    pub fn of(root: &Node) -> Uses {
658        let mut uses = Uses::default();
659        uses.add(root);
660        uses
661    }
662
663    /// Counts the files `n` and every node under it use.
664    fn add(&mut self, n: &Node) {
665        self.add_own(n);
666        for c in &n.children {
667            self.add(c);
668        }
669    }
670
671    /// Counts the files `n` itself uses, not the nodes under it.
672    fn add_own(&mut self, n: &Node) {
673        if let Some(i) = &n.image {
674            *self.images.entry(i.id).or_default() += 1;
675        }
676        if let Some(font) = n.text.as_ref().and_then(|t| t.font) {
677            *self.fonts.entry(font).or_default() += 1;
678        }
679    }
680
681    /// Uncounts the files `n` and every node under it use; a file left at none
682    /// stays until [`settle`](Self::settle).
683    fn take(&mut self, n: &Node) {
684        self.take_own(n);
685        for c in &n.children {
686            self.take(c);
687        }
688    }
689
690    /// Uncounts the files `n` itself uses, not the nodes under it.
691    fn take_own(&mut self, n: &Node) {
692        let less = |count: Option<&mut usize>| {
693            if let Some(c) = count {
694                *c -= 1;
695            }
696        };
697        if let Some(i) = &n.image {
698            less(self.images.get_mut(&i.id));
699        }
700        if let Some(font) = n.text.as_ref().and_then(|t| t.font) {
701            less(self.fonts.get_mut(&font));
702        }
703    }
704
705    /// Drops the files no node uses any more.
706    fn settle(&mut self) {
707        self.images.retain(|_, c| *c > 0);
708        self.fonts.retain(|_, c| *c > 0);
709    }
710}
711
712#[cfg(test)]
713mod tests;