Skip to main content

crabshell_ui/
animation.rs

1//! Animations: values that move toward a target over a [`Transition`],
2//! and the clock the platform advances only while one is running, so a
3//! shell where nothing moves wakes for nothing.
4
5use std::cell::{Cell, RefCell};
6use std::panic::{self, AssertUnwindSafe};
7use std::rc::Rc;
8use std::time::{Duration, Instant};
9
10use crabshell_reactive::{Owner, ReadSignal, Signal, untrack};
11
12use crate::cx::Cx;
13use crate::geometry::Point;
14use crate::input::panic_message;
15use crate::prop::{IntoProp, Prop, PropKind};
16use crate::style::Color;
17
18/// How an animation moves from its start to its end: what fraction of
19/// the way it has gone at each fraction of its time.
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub enum Easing {
22  /// The same speed all the way.
23  Linear,
24  /// Starts slow.
25  InQuad,
26  /// Ends slow.
27  OutQuad,
28  /// Starts and ends slow.
29  InOutQuad,
30  /// Starts slower.
31  InCubic,
32  /// Ends slower. The default: it settles gently, as most interface
33  /// motion should.
34  #[default]
35  OutCubic,
36  /// Starts and ends slower.
37  InOutCubic,
38  /// Starts slow, along a quarter sine wave.
39  InSine,
40  /// Ends slow, along a quarter sine wave.
41  OutSine,
42  /// Starts and ends slow, along half a sine wave.
43  InOutSine,
44  /// Starts slower than a cubic.
45  InQuart,
46  /// Ends slower than a cubic.
47  OutQuart,
48  /// Starts and ends slower than a cubic.
49  InOutQuart,
50  /// Starts slower still.
51  InQuint,
52  /// Ends slower still.
53  OutQuint,
54  /// Starts and ends slower still.
55  InOutQuint,
56  /// Barely moves, then rushes in: each tenth of the time doubles it.
57  InExpo,
58  /// Rushes out, then barely moves.
59  OutExpo,
60  /// Barely moves at both ends.
61  InOutExpo,
62  /// Starts slow along a quarter circle.
63  InCirc,
64  /// Ends slow along a quarter circle.
65  OutCirc,
66  /// Starts and ends slow along quarter circles.
67  InOutCirc,
68  /// Pulls back about 10% behind the start, then goes.
69  InBack,
70  /// Runs about 10% past the end, then settles back.
71  OutBack,
72  /// Pulls back at the start and runs past the end.
73  InOutBack,
74  /// A cubic Bézier from (0, 0) to (1, 1) through the control points
75  /// `(x1, y1)` and `(x2, y2)`, as CSS's `cubic-bezier`. The x values are
76  /// kept within 0 to 1.
77  Bezier(f32, f32, f32, f32),
78  /// Cubic Bézier segments joined end to end, as Qt's
79  /// `Easing.BezierSpline`. Each is `[c1x, c1y, c2x, c2y, end_x, end_y]`:
80  /// two control points and an end, starting from the previous end, the
81  /// first from (0, 0). The last must end at (1, 1), and the ends' x
82  /// values must never go back. A spline that breaks either rule, is
83  /// empty, or holds a number that isn't finite moves linearly instead.
84  /// A control point's x is kept within its segment.
85  ///
86  /// Material 3's emphasized curve:
87  ///
88  /// ```
89  /// use crabshell_ui::{Easing, Transition};
90  ///
91  /// const EMPHASIZED: Easing = Easing::Spline(&[
92  ///     [0.05, 0.0, 0.133333, 0.06, 0.166666, 0.4],
93  ///     [0.208333, 0.82, 0.25, 1.0, 1.0, 1.0],
94  /// ]);
95  /// const ENTER: Transition = Transition::new(500).easing(EMPHASIZED);
96  /// ```
97  Spline(&'static [[f32; 6]]),
98}
99
100impl Easing {
101  /// How far along the animation is, from 0 to 1 (Back, a Bézier or a
102  /// spline may overshoot either end), when `t` of its time has passed.
103  /// `t` is kept within 0 to 1.
104  pub fn value_at(self, t: f32) -> f32 {
105    use std::f32::consts::PI;
106    // Back's overshoot, the usual constant: about 10%.
107    const C1: f32 = 1.70158;
108    const C2: f32 = C1 * 1.525;
109    let t = if t.is_nan() { 1.0 } else { t.clamp(0.0, 1.0) };
110    match self {
111      Easing::Linear => t,
112      Easing::InQuad => t * t,
113      Easing::OutQuad => 1.0 - (1.0 - t) * (1.0 - t),
114      Easing::InOutQuad if t < 0.5 => 2.0 * t * t,
115      Easing::InOutQuad => 1.0 - (-2.0 * t + 2.0).powi(2) / 2.0,
116      Easing::InCubic => t * t * t,
117      Easing::OutCubic => 1.0 - (1.0 - t).powi(3),
118      Easing::InOutCubic if t < 0.5 => 4.0 * t * t * t,
119      Easing::InOutCubic => 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0,
120      Easing::InSine => 1.0 - (t * PI / 2.0).cos(),
121      Easing::OutSine => (t * PI / 2.0).sin(),
122      Easing::InOutSine => (1.0 - (PI * t).cos()) / 2.0,
123      Easing::InQuart => t.powi(4),
124      Easing::OutQuart => 1.0 - (1.0 - t).powi(4),
125      Easing::InOutQuart if t < 0.5 => 8.0 * t.powi(4),
126      Easing::InOutQuart => 1.0 - (-2.0 * t + 2.0).powi(4) / 2.0,
127      Easing::InQuint => t.powi(5),
128      Easing::OutQuint => 1.0 - (1.0 - t).powi(5),
129      Easing::InOutQuint if t < 0.5 => 16.0 * t.powi(5),
130      Easing::InOutQuint => 1.0 - (-2.0 * t + 2.0).powi(5) / 2.0,
131      // The formulas miss their ends by 2^-10, so the ends are exact.
132      Easing::InExpo | Easing::OutExpo | Easing::InOutExpo if t == 0.0 || t == 1.0 => t,
133      Easing::InExpo => 2_f32.powf(10.0 * t - 10.0),
134      Easing::OutExpo => 1.0 - 2_f32.powf(-10.0 * t),
135      Easing::InOutExpo if t < 0.5 => 2_f32.powf(20.0 * t - 10.0) / 2.0,
136      Easing::InOutExpo => (2.0 - 2_f32.powf(-20.0 * t + 10.0)) / 2.0,
137      Easing::InCirc => 1.0 - (1.0 - t * t).sqrt(),
138      Easing::OutCirc => (1.0 - (t - 1.0).powi(2)).sqrt(),
139      Easing::InOutCirc if t < 0.5 => (1.0 - (1.0 - (2.0 * t).powi(2)).sqrt()) / 2.0,
140      Easing::InOutCirc => ((1.0 - (-2.0 * t + 2.0).powi(2)).sqrt() + 1.0) / 2.0,
141      Easing::InBack => (C1 + 1.0) * t.powi(3) - C1 * t * t,
142      Easing::OutBack => 1.0 + (C1 + 1.0) * (t - 1.0).powi(3) + C1 * (t - 1.0).powi(2),
143      Easing::InOutBack if t < 0.5 => (2.0 * t).powi(2) * ((C2 + 1.0) * 2.0 * t - C2) / 2.0,
144      Easing::InOutBack => {
145        ((2.0 * t - 2.0).powi(2) * ((C2 + 1.0) * (2.0 * t - 2.0) + C2) + 2.0) / 2.0
146      }
147      Easing::Bezier(x1, y1, x2, y2) => bezier(t, (0.0, 0.0), [x1, y1, x2, y2, 1.0, 1.0]),
148      Easing::Spline(segments) => spline(t, segments),
149    }
150  }
151}
152
153/// A spline's y where its x is `x`, or `x` itself for a spline that
154/// breaks the rules [`Easing::Spline`] gives.
155fn spline(x: f32, segments: &[[f32; 6]]) -> f32 {
156  let mut end = 0.0;
157  let valid = segments.iter().all(|segment| {
158    let forward = segment[4] >= end;
159    end = segment[4];
160    forward && segment.iter().all(|n| n.is_finite())
161  }) && segments
162    .last()
163    .is_some_and(|last| last[4] == 1.0 && last[5] == 1.0);
164  if !valid {
165    return x;
166  }
167  let mut start = (0.0, 0.0);
168  for segment in segments {
169    if x <= segment[4] {
170      return bezier(x, start, *segment);
171    }
172    start = (segment[4], segment[5]);
173  }
174  1.0
175}
176
177/// The y of a cubic Bézier from `start` through the control points and
178/// to the end in `segment` (laid out as in [`Easing::Spline`]) at the
179/// point whose x is `x`, found by bisection: x grows with the curve's
180/// parameter once both control x values are kept between the ends.
181fn bezier(x: f32, (x0, y0): (f32, f32), segment: [f32; 6]) -> f32 {
182  let [x1, y1, x2, y2, x3, y3] = segment;
183  let (x1, x2) = (x1.clamp(x0, x3), x2.clamp(x0, x3));
184  let at = |p0: f32, p1: f32, p2: f32, p3: f32, s: f32| {
185    let r = 1.0 - s;
186    r * r * r * p0 + 3.0 * r * r * s * p1 + 3.0 * r * s * s * p2 + s * s * s * p3
187  };
188  let (mut low, mut high) = (0.0_f32, 1.0_f32);
189  for _ in 0..32 {
190    let middle = (low + high) / 2.0;
191    if at(x0, x1, x2, x3, middle) < x {
192      low = middle;
193    } else {
194      high = middle;
195    }
196  }
197  at(y0, y1, y2, y3, (low + high) / 2.0)
198}
199
200/// How long an animation takes, how it moves, and how long it waits
201/// first. Copy it into styles and constants like a color.
202#[derive(Clone, Copy, Debug, PartialEq)]
203pub struct Transition {
204  /// The time it takes, in milliseconds. 0 with no delay jumps straight
205  /// to the end in the flush that sets the new target, so the same turn's
206  /// layout and draw already show it and the clock never runs.
207  pub ms: u32,
208  /// How it moves.
209  pub easing: Easing,
210  /// How long it waits before it moves, in milliseconds.
211  pub delay: u32,
212  /// Whether a [`Cx::cycle`] comes back each round instead of starting
213  /// over. Nothing else reads it.
214  pub alternate: bool,
215}
216
217impl Transition {
218  /// A transition of `ms` milliseconds, easing out, with no delay.
219  pub const fn new(ms: u32) -> Transition {
220    Transition {
221      ms,
222      easing: Easing::OutCubic,
223      delay: 0,
224      alternate: false,
225    }
226  }
227
228  /// The same transition moving as `easing` says.
229  pub const fn easing(self, easing: Easing) -> Transition {
230    Transition { easing, ..self }
231  }
232
233  /// The same transition waiting `ms` milliseconds before it moves.
234  pub const fn delay(self, ms: u32) -> Transition {
235    Transition { delay: ms, ..self }
236  }
237
238  /// The same transition coming back after each round of a
239  /// [`Cx::cycle`], so it goes 0 to 1 to 0, each way taking `ms`.
240  pub const fn alternate(self) -> Transition {
241    Transition {
242      alternate: true,
243      ..self
244    }
245  }
246
247  /// Whether it takes no time at all, so the new value shows at once.
248  pub(crate) fn is_instant(self) -> bool {
249    self.ms == 0 && self.delay == 0
250  }
251
252  /// Whether an animation that started at `start` is still waiting out
253  /// its delay at `now`, so nothing it moves has changed yet.
254  pub(crate) fn waiting(self, start: Instant, now: Instant) -> bool {
255    now.saturating_duration_since(start) < Duration::from_millis(self.delay.into())
256  }
257
258  /// How far along an animation that started at `start` is at `now`,
259  /// eased, and whether it has ended. It stays at 0 through the delay.
260  pub(crate) fn progress(self, start: Instant, now: Instant) -> (f32, bool) {
261    let elapsed = now.saturating_duration_since(start).as_secs_f32() * 1000.0 - self.delay as f32;
262    if elapsed < 0.0 {
263      return (0.0, false);
264    }
265    if self.ms == 0 {
266      return (1.0, true);
267    }
268    let t = elapsed / self.ms as f32;
269    if t >= 1.0 {
270      (1.0, true)
271    } else {
272      (self.easing.value_at(t), false)
273    }
274  }
275}
276
277/// The spring a [`Cx::spring`] value follows its target on, as Qt's
278/// `SpringAnimation`. Time is in seconds and distance in the value's own
279/// units. The target pulls the value with `stiffness` times the distance,
280/// per second squared, and friction slows it as `damping` says, as a
281/// ratio: 1 comes to rest as fast as it can without passing the target,
282/// less overshoots and bounces, more creeps in. The default, 700 and 0.9,
283/// is Material 3's default spatial spring; its expressive one is 380 and
284/// 0.8.
285#[derive(Clone, Copy, Debug, PartialEq)]
286pub struct Spring {
287  /// How hard the target pulls, per second squared: higher is faster.
288  pub stiffness: f32,
289  /// The damping ratio: 1 never passes the target, less bounces.
290  pub damping: f32,
291}
292
293impl Spring {
294  /// A spring of `stiffness` and `damping` ratio.
295  pub const fn new(stiffness: f32, damping: f32) -> Spring {
296    Spring { stiffness, damping }
297  }
298
299  /// Whether it can move anything: a stiffness above 0, a damping of 0
300  /// or more, both finite.
301  fn is_valid(self) -> bool {
302    self.stiffness.is_finite()
303      && self.stiffness > 0.0
304      && self.damping.is_finite()
305      && self.damping >= 0.0
306  }
307
308  /// Moves the value `x`, with speed `v`, toward `goal` over `seconds`,
309  /// in implicit Euler steps of at most a millisecond, which stay stable
310  /// whatever the spring and the step.
311  pub(crate) fn advance(self, x: &mut f64, v: &mut f64, goal: f64, seconds: f64) {
312    let k = f64::from(self.stiffness);
313    let c = 2.0 * f64::from(self.damping) * k.sqrt();
314    let steps = (seconds * 1000.0).ceil().max(1.0);
315    let dt = seconds / steps;
316    for _ in 0..steps as u32 {
317      *v = (*v - dt * k * (*x - goal)) / (1.0 + dt * c + dt * dt * k);
318      *x += dt * *v;
319    }
320  }
321}
322
323impl Default for Spring {
324  fn default() -> Spring {
325    Spring::new(700.0, 0.9)
326  }
327}
328
329/// The most time one tick moves a spring: a frame that comes late moves
330/// it this far and no more, so a stall can't cost a long run of steps.
331const SPRING_MAX_STEP: f64 = 0.25;
332
333/// The distance from its target a spring counts as at rest within, and the
334/// speed per second below which it counts as still.
335const SPRING_REST: (f64, f64) = (0.001, 0.01);
336
337/// One step of a [`Cx::sequence`]: a move to a value over a
338/// [`Transition`], or a hold that keeps the value for a while. Steps are
339/// built in `const`s, so a config keeps a whole sequence in a `const`
340/// array.
341#[derive(Clone, Copy, Debug, PartialEq)]
342pub struct Step<T> {
343  to: Option<T>,
344  transition: Transition,
345}
346
347impl<T> Step<T> {
348  /// A move from wherever the value is to `value`, over `transition`,
349  /// after its delay.
350  pub const fn to(value: T, transition: Transition) -> Step<T> {
351    Step {
352      to: Some(value),
353      transition,
354    }
355  }
356
357  /// A pause of `ms` milliseconds that keeps the value where it is, as
358  /// Qt's `PauseAnimation`.
359  pub const fn hold(ms: u32) -> Step<T> {
360    Step {
361      to: None,
362      transition: Transition::new(0).delay(ms),
363    }
364  }
365
366  /// When it starts to move and when it ends, in microseconds after it
367  /// begins. A hold never moves, so both are its end.
368  fn times(&self) -> (u64, u64) {
369    let moves = u64::from(self.transition.delay) * 1000;
370    (moves, moves + u64::from(self.transition.ms) * 1000)
371  }
372}
373
374impl<T: Animate> IntoProp<Vec<Step<T>>> for Vec<Step<T>> {
375  fn into_prop(self) -> Prop<Vec<Step<T>>> {
376    Prop(PropKind::Value(self))
377  }
378}
379
380/// A fixed array of steps, such as a `const` sequence.
381impl<T: Animate, const N: usize> IntoProp<Vec<Step<T>>> for [Step<T>; N] {
382  fn into_prop(self) -> Prop<Vec<Step<T>>> {
383    Prop(PropKind::Value(self.into()))
384  }
385}
386
387/// Where a play of a sequence is at a time.
388enum Spot<T> {
389  /// Moving, here.
390  Moving(T),
391  /// Holding here until the time given, in microseconds, when the value
392  /// next changes.
393  Holding(T, u64),
394  /// Past its last step, here.
395  Ended(T),
396}
397
398/// Where a play of `steps`, begun with the value at `from`, is `at`
399/// microseconds in.
400fn spot<T: Animate>(steps: &[Step<T>], from: &T, at: u64) -> Spot<T> {
401  let mut from = from.clone();
402  let mut begins = 0;
403  for (i, step) in steps.iter().enumerate() {
404    let (moves, ends) = step.times();
405    if at < begins + moves {
406      // A pause goes on through the holds and delays right after it.
407      let mut until = begins + moves;
408      if step.to.is_none() {
409        for next in &steps[i + 1..] {
410          until += next.times().0;
411          if next.to.is_some() {
412            break;
413          }
414        }
415      }
416      return Spot::Holding(from, until);
417    }
418    if let Some(to) = &step.to {
419      if at < begins + ends {
420        let t = (at - begins - moves) as f32 / (ends - moves) as f32;
421        return Spot::Moving(from.lerp(to, step.transition.easing.value_at(t)));
422      }
423      from = to.clone();
424    }
425    begins += ends;
426  }
427  Spot::Ended(from)
428}
429
430/// A value an animation can move between two of: `lerp` gives the value
431/// `t` of the way from `self` to `to`, where `t` may stray a little past 0
432/// or 1 for an easing that overshoots.
433pub trait Animate: Clone + PartialEq + 'static {
434  /// The value `t` of the way from `self` to `to`.
435  fn lerp(&self, to: &Self, t: f32) -> Self;
436}
437
438impl Animate for f32 {
439  fn lerp(&self, to: &f32, t: f32) -> f32 {
440    self + (to - self) * t
441  }
442}
443
444impl Animate for Point {
445  fn lerp(&self, to: &Point, t: f32) -> Point {
446    Point::new(self.x.lerp(&to.x, t), self.y.lerp(&to.y, t))
447  }
448}
449
450impl Animate for Color {
451  fn lerp(&self, to: &Color, t: f32) -> Color {
452    let channel = |a: u8, b: u8| {
453      f32::from(a)
454        .lerp(&f32::from(b), t)
455        .round()
456        .clamp(0.0, 255.0) as u8
457    };
458    Color::rgba(
459      channel(self.r, to.r),
460      channel(self.g, to.g),
461      channel(self.b, to.b),
462      channel(self.a, to.a),
463    )
464  }
465}
466
467/// One running animation: advanced to a time, it says whether it still
468/// runs.
469type Tick = Box<dyn FnMut(Instant) -> bool>;
470
471/// A step on the clock, named for log lines and counted in its item.
472type Running = (Rc<str>, Option<Busy>, Tick);
473
474/// How many animations run inside one item of a list with an exit, and
475/// the item around it, so a leaving item knows when everything in it has
476/// stopped.
477pub(crate) struct Activity {
478  running: Cell<usize>,
479  outer: Option<Rc<Activity>>,
480}
481
482impl Activity {
483  pub(crate) fn new(outer: Option<Rc<Activity>>) -> Rc<Activity> {
484    Rc::new(Activity {
485      running: Cell::new(0),
486      outer,
487    })
488  }
489
490  /// Adds `by` to this item's count and every item's around it.
491  fn add(&self, by: isize) {
492    let mut at = Some(self);
493    while let Some(activity) = at {
494      activity
495        .running
496        .set(activity.running.get().wrapping_add_signed(by));
497      at = activity.outer.as_deref();
498    }
499  }
500}
501
502/// One animation counted as running in its item until it is dropped.
503pub(crate) struct Busy(Rc<Activity>);
504
505impl Busy {
506  pub(crate) fn new(activity: &Rc<Activity>) -> Busy {
507    activity.add(1);
508    Busy(Rc::clone(activity))
509  }
510}
511
512impl Drop for Busy {
513  fn drop(&mut self) {
514    self.0.add(-1);
515  }
516}
517
518/// A leaving item waiting for everything in it to stop: `done` runs at
519/// the first tick that finds nothing running there, unless `owner`, its
520/// exit's, went first.
521struct Watch {
522  owner: Owner,
523  activity: Rc<Activity>,
524  done: Box<dyn FnOnce()>,
525}
526
527thread_local! {
528  /// Everything is on one thread, so the clock is too. Each animation is
529  /// named for log lines.
530  static RUNNING: RefCell<Vec<Running>> = const { RefCell::new(Vec::new()) };
531  static WATCHES: RefCell<Vec<Watch>> = const { RefCell::new(Vec::new()) };
532  /// Steps taken off the clock through a pause. The timers wake them.
533  static ASLEEP: RefCell<Vec<Sleeper>> = const { RefCell::new(Vec::new()) };
534  /// What the step now running asked with [`sleep_until`].
535  static SLEEP: Cell<Option<Nap>> = const { Cell::new(None) };
536  /// When the clock last ticked.
537  static LAST_TICK: Cell<Option<Instant>> = const { Cell::new(None) };
538}
539
540/// Starts `step`, named `label` for log lines and counted in `busy`'s
541/// item, at the next [`advance_animations`].
542pub(crate) fn start(label: Rc<str>, busy: Option<Busy>, step: Tick) {
543  RUNNING.with(|running| running.borrow_mut().push((label, busy, step)));
544}
545
546/// A pause a step asked for: until when, the owner whose going frees it,
547/// and the play it belongs to, as its generation cell and the number it
548/// started at, so a play replaced while asleep is freed too.
549pub(crate) struct Nap {
550  pub(crate) deadline: Instant,
551  pub(crate) owner: Owner,
552  pub(crate) play: (Rc<Cell<u64>>, u64),
553}
554
555/// A step asleep through its pause.
556struct Sleeper {
557  nap: Nap,
558  running: Running,
559}
560
561impl Nap {
562  /// Whether nothing waits for it any more.
563  fn stale(&self) -> bool {
564    self.owner.is_disposed() || self.play.0.get() != self.play.1
565  }
566}
567
568/// Takes the step now running off the clock once it returns `true`, until
569/// the nap's deadline, so a pause wakes the loop once instead of every
570/// frame. It stays counted in its item, and is freed unwoken once stale.
571pub(crate) fn sleep_until(nap: Nap) {
572  SLEEP.with(|sleep| sleep.set(Some(nap)));
573}
574
575/// Frees the sleeping steps whose owner is gone or whose play was
576/// replaced, dropping them with the table released.
577fn sweep_asleep() {
578  let gone = ASLEEP.with(|asleep| {
579    let mut asleep = asleep.borrow_mut();
580    let (gone, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut *asleep)
581      .into_iter()
582      .partition(|sleeper| sleeper.nap.stale());
583    *asleep = kept;
584    gone
585  });
586  for Sleeper {
587    running: (label, busy, step),
588    ..
589  } in gone
590  {
591    drop(busy);
592    drop_isolated(&label, step);
593  }
594}
595
596/// When the first sleeping step wakes, having freed the stale ones.
597pub(crate) fn next_wake() -> Option<Instant> {
598  sweep_asleep();
599  ASLEEP.with(|asleep| {
600    let asleep = asleep.borrow();
601    asleep.iter().map(|sleeper| sleeper.nap.deadline).min()
602  })
603}
604
605/// Puts the sleeping steps due at `now` back on the clock, having freed
606/// the stale ones.
607pub(crate) fn wake(now: Instant) {
608  sweep_asleep();
609  let due: Vec<Running> = ASLEEP.with(|asleep| {
610    let mut asleep = asleep.borrow_mut();
611    let (due, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut *asleep)
612      .into_iter()
613      .partition(|sleeper| sleeper.nap.deadline <= now);
614    *asleep = kept;
615    due.into_iter().map(|sleeper| sleeper.running).collect()
616  });
617  RUNNING.with(|running| running.borrow_mut().extend(due));
618}
619
620/// How many steps sleep, for tests.
621#[cfg(test)]
622pub(crate) fn asleep() -> usize {
623  ASLEEP.with(|asleep| asleep.borrow().len())
624}
625
626/// Runs `done` at the first tick that finds nothing running in
627/// `activity`'s item, while `owner` lasts. The clock ticks for it, so an
628/// item with nothing moving is judged at once.
629pub(crate) fn watch(owner: Owner, activity: Rc<Activity>, done: impl FnOnce() + 'static) {
630  WATCHES.with(|watches| {
631    watches.borrow_mut().push(Watch {
632      owner,
633      activity,
634      done: Box::new(done),
635    });
636  });
637}
638
639/// Runs the watches whose items have stopped. Judged before the steps
640/// move, so an animation started in the flush after the last tick, as
641/// one that follows another's end, still counts.
642fn judge_watches() {
643  let watches = WATCHES.with(|watches| std::mem::take(&mut *watches.borrow_mut()));
644  let mut kept = Vec::with_capacity(watches.len());
645  for watch in watches {
646    if watch.owner.is_disposed() {
647      continue;
648    }
649    if watch.activity.running.get() == 0 {
650      (watch.done)();
651    } else {
652      kept.push(watch);
653    }
654  }
655  WATCHES.with(|watches| {
656    let mut watches = watches.borrow_mut();
657    kept.append(&mut watches);
658    *watches = kept;
659  });
660}
661
662/// When an animation starting now should count from: the clock's last
663/// tick while it runs, so one that replaces another moves at the very
664/// next tick, or `None` when it is still, so the first tick is time 0.
665pub(crate) fn start_time() -> Option<Instant> {
666  if animating() {
667    LAST_TICK.with(Cell::get)
668  } else {
669    None
670  }
671}
672
673/// Whether an animation is running, so the platform should advance the
674/// clock soon. `false` means nothing moves and nothing needs waking.
675pub fn animating() -> bool {
676  RUNNING.with(|running| !running.borrow().is_empty())
677    || WATCHES.with(|watches| !watches.borrow().is_empty())
678}
679
680/// Advances every running animation to `now`, writing their values, and
681/// returns whether any still runs. Each one starts at the first call after
682/// it began, so `now` there is its time 0. One that panics is logged and
683/// dropped.
684pub fn advance_animations(now: Instant) -> bool {
685  LAST_TICK.with(|last| last.set(Some(now)));
686  judge_watches();
687  let steps = RUNNING.with(|running| std::mem::take(&mut *running.borrow_mut()));
688  let mut kept = Vec::with_capacity(steps.len());
689  for (label, busy, mut step) in steps {
690    let ran = panic::catch_unwind(AssertUnwindSafe(|| step(now)));
691    let sleep = SLEEP.with(Cell::take);
692    match ran {
693      Ok(true) => match sleep {
694        Some(nap) => {
695          let running = (label, busy, step);
696          ASLEEP.with(|asleep| asleep.borrow_mut().push(Sleeper { nap, running }));
697        }
698        None => kept.push((label, busy, step)),
699      },
700      Ok(false) => drop_isolated(&label, step),
701      Err(payload) => {
702        tracing::error!(
703          "animation {label} panicked and stops: {}",
704          panic_message(payload.as_ref())
705        );
706        drop_isolated(&label, step);
707      }
708    }
709  }
710  RUNNING.with(|running| {
711    // Animations started while these ran go after them.
712    let mut running = running.borrow_mut();
713    kept.append(&mut running);
714    *running = kept;
715  });
716  let still = animating();
717  if !still {
718    // The clock stops, so the next animation counts from its own first
719    // tick, not this one.
720    LAST_TICK.with(|last| last.set(None));
721  }
722  still
723}
724
725/// Drops a finished step, and the user's values it holds, isolated.
726fn drop_isolated(label: &str, step: Tick) {
727  if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(step))) {
728    tracing::error!(
729      "dropping animation {label} panicked: {}",
730      panic_message(payload.as_ref())
731    );
732  }
733}
734
735/// Runs `f`, a config's closure for the animation `label`, and logs a
736/// panic as that animation's, giving `None`.
737fn guarded<R>(label: &str, f: impl FnOnce() -> R) -> Option<R> {
738  match panic::catch_unwind(AssertUnwindSafe(f)) {
739    Ok(value) => Some(value),
740    Err(payload) => {
741      tracing::error!(
742        "animation {label} panicked and stops: {}",
743        panic_message(payload.as_ref())
744      );
745      None
746    }
747  }
748}
749
750/// Sets `signal` to `value` only when that changes it, since a set always
751/// tells its readers.
752fn set_changed<T: PartialEq + 'static>(signal: Signal<T>, value: T) {
753  if untrack(|| signal.try_with(|old| *old != value)) == Some(true) {
754    signal.try_set(value);
755  }
756}
757
758/// A value moving toward its target, from [`Cx::animation`] or
759/// [`Cx::spring`]: a `Copy`
760/// handle to its value and to whether it moves.
761pub struct Animation<T: 'static> {
762  value: ReadSignal<T>,
763  running: ReadSignal<bool>,
764}
765
766impl<T> Clone for Animation<T> {
767  fn clone(&self) -> Self {
768    *self
769  }
770}
771
772impl<T> Copy for Animation<T> {}
773
774impl<T> Animation<T> {
775  /// The value, as [`Cx::animate`] gives it.
776  pub fn value(&self) -> ReadSignal<T> {
777    self.value
778  }
779
780  /// `true` from the moment a new target starts it, through its delay,
781  /// until it settles there. It turns `false` once per animation, so an
782  /// effect on it is the place for what follows; one that takes no time,
783  /// a 0 ms target or a sequence of only 0 ms steps, never turns it true,
784  /// so read its trigger too if what follows must run after it.
785  pub fn running(&self) -> ReadSignal<bool> {
786    self.running
787  }
788}
789
790impl Cx {
791  /// A value that follows `target`, moving to each new one over
792  /// `transition` instead of jumping. It starts at `target`'s first value.
793  /// A new target while it moves starts a new animation from where it is.
794  /// A 0 ms transition with no delay lands in the flush that changes the
795  /// target, so the same turn's layout and draw already show it.
796  /// The animation goes when this context's owner does. It is
797  /// [`Cx::animation`]'s value.
798  ///
799  /// ```
800  /// use crabshell_ui::{Cx, Transition};
801  ///
802  /// fn slide(cx: &Cx) {
803  ///     let open = cx.signal(false);
804  ///     let offset = cx.animate(move || if open.get() { 0.0 } else { -200.0 }, Transition::new(200));
805  ///     // Read `offset.get()` in a binding, such as a style's width.
806  /// }
807  /// ```
808  #[track_caller]
809  pub fn animate<T: Animate>(
810    &self,
811    target: impl FnMut() -> T + 'static,
812    transition: impl IntoProp<Transition>,
813  ) -> ReadSignal<T> {
814    self.follow("cx.animate", target, transition).value
815  }
816
817  /// A value that follows `target` as [`Cx::animate`]'s does, and whether
818  /// it moves. A panic in `target` is logged with this call's place, and
819  /// the value stays where it was.
820  ///
821  /// ```
822  /// use crabshell_ui::{Cx, Transition};
823  ///
824  /// fn slide_in_then_focus(cx: &Cx) {
825  ///     let open = cx.signal(false);
826  ///     let ready = cx.signal(false);
827  ///     let slide = cx.animation(move || if open.get() { 0.0 } else { -200.0 }, Transition::new(200));
828  ///     cx.effect(move || {
829  ///         if open.get() && !slide.running().get() {
830  ///             ready.set(true);
831  ///         }
832  ///     });
833  /// }
834  /// ```
835  #[track_caller]
836  pub fn animation<T: Animate>(
837    &self,
838    target: impl FnMut() -> T + 'static,
839    transition: impl IntoProp<Transition>,
840  ) -> Animation<T> {
841    self.follow("cx.animation", target, transition)
842  }
843
844  /// [`Cx::animation`], logged as `what` at the caller's place.
845  #[track_caller]
846  fn follow<T: Animate>(
847    &self,
848    what: &str,
849    mut target: impl FnMut() -> T + 'static,
850    transition: impl IntoProp<Transition>,
851  ) -> Animation<T> {
852    let label: Rc<str> = format!("{what} at {}", std::panic::Location::caller()).into();
853    let transition = transition.into_prop().shared();
854    let activity = self.activity.clone();
855    let first = untrack(&mut target);
856    let value = self.signal(first.clone());
857    let running = self.signal(false);
858    let mut last = first;
859    // Bumped by each new target, so the animation it replaces stops.
860    let generation = Rc::new(Cell::new(0_u64));
861    let mut broken = false;
862    self.effect(move || {
863      if broken {
864        return;
865      }
866      let Some(to) = guarded(&label, &mut target) else {
867        broken = true;
868        generation.set(generation.get() + 1);
869        set_changed(running, false);
870        return;
871      };
872      if to == last {
873        return;
874      }
875      // Read as each move starts, so a binding can pick its curve.
876      let Some(transition) = guarded(&label, || untrack(&*transition)) else {
877        broken = true;
878        generation.set(generation.get() + 1);
879        set_changed(running, false);
880        return;
881      };
882      last = to.clone();
883      let Some(from) = untrack(|| value.try_get()) else {
884        return;
885      };
886      let current = generation.get() + 1;
887      generation.set(current);
888      // No time to take: the new value shows in this flush.
889      if transition.is_instant() {
890        value.try_set(to);
891        set_changed(running, false);
892        return;
893      }
894      set_changed(running, true);
895      let generation = Rc::clone(&generation);
896      let mut started = start_time();
897      let step_label = Rc::clone(&label);
898      start(
899        Rc::clone(&label),
900        activity.as_ref().map(Busy::new),
901        Box::new(move |now| {
902          if generation.get() != current {
903            return false;
904          }
905          let begun = *started.get_or_insert(now);
906          if transition.waiting(begun, now) {
907            // The value is still `from`; setting it would rerun its readers.
908            return true;
909          }
910          let (t, ended) = transition.progress(begun, now);
911          // `lerp` and `clone` may be a config's own; a panic ends the
912          // animation with `running` false, so whatever waits on it runs.
913          let Some(next) = guarded(&step_label, || {
914            if ended { to.clone() } else { from.lerp(&to, t) }
915          }) else {
916            running.try_set(false);
917            return false;
918          };
919          // A value whose owner is gone stops its animation.
920          let kept = value.try_set(next);
921          if ended {
922            running.try_set(false);
923          }
924          kept && !ended
925        }),
926      );
927    });
928    Animation {
929      value: value.read_only(),
930      running: running.read_only(),
931    }
932  }
933
934  /// Progress from 0 to 1, eased, repeating every `transition.ms` while
935  /// `running` gives `true`, for spinners and pulses. With
936  /// [`Transition::alternate`] it comes back, 0 to 1 to 0, each way taking
937  /// `ms`. It waits out the delay once, at the start. When `running` turns
938  /// `false`, the round it is in runs to its end, then it rests at 0 and
939  /// the clock stops; `true` again before then keeps it going, and after
940  /// it begins at 0. A 0 ms cycle never moves. A panic in `running` is
941  /// logged with this call's place and ends the cycle after its round.
942  ///
943  /// ```
944  /// use crabshell_ui::{Cx, Easing, Transition};
945  ///
946  /// const SPIN: Transition = Transition::new(1000).easing(Easing::Linear);
947  /// const PULSE: Transition = Transition::new(600).easing(Easing::InOutSine).alternate();
948  ///
949  /// fn busy(cx: &Cx) {
950  ///     let loading = cx.signal(true);
951  ///     let turn = cx.cycle(move || loading.get(), SPIN); // turns: turn.get() * 360.0
952  ///     let glow = cx.cycle(move || loading.get(), PULSE); // an opacity: 0.5 + glow.get() / 2.0
953  /// }
954  /// ```
955  #[track_caller]
956  pub fn cycle(
957    &self,
958    mut running: impl FnMut() -> bool + 'static,
959    transition: Transition,
960  ) -> ReadSignal<f32> {
961    let label: Rc<str> = format!("cx.cycle at {}", std::panic::Location::caller()).into();
962    let activity = self.activity.clone();
963    let value = self.signal(0.0_f32);
964    // What `running` last gave, and whether a round is on the clock.
965    let wanted = Rc::new(Cell::new(false));
966    let ticking = Rc::new(Cell::new(false));
967    let mut broken = false;
968    self.effect(move || {
969      let on = !broken
970        && guarded(&label, &mut running).unwrap_or_else(|| {
971          broken = true;
972          false
973        });
974      wanted.set(on);
975      if !on || ticking.get() || transition.ms == 0 {
976        return;
977      }
978      ticking.set(true);
979      let (wanted, ticking) = (Rc::clone(&wanted), Rc::clone(&ticking));
980      let leg = f64::from(transition.ms);
981      let period = if transition.alternate { 2.0 * leg } else { leg };
982      let mut started = start_time();
983      // Round 0 is the delay, then 1, 2 and on.
984      let mut round = 0_u64;
985      start(
986        Rc::clone(&label),
987        activity.as_ref().map(Busy::new),
988        Box::new(move |now| {
989          let begun = *started.get_or_insert(now);
990          let elapsed = now.saturating_duration_since(begun).as_secs_f64() * 1000.0
991            - f64::from(transition.delay);
992          let now_round = if elapsed < 0.0 {
993            0
994          } else {
995            (elapsed / period) as u64 + 1
996          };
997          let ended = !wanted.get() && (now_round == 0 || now_round > round);
998          round = now_round;
999          if ended {
1000            ticking.set(false);
1001            value.try_set(0.0);
1002            return false;
1003          }
1004          let phase = elapsed.max(0.0) % period / leg;
1005          let t = if phase <= 1.0 { phase } else { 2.0 - phase };
1006          value.try_set(transition.easing.value_at(t as f32))
1007        }),
1008      );
1009    });
1010    value.read_only()
1011  }
1012
1013  /// The time since `running` turned `true`, updated at each tick of the
1014  /// animation clock while it stays true, as Qt's `FrameAnimation` gives.
1015  /// Nothing ticks while it is false, and the time stays where it was
1016  /// until the next run starts again from 0. A panic in `running` is
1017  /// logged with this call's place and stops it.
1018  ///
1019  /// ```
1020  /// use crabshell_ui::Cx;
1021  ///
1022  /// fn wave(cx: &Cx) {
1023  ///     let shown = cx.signal(true);
1024  ///     let time = cx.frames(move || shown.get());
1025  ///     // A bar's height: 10.0 + 5.0 * (time.get().as_secs_f32() * 6.0).sin()
1026  /// }
1027  /// ```
1028  #[track_caller]
1029  pub fn frames(&self, mut running: impl FnMut() -> bool + 'static) -> ReadSignal<Duration> {
1030    let label: Rc<str> = format!("cx.frames at {}", std::panic::Location::caller()).into();
1031    let activity = self.activity.clone();
1032    let value = self.signal(Duration::ZERO);
1033    let wanted = Rc::new(Cell::new(false));
1034    let ticking = Rc::new(Cell::new(false));
1035    let mut broken = false;
1036    self.effect(move || {
1037      let on = !broken
1038        && guarded(&label, &mut running).unwrap_or_else(|| {
1039          broken = true;
1040          false
1041        });
1042      wanted.set(on);
1043      if !on || ticking.get() {
1044        return;
1045      }
1046      ticking.set(true);
1047      let (wanted, ticking) = (Rc::clone(&wanted), Rc::clone(&ticking));
1048      let mut started = start_time();
1049      start(
1050        Rc::clone(&label),
1051        activity.as_ref().map(Busy::new),
1052        Box::new(move |now| {
1053          if !wanted.get() {
1054            ticking.set(false);
1055            return false;
1056          }
1057          let begun = *started.get_or_insert(now);
1058          value.try_set(now.saturating_duration_since(begun))
1059        }),
1060      );
1061    });
1062    value.read_only()
1063  }
1064
1065  /// A value that follows `target` on `spring`, as Qt's
1066  /// `SpringAnimation`: a new target while it moves keeps its speed, so a
1067  /// value chasing a moving target never stops dead. It starts at
1068  /// `target`'s first value and comes to rest exactly on the target, when
1069  /// the clock stops. A target that isn't finite, or a spring that isn't
1070  /// valid (see [`Spring`]), jumps there at once. A panic in `target` is
1071  /// logged with this call's place, and the value stops where it is. The
1072  /// [`Animation`]'s `running()` is true from a new target until it comes
1073  /// to rest, and never for a jump.
1074  ///
1075  /// ```
1076  /// use crabshell_ui::{Cx, Spring};
1077  ///
1078  /// fn indicator(cx: &Cx) {
1079  ///     let hovered = cx.signal(0_usize);
1080  ///     let x = cx.spring(move || hovered.get() as f32 * 40.0, Spring::new(380.0, 0.8));
1081  ///     // Read `x.value().get()` in a binding, such as a style's padding.
1082  /// }
1083  /// ```
1084  #[track_caller]
1085  pub fn spring(
1086    &self,
1087    mut target: impl FnMut() -> f32 + 'static,
1088    spring: Spring,
1089  ) -> Animation<f32> {
1090    let label: Rc<str> = format!("cx.spring at {}", std::panic::Location::caller()).into();
1091    let activity = self.activity.clone();
1092    let first = untrack(&mut target);
1093    let value = self.signal(first);
1094    let running = self.signal(false);
1095    let mut last = first;
1096    // Where the step on the clock heads, and whether there is one. A goal
1097    // that isn't finite stops it.
1098    let goal = Rc::new(Cell::new(first));
1099    let ticking = Rc::new(Cell::new(false));
1100    let mut broken = false;
1101    self.effect(move || {
1102      if broken {
1103        return;
1104      }
1105      let Some(to) = guarded(&label, &mut target) else {
1106        broken = true;
1107        goal.set(f32::NAN);
1108        set_changed(running, false);
1109        return;
1110      };
1111      if to == last {
1112        return;
1113      }
1114      last = to;
1115      goal.set(to);
1116      if !to.is_finite() || !spring.is_valid() {
1117        value.try_set(to);
1118        // One on the clock stops at its next tick.
1119        set_changed(running, false);
1120        return;
1121      }
1122      if ticking.get() {
1123        // Still on the clock after a jump, it moves again.
1124        set_changed(running, true);
1125        return;
1126      }
1127      let Some(from) = untrack(|| value.try_get()) else {
1128        return;
1129      };
1130      ticking.set(true);
1131      set_changed(running, true);
1132      let (goal, ticking) = (Rc::clone(&goal), Rc::clone(&ticking));
1133      let (mut x, mut v) = (f64::from(from), 0.0);
1134      let mut previous = start_time();
1135      start(
1136        Rc::clone(&label),
1137        activity.as_ref().map(Busy::new),
1138        Box::new(move |now| {
1139          let to = f64::from(goal.get());
1140          if !to.is_finite() {
1141            ticking.set(false);
1142            set_changed(running, false);
1143            return false;
1144          }
1145          let seconds = previous.map_or(0.0, |previous| {
1146            now
1147              .saturating_duration_since(previous)
1148              .as_secs_f64()
1149              .min(SPRING_MAX_STEP)
1150          });
1151          previous = Some(now);
1152          spring.advance(&mut x, &mut v, to, seconds);
1153          let (near, slow) = SPRING_REST;
1154          // A value that started out not finite lands at once.
1155          let rest = !(x.is_finite() && v.is_finite()) || ((x - to).abs() < near && v.abs() < slow);
1156          if rest {
1157            x = to;
1158          }
1159          let kept = value.try_set(x as f32);
1160          if rest || !kept {
1161            ticking.set(false);
1162            set_changed(running, false);
1163          }
1164          kept && !rest
1165        }),
1166      );
1167    });
1168    Animation {
1169      value: value.read_only(),
1170      running: running.read_only(),
1171    }
1172  }
1173
1174  /// A value that plays `steps` one after another each time `trigger`'s
1175  /// value changes, as Qt's `SequentialAnimation`: a shake on a wrong
1176  /// password, bumped by a counter, or a pause and then a slide. It starts
1177  /// at `initial`, and `trigger`'s first value plays nothing. Each step
1178  /// moves from wherever the value is, so a new trigger mid-play starts
1179  /// over from there, and once played the value rests at the last step's
1180  /// target. `steps` is a value or a closure, read untracked as each play
1181  /// starts; an empty list plays nothing. The steps at the start that take
1182  /// no time, 0 ms with no delay, land in the flush where `trigger`
1183  /// changes, so the same turn's layout and draw already show the value
1184  /// they leave and the next step moves from there; a play of no time at
1185  /// all ends in that flush, and the clock never runs.
1186  ///
1187  /// The [`Animation`]'s `running()` is true from the trigger until the
1188  /// last step ends, holds included, so an effect on it runs what comes
1189  /// after. A hold, or a delay, takes the value off the animation clock:
1190  /// the loop sleeps until it ends instead of waking each frame. A panic in
1191  /// `trigger` is logged with this call's place and stops the sequence
1192  /// where it is for good; one in `steps` or a config's own `lerp`,
1193  /// `clone` or `PartialEq` stops that play.
1194  ///
1195  /// ```
1196  /// use crabshell_ui::{Cx, Easing, Step, Transition};
1197  ///
1198  /// const SHAKE: [Step<f32>; 3] = [
1199  ///     Step::to(-14.0, Transition::new(70).easing(Easing::OutQuad)),
1200  ///     Step::to(12.0, Transition::new(90).easing(Easing::InOutQuad)),
1201  ///     Step::to(0.0, Transition::new(95).easing(Easing::OutQuad)),
1202  /// ];
1203  ///
1204  /// fn pill(cx: &Cx) {
1205  ///     let wrong = cx.signal(0_u32); // bumped on each wrong password
1206  ///     let shake = cx.sequence(0.0, move || wrong.get(), SHAKE);
1207  ///     // Read `shake.value().get()` in a binding, such as a translate.
1208  /// }
1209  /// ```
1210  #[track_caller]
1211  pub fn sequence<T: Animate, K: PartialEq + 'static>(
1212    &self,
1213    initial: T,
1214    mut trigger: impl FnMut() -> K + 'static,
1215    steps: impl IntoProp<Vec<Step<T>>>,
1216  ) -> Animation<T> {
1217    let player = self.player("cx.sequence", initial, steps);
1218    let mut last = None;
1219    let mut broken = false;
1220    let animation = player.animation();
1221    self.effect(move || {
1222      if broken {
1223        return;
1224      }
1225      let Some(now) = guarded(&player.label, &mut trigger) else {
1226        broken = true;
1227        player.stop();
1228        return;
1229      };
1230      if last.as_ref().is_some_and(|last| *last != now) {
1231        player.play(false);
1232      }
1233      last = Some(now);
1234    });
1235    animation
1236  }
1237
1238  /// A value that plays `steps` once, starting as soon as it is made: an
1239  /// entrance that plays each time its widget is built, such as a card
1240  /// that waits its turn with a [`Step::hold`] and then fades in. It
1241  /// starts at `initial`, and once played it rests at the last step's
1242  /// target. `steps` is a value or a closure, read untracked once, now; an
1243  /// empty list plays nothing. Steps at the start that take no time land
1244  /// at once, as in [`Cx::sequence`]. Holds sleep off the clock as in
1245  /// [`Cx::sequence`], and the [`Animation`]'s `running()` is true until
1246  /// the last step ends. To play again on a change, use
1247  /// [`Cx::sequence`]. A panic in `steps` or a config's own `lerp` is
1248  /// logged with this call's place and stops the play.
1249  ///
1250  /// ```
1251  /// use crabshell_ui::{Cx, Easing, Step, Transition};
1252  ///
1253  /// const FADE: Transition = Transition::new(200).easing(Easing::OutCubic);
1254  ///
1255  /// fn card(cx: &Cx, index: u32) {
1256  ///     let opacity = cx.sequence_now(0.0, [Step::hold(index * 40), Step::to(1.0, FADE)]);
1257  ///     // Read `opacity.value().get()` in a binding.
1258  /// }
1259  /// ```
1260  #[track_caller]
1261  pub fn sequence_now<T: Animate>(
1262    &self,
1263    initial: T,
1264    steps: impl IntoProp<Vec<Step<T>>>,
1265  ) -> Animation<T> {
1266    let player = self.player("cx.sequence_now", initial, steps);
1267    player.play(false);
1268    player.animation()
1269  }
1270
1271  /// A value that plays `steps` over and over while `running` gives
1272  /// `true`, each round with its holds, as a `SequentialAnimation` with
1273  /// infinite loops: a pulse while something loads. It starts at
1274  /// `initial`; round 0 moves from where the value is, and each later
1275  /// round from the last step's target. When `running` turns `false`, the
1276  /// round it is in runs to its end and the value rests at the last step's
1277  /// target; `true` again before then keeps it going, and after it starts
1278  /// again at round 0. Round 0's steps at the start that take no time land
1279  /// in the flush where `running` turns `true`, as in [`Cx::sequence`]; a
1280  /// later round's land at its first tick. A round of no time plays once,
1281  /// in that flush. Holds sleep off the clock as in [`Cx::sequence`]. A
1282  /// panic in `running` is logged with
1283  /// this call's place and ends it after its round.
1284  ///
1285  /// ```
1286  /// use crabshell_ui::{Cx, Easing, Step, Transition};
1287  ///
1288  /// const SINE: Transition = Transition::new(1100).easing(Easing::InOutSine);
1289  ///
1290  /// fn tile(cx: &Cx, index: u32) {
1291  ///     let loading = cx.signal(true);
1292  ///     let steps = [Step::hold(index * 140), Step::to(0.4, SINE), Step::to(1.0, SINE)];
1293  ///     let opacity = cx.sequence_loop(1.0, move || loading.get(), steps);
1294  /// }
1295  /// ```
1296  #[track_caller]
1297  pub fn sequence_loop<T: Animate>(
1298    &self,
1299    initial: T,
1300    mut running: impl FnMut() -> bool + 'static,
1301    steps: impl IntoProp<Vec<Step<T>>>,
1302  ) -> Animation<T> {
1303    let player = self.player("cx.sequence_loop", initial, steps);
1304    let mut broken = false;
1305    let animation = player.animation();
1306    self.effect(move || {
1307      let on = !broken
1308        && guarded(&player.label, &mut running).unwrap_or_else(|| {
1309          broken = true;
1310          false
1311        });
1312      player.wanted.set(on);
1313      if on && untrack(|| player.running.try_get()) == Some(false) {
1314        player.play(true);
1315      }
1316    });
1317    animation
1318  }
1319
1320  /// The state [`Cx::sequence`], [`Cx::sequence_now`] and
1321  /// [`Cx::sequence_loop`] share, logged as
1322  /// `what` at the caller's place.
1323  #[track_caller]
1324  fn player<T: Animate>(
1325    &self,
1326    what: &str,
1327    initial: T,
1328    steps: impl IntoProp<Vec<Step<T>>>,
1329  ) -> Rc<Player<T>> {
1330    Rc::new(Player {
1331      label: format!("{what} at {}", std::panic::Location::caller()).into(),
1332      steps: steps.into_prop().shared(),
1333      value: self.signal(initial),
1334      running: self.signal(false),
1335      generation: Rc::new(Cell::new(0)),
1336      wanted: Rc::new(Cell::new(false)),
1337      owner: self.owner(),
1338      activity: self.activity.clone(),
1339    })
1340  }
1341}
1342
1343/// A sequence's value, its steps, and the play on the clock.
1344struct Player<T: 'static> {
1345  label: Rc<str>,
1346  steps: Rc<dyn Fn() -> Vec<Step<T>>>,
1347  value: Signal<T>,
1348  running: Signal<bool>,
1349  /// Bumped by each new play, so the one it replaces stops.
1350  generation: Rc<Cell<u64>>,
1351  /// What a loop's `running` last gave.
1352  wanted: Rc<Cell<bool>>,
1353  owner: Owner,
1354  activity: Option<Rc<Activity>>,
1355}
1356
1357impl<T: Animate> Player<T> {
1358  fn animation(&self) -> Animation<T> {
1359    Animation {
1360      value: self.value.read_only(),
1361      running: self.running.read_only(),
1362    }
1363  }
1364
1365  /// Stops the play on the clock where it is.
1366  fn stop(&self) {
1367    self.generation.set(self.generation.get() + 1);
1368    set_changed(self.running, false);
1369  }
1370
1371  /// Starts a play of the steps from where the value is, looping while
1372  /// `wanted` if `looping`.
1373  fn play(&self, looping: bool) {
1374    self.stop();
1375    let label = Rc::clone(&self.label);
1376    // Read as each play starts, so a binding can pick the steps; the
1377    // clones are a config's own.
1378    let Some((steps, origin, last)) = guarded(&label, || {
1379      let steps = untrack(&*self.steps);
1380      let origin = untrack(|| self.value.try_get())?;
1381      let last = steps.iter().rev().find_map(|step| step.to.clone());
1382      let last = last.unwrap_or_else(|| origin.clone());
1383      // The steps that take no time land in this flush, so a layout or
1384      // draw in this turn already sees them; the clock's first tick, a
1385      // frame later, would show the old value once.
1386      let leading = steps
1387        .iter()
1388        .take_while(|step| step.transition.is_instant())
1389        .filter_map(|step| step.to.clone())
1390        .last();
1391      if let Some(leading) = leading {
1392        set_changed(self.value, leading);
1393      }
1394      Some((steps, origin, last))
1395    })
1396    .flatten() else {
1397      return;
1398    };
1399    let length: u64 = steps.iter().map(|step| step.times().1).sum();
1400    // A play of no time has ended already, with nothing for the clock.
1401    if length == 0 {
1402      return;
1403    }
1404    set_changed(self.running, true);
1405    let current = self.generation.get();
1406    let (generation, wanted) = (Rc::clone(&self.generation), Rc::clone(&self.wanted));
1407    let (value, running, owner) = (self.value, self.running, self.owner);
1408    let step_label = Rc::clone(&label);
1409    let mut started = start_time();
1410    let mut round = 0;
1411    start(
1412      label,
1413      self.activity.as_ref().map(Busy::new),
1414      Box::new(move |now| {
1415        if generation.get() != current {
1416          return false;
1417        }
1418        let begun = *started.get_or_insert(now);
1419        let at = now.saturating_duration_since(begun).as_micros();
1420        let at = u64::try_from(at).unwrap_or(u64::MAX);
1421        let (now_round, within) = if looping {
1422          (at / length, at % length)
1423        } else {
1424          (0, at)
1425        };
1426        let ended = now_round > round && !wanted.get();
1427        round = now_round;
1428        let spot = guarded(&step_label, || {
1429          if ended {
1430            return Spot::Ended(last.clone());
1431          }
1432          spot(&steps, if round == 0 { &origin } else { &last }, within)
1433        });
1434        let (next, sleep) = match spot {
1435          Some(Spot::Moving(next)) => (next, None),
1436          Some(Spot::Holding(next, until)) => (next, Some(round * length + until)),
1437          Some(Spot::Ended(next)) => {
1438            // A config's own `PartialEq` runs in the write.
1439            guarded(&step_label, || set_changed(value, next));
1440            running.try_set(false);
1441            return false;
1442          }
1443          // A panicking `lerp` ends the play with `running` false, so
1444          // whatever waits on it runs.
1445          None => {
1446            running.try_set(false);
1447            return false;
1448          }
1449        };
1450        // A value whose owner is gone stops its sequence.
1451        if untrack(|| value.try_with(|_| ())).is_none() {
1452          return false;
1453        }
1454        if guarded(&step_label, || set_changed(value, next)).is_none() {
1455          running.try_set(false);
1456          return false;
1457        }
1458        if let Some(until) = sleep {
1459          sleep_until(Nap {
1460            deadline: begun + Duration::from_micros(until),
1461            owner,
1462            play: (Rc::clone(&generation), current),
1463          });
1464        }
1465        true
1466      }),
1467    );
1468  }
1469}