Skip to main content

zng_var/
var_any.rs

1use core::fmt;
2use std::{
3    any::{Any, TypeId},
4    borrow::Cow,
5    marker::PhantomData,
6    mem,
7    sync::Arc,
8};
9
10use parking_lot::Mutex;
11use smallbox::{SmallBox, smallbox};
12use zng_clone_move::clmv;
13use zng_txt::{Txt, formatx};
14
15use crate::{
16    AnyVarModify, AnyVarValue, BoxAnyVarValue, VARS, Var, VarCapability, VarHandle, VarHandles, VarImpl, VarIsReadOnlyError, VarModify,
17    VarModifyUpdate, VarUpdateId, VarValue, WeakVarImpl,
18    animation::{Animation, AnimationController, AnimationHandle, AnimationStopFn},
19    any_contextual_var,
20};
21
22/// Variable of any type.
23pub struct AnyVar(pub(crate) crate::var_impl::DynAnyVar);
24impl Clone for AnyVar {
25    fn clone(&self) -> Self {
26        Self(self.0.clone_dyn())
27    }
28}
29impl fmt::Debug for AnyVar {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.debug_tuple("AnyVar").field(&self.0).finish()
32    }
33}
34/// Value.
35impl AnyVar {
36    /// Visit a reference to the current value.
37    pub fn with<O>(&self, visitor: impl FnOnce(&dyn AnyVarValue) -> O) -> O {
38        let mut once = Some(visitor);
39        let mut output = None;
40        self.0.with(&mut |v| {
41            output = Some(once.take().unwrap()(v));
42        });
43        output.unwrap()
44    }
45
46    /// Get a clone of the current value.
47    pub fn get(&self) -> BoxAnyVarValue {
48        self.0.get()
49    }
50
51    /// Debug format the current value.
52    pub fn get_debug(&self, alternate: bool) -> Txt {
53        let mut r = Txt::default();
54        self.0.with(&mut |v| {
55            r = if alternate { formatx!("{v:#?}") } else { formatx!("{v:?}") };
56        });
57        r
58    }
59
60    /// Gets if the value updated.
61    ///
62    /// Returns `true` if the [`last_update`] is the current one. Note that this will only work reliably in
63    /// UI code that is synchronized with app updates, prefer [`wait_update`] in async code.
64    ///
65    /// [`last_update`]: Self::last_update
66    /// [`wait_update`]: Self::wait_update
67    pub fn is_new(&self) -> bool {
68        self.last_update() == VARS.update_id()
69    }
70
71    /// Gets a clone of the current value if it [`is_new`].
72    ///
73    /// [`is_new`]: Self::is_new
74    pub fn get_new(&self) -> Option<BoxAnyVarValue> {
75        if self.is_new() { Some(self.get()) } else { None }
76    }
77
78    /// Visit a reference to the current value if it [`is_new`].
79    ///
80    /// [`is_new`]: Self::is_new
81    pub fn with_new<O>(&self, visitor: impl FnOnce(&dyn AnyVarValue) -> O) -> Option<O> {
82        if self.is_new() { Some(self.with(visitor)) } else { None }
83    }
84
85    /// Schedule `new_value` to be assigned next update, if the variable is not read-only.
86    ///
87    /// Panics if the value type does not match.
88    pub fn try_set(&self, new_value: BoxAnyVarValue) -> Result<(), VarIsReadOnlyError> {
89        if new_value.type_id() != self.value_type() {
90            #[cfg(feature = "type_names")]
91            panic!(
92                "cannot set `{}` on variable of type `{}`",
93                new_value.type_name(),
94                self.value_type_name()
95            );
96            #[cfg(not(feature = "type_names"))]
97            panic!("cannot set variable, type mismatch");
98        }
99        self.handle_modify(self.0.set(new_value))
100    }
101
102    /// Schedule `new_value` to be assigned next update.
103    ///
104    /// If the variable is read-only this is ignored and a DEBUG level log is recorded.
105    /// Use [`try_set`] to get an error for read-only vars.
106    ///
107    /// [`try_set`]: Self::try_set
108    pub fn set(&self, new_value: BoxAnyVarValue) {
109        trace_debug_error!(self.try_set(new_value))
110    }
111
112    /// Schedule an update notification, without actually changing the value, if the variable is not read-only.
113    pub fn try_update(&self) -> Result<(), VarIsReadOnlyError> {
114        self.handle_modify(self.0.update())
115    }
116
117    /// Show variable value as new next update, without actually changing the value.
118    ///
119    /// If the variable is read-only this is ignored and a DEBUG level log is recorded.
120    /// Use [`try_update`] to get an error for read-only vars.
121    ///
122    /// [`try_update`]: Self::try_set
123    pub fn update(&self) {
124        trace_debug_error!(self.try_update())
125    }
126
127    /// Schedule `modify` to be called on the value for the next update, if the variable is not read-only.
128    ///
129    /// If the [`AnyVarModify`] closure input is deref_mut the variable will notify an update.
130    pub fn try_modify(&self, modify: impl FnOnce(&mut AnyVarModify) + Send + 'static) -> Result<(), VarIsReadOnlyError> {
131        // can't have a SmallBox<dyn FnOnce> because Rust has special compiler magic for Box<dyn FnOnce>,
132        // so we wrap in an Option and FnMut that is only called once.
133        let mut modify = Some(modify);
134        let modify = move |value: &mut AnyVarModify| {
135            #[cfg(debug_assertions)]
136            let type_id = (&*value.value as &dyn Any).type_id();
137
138            modify.take().unwrap()(value);
139
140            #[cfg(debug_assertions)]
141            if !value.update.is_empty() {
142                assert_eq!((&*value.value as &dyn Any).type_id(), type_id, "AnyVar::modify changed value type");
143            }
144        };
145
146        self.handle_modify(self.0.modify(smallbox!(modify)))
147    }
148
149    /// Schedule `modify` to be called on the value for the next update, if the variable is not read-only.
150    ///
151    /// If the [`AnyVarModify`] closure input is deref_mut the variable will notify an update.
152    ///
153    /// If the variable is read-only this is ignored and a DEBUG level log is recorded.
154    /// Use [`try_modify`] to get an error for read-only vars.
155    ///
156    /// [`try_modify`]: Self::try_modify
157    pub fn modify(&self, modify: impl FnOnce(&mut AnyVarModify) + Send + 'static) {
158        trace_debug_error!(self.try_modify(modify))
159    }
160
161    /// Schedule a new `value` for the variable, it will be set in the end of the current app update to the updated
162    /// value of `other`, so if the other var has already scheduled an update, the updated value will be used.
163    ///  
164    /// This can be used just before creating a binding to start with synchronized values.
165    pub fn try_set_from(&self, other: &AnyVar) -> Result<(), VarIsReadOnlyError> {
166        if self.capabilities().is_read_only() {
167            return Err(VarIsReadOnlyError {});
168        }
169        let caps = other.capabilities();
170        if caps.is_const() {
171            return self.try_set(other.get());
172        }
173        let weak_other = if caps.is_contextual() {
174            let other = other.current_context();
175            if other.capabilities().is_const() {
176                return self.try_set(other.get());
177            }
178            other.downgrade()
179        } else {
180            other.downgrade()
181        };
182        self.try_modify(move |v| {
183            if let Some(other) = weak_other.upgrade() {
184                other.with(|ov| {
185                    if *ov != **v {
186                        // only clone if really changed
187                        let mut new_value = ov.clone_boxed();
188                        assert!(v.try_swap(&mut *new_value), "set_from other var not of the same type");
189
190                        // tag for bidi bindings
191                        v.push_tag(other.var_instance_tag());
192                    }
193                    // don't break animation of this if other just started animating after the `set_from` request was scheduled
194                    v.set_modify_importance(other.modify_importance());
195                });
196            }
197        })
198    }
199
200    /// Schedule a new `value` for the variable, it will be set in the end of the current app update to the updated
201    /// value of `other`, so if the other var has already scheduled an update, the updated value will be used.
202    ///  
203    /// This can be used just before creating a binding to start with synchronized values.
204    ///
205    /// If the variable is read-only this is ignored and a DEBUG level log is recorded.
206    /// Use [`try_set_from`] to get an error for read-only vars.
207    ///
208    /// [`try_set_from`]: Self::try_set_from
209    pub fn set_from(&self, other: &AnyVar) {
210        trace_debug_error!(self.try_set_from(other))
211    }
212
213    /// Like [`try_set_from`], but uses `map` to produce the new value from the updated value of `other`.
214    ///
215    /// [`try_set_from`]: Self::try_set_from
216    pub fn try_set_from_map(
217        &self,
218        other: &AnyVar,
219        map: impl FnOnce(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
220    ) -> Result<(), VarIsReadOnlyError> {
221        if self.capabilities().is_read_only() {
222            return Err(VarIsReadOnlyError {});
223        }
224        let caps = other.capabilities();
225        if caps.is_const() {
226            return self.try_set(other.with(map));
227        }
228        let weak_other = if caps.is_contextual() {
229            let other = other.current_context();
230            if other.capabilities().is_const() {
231                return self.try_set(other.with(map));
232            }
233            other.downgrade()
234        } else {
235            other.downgrade()
236        };
237        self.try_modify(move |v| {
238            if let Some(other) = weak_other.upgrade() {
239                other.with(|ov| {
240                    let new_value = map(ov);
241                    if v.set(new_value) {
242                        // tag for bidi bindings
243                        v.push_tag(other.var_instance_tag());
244                    }
245                    // don't break animation of this if other just started animating after the `set_from` request was scheduled
246                    v.set_modify_importance(other.modify_importance());
247                });
248            }
249        })
250    }
251
252    /// Like [`set_from`], but uses `map` to produce the new value from the updated value of `other`.
253    ///
254    /// If the variable is read-only this is ignored and a DEBUG level log is recorded.
255    /// Use [`try_set_from_map`] to get an error for read-only vars.
256    ///
257    /// [`try_set_from_map`]: Self::try_set_from_map
258    /// [`set_from`]: Self::set_from
259    pub fn set_from_map(&self, other: &AnyVar, map: impl FnOnce(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static) {
260        trace_debug_error!(self.try_set_from_map(other, map))
261    }
262
263    /// Setups a callback for just after the variable value update is applied, the closure runs in the root app context, just like
264    /// the `modify` closure. The closure must return `true` to be retained and `false` to be dropped.
265    ///
266    /// If you modify another variable in the closure modification applies in the same update, variable mapping and
267    /// binding is implemented using hooks.
268    ///
269    /// The variable store a weak reference to the callback if it has the `MODIFY` or `CAPS_CHANGE` capabilities, otherwise
270    /// the callback is discarded and [`VarHandle::dummy`] returned.
271    pub fn hook(&self, on_update: impl FnMut(&AnyVarHookArgs) -> bool + Send + 'static) -> VarHandle {
272        self.0.hook(smallbox!(on_update))
273    }
274
275    ///Awaits for a value that passes the `predicate`, including the current value.
276    #[allow(clippy::manual_async_fn)] // false positive, async fn futures are not Send + Sync
277    pub fn wait_match(&self, predicate: impl Fn(&dyn AnyVarValue) -> bool + Send + Sync) -> impl Future<Output = ()> + Send + Sync {
278        async move {
279            while !self.with(&predicate) {
280                let future = self.wait_update();
281                if self.with(&predicate) {
282                    break;
283                }
284                future.await;
285            }
286        }
287    }
288
289    /// Awaits for an update them [`get`] the value.
290    ///
291    /// [`get`]: Self::get
292    #[allow(clippy::manual_async_fn)] // false positive, async fn futures are not Send + Sync
293    pub fn wait_next(&self) -> impl Future<Output = BoxAnyVarValue> + Send + Sync {
294        async {
295            self.wait_update().await;
296            self.get()
297        }
298    }
299
300    /// Last update ID a variable was modified.
301    ///
302    /// If the ID equals [`VARS.update_id`] the variable [`is_new`].
303    ///
304    /// [`is_new`]: Self::is_new
305    /// [`VARS.update_id`]: VARS::update_id
306    pub fn last_update(&self) -> VarUpdateId {
307        self.0.last_update()
308    }
309
310    /// Awaits for the [`last_update`] to change.
311    ///
312    /// Note that [`is_new`] will be `true` when the future elapses only when polled
313    /// in sync with the UI, but it will elapse in any thread when the variable updates after the future is instantiated.
314    ///
315    /// Note that outside of the UI tree there is no variable synchronization across multiple var method calls, so
316    /// a sequence of `get(); wait_update().await; get();` can miss a value between `get` and `wait_update`. The returned
317    /// future captures the [`last_update`] at the moment this method is called, this can be leveraged by double-checking to
318    /// avoid race conditions, see the [`wait_match`] default implementation for more details.
319    ///
320    /// [`wait_match`]: Self::wait_match
321    /// [`last_update`]: Self::last_update
322    /// [`is_new`]: Self::is_new
323    pub fn wait_update(&self) -> impl Future<Output = VarUpdateId> + Send + Sync {
324        crate::future::WaitUpdateFut::new(self)
325    }
326
327    /// Debug helper for tracing the lifetime of a value in this variable.
328    ///
329    /// See [`trace_value`] for more details.
330    ///
331    /// [`trace_value`]: Var::trace_value
332    pub fn trace_value<S: Send + 'static>(&self, mut enter_value: impl FnMut(&AnyVarHookArgs) -> S + Send + 'static) -> VarHandle {
333        let span = self.with(|v| {
334            enter_value(&AnyVarHookArgs {
335                var_instance_tag: self.var_instance_tag(),
336                value: v,
337                update: false,
338                tags: &[],
339            })
340        });
341        let mut span = Some(span);
342        self.hook(move |v| {
343            let _ = span.take();
344            span = Some(enter_value(v));
345            true
346        })
347    }
348
349    fn handle_modify(&self, scheduled: bool) -> Result<(), VarIsReadOnlyError> {
350        match scheduled {
351            true => Ok(()),
352            false => Err(VarIsReadOnlyError {}),
353        }
354    }
355}
356/// Value mapping.
357impl AnyVar {
358    /// Create a mapping variable from any to any.
359    ///
360    /// The `map` closure must only output values of `value_type`, this type is validated in debug builds and
361    /// is necessary for contextualizing variables.
362    ///
363    /// See [`map`] for more details about mapping variables.
364    ///
365    /// [`map`]: Var::map
366    pub fn map_any(&self, map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static, value_type: TypeId) -> AnyVar {
367        let caps = self.capabilities();
368
369        #[cfg(debug_assertions)]
370        let map = {
371            let mut map = map;
372            move |v: &dyn AnyVarValue| {
373                let output = map(v);
374                assert_eq!(value_type, output.type_id(), "map_any value type does not match");
375                output
376            }
377        };
378
379        if caps.is_contextual() {
380            let me = self.clone();
381            let map = Arc::new(Mutex::new(map));
382            // clone again inside the context to get a new clear (me as contextual_var)
383            return any_contextual_var(move || me.clone().map_any_tail(clmv!(map, |v| map.lock()(v)), None), value_type);
384        }
385        self.map_any_tail(map, Some(caps))
386    }
387    // to avoid infinite closure type (contextual case)
388    fn map_any_tail(
389        &self,
390        mut map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
391        caps: Option<VarCapability>,
392    ) -> AnyVar {
393        let me = self.current_context();
394        let caps = caps.unwrap_or_else(|| me.capabilities());
395
396        let mut init_value = None;
397        me.with(&mut |v: &dyn AnyVarValue| init_value = Some(map(v)));
398        let init_value = init_value.unwrap();
399
400        if caps.is_const() {
401            return crate::any_const_var(init_value);
402        }
403
404        let output = crate::any_var_derived(init_value, &me);
405        me.bind_impl(&output, map).perm();
406        output.hold(me).perm();
407
408        output.read_only()
409    }
410
411    /// Create a strongly typed mapping variable.
412    ///
413    /// The `map` closure must produce a strongly typed value for every update of this variable.
414    ///
415    /// See [`map`] for more details about mapping variables.
416    ///
417    /// [`map`]: Var::map
418    pub fn map<O: VarValue>(&self, mut map: impl FnMut(&dyn AnyVarValue) -> O + Send + 'static) -> Var<O> {
419        let mapping = self.map_any(move |v| BoxAnyVarValue::new(map(v)), TypeId::of::<O>());
420        Var::new_any(mapping)
421    }
422
423    /// Create a mapping variable that contains the debug formatted value from this variable.
424    ///
425    /// See [`map`] for more details about mapping variables.
426    ///
427    /// [`map`]: Var::map
428    pub fn map_debug(&self, alternate: bool) -> Var<Txt> {
429        if alternate {
430            self.map(|v| formatx!("{v:#?}"))
431        } else {
432            self.map(|v| formatx!("{v:?}"))
433        }
434    }
435
436    /// Create a mapping variable that can skip updates.
437    ///
438    /// The `map` closure is called for every update this variable and if it returns a new value the mapping variable updates.
439    ///
440    /// If the `map` closure does not produce a value on init the `fallback_init` closure is called.
441    ///
442    /// See [`filter_map`] for more details about mapping variables.
443    ///
444    /// [`filter_map`]: Var::filter_map
445    pub fn filter_map_any(
446        &self,
447        map: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
448        fallback_init: impl Fn() -> BoxAnyVarValue + Send + 'static,
449        value_type: TypeId,
450    ) -> AnyVar {
451        let caps = self.capabilities();
452
453        if caps.is_contextual() {
454            let me = self.clone();
455            let fns = Arc::new(Mutex::new((map, fallback_init)));
456            // clone again inside the context to get a new clear (me as contextual_var)
457            return any_contextual_var(
458                move || {
459                    me.clone()
460                        .filter_map_any_tail(clmv!(fns, |v| fns.lock().0(v)), clmv!(fns, || fns.lock().1()), None)
461                },
462                value_type,
463            );
464        }
465
466        self.filter_map_any_tail(map, fallback_init, Some(caps))
467    }
468    // to avoid infinite closure type (contextual case)
469    fn filter_map_any_tail(
470        &self,
471        mut map: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
472        fallback_init: impl Fn() -> BoxAnyVarValue + Send + 'static,
473        caps: Option<VarCapability>,
474    ) -> AnyVar {
475        let me = self.current_context();
476        let caps = caps.unwrap_or_else(|| me.capabilities());
477
478        let mut init_value = None;
479        me.with(&mut |v: &dyn AnyVarValue| init_value = map(v));
480        let init_value = match init_value {
481            Some(v) => v,
482            None => fallback_init(),
483        };
484
485        if caps.is_const() {
486            return crate::any_const_var(init_value);
487        }
488
489        let output = crate::any_var_derived(init_value, &me);
490        let weak_output = output.downgrade();
491
492        me.hook(move |args| {
493            match weak_output.upgrade() {
494                Some(o) => {
495                    if let Some(new_value) = map(args.value) {
496                        o.set(new_value);
497                    }
498                    true
499                }
500                None => {
501                    // don't retain, output var dropped
502                    false
503                }
504            }
505        })
506        .perm();
507        output.hold(me).perm();
508
509        output.read_only()
510    }
511
512    /// Create a strongly typed mapping variable that can skip updates.
513    ///
514    /// The `map` closure is called for every update this variable and if it returns a new value the mapping variable updates.
515    ///
516    /// If the `map` closure does not produce a value on init the `fallback_init` closure is called.
517    ///
518    /// See [`filter_map`] for more details about mapping variables.
519    ///
520    /// [`filter_map`]: Var::filter_map
521    pub fn filter_map<O: VarValue>(
522        &self,
523        mut map: impl FnMut(&dyn AnyVarValue) -> Option<O> + Send + 'static,
524        fallback_init: impl Fn() -> O + Send + 'static,
525    ) -> Var<O> {
526        let mapping = self.filter_map_any(
527            move |v| map(v).map(BoxAnyVarValue::new),
528            move || BoxAnyVarValue::new(fallback_init()),
529            TypeId::of::<O>(),
530        );
531        Var::new_any(mapping)
532    }
533
534    /// Create a bidirectional mapping variable.
535    ///
536    /// The `map` closure must only output values of `value_type`, predefining this type is
537    /// is necessary for contextualizing variables.
538    ///
539    /// The `map_back` closure must produce values of the same type as this variable, this variable will panic
540    /// if map back value is not the same.
541    ///
542    /// See [`map_bidi`] for more details about bidirectional mapping variables.
543    ///
544    /// [`map_bidi`]: Var::map_bidi
545    pub fn map_bidi_any(
546        &self,
547        map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
548        map_back: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
549        value_type: TypeId,
550    ) -> AnyVar {
551        let caps = self.capabilities();
552
553        if caps.is_contextual() {
554            let me = self.clone();
555            let fns = Arc::new(Mutex::new((map, map_back)));
556            // clone again inside the context to get a new clear (me as contextual_var)
557            return any_contextual_var(
558                move || {
559                    me.clone()
560                        .map_bidi_tail(clmv!(fns, |v| fns.lock().0(v)), clmv!(fns, |v| fns.lock().1(v)), None)
561                },
562                value_type,
563            );
564        }
565
566        self.map_bidi_tail(map, map_back, Some(caps))
567    }
568    fn map_bidi_tail(
569        &self,
570        mut map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
571        map_back: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
572        caps: Option<VarCapability>,
573    ) -> AnyVar {
574        let me = self.current_context();
575        let caps = caps.unwrap_or_else(|| me.capabilities());
576
577        let mut init_value = None;
578        me.with(&mut |v: &dyn AnyVarValue| init_value = Some(map(v)));
579        let init_value = init_value.unwrap();
580
581        if caps.is_const() {
582            return crate::any_const_var(init_value);
583        }
584
585        let output = crate::any_var_derived(init_value, &me);
586
587        me.bind_map_bidi_any(&output, map, map_back).perm();
588        output.hold(me).perm();
589
590        output
591    }
592
593    /// Create a bidirectional mapping variable that modifies the source variable on change, instead of mapping back.
594    ///
595    /// The `map` closure must only output values of `value_type`, predefining this type is
596    /// is necessary for contextualizing variables.
597    ///
598    /// The `modify_back` closure is called to modify the source variable with the new output value.
599    ///
600    /// See [`map_bidi_modify`] for more details about bidirectional mapping variables.
601    ///
602    /// [`map_bidi_modify`]: Var::map_bidi_modify
603    pub fn map_bidi_modify_any(
604        &self,
605        map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
606        modify_back: impl FnMut(&dyn AnyVarValue, &mut AnyVarModify) + Send + 'static,
607        value_type: TypeId,
608    ) -> AnyVar {
609        let caps = self.capabilities();
610
611        if caps.is_contextual() {
612            let me = self.clone();
613            let fns = Arc::new(Mutex::new((map, modify_back)));
614            // clone again inside the context to get a new clear (me as contextual_var)
615            return any_contextual_var(
616                move || {
617                    me.clone()
618                        .map_bidi_modify_tail(clmv!(fns, |v| fns.lock().0(v)), clmv!(fns, |v, m| fns.lock().1(v, m)), None)
619                },
620                value_type,
621            );
622        }
623        self.map_bidi_modify_tail(map, modify_back, Some(caps))
624    }
625    fn map_bidi_modify_tail(
626        &self,
627        mut map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
628        modify_back: impl FnMut(&dyn AnyVarValue, &mut AnyVarModify) + Send + 'static,
629        caps: Option<VarCapability>,
630    ) -> AnyVar {
631        let me = self.current_context();
632        let caps = caps.unwrap_or_else(|| me.capabilities());
633
634        let mut init_value = None;
635        me.with(&mut |v: &dyn AnyVarValue| init_value = Some(map(v)));
636        let init_value = init_value.unwrap();
637
638        if caps.is_const() {
639            return crate::any_const_var(init_value);
640        }
641
642        let output = crate::any_var_derived(init_value, &me);
643        self.bind_map_any(&output, map).perm();
644        output.bind_modify_any(&me, modify_back).perm();
645        output.hold(me).perm();
646        output
647    }
648
649    /// Create a bidirectional mapping variable that can skip updates.
650    ///
651    /// The `map` closure must only output values of `value_type`, predefining this type is
652    /// is necessary for contextualizing variables.
653    ///
654    /// The `map_back` closure must produce values of the same type as this variable, this variable will panic
655    /// if map back value is not the same.
656    ///
657    /// See [`filter_map_bidi`] for more details about bidirectional mapping variables.
658    ///
659    /// [`filter_map_bidi`]: Var::filter_map_bidi
660    pub fn filter_map_bidi_any(
661        &self,
662        map: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
663        map_back: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
664        fallback_init: impl Fn() -> BoxAnyVarValue + Send + 'static,
665        value_type: TypeId,
666    ) -> AnyVar {
667        let caps = self.capabilities();
668
669        if caps.is_contextual() {
670            let me = self.clone();
671            let fns = Arc::new(Mutex::new((map, map_back, fallback_init)));
672            // clone again inside the context to get a new clear (me as contextual_var)
673            return any_contextual_var(
674                move || {
675                    me.clone().filter_map_bidi_tail(
676                        clmv!(fns, |v| fns.lock().0(v)),
677                        clmv!(fns, |v| fns.lock().1(v)),
678                        clmv!(fns, || fns.lock().2()),
679                        None,
680                    )
681                },
682                value_type,
683            );
684        }
685
686        self.filter_map_bidi_tail(map, map_back, fallback_init, Some(caps))
687    }
688    fn filter_map_bidi_tail(
689        &self,
690        mut map: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
691        map_back: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
692        fallback_init: impl Fn() -> BoxAnyVarValue + Send + 'static,
693        caps: Option<VarCapability>,
694    ) -> AnyVar {
695        let me = self.current_context();
696        let caps = caps.unwrap_or_else(|| me.capabilities());
697
698        let mut init_value = None;
699        me.with(&mut |v: &dyn AnyVarValue| init_value = map(v));
700        let init_value = init_value.unwrap_or_else(&fallback_init);
701
702        if caps.is_const() {
703            return crate::any_const_var(init_value);
704        }
705
706        let output = crate::any_var_derived(init_value, &me);
707
708        me.bind_filter_map_bidi_any(&output, map, map_back).perm();
709        output.hold(me).perm();
710
711        output
712    }
713
714    /// Create a mapping variable from any to any that *unwraps* an inner variable.
715    ///
716    /// See [`flat_map`] for more details about flat mapping variables.
717    ///
718    /// [`flat_map`]: Var::flat_map
719    pub fn flat_map_any(&self, map: impl FnMut(&dyn AnyVarValue) -> AnyVar + Send + 'static, value_type: TypeId) -> AnyVar {
720        let caps = self.capabilities();
721
722        if caps.is_contextual() {
723            let me = self.clone();
724            let map = Arc::new(Mutex::new(map));
725            // clone again inside the context to get a new clear (me as contextual_var)
726            return any_contextual_var(move || me.clone().flat_map_tail(clmv!(map, |v| map.lock()(v)), None), value_type);
727        }
728
729        self.flat_map_tail(map, Some(caps))
730    }
731    fn flat_map_tail(&self, map: impl FnMut(&dyn AnyVarValue) -> AnyVar + Send + 'static, caps: Option<VarCapability>) -> AnyVar {
732        let me = self.current_context();
733        let caps = caps.unwrap_or_else(|| me.capabilities());
734        if caps.is_const() {
735            return me.with(map);
736        }
737        let mapping = crate::var_impl::flat_map_var::FlatMapVar::new(me, smallbox!(map));
738        AnyVar(crate::DynAnyVar::FlatMap(mapping))
739    }
740
741    /// Create a strongly typed flat mapping variable.
742    ///
743    /// See [`flat_map`] for more details about mapping variables.
744    ///
745    /// [`flat_map`]: Var::flat_map
746    pub fn flat_map<O: VarValue>(&self, mut map: impl FnMut(&dyn AnyVarValue) -> Var<O> + Send + 'static) -> Var<O> {
747        let mapping = self.flat_map_any(
748            move |v| {
749                let typed = map(v);
750                typed.into()
751            },
752            TypeId::of::<O>(),
753        );
754        Var::new_any(mapping)
755    }
756}
757/// Binding
758impl AnyVar {
759    /// Bind `other` to receive the new values from this variable.
760    ///
761    /// See [`bind`] for more details about variable bindings.
762    ///
763    /// [`bind`]: Var::bind
764    pub fn bind(&self, other: &AnyVar) -> VarHandle {
765        self.bind_map_any(other, |v| v.clone_boxed())
766    }
767
768    /// Like [`bind`] but also sets `other` to the current value.
769    ///
770    /// See [`set_bind`] for more details.
771    ///
772    /// [`bind`]: Self::bind
773    /// [`set_bind`]: Var::set_bind
774    pub fn set_bind(&self, other: &AnyVar) -> VarHandle {
775        other.set_from(self);
776        self.bind(other)
777    }
778
779    /// Bind `other` to receive the new values mapped from this variable.
780    ///
781    /// See [`bind_map`] for more details about variable bindings.
782    ///
783    /// [`bind_map`]: Var::bind_map
784    pub fn bind_map_any(&self, other: &AnyVar, map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static) -> VarHandle {
785        let other_caps = other.capabilities();
786        if self.capabilities().is_const() || other_caps.is_always_read_only() {
787            return VarHandle::dummy();
788        }
789
790        if other_caps.is_contextual() {
791            self.bind_impl(&other.current_context(), map)
792        } else {
793            self.bind_impl(other, map)
794        }
795    }
796
797    /// Bind `other` to be modified when this variable updates.
798    ///
799    /// See [`bind_modify`] for more details about modify bindings.
800    ///
801    /// [`bind_modify`]: Var::bind_modify
802    pub fn bind_modify_any(&self, other: &AnyVar, modify: impl FnMut(&dyn AnyVarValue, &mut AnyVarModify) + Send + 'static) -> VarHandle {
803        let self_caps = other.capabilities();
804        let other_caps = other.capabilities();
805        if self_caps.is_const() || other_caps.is_always_read_only() {
806            return VarHandle::dummy();
807        }
808
809        let mut source = Cow::Borrowed(self);
810        if self_caps.is_contextual() {
811            source = Cow::Owned(self.current_context());
812        }
813
814        if other_caps.is_contextual() {
815            source.bind_modify_impl(&other.current_context(), modify)
816        } else {
817            source.bind_modify_impl(other, modify)
818        }
819    }
820
821    /// Like [`bind_map_any`] but also sets `other` to the current value.
822    ///
823    /// See [`set_bind_map`] for more details.
824    ///
825    /// [`bind_map_any`]: Self::bind_map_any
826    /// [`set_bind_map`]: Var::set_bind_map
827    pub fn set_bind_map_any(&self, other: &AnyVar, map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static) -> VarHandle {
828        let map = Arc::new(Mutex::new(map));
829        other.set_from_map(self, clmv!(map, |v| map.lock()(v)));
830
831        enum MapFn<F> {
832            Hot(F),
833            Cold(Arc<Mutex<F>>),
834            Taken,
835        }
836        let mut map = MapFn::Cold(map);
837        self.bind_map_any(other, move |v| match mem::replace(&mut map, MapFn::Taken) {
838            MapFn::Hot(mut f) => {
839                let r = f(v);
840                map = MapFn::Hot(f);
841                r
842            }
843            MapFn::Cold(f) => match Arc::try_unwrap(f) {
844                Ok(f) => {
845                    let mut f = f.into_inner();
846                    let r = f(v);
847                    map = MapFn::Hot(f);
848                    r
849                }
850                Err(f) => {
851                    let r = f.lock()(v);
852                    map = MapFn::Cold(f);
853                    r
854                }
855            },
856            MapFn::Taken => unreachable!(),
857        })
858    }
859
860    /// Bind strongly typed `other` to receive the new values mapped from this variable.
861    ///
862    /// See [`bind_map`] for more details about variable bindings.
863    ///
864    /// [`bind_map`]: Var::bind_map
865    pub fn bind_map<O: VarValue>(&self, other: &Var<O>, mut map: impl FnMut(&dyn AnyVarValue) -> O + Send + 'static) -> VarHandle {
866        self.bind_map_any(other, move |v| BoxAnyVarValue::new(map(v)))
867    }
868
869    /// Bind `other` to be modified when this variable updates.
870    ///
871    /// See [`bind_modify`] for more details about modify bindings.
872    ///
873    /// [`bind_modify`]: Var::bind_modify
874    pub fn bind_modify<O: VarValue>(
875        &self,
876        other: &Var<O>,
877        mut modify: impl FnMut(&dyn AnyVarValue, &mut VarModify<O>) + Send + 'static,
878    ) -> VarHandle {
879        self.bind_modify_any(other, move |v, m| modify(v, &mut m.downcast::<O>().unwrap()))
880    }
881
882    /// Like [`bind_map_any`] but also sets `other` to the current value.
883    ///
884    /// See [`set_bind_map`] for more details.
885    ///
886    /// [`bind_map_any`]: Self::bind_map_any
887    /// [`set_bind_map`]: Var::set_bind_map
888    pub fn set_bind_map<O: VarValue>(&self, other: &Var<O>, mut map: impl FnMut(&dyn AnyVarValue) -> O + Send + 'static) -> VarHandle {
889        self.set_bind_map_any(other, move |v| BoxAnyVarValue::new(map(v)))
890    }
891
892    /// Bind `other` to receive the new values from this variable and this variable to receive new values from `other`.
893    ///
894    /// See [`bind_bidi`] for more details about variable bindings.
895    ///
896    /// [`bind_bidi`]: Var::bind_bidi
897    pub fn bind_bidi(&self, other: &AnyVar) -> VarHandles {
898        self.bind_map_bidi_any(other, |v| v.clone_boxed(), |v| v.clone_boxed())
899    }
900
901    /// Bind `other` to receive the new mapped values from this variable and this variable to receive new mapped values from `other`.
902    ///
903    /// See [`bind_bidi`] for more details about variable bindings.
904    ///
905    /// [`bind_bidi`]: Var::bind_bidi
906    pub fn bind_map_bidi_any(
907        &self,
908        other: &AnyVar,
909        map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
910        map_back: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static,
911    ) -> VarHandles {
912        assert!(!self.var_eq(other), "cannot bind var to itself");
913
914        let self_cap = self.capabilities();
915        let other_cap = other.capabilities();
916        if self_cap.is_const() || other_cap.is_const() {
917            return VarHandles::dummy();
918        }
919        if self_cap.is_always_read_only() {
920            return self.bind_map_any(other, map).into();
921        }
922        if other_cap.is_always_read_only() {
923            return other.bind_map_any(self, map_back).into();
924        }
925
926        let a = if other_cap.is_contextual() {
927            self.bind_impl(&other.current_context(), map)
928        } else {
929            self.bind_impl(other, map)
930        };
931        let b = if self_cap.is_contextual() {
932            other.bind_impl(&self.current_context(), map_back)
933        } else {
934            other.bind_impl(self, map_back)
935        };
936
937        a.chain(b)
938    }
939
940    /// Bind `other` to be modified when this variable updates and this variable to be modified when `other` updates.
941    ///
942    /// See [`bind_modify_bidi`] for more details about modify bindings.
943    ///
944    /// [`bind_modify_bidi`]: Var::bind_modify_bidi
945    pub fn bind_modify_bidi_any(
946        &self,
947        other: &AnyVar,
948        modify: impl FnMut(&dyn AnyVarValue, &mut AnyVarModify) + Send + 'static,
949        modify_back: impl FnMut(&dyn AnyVarValue, &mut AnyVarModify) + Send + 'static,
950    ) -> VarHandles {
951        let self_cap = self.capabilities();
952        let other_cap = other.capabilities();
953        if self_cap.is_const() || other_cap.is_const() {
954            return VarHandles::dummy();
955        }
956        if self_cap.is_always_read_only() {
957            return self.bind_modify_any(other, modify).into();
958        }
959        if other_cap.is_always_read_only() {
960            return other.bind_modify_any(self, modify_back).into();
961        }
962
963        let mut self_ = Cow::Borrowed(self);
964        if self_cap.is_contextual() {
965            self_ = Cow::Owned(self.current_context());
966        }
967
968        let a = if other_cap.is_contextual() {
969            self_.bind_modify_impl(&other.current_context(), modify)
970        } else {
971            self_.bind_modify_impl(other, modify)
972        };
973        let b = other.bind_modify_impl(&self_, modify_back);
974
975        a.chain(b)
976    }
977
978    /// Bind `other` to be modified when this variable updates and this variable to be modified when `other` updates.
979    ///
980    /// See [`bind_modify_bidi`] for more details about modify bindings.
981    ///
982    /// [`bind_modify_bidi`]: Var::bind_modify_bidi
983    pub fn bind_modify_bidi<O: VarValue>(
984        &self,
985        other: &Var<O>,
986        mut modify: impl FnMut(&dyn AnyVarValue, &mut VarModify<O>) + Send + 'static,
987        mut modify_back: impl FnMut(&O, &mut AnyVarModify) + Send + 'static,
988    ) -> VarHandles {
989        self.bind_modify_bidi_any(
990            other,
991            move |v, m| modify(v, &mut m.downcast::<O>().unwrap()),
992            move |v, m| modify_back(v.downcast_ref::<O>().unwrap(), m),
993        )
994    }
995
996    /// Bind `other` to receive the new values filtered mapped from this variable.
997    ///
998    /// See [`bind_filter_map`] for more details about variable bindings.
999    ///
1000    /// [`bind_filter_map`]: Var::bind_filter_map
1001    pub fn bind_filter_map_any(
1002        &self,
1003        other: &AnyVar,
1004        map: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
1005    ) -> VarHandle {
1006        if self.capabilities().is_const() || other.capabilities().is_always_read_only() {
1007            return VarHandle::dummy();
1008        }
1009
1010        self.bind_filter_map_impl(other, map)
1011    }
1012
1013    /// Bind strongly typed `other` to receive the new values filtered mapped from this variable.
1014    ///
1015    /// See [`bind_filter_map`] for more details about variable bindings.
1016    ///
1017    /// [`bind_filter_map`]: Var::bind_filter_map
1018    pub fn bind_filter_map<O: VarValue>(
1019        &self,
1020        other: &AnyVar,
1021        mut map: impl FnMut(&dyn AnyVarValue) -> Option<O> + Send + 'static,
1022    ) -> VarHandle {
1023        self.bind_filter_map_any(other, move |v| map(v).map(BoxAnyVarValue::new))
1024    }
1025
1026    /// Bind `other` to receive the new filtered mapped values from this variable and this variable to receive
1027    /// new filtered mapped values from `other`.
1028    ///
1029    /// See [`bind_filter_map_bidi`] for more details about variable bindings.
1030    ///
1031    /// [`bind_filter_map_bidi`]: Var::bind_filter_map_bidi
1032    pub fn bind_filter_map_bidi_any(
1033        &self,
1034        other: &AnyVar,
1035        map: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
1036        map_back: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
1037    ) -> VarHandles {
1038        let self_cap = self.capabilities();
1039        let other_cap = other.capabilities();
1040        if self_cap.is_const() || other_cap.is_const() {
1041            return VarHandles::dummy();
1042        }
1043        if self_cap.is_always_read_only() {
1044            return self.bind_filter_map_any(other, map).into();
1045        }
1046        if other_cap.is_always_read_only() {
1047            return other.bind_filter_map_any(self, map_back).into();
1048        }
1049
1050        let a = self.bind_filter_map_impl(other, map);
1051        let b = other.bind_filter_map_impl(self, map_back);
1052
1053        a.chain(b)
1054    }
1055
1056    /// Expects `other` to be contextualized
1057    fn bind_impl(&self, other: &AnyVar, mut map: impl FnMut(&dyn AnyVarValue) -> BoxAnyVarValue + Send + 'static) -> VarHandle {
1058        let weak_other = other.downgrade();
1059        self.hook(move |args| {
1060            if let Some(other) = weak_other.upgrade() {
1061                if args.contains_tag(&other.var_instance_tag()) {
1062                    // skip circular update
1063                    return true;
1064                }
1065                let self_tag = args.var_instance_tag();
1066
1067                let new_value = map(args.value());
1068                let update = args.update();
1069                other.modify(move |v| {
1070                    if v.set(new_value) || update {
1071                        // tag to avoid circular update
1072                        v.push_tag(self_tag);
1073                    }
1074                    if update {
1075                        // propagate explicit update requests
1076                        v.update();
1077                    }
1078                });
1079                true
1080            } else {
1081                false
1082            }
1083        })
1084    }
1085
1086    /// Expects `self` and `other` to be contextualized
1087    fn bind_modify_impl(&self, other: &AnyVar, modify: impl FnMut(&dyn AnyVarValue, &mut AnyVarModify) + Send + 'static) -> VarHandle {
1088        let weak_other = other.downgrade();
1089        let weak_self = self.downgrade();
1090        let modify = Arc::new(Mutex::new(modify));
1091        self.hook(move |args| {
1092            if let Some(other) = weak_other.upgrade() {
1093                if args.contains_tag(&other.var_instance_tag()) {
1094                    // skip circular update
1095                    return true;
1096                }
1097
1098                let self_ = weak_self.upgrade().unwrap();
1099                let update = args.update();
1100                other.modify(clmv!(modify, |v| {
1101                    let prev_update = mem::replace(&mut v.update, VarModifyUpdate::empty());
1102                    self_.with(|source| {
1103                        modify.lock()(source, v);
1104                    });
1105
1106                    if !v.update.is_empty() || update {
1107                        // tag to avoid circular update
1108                        v.push_tag(self_.var_instance_tag());
1109                    }
1110                    if update {
1111                        // propagate explicit update requests
1112                        v.update();
1113                    }
1114                    v.update |= prev_update;
1115                }));
1116                true
1117            } else {
1118                false
1119            }
1120        })
1121    }
1122
1123    fn bind_filter_map_impl(
1124        &self,
1125        other: &AnyVar,
1126        mut map: impl FnMut(&dyn AnyVarValue) -> Option<BoxAnyVarValue> + Send + 'static,
1127    ) -> VarHandle {
1128        let weak_other = other.downgrade();
1129        self.hook(move |args| {
1130            if let Some(other) = weak_other.upgrade() {
1131                if args.contains_tag(&other.var_instance_tag()) {
1132                    // skip circular update
1133                    return true;
1134                }
1135                let self_tag = args.var_instance_tag();
1136                let update = args.update();
1137                if let Some(new_value) = map(args.value()) {
1138                    other.modify(move |v| {
1139                        if v.set(new_value) || update {
1140                            // tag to avoid circular update
1141                            v.push_tag(self_tag);
1142                        }
1143                        if update {
1144                            // propagate explicit update requests
1145                            v.update();
1146                        }
1147                    });
1148                } else if update {
1149                    other.modify(move |v| {
1150                        v.update();
1151                        v.push_tag(self_tag);
1152                    });
1153                }
1154
1155                true
1156            } else {
1157                false
1158            }
1159        })
1160    }
1161}
1162/// Animation
1163impl AnyVar {
1164    /// Schedule an animation that targets this variable.
1165    ///
1166    /// See [`animate`] for more details.
1167    ///
1168    /// [`animate`]: Var::animate
1169    pub fn animate(&self, animate: impl FnMut(&Animation, &mut AnyVarModify) + Send + 'static) -> AnimationHandle {
1170        if !self.capabilities().is_always_read_only() {
1171            let target = self.current_context();
1172            if !target.capabilities().is_always_read_only() {
1173                // target var can be animated.
1174
1175                let wk_target = target.downgrade();
1176                let animate = Arc::new(Mutex::new(animate));
1177
1178                return VARS.animate(move |args| {
1179                    // animation
1180
1181                    if let Some(target) = wk_target.upgrade() {
1182                        // target still exists
1183
1184                        if target.modify_importance() > VARS.current_modify().importance {
1185                            // var modified by a more recent animation or directly, this animation cannot
1186                            // affect it anymore.
1187                            args.stop();
1188                            return;
1189                        }
1190
1191                        // try update
1192                        let r = target.try_modify(clmv!(animate, args, |value| {
1193                            (animate.lock())(&args, value);
1194                        }));
1195
1196                        if let Err(VarIsReadOnlyError { .. }) = r {
1197                            // var can maybe change to allow write again, but we wipe all animations anyway.
1198                            args.stop();
1199                        }
1200                    } else {
1201                        // target dropped.
1202                        args.stop();
1203                    }
1204                });
1205            }
1206        }
1207        AnimationHandle::dummy()
1208    }
1209
1210    /// Schedule animations started by `animate`, the closure is called once at the start to begin, then again every time
1211    /// the variable stops animating.
1212    ///
1213    /// See [`sequence`] for more details.
1214    ///
1215    /// [`sequence`]: Var::sequence
1216    pub fn sequence(&self, animate: impl FnMut(AnyVar) -> AnimationHandle + Send + 'static) -> VarHandle {
1217        if !self.capabilities().is_always_read_only() {
1218            let target = self.current_context();
1219            if !target.capabilities().is_always_read_only() {
1220                // target var can be animated.
1221
1222                let (handle_hook, handle) = VarHandle::new();
1223
1224                let wk_target = target.downgrade();
1225
1226                #[derive(Clone)]
1227                struct SequenceController(Arc<dyn Fn() + Send + Sync + 'static>);
1228                impl AnimationController for SequenceController {
1229                    fn on_stop(&self, _: &Animation) {
1230                        let ctrl = self.clone();
1231                        VARS.with_animation_controller(ctrl, || (self.0)());
1232                    }
1233                }
1234                let animate = Mutex::new(animate);
1235                let animate = Arc::new(move || {
1236                    if let Some(target) = wk_target.upgrade()
1237                        && target.modify_importance() <= VARS.current_modify().importance()
1238                        && handle_hook.is_alive()
1239                        && VARS.animations_enabled().get()
1240                    {
1241                        (animate.lock())(target).perm();
1242                    }
1243                });
1244                VARS.with_animation_controller(SequenceController(animate.clone()), || {
1245                    animate();
1246                });
1247
1248                return handle;
1249            }
1250        }
1251        VarHandle::dummy()
1252    }
1253
1254    /// If the variable current value was set by an active animation.
1255    ///
1256    /// The variable [`is_new`] when this changes to `true`, but it **may not be new** when the value changes to `false`.
1257    /// If the variable is not updated at the last frame of the animation that has last set it, it will not update
1258    /// just because that animation has ended. You can use [`hook_animation_stop`] to get a notification when the
1259    /// last animation stops, or use [`wait_animation`] to get a future that is ready when `is_animating` changes
1260    /// from `true` to `false`.
1261    ///
1262    /// [`is_new`]: AnyVar::is_new
1263    /// [`hook_animation_stop`]: AnyVar::hook_animation_stop
1264    /// [`wait_animation`]: AnyVar::wait_animation
1265    pub fn is_animating(&self) -> bool {
1266        self.0.is_animating()
1267    }
1268
1269    /// Gets the minimum *importance* clearance that is needed to modify this variable.
1270    ///
1271    /// Direct modify/set requests always apply, but requests made from inside an animation only apply if
1272    /// the animation *importance* is greater or equal this value.This is the mechanism that ensures that only
1273    /// the latest animation has *control* of the variable value.
1274    ///
1275    /// [`MODIFY`]: VarCapability::MODIFY
1276    /// [`VARS.current_modify`]: VARS::current_modify
1277    /// [`VARS.animate`]: VARS::animate
1278    pub fn modify_importance(&self) -> usize {
1279        self.0.modify_importance()
1280    }
1281
1282    /// Register a `handler` to be called when the current animation stops.
1283    ///
1284    /// Note that the `handler` is owned by the animation, not the variable, it will only be called/dropped when the
1285    /// animation stops.
1286    ///
1287    /// Returns the [`VarHandle::is_dummy`] if the variable is not animating. Note that if you are interacting
1288    /// with the variable from a non-UI thread the variable can stops animating between checking [`is_animating`]
1289    /// and registering the hook, in this case the dummy is returned as well.
1290    ///
1291    /// [`modify_importance`]: AnyVar::modify_importance
1292    /// [`is_animating`]: AnyVar::is_animating
1293    pub fn hook_animation_stop(&self, handler: impl FnOnce() + Send + 'static) -> VarHandle {
1294        let mut once = Some(handler);
1295        let handler: AnimationStopFn = smallbox!(move || { once.take().unwrap()() });
1296        self.0.hook_animation_stop(handler)
1297    }
1298
1299    /// Awaits for [`is_animating`] to change from `true` to `false`.
1300    ///
1301    /// If the variable is not animating at the moment of this call the future will await until the animation starts and stops.
1302    ///
1303    /// [`is_animating`]: Self::is_animating
1304    pub fn wait_animation(&self) -> impl Future<Output = ()> + Send + Sync {
1305        crate::future::WaitIsNotAnimatingFut::new(self)
1306    }
1307}
1308/// Value type.
1309impl AnyVar {
1310    /// Returns the strongly typed variable, if its of of value type `T`.
1311    pub fn downcast<T: VarValue>(self) -> Result<Var<T>, AnyVar> {
1312        if self.value_is::<T>() { Ok(Var::new_any(self)) } else { Err(self) }
1313    }
1314
1315    /// Returns [`downcast`] or `fallback_var`.
1316    ///
1317    /// [`downcast`]: Self::downcast
1318    pub fn downcast_or<T: VarValue, F: Into<Var<T>>>(self, fallback_var: impl FnOnce(AnyVar) -> F) -> Var<T> {
1319        match self.downcast() {
1320            Ok(tv) => tv,
1321            Err(av) => fallback_var(av).into(),
1322        }
1323    }
1324
1325    /// Gets the value type.
1326    pub fn value_type(&self) -> TypeId {
1327        self.0.value_type()
1328    }
1329
1330    /// Gets the value type name.
1331    ///
1332    /// Note that this string is not stable and should be used for debug only.
1333    #[cfg(feature = "type_names")]
1334    pub fn value_type_name(&self) -> &'static str {
1335        self.0.value_type_name()
1336    }
1337
1338    /// Gets if the value type is `T`.
1339    pub fn value_is<T: VarValue>(&self) -> bool {
1340        self.value_type() == TypeId::of::<T>()
1341    }
1342}
1343/// Variable type.
1344impl AnyVar {
1345    /// Flags that indicate what operations the variable is capable of in this update.
1346    pub fn capabilities(&self) -> VarCapability {
1347        self.0.capabilities()
1348    }
1349
1350    /// Current count of strong references to this variable.
1351    ///
1352    /// If this variable is [`SHARE`] cloning the variable only clones a reference to the variable.
1353    /// If this variable is local this is always `1` as it clones the value.
1354    ///
1355    /// [`SHARE`]: VarCapability::SHARE
1356    pub fn strong_count(&self) -> usize {
1357        self.0.strong_count()
1358    }
1359
1360    /// Create a weak reference to this variable.
1361    ///
1362    /// If this variable is [`SHARE`] returns a weak reference to the variable that can be upgraded to the variable it
1363    /// it is still alive. If this variable is local returns a dummy weak reference that cannot upgrade.
1364    ///
1365    /// [`SHARE`]: VarCapability::SHARE
1366    pub fn downgrade(&self) -> WeakAnyVar {
1367        WeakAnyVar(self.0.downgrade())
1368    }
1369
1370    /// Gets if this variable is the same as `other`.
1371    ///
1372    /// Shared variables are equal if they point to the same value and have the same capabilities.
1373    /// Const variables are equal if their value is equal. Contextual variables are equal if they are
1374    /// the same context variable.
1375    ///
1376    /// Use [`current_context`] to compare the variables at the caller context.
1377    ///
1378    /// Use [`var_instance_tag`] to compare only the shared pointers at the caller context.
1379    ///
1380    /// [`current_context`]: Self::current_context
1381    /// [`var_instance_tag`]: Self::var_instance_tag
1382    pub fn var_eq(&self, other: &AnyVar) -> bool {
1383        self.0.var_eq(&other.0)
1384    }
1385
1386    /// Copy ID that identifies this variable instance.
1387    ///
1388    /// The ID is only unique if this variable is [`SHARE`] and only while the variable is alive.
1389    /// This can be used with [`VarModify::push_tag`] and [`AnyVarHookArgs::contains_tag`] to avoid cyclic updates in custom
1390    /// bidirectional bindings.
1391    ///
1392    /// [`SHARE`]: VarCapability::SHARE
1393    pub fn var_instance_tag(&self) -> VarInstanceTag {
1394        self.0.var_instance_tag()
1395    }
1396
1397    /// Gets a clone of the var that is always read-only.
1398    ///
1399    /// The returned variable can still update if `self` is modified, but it does not have the [`MODIFY`] capability.
1400    ///
1401    /// [`MODIFY`]: VarCapability::MODIFY
1402    pub fn read_only(&self) -> AnyVar {
1403        AnyVar(self.0.clone_dyn().into_read_only())
1404    }
1405
1406    /// Create a var that updates with this var until it is set.
1407    ///
1408    /// The return variable is *clone-on-write* and has the `MODIFY` capability independent of the source capabilities, when
1409    /// a modify request is made the source value is cloned and offered for modification, if modified the source variable is dropped,
1410    /// if the modify closure does not update the source variable is retained.
1411    pub fn cow(&self) -> AnyVar {
1412        let caps = self.capabilities();
1413
1414        if caps.is_contextual() {
1415            let me = self.clone();
1416            // clone again inside the context to get a new clear (me as contextual_var)
1417            return any_contextual_var(move || me.clone().cow_tail(None), self.value_type());
1418        }
1419        self.cow_tail(Some(caps))
1420    }
1421    // to avoid infinite closure type (contextual case)
1422    fn cow_tail(&self, caps: Option<VarCapability>) -> AnyVar {
1423        let me = self.current_context();
1424        let caps = caps.unwrap_or_else(|| me.capabilities());
1425
1426        let mut init_value = None;
1427        me.with(&mut |v: &dyn AnyVarValue| init_value = Some(v.clone_boxed()));
1428        let init_value = init_value.unwrap();
1429
1430        let output = crate::any_var_derived(init_value, &me);
1431        if caps.is_const() {
1432            return output;
1433        }
1434
1435        let read_handle = me.bind_impl(&output, |a| a.clone_boxed());
1436        output
1437            .hook(move |a| {
1438                // hold source and binding handle
1439                let _hold = &read_handle;
1440                // while updates are only from source
1441                a.contains_tag(&me.var_instance_tag())
1442            })
1443            .perm();
1444
1445        output
1446    }
1447
1448    /// Hold the variable in memory until the app exit.
1449    ///
1450    /// Note that this is different from [`std::mem::forget`], if the app is compiled with `"multi_app"` feature
1451    /// the variable will be dropped before the new app instance in the same process.
1452    pub fn perm(&self) {
1453        VARS.perm(self.clone());
1454    }
1455
1456    /// Hold arbitrary `thing` for the lifetime of this variable or the return handle.
1457    pub fn hold(&self, thing: impl Any + Send) -> VarHandle {
1458        self.hold_impl(smallbox!(thing))
1459    }
1460    fn hold_impl(&self, thing: SmallBox<dyn Any + Send, smallbox::space::S2>) -> VarHandle {
1461        self.hook(move |_| {
1462            let _hold = &thing;
1463            true
1464        })
1465    }
1466
1467    /// Register a closure to be called when all strong references to this variable are dropped.
1468    ///
1469    /// If the return handle is dropped, the hook is unregistered without calling.
1470    pub fn hook_drop(&self, on_drop: impl FnOnce() + Send + 'static) -> VarHandle {
1471        self.hook_drop_impl(Box::new(on_drop))
1472    }
1473    fn hook_drop_impl(&self, on_drop: Box<dyn FnOnce() + Send + 'static>) -> VarHandle {
1474        let (handler_owner, handle) = VarHandle::new();
1475
1476        struct CallOnDrop(Option<Box<dyn FnOnce() + Send + 'static>>, crate::VarHandlerOwner);
1477        impl Drop for CallOnDrop {
1478            fn drop(&mut self) {
1479                if let Some(f) = self.0.take()
1480                    && self.1.is_alive()
1481                {
1482                    f();
1483                }
1484            }
1485        }
1486        let hold = CallOnDrop(Some(on_drop), handler_owner);
1487
1488        self.hook(move |_| hold.1.is_alive()).perm();
1489
1490        handle
1491    }
1492
1493    /// Gets the underlying var in the current calling context.
1494    ///
1495    /// If this variable is [`CONTEXT`] returns a clone of the inner variable,
1496    /// otherwise returns a clone of this variable.
1497    ///
1498    /// [`CONTEXT`]: VarCapability::CONTEXT
1499    pub fn current_context(&self) -> AnyVar {
1500        if self.capabilities().is_contextual() {
1501            AnyVar(self.0.current_context())
1502        } else {
1503            self.clone()
1504        }
1505    }
1506}
1507
1508/// Weak reference to a [`AnyVar`].
1509pub struct WeakAnyVar(pub(crate) crate::var_impl::DynWeakAnyVar);
1510impl fmt::Debug for WeakAnyVar {
1511    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1512        f.debug_tuple("WeakAnyVar").field(&self.0).finish()
1513    }
1514}
1515impl Clone for WeakAnyVar {
1516    fn clone(&self) -> Self {
1517        Self(self.0.clone_dyn())
1518    }
1519}
1520impl WeakAnyVar {
1521    /// Current count of strong references to the variable.
1522    pub fn strong_count(&self) -> usize {
1523        self.0.strong_count()
1524    }
1525
1526    /// Attempt to create a strong reference to the variable.
1527    pub fn upgrade(&self) -> Option<AnyVar> {
1528        self.0.upgrade().map(AnyVar)
1529    }
1530
1531    /// New weak var that does not upgrade.
1532    pub const fn new() -> Self {
1533        Self(crate::var_impl::DynWeakAnyVar::Const(crate::var_impl::const_var::WeakConstVar))
1534    }
1535
1536    /// Gets if this and `other` are a weak reference to the same var.
1537    pub fn var_eq(&self, other: &Self) -> bool {
1538        self.0.var_eq(&other.0)
1539    }
1540}
1541impl Default for WeakAnyVar {
1542    fn default() -> Self {
1543        Self::new()
1544    }
1545}
1546
1547/// Arguments for [`AnyVar::hook`].
1548pub struct AnyVarHookArgs<'a> {
1549    pub(super) var_instance_tag: VarInstanceTag,
1550    pub(super) value: &'a dyn AnyVarValue,
1551    pub(super) update: bool,
1552    pub(super) tags: &'a [BoxAnyVarValue],
1553}
1554impl<'a> AnyVarHookArgs<'a> {
1555    /// New from updated value and custom tag.
1556    pub fn new(var_instance_tag: VarInstanceTag, value: &'a dyn AnyVarValue, update: bool, tags: &'a [BoxAnyVarValue]) -> Self {
1557        Self {
1558            var_instance_tag,
1559            value,
1560            update,
1561            tags,
1562        }
1563    }
1564
1565    /// Tag that represents the viable.
1566    pub fn var_instance_tag(&self) -> VarInstanceTag {
1567        self.var_instance_tag
1568    }
1569
1570    /// Reference the updated value.
1571    pub fn value(&self) -> &'a dyn AnyVarValue {
1572        self.value
1573    }
1574
1575    /// If update was explicitly requested.
1576    ///
1577    /// Note that bindings/mappings propagate this update request.
1578    pub fn update(&self) -> bool {
1579        self.update
1580    }
1581
1582    /// Value type ID.
1583    pub fn value_type(&self) -> TypeId {
1584        self.value.type_id()
1585    }
1586
1587    /// Custom tag objects.
1588    pub fn tags(&self) -> &[BoxAnyVarValue] {
1589        self.tags
1590    }
1591
1592    /// Clone the custom tag objects set by the code that updated the value.
1593    pub fn tags_vec(&self) -> Vec<BoxAnyVarValue> {
1594        self.tags.iter().map(|t| (*t).clone_boxed()).collect()
1595    }
1596
1597    /// Reference the value, if it is of type `T`.
1598    pub fn downcast_value<T: VarValue>(&self) -> Option<&T> {
1599        self.value.downcast_ref()
1600    }
1601
1602    /// Reference all custom tag values of type `T`.
1603    pub fn downcast_tags<T: VarValue>(&self) -> impl Iterator<Item = &T> + '_ {
1604        self.tags.iter().filter_map(|t| (*t).downcast_ref::<T>())
1605    }
1606
1607    /// Gets if the `tag` is in [`tags`].
1608    ///
1609    /// [`tags`]: Self::tags
1610    pub fn contains_tag<T: VarValue>(&self, tag: &T) -> bool {
1611        self.downcast_tags::<T>().any(|t| t == tag)
1612    }
1613
1614    /// Try cast to strongly typed args.
1615    pub fn downcast<T: VarValue>(&self) -> Option<crate::VarHookArgs<'_, T>> {
1616        if TypeId::of::<T>() == self.value_type() {
1617            Some(crate::VarHookArgs {
1618                any: self,
1619                _t: PhantomData,
1620            })
1621        } else {
1622            None
1623        }
1624    }
1625}
1626
1627/// Unique identifier of a share variable, while it is alive.
1628///
1629/// See [`AnyVar::var_instance_tag`] for more details
1630#[derive(Clone, Copy, PartialEq, Eq)]
1631pub struct VarInstanceTag(pub(crate) usize);
1632impl fmt::Debug for VarInstanceTag {
1633    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1634        if *self == Self::NOT_SHARED {
1635            write!(f, "NOT_SHARED")
1636        } else {
1637            write!(f, "0x{:X}", self.0)
1638        }
1639    }
1640}
1641impl VarInstanceTag {
1642    /// ID for variables that are not [`SHARE`].
1643    ///
1644    /// [`SHARE`]: VarCapability::SHARE
1645    pub const NOT_SHARED: VarInstanceTag = VarInstanceTag(0);
1646}