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