Skip to main content

kui_core/
depart.rs

1//! Exit transitions: a subtree the view stopped declaring, kept as a
2//! picture and played out.
3//!
4//! A view asks for one with `NodeSpec::exit` (an [`crate::enter::Enter`]
5//! read the other way: where the slots end) together with a `transition`.
6//! When such a node is in one frame's tree and not the next, while its
7//! parent still is, its specs, contents and laid-out rects are copied out
8//! of the previous frame into this store as a **ghost**, and every later
9//! frame replays it until its transition ends. An app never calls into
10//! this module: `Core` owns the [`DepartStore`], and a driver only sees
11//! that another frame is owed while [`DepartStore::animating`] is true.
12//!
13//! A ghost is:
14//!
15//! - **frozen, not re-laid-out.** Its rects are the ones layout gave it
16//!   the last time it existed, so a dying node never fights the live
17//!   layout for space.
18//! - **in its place, and unclipped.** It is painted where the node was in
19//!   the paint order, just under the node that painted after it, so a
20//!   panel that sat under a HUD leaves under it. Its ancestors may be
21//!   gone, so it draws outside every clip they held; the clips inside the
22//!   picture stay.
23//! - **inert.** No hit region, no place in the Tab ring, no access row.
24//! - **self-easing.** Its slots are one lerp over its own clock; a spring
25//!   easing samples as ease-out.
26//!
27//! A ghost is dropped when its transition ends, when the same key comes
28//! back (the live node wins at once, so a toast dismissed and re-shown
29//! does not double), when it has gone unreplayed for a while, and when a
30//! later frame's removal needs the room. The store holds at most
31//! [`MAX_NODES`] nodes, judged per frame's removal as a whole: the oldest
32//! ghosts are evicted until the removal fits, and a removal larger than
33//! the budget on its own is not animated at all, so a list never gets
34//! half its rows sliding out and the rest blinking away. A node that goes
35//! because an ancestor went goes at once with it, unless that ancestor
36//! has an `exit` of its own.
37
38use crate::anim::Easing;
39use crate::color::Color;
40use crate::enter::Enter;
41use crate::geom::{Rect, Vec2};
42use crate::key::Key;
43use crate::resources::ImageId;
44use crate::spec::{NodeSpec, Sizing};
45use crate::tree::{NIL, NodeContent, Tree};
46
47/// The most nodes every departing subtree together may retain. The budget
48/// is over *nodes* rather than subtrees because a node is what a replayed
49/// frame pays for. A frame whose removal is larger than this gets none of
50/// it animated (every departing node vanishes at once, as a node with no
51/// `exit` does) rather than the first of them sliding out and the rest
52/// blinking. A departing subtree costs about 0.065 µs a node in the frame
53/// it leaves and 0.021 µs a node a frame while it plays, so the bound is
54/// on memory and on a removal nobody meant to animate, not on time.
55pub const MAX_NODES: usize = 4096;
56
57/// Whether a node can depart at all: it declared an `exit`, and a
58/// `transition` with a duration to run it over. The diff counts a frame's
59/// removal by this before the store copies any of it, and
60/// [`DepartStore::depart`] returns early on the same two conditions, so a
61/// subtree counted is a subtree copied.
62#[inline]
63pub(crate) fn can_depart(spec: &NodeSpec) -> bool {
64    spec.anim().exit.is_some()
65        && spec
66            .transition
67            .as_ref()
68            .is_some_and(|t| t.duration_ms > 0.0)
69}
70
71/// A departing node's content. Same leaves a live node has, in the forms
72/// that outlive the frame that made them: a `TextId` indexes the frame's
73/// text list, which is rebuilt every frame, so a ghost carries the cache
74/// key of the shaped buffer behind it instead.
75#[derive(Clone, Copy, Debug, PartialEq)]
76pub(crate) enum GhostContent {
77    Container,
78    Text {
79        cache_key: u64,
80        color: Color,
81    },
82    Edit(Key),
83    Image(ImageId, crate::resources::ImageOpts),
84    /// A stroke: `len` points from `first` in the ghost's own point list
85    /// (relative to the node's box, like the live run's), drawn `width`
86    /// wide in the colour the node's `bg` slot eases to.
87    Line {
88        first: u32,
89        len: u32,
90        width: f32,
91    },
92    /// A fragment, by value: the handle and the parameters the node last
93    /// declared. The ghost re-declares them every frame it draws, so the
94    /// picture is frozen at departure while the box eases.
95    Fragment(crate::fragment::Draw),
96    /// A polygon, by value like a fragment; the fill is the colour the
97    /// node's `bg` slot eases to.
98    Polygon(crate::fragment::Draw),
99}
100
101pub(crate) struct GhostNode {
102    /// Index within this ghost, `NIL` for its root.
103    pub parent: u32,
104    pub spec: NodeSpec,
105    pub content: GhostContent,
106    /// Where layout left it, logical, in viewport coordinates.
107    pub rect: Rect,
108}
109
110/// Where a departing subtree sat in the paint order: the
111/// layer, and the key of the first node painted after it in that layer
112/// that the frame which noticed it gone still declares. Its ghost is
113/// painted just under that node — and at the end of its layer once the
114/// node is gone too, or on top of everything once the layer is.
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub(crate) enum Place {
117    /// In the in-flow layer, just under `before`; at its end for `None`.
118    InFlow { before: Option<Key> },
119    /// Inside the float layer rooted at `layer`, just under `before`; at
120    /// that layer's end for `None`.
121    InLayer { layer: Key, before: Option<Key> },
122    /// A float layer of its own, just under the layer rooted at `before`;
123    /// on top of the stack for `None`.
124    Layer { before: Option<Key> },
125}
126
127impl Place {
128    /// The key a per-node ask names, for the membership mask: the node a
129    /// ghost is painted under, or for one at a layer's end the layer.
130    fn mask_key(self) -> Option<Key> {
131        match self {
132            Place::InFlow { before } | Place::Layer { before } => before,
133            Place::InLayer { layer, before } => Some(before.unwrap_or(layer)),
134        }
135    }
136
137    /// The node (or, for a whole layer, the layer) the ghost is painted
138    /// just under; `None` at the end of wherever it is.
139    fn before(self) -> Option<Key> {
140        match self {
141            Place::InFlow { before } | Place::Layer { before } | Place::InLayer { before, .. } => {
142                before
143            }
144        }
145    }
146
147    /// The same place, under something else.
148    fn with_before(self, before: Option<Key>) -> Self {
149        match self {
150            Place::InFlow { .. } => Place::InFlow { before },
151            Place::InLayer { layer, .. } => Place::InLayer { layer, before },
152            Place::Layer { .. } => Place::Layer { before },
153        }
154    }
155}
156
157/// One ask a pass makes of the replay: the slot the emission has reached.
158/// The three `Under*` asks are per node and gated by [`Replay::may_precede`];
159/// the three `*End`/`Top` asks are per layer and also sweep up every
160/// ghost of that layer whose `before` node is gone.
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162pub(crate) enum At {
163    /// Just under in-flow node `key`.
164    UnderInFlow(Key),
165    /// The end of the in-flow layer.
166    InFlowEnd,
167    /// Just under the float layer rooted at `key`.
168    UnderLayer(Key),
169    /// Just under node `key` inside a float layer.
170    UnderInLayer(Key),
171    /// The end of the float layer rooted at `key`.
172    LayerEnd(Key),
173    /// Above every layer: whatever is still unpainted.
174    Top,
175}
176
177/// One departing subtree, with what it needs to play itself out.
178pub(crate) struct Ghost {
179    pub key: Key,
180    pub nodes: Vec<GhostNode>,
181    /// The points of every `line` in the subtree, copied out of the frame
182    /// that had them (a `LineId` indexes a list that is rebuilt every
183    /// frame). Empty, and unallocated, for a subtree with no lines.
184    pub points: Vec<Vec2>,
185    /// Where it is painted, relative to the live frame.
186    pub place: Place,
187    /// Clock reading (driver seconds) of the frame that noticed it gone.
188    left_at: f64,
189    /// How long the exit runs, in seconds (the root's `transition`).
190    duration: f64,
191    easing: Easing,
192    /// Where the root's slots are headed.
193    exit: Enter,
194    /// The group opacity the departing root inherited from ancestors that
195    /// may no longer exist.
196    base_opacity: f32,
197    last_used: u64,
198}
199
200/// A ghost's root as it should be painted this frame: the eased slots, and
201/// the offset to move every rect in the subtree by.
202pub(crate) struct Playback {
203    pub offset: Vec2,
204    pub bg: Option<Color>,
205    pub radius: Option<[f32; 4]>,
206    pub size: Option<(Option<f32>, Option<f32>)>,
207    /// Multiplied into the root's own opacity.
208    pub opacity: f32,
209    pub base_opacity: f32,
210}
211
212impl Ghost {
213    /// Where the exit has got to at `now`: `None` once it is over.
214    fn playback(&self, now: f64) -> Option<Playback> {
215        let raw = ((now - self.left_at) / self.duration) as f32;
216        if raw >= 1.0 || raw.is_nan() {
217            return None;
218        }
219        let p = self.easing.apply(raw.max(0.0));
220        let root = &self.nodes[0].spec;
221        let lerp = |from: f32, to: f32| from + (to - from) * p;
222        let e = &self.exit;
223        Some(Playback {
224            offset: Vec2::new(e.dx * p, e.dy * p),
225            bg: e.bg.map(|to| root.style.bg.lerp(to, p)),
226            radius: e
227                .radius
228                .map(|to| root.style.radius.map(|from| lerp(from, to))),
229            size: (e.width.is_some() || e.height.is_some()).then(|| {
230                let rect = self.nodes[0].rect;
231                (
232                    e.width.and_then(Sizing::amount).map(|to| lerp(rect.w, to)),
233                    e.height.and_then(Sizing::amount).map(|to| lerp(rect.h, to)),
234                )
235            }),
236            opacity: match e.opacity {
237                Some(to) => lerp(root.style.opacity, to),
238                None => root.style.opacity,
239            },
240            base_opacity: self.base_opacity,
241        })
242    }
243}
244
245/// The departing subtrees, bounded (see [`MAX_NODES`]).
246#[derive(Default)]
247pub struct DepartStore {
248    ghosts: Vec<Ghost>,
249    /// Nodes across every ghost, kept in step with `ghosts` so the budget
250    /// is a comparison rather than a walk.
251    nodes: usize,
252    /// The core's frame counter as of `begin_frame`.
253    frame_no: u64,
254    /// Whether a ghost replayed this frame is still mid-flight.
255    active: bool,
256    /// A membership mask over the ghosts' `before` keys, so a departure
257    /// whose key no ghost sits under — every row of a mass removal — skips
258    /// the walk that would hand its place on. Never cleared: a stale bit
259    /// costs one walk, and there are at most a few hundred ghosts to walk.
260    before_mask: u64,
261    /// The ghosts' own keys, as an exact set kept in step with `ghosts`,
262    /// so a departure of a key no ghost holds skips [`Self::retire`] —
263    /// which is a pass over the whole store, and a mass removal would
264    /// otherwise pay one per row. Exact rather than a 64-bit mask like
265    /// `before_mask`: a mass removal is hundreds of distinct keys, which
266    /// saturates 64 bits and makes a mask answer "maybe" every time.
267    held: rustc_hash::FxHashSet<Key>,
268}
269
270impl DepartStore {
271    /// Starts a frame under the core's counter.
272    pub(crate) fn begin_frame(&mut self, frame_no: u64) {
273        self.frame_no = frame_no;
274        self.active = false;
275        // A ghost not replayed for a while goes — the same backstop the
276        // anim store keeps, for a driver whose clock stops moving while
277        // frames keep coming (`retain::sweep_cutoff`).
278        if !self.ghosts.is_empty()
279            && let Some(cutoff) = crate::retain::sweep_cutoff(self.frame_no)
280        {
281            self.drop_where(|g| g.last_used < cutoff);
282        }
283    }
284
285    /// True when a ghost replayed this frame is still mid-flight, i.e. the
286    /// driver owes another frame.
287    pub fn animating(&self) -> bool {
288        self.active
289    }
290
291    /// Whether anything is departing at all — the gate every pass that
292    /// would otherwise walk an empty store checks first.
293    pub fn is_empty(&self) -> bool {
294        self.ghosts.is_empty()
295    }
296
297    /// How many nodes are retained across every departing subtree.
298    pub fn node_count(&self) -> usize {
299        self.nodes
300    }
301
302    /// The keys of the departing roots — what a caller tests the live tree
303    /// against to notice one coming back.
304    pub fn keys(&self) -> impl Iterator<Item = Key> + '_ {
305        self.ghosts.iter().map(|g| g.key)
306    }
307
308    /// Each departing root's key and the spec it left with — what a
309    /// trace names a departure by, since its node is no longer in any
310    /// tree.
311    pub(crate) fn roots(&self) -> impl Iterator<Item = (Key, &NodeSpec)> + '_ {
312        self.ghosts
313            .iter()
314            .filter_map(|g| g.nodes.first().map(|n| (g.key, &n.spec)))
315    }
316
317    fn drop_where(&mut self, mut pred: impl FnMut(&Ghost) -> bool) {
318        let nodes = &mut self.nodes;
319        let held = &mut self.held;
320        self.ghosts.retain(|g| {
321            let drop = pred(g);
322            if drop {
323                *nodes -= g.nodes.len();
324                held.remove(&g.key);
325            }
326            !drop
327        });
328    }
329
330    /// A key the view declared again: the live node wins and its ghost is
331    /// discarded, so a dismissed and re-shown toast does not draw twice.
332    pub(crate) fn retire(&mut self, key: Key) {
333        self.drop_where(|g| g.key == key);
334    }
335
336    /// The same, for every ghost whose key is in `live` — the whole of a
337    /// frame's returns in one pass.
338    pub(crate) fn retire_returned(&mut self, live: &rustc_hash::FxHashSet<Key>) {
339        if !live.is_empty() {
340            self.drop_where(|g| live.contains(&g.key));
341        }
342    }
343
344    /// The budget, applied to a frame's removal whole: `wanted` is every node the frame's departing subtrees
345    /// would add together, counted before any of them is copied. A removal
346    /// that fits an empty store is admitted — and if the store is holding
347    /// earlier exits it has no room beside, the **oldest** ghosts go first
348    /// until it fits, since they are the ones furthest through their own
349    /// fade and the removal the user just caused is the one they are
350    /// looking at. A removal larger than [`MAX_NODES`] on its own is refused
351    /// whole: `false`, no ghost, and the caller raises `exit-budget` for
352    /// the frame. There is no partial credit either way, so a view never
353    /// gets half its rows animating and the rest blinking, and how a
354    /// removal reads cannot depend on what else the app happened to be
355    /// doing 100 ms earlier.
356    pub(crate) fn admit(&mut self, wanted: usize) -> bool {
357        if wanted > MAX_NODES {
358            return false;
359        }
360        let mut evict = 0;
361        while self.nodes + wanted > MAX_NODES {
362            // Store order is departure order, so the front is the oldest.
363            let g = &self.ghosts[evict];
364            self.nodes -= g.nodes.len();
365            self.held.remove(&g.key);
366            evict += 1;
367        }
368        if evict > 0 {
369            self.ghosts.drain(..evict);
370        }
371        true
372    }
373
374    /// Copies `root`'s subtree out of `tree` (which is the *previous*
375    /// frame's, the last one that had it) and starts its exit at `now`.
376    /// `text` is read for that same frame's list, since the subtree's text
377    /// nodes carry its ids.
378    /// The budget is not checked here: the caller has counted the frame's
379    /// whole removal and had it admitted ([`Self::admit`]) before copying
380    /// any of it, so a subtree that reaches this always fits.
381    // The two lists at the end are the frame's per-node side tables, read
382    // for the same kept frame `tree` is; a struct for the pair would name
383    // one thing that only exists here.
384    #[allow(clippy::too_many_arguments)]
385    pub(crate) fn depart(
386        &mut self,
387        tree: &Tree,
388        root: usize,
389        now: f64,
390        base_opacity: f32,
391        place: Place,
392        text: &crate::text::TextSystem,
393        lines: &crate::line::LineStore,
394        fragments: &crate::fragment::FragmentList,
395    ) {
396        let spec = &tree.specs[root];
397        let (Some(t), Some(exit)) = (spec.transition, spec.anim().exit) else {
398            return;
399        };
400        let duration = t.duration_ms.max(0.0) as f64 / 1000.0;
401        if duration <= 0.0 {
402            return;
403        }
404        let end = tree.subtree_end(root);
405        let key = tree.keys[root];
406        // A second departure of the same key (the view showed it, dropped
407        // it, showed it and dropped it again inside one exit) replaces the
408        // first: two pictures of one node are never right. Behind `held`
409        // because `retire` walks the whole store: unguarded, a frame that
410        // drops a thousand rows pays one walk per row, which is the one
411        // quadratic left in a mass removal — 32 ms for 10k subtrees
412        // against 1.05 ms guarded, and 44% of the departing frame at
413        // today's budget. Kept rather than deleted even though the frame
414        // path cannot reach it — `collect_departures` retires a returning
415        // key before it can depart again — because that argument runs
416        // through another module's early returns, and a set lookup is a
417        // cheap thing to be wrong about.
418        if self.held.contains(&key) {
419            self.retire(key);
420        }
421        let mut points = Vec::new();
422        let nodes = (root..end)
423            .map(|i| GhostNode {
424                parent: if i == root {
425                    NIL
426                } else {
427                    tree.parent[i] - root as u32
428                },
429                spec: tree.specs[i].clone(),
430                content: match tree.content[i] {
431                    NodeContent::Container => GhostContent::Container,
432                    NodeContent::Text(id) => {
433                        let (cache_key, color) = text.prev_frame_text(id);
434                        GhostContent::Text { cache_key, color }
435                    }
436                    NodeContent::Edit(k) => GhostContent::Edit(k),
437                    NodeContent::Image(id, opts) => GhostContent::Image(id, opts),
438                    // A departing grid is its box: the cells are the
439                    // frame's and go with it.
440                    NodeContent::Cells(_) => GhostContent::Container,
441                    // A departing fragment keeps painting. Its draw is
442                    // sixteen floats and a handle, fixed-size and `Copy`,
443                    // so the ghost owns a copy outright rather than
444                    // indexing a list that has to outlive the frame —
445                    // which is what the fixed sixteen buys. The copy comes
446                    // from the previous frame's list, because that is the
447                    // tree this ghost is being cut out of.
448                    NodeContent::Fragment(id) => match fragments.prev_get(id) {
449                        Some(draw) => GhostContent::Fragment(draw),
450                        None => GhostContent::Container,
451                    },
452                    NodeContent::Polygon(id) => match fragments.prev_get(id) {
453                        Some(draw) => GhostContent::Polygon(draw),
454                        None => GhostContent::Container,
455                    },
456                    NodeContent::Line(id) => {
457                        let (run, pts) = lines.prev_run(id);
458                        let first = points.len() as u32;
459                        points.extend_from_slice(pts);
460                        GhostContent::Line {
461                            first,
462                            len: pts.len() as u32,
463                            width: run.width,
464                        }
465                    }
466                },
467                rect: Rect::from_pos_size(tree.pos[i], tree.size[i]),
468            })
469            .collect::<Vec<_>>();
470        debug_assert!(
471            self.nodes + nodes.len() <= MAX_NODES,
472            "a departure the frame did not have admitted"
473        );
474        self.nodes += nodes.len();
475        // A ghost that was painted just under this node loses its place
476        // with it, and takes the place this one is taking: the two stay in
477        // the order they had, since the store keeps departures in order.
478        if self.before_mask & (1u64 << (key.0 & 63)) != 0 {
479            for g in &mut self.ghosts {
480                if g.place.before() == Some(key) {
481                    g.place = g.place.with_before(place.before());
482                }
483            }
484        }
485        if let Some(before) = place.before() {
486            self.before_mask |= 1u64 << (before.0 & 63);
487        }
488        self.held.insert(key);
489        self.ghosts.push(Ghost {
490            key,
491            nodes,
492            points,
493            place,
494            left_at: now,
495            duration,
496            easing: t.curve(),
497            exit,
498            base_opacity,
499            last_used: self.frame_no,
500        });
501    }
502
503    /// Starts this frame's replay: drops the ghosts whose exit is over,
504    /// and hands the rest out with where each has got to at `now`, taken
505    /// out of the store so the emitter can borrow the rest of the core
506    /// while it paints them between the live nodes. [`Self::end_replay`]
507    /// puts them back.
508    pub(crate) fn begin_replay(&mut self, now: f64) -> Replay {
509        let frame_no = self.frame_no;
510        let nodes = &mut self.nodes;
511        let held = &mut self.held;
512        let mut plays = Vec::with_capacity(self.ghosts.len());
513        let mut mask = 0u64;
514        self.ghosts.retain_mut(|g| match g.playback(now) {
515            Some(play) => {
516                g.last_used = frame_no;
517                if let Some(k) = g.place.mask_key() {
518                    mask |= 1u64 << (k.0 & 63);
519                }
520                plays.push(play);
521                true
522            }
523            None => {
524                *nodes -= g.nodes.len();
525                held.remove(&g.key);
526                false
527            }
528        });
529        self.active = !self.ghosts.is_empty();
530        Replay {
531            painted: vec![false; self.ghosts.len()],
532            ghosts: std::mem::take(&mut self.ghosts),
533            plays,
534            mask,
535        }
536    }
537
538    /// The other half of [`Self::begin_replay`]. Nothing departs between
539    /// the two — the diff runs before the passes — so nothing can have
540    /// been pushed while the ghosts were out.
541    pub(crate) fn end_replay(&mut self, replay: Replay) {
542        debug_assert!(self.ghosts.is_empty());
543        self.ghosts = replay.ghosts;
544        // `held` is what lets `depart` skip the walk, so it has to be the
545        // ghosts' keys exactly: a key missing from it is a retire that
546        // will not happen, which is two pictures of one node. Checked here
547        // because every frame that replays passes through.
548        debug_assert_eq!(self.held.len(), self.ghosts.len());
549    }
550
551    /// Every still-running ghost handed to `emit` in store order, and the
552    /// finished ones dropped — the replay without the passes, for a test
553    /// that has no frame to paint.
554    #[cfg(test)]
555    pub(crate) fn replay(&mut self, now: f64, mut emit: impl FnMut(&Ghost, &Playback)) {
556        let mut replay = self.begin_replay(now);
557        replay.paint(At::Top, &mut emit);
558        self.end_replay(replay);
559    }
560
561    /// Drops every ghost. The frame driver has no reason to; a test that
562    /// wants a clean slate does.
563    pub fn clear(&mut self) {
564        self.ghosts.clear();
565        self.held.clear();
566        self.nodes = 0;
567        self.active = false;
568    }
569}
570
571/// One frame's ghosts, out of the store for the length of the emission
572/// passes (see [`DepartStore::begin_replay`]). The passes ask for the
573/// ghosts under each node as they reach it, and for the rest of a pass
574/// once they are through it.
575#[derive(Default)]
576pub(crate) struct Replay {
577    ghosts: Vec<Ghost>,
578    plays: Vec<Playback>,
579    /// Painted this frame already: a ghost is painted once, whichever of
580    /// the two asks finds it first.
581    painted: Vec<bool>,
582    /// A membership mask over the `before` keys, so a pass answers
583    /// "nothing under this node" with one AND for almost every node
584    /// rather than a walk over the ghosts.
585    mask: u64,
586}
587
588impl Replay {
589    pub fn is_empty(&self) -> bool {
590        self.ghosts.is_empty()
591    }
592
593    /// Whether any ghost *may* be painted just under `key`: false is
594    /// certain, true is worth the walk [`Self::paint`] makes.
595    #[inline]
596    pub fn may_precede(&self, key: Key) -> bool {
597        self.mask & (1u64 << (key.0 & 63)) != 0
598    }
599
600    /// Hands `emit` the ghosts whose place is `at` — and, for a layer's
601    /// end, every ghost of that layer not painted yet, which is where a
602    /// ghost whose `before` node is gone ends up: at the end of its layer,
603    /// still under everything above it. `At::Top` takes what is left,
604    /// which is a ghost whose whole layer is gone.
605    pub fn paint(&mut self, at: At, mut emit: impl FnMut(&Ghost, &Playback)) {
606        for i in 0..self.ghosts.len() {
607            if self.painted[i] {
608                continue;
609            }
610            let here = match (at, self.ghosts[i].place) {
611                (At::UnderInFlow(k), Place::InFlow { before }) => before == Some(k),
612                (At::InFlowEnd, Place::InFlow { .. }) => true,
613                (At::UnderLayer(k), Place::Layer { before }) => before == Some(k),
614                (At::UnderInLayer(k), Place::InLayer { before, .. }) => before == Some(k),
615                (At::LayerEnd(k), Place::InLayer { layer, .. }) => layer == k,
616                (At::Top, _) => true,
617                _ => false,
618            };
619            if !here {
620                continue;
621            }
622            self.painted[i] = true;
623            emit(&self.ghosts[i], &self.plays[i]);
624        }
625    }
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631
632    /// The core's frame counter, stood in for: each test's frames count
633    /// from one.
634    struct Frames(u64);
635    impl Frames {
636        fn next(&mut self) -> u64 {
637            self.0 += 1;
638            self.0
639        }
640    }
641    use crate::tree::OriginId;
642
643    const IN_FLOW: Place = Place::InFlow { before: None };
644
645    fn tree_with(spec: NodeSpec, children: usize) -> Tree {
646        let mut t = Tree::new();
647        let root = t.push(
648            NIL,
649            Key::ROOT,
650            OriginId::HOST,
651            NodeSpec::default(),
652            NodeContent::Container,
653        );
654        let node = t.push(
655            root,
656            Key::ROOT.str("x"),
657            OriginId::HOST,
658            spec,
659            NodeContent::Container,
660        );
661        for i in 0..children {
662            t.push(
663                node,
664                Key::ROOT.str("x").index(i as u64),
665                OriginId::HOST,
666                NodeSpec::default(),
667                NodeContent::Container,
668            );
669        }
670        t
671    }
672
673    fn departing(spec: NodeSpec) -> NodeSpec {
674        spec.transition(100.0)
675            .exit(Enter::from(50.0, 0.0).opacity(0.0))
676    }
677
678    #[test]
679    fn a_ghost_plays_out_and_then_goes() {
680        let mut d = DepartStore::default();
681        let mut frame = Frames(0);
682        let text = crate::text::TextSystem::new();
683        let lines = crate::line::LineStore::default();
684        let fragments = crate::fragment::FragmentList::default();
685        let tree = tree_with(departing(NodeSpec::column()), 2);
686        d.begin_frame(frame.next());
687        d.depart(&tree, 1, 0.0, 1.0, IN_FLOW, &text, &lines, &fragments);
688        assert_eq!(d.node_count(), 3, "the subtree, not just its root");
689
690        let mut seen = Vec::new();
691        d.begin_frame(frame.next());
692        d.replay(0.05, |_, p| seen.push(p.offset.x));
693        assert!(d.animating());
694        assert_eq!(seen.len(), 1);
695        assert!(seen[0] > 0.0 && seen[0] < 50.0, "halfway out: {}", seen[0]);
696
697        d.begin_frame(frame.next());
698        d.replay(0.2, |_, _| panic!("the exit is over"));
699        assert!(!d.animating());
700        assert!(d.is_empty());
701        assert_eq!(d.node_count(), 0);
702    }
703
704    #[test]
705    fn a_key_that_comes_back_takes_its_ghost_with_it() {
706        let mut d = DepartStore::default();
707        let mut frame = Frames(0);
708        let text = crate::text::TextSystem::new();
709        let lines = crate::line::LineStore::default();
710        let fragments = crate::fragment::FragmentList::default();
711        let tree = tree_with(departing(NodeSpec::column()), 0);
712        d.begin_frame(frame.next());
713        d.depart(&tree, 1, 0.0, 1.0, IN_FLOW, &text, &lines, &fragments);
714        assert_eq!(d.keys().collect::<Vec<_>>(), vec![Key::ROOT.str("x")]);
715        d.retire(Key::ROOT.str("x"));
716        assert!(d.is_empty());
717        assert_eq!(d.node_count(), 0);
718    }
719
720    /// One key departing twice with no return in between: the second
721    /// picture replaces the first rather than joining it. The frame path
722    /// cannot produce this — `collect_departures` retires a returning key
723    /// first — so this is the only cover the `retire` inside `depart` has,
724    /// and it is what says the `held` guard (ADR 0012 decision 5) does not
725    /// skip a retire it owed.
726    #[test]
727    fn a_second_departure_of_one_key_replaces_the_first() {
728        let mut d = DepartStore::default();
729        let mut frame = Frames(0);
730        let text = crate::text::TextSystem::new();
731        let lines = crate::line::LineStore::default();
732        let fragments = crate::fragment::FragmentList::default();
733        let tree = tree_with(departing(NodeSpec::column()), 2);
734        d.begin_frame(frame.next());
735        d.depart(&tree, 1, 0.0, 1.0, IN_FLOW, &text, &lines, &fragments);
736        assert_eq!(d.keys().count(), 1);
737        assert_eq!(d.node_count(), 3);
738
739        d.depart(&tree, 1, 0.05, 1.0, IN_FLOW, &text, &lines, &fragments);
740        assert_eq!(d.keys().count(), 1, "one picture of one node, not two");
741        assert_eq!(d.node_count(), 3, "and the budget charged once for it");
742    }
743
744    #[test]
745    fn a_node_without_both_halves_never_departs() {
746        let text = crate::text::TextSystem::new();
747        let lines = crate::line::LineStore::default();
748        let fragments = crate::fragment::FragmentList::default();
749        for spec in [
750            NodeSpec::column(),
751            NodeSpec::column().transition(100.0),
752            // An `exit` with no duration to run over.
753            NodeSpec::column()
754                .exit(Enter::from(10.0, 0.0))
755                .transition(0.0),
756        ] {
757            assert!(!can_depart(&spec), "and the diff never counts it");
758            let mut d = DepartStore::default();
759            let mut frame = Frames(0);
760            let tree = tree_with(spec, 0);
761            d.begin_frame(frame.next());
762            d.depart(&tree, 1, 0.0, 1.0, IN_FLOW, &text, &lines, &fragments);
763            assert!(d.is_empty());
764        }
765    }
766
767    /// `count` subtrees of 16 nodes each, keyed `ROOT[i]` from `from`,
768    /// departed one after another at `now` — the way `collect_departures`
769    /// feeds a frame's admitted removal to the store.
770    fn depart_sixteens(d: &mut DepartStore, from: u64, count: u64, now: f64) {
771        let text = crate::text::TextSystem::new();
772        let lines = crate::line::LineStore::default();
773        let fragments = crate::fragment::FragmentList::default();
774        let spec = departing(NodeSpec::column());
775        for i in from..from + count {
776            let mut t = Tree::new();
777            let root = t.push(
778                NIL,
779                Key::ROOT,
780                OriginId::HOST,
781                NodeSpec::default(),
782                NodeContent::Container,
783            );
784            let node = t.push(
785                root,
786                Key::ROOT.index(i),
787                OriginId::HOST,
788                spec.clone(),
789                NodeContent::Container,
790            );
791            for c in 0..15 {
792                t.push(
793                    node,
794                    Key::ROOT.index(i).index(c),
795                    OriginId::HOST,
796                    NodeSpec::default(),
797                    NodeContent::Container,
798                );
799            }
800            d.depart(&t, 1, now, 1.0, IN_FLOW, &text, &lines, &fragments);
801        }
802    }
803
804    /// ADR 0012 decision 2: a removal is judged whole. One larger than the
805    /// budget is refused before anything is copied, and the store is
806    /// exactly what it was.
807    #[test]
808    fn a_removal_over_the_budget_is_refused_whole() {
809        let mut d = DepartStore::default();
810        let mut frame = Frames(0);
811        d.begin_frame(frame.next());
812        assert!(d.admit(3 * 16));
813        depart_sixteens(&mut d, 0, 3, 0.0);
814        d.begin_frame(frame.next());
815        assert!(!d.admit(MAX_NODES + 1), "one node past the budget");
816        assert_eq!(d.keys().count(), 3, "and the store was not touched");
817        assert_eq!(d.node_count(), 48);
818        assert!(d.admit(MAX_NODES), "the budget itself fits an empty store");
819    }
820
821    /// ADR 0012 decision 3: a removal that fits the budget but not the
822    /// room beside earlier exits evicts those, oldest first, and exactly
823    /// as many as it needs.
824    #[test]
825    fn a_new_removal_evicts_the_oldest_ghosts_until_it_fits() {
826        let mut d = DepartStore::default();
827        let mut frame = Frames(0);
828        // Subtrees of 16 in flight, keyed ROOT[0..n], filling the store to
829        // 192 short of the budget.
830        let n = (MAX_NODES - 192) / 16;
831        d.begin_frame(frame.next());
832        assert!(d.admit(n * 16));
833        depart_sixteens(&mut d, 0, n as u64, 0.0);
834        assert_eq!(d.node_count(), MAX_NODES - 192);
835        // A frame wants 15 more of 16 = 240, 48 past the budget, so three
836        // ghosts have to go, and they are ROOT[0], [1], [2].
837        d.begin_frame(frame.next());
838        assert!(d.admit(15 * 16));
839        assert_eq!(
840            d.node_count(),
841            MAX_NODES - 192 - 48,
842            "three evicted, not four, not two"
843        );
844        assert_eq!(
845            d.keys().next(),
846            Some(Key::ROOT.index(3)),
847            "the oldest went first"
848        );
849        depart_sixteens(&mut d, 100_000, 15, 0.1);
850        assert_eq!(
851            d.node_count(),
852            MAX_NODES,
853            "full, with the new removal whole"
854        );
855        assert_eq!(d.keys().count(), n - 3 + 15);
856        assert!(d.held.contains(&Key::ROOT.index(100_014)));
857        assert!(!d.held.contains(&Key::ROOT.index(2)), "and `held` followed");
858    }
859
860    /// The case decisions 2 and 3 exist to leave alone: a removal that fits
861    /// beside what is in flight evicts nothing.
862    #[test]
863    fn a_removal_that_fits_evicts_nothing() {
864        let mut d = DepartStore::default();
865        let mut frame = Frames(0);
866        d.begin_frame(frame.next());
867        assert!(d.admit(16));
868        depart_sixteens(&mut d, 0, 1, 0.0);
869        d.begin_frame(frame.next());
870        assert!(d.admit(MAX_NODES - 16));
871        assert_eq!(d.keys().count(), 1);
872        assert_eq!(d.node_count(), 16);
873        assert!(d.admit(0), "and nothing wanted is always admitted");
874    }
875
876    #[test]
877    fn a_ghost_nobody_replays_is_swept() {
878        let mut d = DepartStore::default();
879        let mut frame = Frames(0);
880        let text = crate::text::TextSystem::new();
881        let lines = crate::line::LineStore::default();
882        let fragments = crate::fragment::FragmentList::default();
883        let tree = tree_with(departing(NodeSpec::column()), 0);
884        d.begin_frame(frame.next());
885        d.depart(&tree, 1, 0.0, 1.0, IN_FLOW, &text, &lines, &fragments);
886        // Frames without a replay: the sweep runs on the 240th.
887        for _ in 0..480 {
888            d.begin_frame(frame.next());
889        }
890        assert!(d.is_empty(), "an unreplayed ghost does not live forever");
891        assert_eq!(d.node_count(), 0);
892    }
893
894    #[test]
895    fn springs_play_out_as_ease_out() {
896        let mut d = DepartStore::default();
897        let mut frame = Frames(0);
898        let text = crate::text::TextSystem::new();
899        let lines = crate::line::LineStore::default();
900        let fragments = crate::fragment::FragmentList::default();
901        let spec = NodeSpec::column()
902            .transition(100.0)
903            .easing(Easing::Spring)
904            .exit(Enter::from(100.0, 0.0));
905        let tree = tree_with(spec, 0);
906        d.begin_frame(frame.next());
907        d.depart(&tree, 1, 0.0, 1.0, IN_FLOW, &text, &lines, &fragments);
908        let mut x = 0.0;
909        d.replay(0.05, |_, p| x = p.offset.x);
910        let expect = Easing::EaseOut.apply(0.5) * 100.0;
911        assert!((x - expect).abs() < 1e-3, "{x} != {expect}");
912    }
913
914    #[test]
915    fn the_exit_reads_an_enter_backwards() {
916        let mut d = DepartStore::default();
917        let mut frame = Frames(0);
918        let text = crate::text::TextSystem::new();
919        let lines = crate::line::LineStore::default();
920        let fragments = crate::fragment::FragmentList::default();
921        let spec = NodeSpec::column()
922            .bg(Color::hex(0xff0000ff))
923            .radius(10.0)
924            .transition(100.0)
925            .easing(Easing::Linear)
926            .exit(
927                Enter::default()
928                    .bg(Color::hex(0xff000000))
929                    .radius(0.0)
930                    .opacity(0.0),
931            );
932        let mut tree = tree_with(spec, 0);
933        tree.size[1] = crate::geom::Size::new(40.0, 20.0);
934        d.begin_frame(frame.next());
935        d.depart(&tree, 1, 0.0, 1.0, IN_FLOW, &text, &lines, &fragments);
936        d.replay(0.05, |_, p| {
937            assert!((p.opacity - 0.5).abs() < 1e-4, "halfway faded");
938            assert!((p.bg.unwrap().a - 0.5).abs() < 1e-4, "halfway transparent");
939            assert!((p.radius.unwrap()[0] - 5.0).abs() < 1e-4, "halfway square");
940            assert!(p.size.is_none(), "an exit that names no size resizes none");
941        });
942    }
943}