zng_var/
vars.rs

1//!: Vars service.
2
3use std::{mem, sync::Arc, thread::ThreadId, time::Duration};
4
5use parking_lot::Mutex;
6use smallbox::SmallBox;
7use zng_app_context::{app_local, context_local};
8use zng_time::{DInstant, Deadline, INSTANT, INSTANT_APP};
9use zng_unit::{Factor, FactorUnits as _, TimeUnits as _};
10
11use smallbox::smallbox;
12
13use crate::{
14    AnyVar, Var,
15    animation::{Animation, AnimationController, AnimationHandle, AnimationTimer, ModifyInfo},
16    var,
17};
18
19/// Represents the last time a variable was mutated or the current update cycle.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, bytemuck::NoUninit)]
21#[repr(transparent)]
22pub struct VarUpdateId(pub(crate) u32);
23impl VarUpdateId {
24    /// ID that is never new.
25    pub const fn never() -> Self {
26        VarUpdateId(0)
27    }
28
29    fn next(&mut self) {
30        if self.0 == u32::MAX {
31            self.0 = 1;
32        } else {
33            self.0 += 1;
34        }
35    }
36}
37impl Default for VarUpdateId {
38    fn default() -> Self {
39        Self::never()
40    }
41}
42
43pub(super) type VarUpdateFn = SmallBox<dyn FnMut() + Send + 'static, smallbox::space::S8>;
44
45app_local! {
46    pub(crate) static VARS_SV: VarsService = VarsService::new();
47}
48context_local! {
49    pub(crate) static VARS_MODIFY_CTX: Option<ModifyInfo> = None;
50    pub(crate) static VARS_ANIMATION_CTRL_CTX: Box<dyn AnimationController> = {
51        let r: Box<dyn AnimationController> = Box::new(());
52        r
53    };
54}
55
56type AnimationFn = SmallBox<dyn FnMut(AnimationUpdateInfo) -> Option<Deadline> + Send, smallbox::space::S8>;
57
58pub(crate) struct VarsService {
59    // animation config
60    animations_enabled: Var<bool>,
61    sys_animations_enabled: Var<bool>,
62    frame_duration: Var<Duration>,
63    animation_time_scale: Var<Factor>,
64
65    // VARS_APP stuff
66    app_waker: Option<SmallBox<dyn Fn() + Send + Sync + 'static, smallbox::space::S2>>,
67    modify_trace: Option<SmallBox<dyn Fn(&'static str) + Send + Sync + 'static, smallbox::space::S2>>,
68
69    // AnyVar::perm storage
70    perm: Mutex<Vec<AnyVar>>,
71
72    // update state
73    update_id: VarUpdateId,
74    updates: Mutex<Vec<(ModifyInfo, VarUpdateFn)>>,
75    updating_thread: Option<ThreadId>,
76    updates_after: Mutex<Vec<(ModifyInfo, VarUpdateFn)>>,
77
78    // animations state
79    ans_animations: Mutex<Vec<AnimationFn>>,
80    ans_animation_imp: usize,
81    ans_current_modify: ModifyInfo,
82    ans_animation_start_time: Option<DInstant>,
83    ans_next_frame: Option<Deadline>,
84}
85impl VarsService {
86    pub(crate) fn new() -> Self {
87        let sys_animations_enabled = var(true);
88        Self {
89            animations_enabled: sys_animations_enabled.cow(),
90            sys_animations_enabled,
91            frame_duration: var((1.0 / 60.0).secs()),
92            animation_time_scale: var(1.fct()),
93
94            app_waker: None,
95            modify_trace: None,
96
97            perm: Mutex::new(vec![]),
98
99            update_id: VarUpdateId::never(),
100            updates: Mutex::new(vec![]),
101            updating_thread: None,
102            updates_after: Mutex::new(vec![]),
103
104            ans_animations: Mutex::new(vec![]),
105            ans_animation_imp: 0,
106            ans_current_modify: ModifyInfo::never(),
107            ans_animation_start_time: None,
108            ans_next_frame: None,
109        }
110    }
111
112    fn wake_app(&self) {
113        if let Some(w) = &self.app_waker {
114            w();
115        }
116    }
117}
118
119/// Variable updates and animation service.
120pub struct VARS;
121impl VARS {
122    /// Id of the current vars update in the app scope.
123    ///
124    /// Variable with [`AnyVar::last_update`] equal to this are *new*.
125    pub fn update_id(&self) -> VarUpdateId {
126        VARS_SV.read().update_id
127    }
128
129    /// Read-write that defines if animations are enabled on the app.
130    ///
131    /// The value is the same as [`sys_animations_enabled`], if set the variable disconnects from system config.
132    ///
133    /// [`sys_animations_enabled`]: Self::sys_animations_enabled
134    pub fn animations_enabled(&self) -> Var<bool> {
135        VARS_SV.read().animations_enabled.clone()
136    }
137
138    /// Read-only that tracks if animations are enabled in the operating system.
139    ///
140    /// This is `true` by default, it updates when the operating system config changes.
141    pub fn sys_animations_enabled(&self) -> Var<bool> {
142        VARS_SV.read().sys_animations_enabled.read_only()
143    }
144
145    /// Variable that defines the global frame duration, the default is 60fps `(1.0 / 60.0).secs()`.
146    pub fn frame_duration(&self) -> Var<Duration> {
147        VARS_SV.read().frame_duration.clone()
148    }
149
150    /// Variable that defines a global scale for the elapsed time of animations.
151    pub fn animation_time_scale(&self) -> Var<Factor> {
152        VARS_SV.read().animation_time_scale.clone()
153    }
154
155    /// Info about the current context when requesting variable modification.
156    ///
157    /// If is currently inside a [`VARS.animate`] closure, or inside a [`Var::modify`] closure requested by an animation, or inside
158    /// an [`AnimationController`], returns the info that was collected at the moment the animation was requested. Outside of animations
159    /// gets an info with [`importance`] guaranteed to override the [`modify_importance`].
160    ///
161    /// [`importance`]: ModifyInfo::importance
162    /// [`modify_importance`]: AnyVar::modify_importance
163    /// [`AnimationController`]: crate::animation::AnimationController
164    /// [`VARS.animate`]: VARS::animate
165    pub fn current_modify(&self) -> ModifyInfo {
166        match VARS_MODIFY_CTX.get_clone() {
167            Some(current) => current, // override set by modify and animation closures.
168            None => VARS_SV.read().ans_current_modify.clone(),
169        }
170    }
171
172    /// Adds an `animation` closure that is called every frame to update captured variables, starting after next frame.
173    ///
174    /// This is used to implement all [`Var<T>`] animations, it enables any kind of variable animation,
175    /// including multiple variables.
176    ///
177    /// Returns an [`AnimationHandle`] that can be used to monitor the animation status and to [`stop`] or to
178    /// make the animation [`perm`].
179    ///
180    /// # Variable Control
181    ///
182    /// Animations assume *control* of a variable on the first time they cause its value to be new, after this
183    /// moment the [`AnyVar::is_animating`] value is `true` and [`AnyVar::modify_importance`] is the animation's importance,
184    /// until the animation stops. Only one animation can control a variable at a time, if an animation loses control of a
185    /// variable all attempts to modify it from inside the animation are ignored.
186    ///
187    /// Later started animations steal control from previous animations, update, modify or set calls also remove the variable
188    /// from being affected by a running animation, even if just set to an equal value, that is, not actually updated.
189    ///
190    /// # Nested Animations
191    ///
192    /// Other animations can be started from inside the animation closure, these *nested* animations have the same importance
193    /// as the *parent* animation, the animation handle is different and [`AnyVar::is_animating`] is `false` if the nested animation
194    /// is dropped before the *parent* animation. But because the animations share the same importance the parent animation can
195    /// set the variable again.
196    ///
197    /// You can also use the [`EasingTime::seg`] method to get a normalized time factor for a given segment or slice of the overall time,
198    /// complex animations targeting multiple variables can be coordinated with precision using this method.
199    ///
200    /// # Examples
201    ///
202    /// The example animates a `text` variable from `"Animation at 0%"` to `"Animation at 100%"`, when the animation
203    /// stops the `completed` variable is set to `true`.
204    ///
205    /// ```
206    /// # use zng_var::{*, animation::easing};
207    /// # use zng_txt::*;
208    /// # use zng_unit::*;
209    /// # use zng_clone_move::*;
210    /// #
211    /// fn animate_text(text: &Var<Txt>, completed: &Var<bool>) {
212    ///     let transition = animation::Transition::new(0u8, 100);
213    ///     let mut prev_value = 101;
214    ///     VARS.animate(clmv!(text, completed, |animation| {
215    ///         let step = easing::expo(animation.elapsed_stop(1.secs()));
216    ///         let value = transition.sample(step);
217    ///         if value != prev_value {
218    ///             if value == 100 {
219    ///                 animation.stop();
220    ///                 let _ = completed.set(true);
221    ///             }
222    ///             let _ = text.set(formatx!("Animation at {value}%"));
223    ///             prev_value = value;
224    ///         }
225    ///     }))
226    ///     .perm()
227    /// }
228    /// ```
229    ///
230    /// Note that the animation can be stopped from the inside, the closure parameter is an [`Animation`]. In
231    /// the example this is the only way to stop the animation, because [`perm`] was called. Animations hold a clone
232    /// of the variables they affect and exist for the duration of the app if not stopped, causing the app to wake and call the
233    /// animation closure for every frame.
234    ///
235    /// This method is the most basic animation interface, used to build all other animations, its rare that you
236    /// will need to use it directly, most of the time animation effects can be composted using the [`Var`] easing and mapping
237    /// methods.
238    ///
239    /// ```
240    /// # use zng_var::{*, animation::easing};
241    /// # use zng_txt::*;
242    /// # use zng_unit::*;
243    /// # fn demo() {
244    /// let value = var(0u8);
245    /// let text = value.map(|v| formatx!("Animation at {v}%"));
246    /// value.ease(100, 1.secs(), easing::expo);
247    /// # }
248    /// ```
249    ///
250    /// # Optimization Tips
251    ///
252    /// When no animation is running the app *sleeps* awaiting for an external event, update request or timer elapse, when at least one
253    /// animation is running the app awakes every [`VARS.frame_duration`]. You can use [`Animation::sleep`] to *pause* the animation
254    /// for a duration, if all animations are sleeping the app is also sleeping.
255    ///
256    /// Animations lose control over a variable permanently when a newer animation modifies the var or
257    /// the var is modified directly, but even if the animation can't control any variables **it keeps running**.
258    /// This happens because the system has no insight of all side effects caused by the `animation` closure. You
259    /// can use the [`VARS.current_modify`] and [`AnyVar::modify_importance`] to detect when the animation no longer affects
260    /// any variables and stop the animation to avoid awaking the app for no reason.
261    ///
262    /// These optimizations are already implemented by the animations provided as methods of [`Var<T>`].
263    ///
264    /// # External Controller
265    ///
266    /// The animation can be controlled from the inside using the [`Animation`] reference, it can be stopped using the returned
267    /// [`AnimationHandle`], and it can also be controlled by a registered [`AnimationController`] that can manage multiple
268    /// animations at the same time, see [`with_animation_controller`] for more details.
269    ///
270    /// [`Animation::sleep`]: Animation::sleep
271    /// [`stop`]: AnimationHandle::stop
272    /// [`perm`]: AnimationHandle::perm
273    /// [`with_animation_controller`]: VARS::with_animation_controller
274    /// [`VARS.frame_duration`]: VARS::frame_duration
275    /// [`VARS.current_modify`]: VARS::current_modify
276    /// [`EasingTime::seg`]: crate::animation::easing::EasingTime::seg
277    pub fn animate<A>(&self, animation: A) -> AnimationHandle
278    where
279        A: FnMut(&Animation) + Send + 'static,
280    {
281        VARS.animate_impl(smallbox!(animation))
282    }
283
284    /// Calls `animate` while `controller` is registered as the animation controller.
285    ///
286    /// The `controller` is notified of animation events for each animation spawned by `animate` and can affect then with the same
287    /// level of access as [`VARS.animate`]. Only one controller can affect animations at a time.
288    ///
289    /// This can be used to manage multiple animations at the same time, or to get [`VARS.animate`] level of access to an animation
290    /// that is not implemented to allow such access. Note that animation implementers are not required to support the full
291    /// [`Animation`] API, for example, there is no guarantee that a restart requested by the controller will repeat the same animation.
292    ///
293    /// The controller can start new animations, these animations will have the same controller if not overridden, you can
294    /// use this method and the `()` controller to avoid this behavior.
295    ///
296    /// [`Animation`]: crate::animation::Animation
297    /// [`VARS.animate`]: VARS::animate
298    pub fn with_animation_controller<R>(&self, controller: impl AnimationController, animate: impl FnOnce() -> R) -> R {
299        let controller: Box<dyn AnimationController> = Box::new(controller);
300        let mut opt = Some(Arc::new(controller));
301        VARS_ANIMATION_CTRL_CTX.with_context(&mut opt, animate)
302    }
303
304    pub(crate) fn schedule_update(&self, value_type_name: &'static str, apply_update: impl FnOnce() + Send + 'static) {
305        let mut once = Some(apply_update);
306        self.schedule_update_impl(
307            value_type_name,
308            smallbox!(move || {
309                let once = once.take().unwrap();
310                once();
311            }),
312        );
313    }
314
315    pub(crate) fn perm(&self, var: AnyVar) {
316        VARS_SV.read().perm.lock().push(var);
317    }
318}
319
320/// VARS APP integration.
321#[expect(non_camel_case_types)]
322pub struct VARS_APP;
323impl VARS_APP {
324    /// Register a closure called when [`apply_updates`] should be called because there are changes pending.
325    ///
326    /// # Panics
327    ///
328    /// Panics if already called for the current app. This must be called by app framework implementers only.
329    ///
330    /// [`apply_updates`]: Self::apply_updates
331    pub fn init_app_waker(&self, waker: impl Fn() + Send + Sync + 'static) {
332        let mut vars = VARS_SV.write();
333        assert!(vars.app_waker.is_none());
334        vars.app_waker = Some(smallbox!(waker));
335    }
336
337    /// Register a closure called when a variable modify is about to be scheduled. The
338    /// closure parameter is the type name of the variable type.
339    ///
340    /// # Panics
341    ///
342    /// Panics if already called for the current app. This must be called by app framework implementers only.
343    pub fn init_modify_trace(&self, trace: impl Fn(&'static str) + Send + Sync + 'static) {
344        let mut vars = VARS_SV.write();
345        assert!(vars.modify_trace.is_none());
346        vars.modify_trace = Some(smallbox!(trace));
347    }
348
349    /// If [`apply_updates`] will do anything.
350    ///
351    /// [`apply_updates`]: Self::apply_updates
352    pub fn has_pending_updates(&self) -> bool {
353        !VARS_SV.write().updates.get_mut().is_empty()
354    }
355
356    /// Sets the `sys_animations_enabled` read-only variable.
357    pub fn set_sys_animations_enabled(&self, enabled: bool) {
358        VARS_SV.read().sys_animations_enabled.set(enabled);
359    }
360
361    /// Apply all pending updates, call hooks and update bindings.
362    ///
363    /// This must be called by app framework implementers only.
364    pub fn apply_updates(&self) {
365        let _s = tracing::trace_span!("VARS").entered();
366        let _t = INSTANT_APP.pause_for_update();
367        VARS.apply_updates_and_after(0)
368    }
369
370    /// Does one animation frame if the frame duration has elapsed.
371    ///
372    /// This must be called by app framework implementers only.
373    pub fn update_animations(&self, timer: &mut impl AnimationTimer) {
374        VARS.update_animations_impl(timer);
375    }
376
377    /// Register the next animation frame, if there are any active animations.
378    ///
379    /// This must be called by app framework implementers only.
380    pub fn next_deadline(&self, timer: &mut impl AnimationTimer) {
381        VARS.next_deadline_impl(timer)
382    }
383}
384
385impl VARS {
386    fn schedule_update_impl(&self, value_type_name: &'static str, update: VarUpdateFn) {
387        let vars = VARS_SV.read();
388        if let Some(trace) = &vars.modify_trace {
389            trace(value_type_name);
390        }
391        let cur_modify = match VARS_MODIFY_CTX.get_clone() {
392            Some(current) => current, // override set by modify and animation closures.
393            None => vars.ans_current_modify.clone(),
394        };
395
396        if let Some(id) = vars.updating_thread {
397            if std::thread::current().id() == id {
398                // is binding request, enqueue for immediate exec.
399                vars.updates.lock().push((cur_modify, update));
400            } else {
401                // is request from app task thread when we are already updating, enqueue for exec after current update.
402                vars.updates_after.lock().push((cur_modify, update));
403            }
404        } else {
405            // request from any app thread,
406            vars.updates.lock().push((cur_modify, update));
407            vars.wake_app();
408        }
409    }
410
411    fn apply_updates_and_after(&self, depth: u8) {
412        let mut vars = VARS_SV.write();
413
414        match depth {
415            0 => {
416                vars.update_id.next();
417                vars.ans_animation_start_time = None;
418            }
419            10 => {
420                // high-pressure from worker threads, skip
421                return;
422            }
423            _ => {}
424        }
425
426        // updates requested by other threads while was applying updates
427        let mut updates = mem::take(vars.updates_after.get_mut());
428        // normal updates
429        if updates.is_empty() {
430            updates = mem::take(vars.updates.get_mut());
431        } else {
432            updates.append(vars.updates.get_mut());
433        }
434        // apply pending updates
435        if !updates.is_empty() {
436            debug_assert!(vars.updating_thread.is_none());
437            vars.updating_thread = Some(std::thread::current().id());
438
439            drop(vars);
440            update_each_and_bindings(updates, 0);
441
442            vars = VARS_SV.write();
443            vars.updating_thread = None;
444
445            if !vars.updates_after.get_mut().is_empty() {
446                drop(vars);
447                VARS.apply_updates_and_after(depth + 1)
448            }
449        }
450
451        fn update_each_and_bindings(updates: Vec<(ModifyInfo, VarUpdateFn)>, depth: u16) {
452            if depth == 1000 {
453                tracing::error!(
454                    "updated variable bindings 1000 times, probably stuck in an infinite loop\n\
455                    will skip next updates"
456                );
457                return;
458            }
459
460            for (info, mut update) in updates {
461                #[allow(clippy::redundant_closure)] // false positive
462                VARS_MODIFY_CTX.with_context(&mut Some(Arc::new(Some(info))), || (update)());
463
464                let mut vars = VARS_SV.write();
465                let updates = mem::take(vars.updates.get_mut());
466                if !updates.is_empty() {
467                    drop(vars);
468                    update_each_and_bindings(updates, depth + 1);
469                }
470            }
471        }
472    }
473
474    fn animate_impl(&self, mut animation: SmallBox<dyn FnMut(&Animation) + Send + 'static, smallbox::space::S4>) -> AnimationHandle {
475        let mut vars = VARS_SV.write();
476
477        // # Modify Importance
478        //
479        // Variables only accept modifications from an importance (IMP) >= the previous IM that modified it.
480        //
481        // Direct modifications always overwrite previous animations, so we advance the IMP for each call to
482        // this method **and then** advance the IMP again for all subsequent direct modifications.
483        //
484        // Example sequence of events:
485        //
486        // |IM| Modification  | Accepted
487        // |--|---------------|----------
488        // | 1| Var::set      | YES
489        // | 2| Var::ease     | YES
490        // | 2| ease update   | YES
491        // | 3| Var::set      | YES
492        // | 3| Var::set      | YES
493        // | 2| ease update   | NO
494        // | 4| Var::ease     | YES
495        // | 2| ease update   | NO
496        // | 4| ease update   | YES
497        // | 5| Var::set      | YES
498        // | 2| ease update   | NO
499        // | 4| ease update   | NO
500
501        // ensure that all animations started in this update have the same exact time, we update then with the same `now`
502        // timestamp also, this ensures that synchronized animations match perfectly.
503        let start_time = if let Some(t) = vars.ans_animation_start_time {
504            t
505        } else {
506            let t = INSTANT.now();
507            vars.ans_animation_start_time = Some(t);
508            t
509        };
510
511        let mut anim_imp = None;
512        if let Some(c) = VARS_MODIFY_CTX.get_clone()
513            && c.is_animating()
514        {
515            // nested animation uses parent importance.
516            anim_imp = Some(c.importance);
517        }
518        let anim_imp = match anim_imp {
519            Some(i) => i,
520            None => {
521                // not nested, advance base imp
522                let mut imp = vars.ans_animation_imp.wrapping_add(1);
523                if imp == 0 {
524                    imp = 1;
525                }
526
527                let mut next_imp = imp.wrapping_add(1);
528                if next_imp == 0 {
529                    next_imp = 1;
530                }
531
532                vars.ans_animation_imp = next_imp;
533                vars.ans_current_modify.importance = next_imp;
534
535                imp
536            }
537        };
538
539        let (handle_owner, handle) = AnimationHandle::new();
540        let weak_handle = handle.downgrade();
541
542        let controller = VARS_ANIMATION_CTRL_CTX.get();
543
544        let anim = Animation::new(vars.animations_enabled.get(), start_time, vars.animation_time_scale.get());
545
546        drop(vars);
547
548        controller.on_start(&anim);
549        let mut controller = Some(controller);
550        let mut anim_modify_info = Some(Arc::new(Some(ModifyInfo {
551            handle: Some(weak_handle.clone()),
552            importance: anim_imp,
553        })));
554
555        let mut vars = VARS_SV.write();
556
557        vars.ans_animations.get_mut().push(smallbox!(move |info: AnimationUpdateInfo| {
558            let _handle_owner = &handle_owner; // capture and own the handle owner.
559
560            if weak_handle.upgrade().is_some() {
561                if anim.stop_requested() {
562                    // drop
563                    controller.as_ref().unwrap().on_stop(&anim);
564                    return None;
565                }
566
567                if let Some(sleep) = anim.sleep_deadline() {
568                    if sleep > info.next_frame {
569                        // retain sleep
570                        return Some(sleep);
571                    } else if sleep.0 > info.now {
572                        // sync-up to frame rate after sleep
573                        anim.reset_sleep();
574                        return Some(info.next_frame);
575                    }
576                }
577
578                anim.reset_state(info.animations_enabled, info.now, info.time_scale);
579
580                VARS_ANIMATION_CTRL_CTX.with_context(&mut controller, || {
581                    VARS_MODIFY_CTX.with_context(&mut anim_modify_info, || animation(&anim))
582                });
583
584                // retain until next frame
585                //
586                // stop or sleep may be requested after this (during modify apply),
587                // these updates are applied on the next frame.
588                Some(info.next_frame)
589            } else {
590                // drop
591                controller.as_ref().unwrap().on_stop(&anim);
592                None
593            }
594        }));
595
596        vars.ans_next_frame = Some(Deadline(DInstant::EPOCH));
597
598        vars.wake_app();
599
600        handle
601    }
602
603    fn update_animations_impl(&self, timer: &mut dyn AnimationTimer) {
604        let mut vars = VARS_SV.write();
605        if let Some(next_frame) = vars.ans_next_frame
606            && timer.elapsed(next_frame)
607        {
608            let mut animations = mem::take(vars.ans_animations.get_mut());
609            debug_assert!(!animations.is_empty());
610
611            let info = AnimationUpdateInfo {
612                animations_enabled: vars.animations_enabled.get(),
613                time_scale: vars.animation_time_scale.get(),
614                now: timer.now(),
615                next_frame: next_frame + vars.frame_duration.get(),
616            };
617
618            let mut min_sleep = Deadline(info.now + Duration::from_secs(60 * 60));
619
620            drop(vars);
621
622            animations.retain_mut(|animate| {
623                if let Some(sleep) = animate(info) {
624                    min_sleep = min_sleep.min(sleep);
625                    true
626                } else {
627                    false
628                }
629            });
630
631            let mut vars = VARS_SV.write();
632
633            let self_animations = vars.ans_animations.get_mut();
634            if !self_animations.is_empty() {
635                min_sleep = Deadline(info.now);
636            }
637            animations.append(self_animations);
638            *self_animations = animations;
639
640            if !self_animations.is_empty() {
641                vars.ans_next_frame = Some(min_sleep);
642                timer.register(min_sleep);
643            } else {
644                vars.ans_next_frame = None;
645            }
646        }
647    }
648
649    fn next_deadline_impl(&self, timer: &mut dyn AnimationTimer) {
650        if let Some(next_frame) = VARS_SV.read().ans_next_frame {
651            timer.register(next_frame);
652        }
653    }
654}
655
656#[derive(Clone, Copy)]
657struct AnimationUpdateInfo {
658    animations_enabled: bool,
659    now: DInstant,
660    time_scale: Factor,
661    next_frame: Deadline,
662}