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
22pub 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}
34impl AnyVar {
36 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 pub fn get(&self) -> BoxAnyVarValue {
48 self.0.get()
49 }
50
51 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 pub fn is_new(&self) -> bool {
68 self.last_update() == VARS.update_id()
69 }
70
71 pub fn get_new(&self) -> Option<BoxAnyVarValue> {
75 if self.is_new() { Some(self.get()) } else { None }
76 }
77
78 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 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 pub fn set(&self, new_value: BoxAnyVarValue) {
109 trace_debug_error!(self.try_set(new_value))
110 }
111
112 pub fn try_update(&self) -> Result<(), VarIsReadOnlyError> {
114 self.handle_modify(self.0.update())
115 }
116
117 pub fn update(&self) {
124 trace_debug_error!(self.try_update())
125 }
126
127 pub fn try_modify(&self, modify: impl FnOnce(&mut AnyVarModify) + Send + 'static) -> Result<(), VarIsReadOnlyError> {
131 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 pub fn modify(&self, modify: impl FnOnce(&mut AnyVarModify) + Send + 'static) {
158 trace_debug_error!(self.try_modify(modify))
159 }
160
161 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 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 v.push_tag(other.var_instance_tag());
192 }
193 v.set_modify_importance(other.modify_importance());
195 });
196 }
197 })
198 }
199
200 pub fn set_from(&self, other: &AnyVar) {
210 trace_debug_error!(self.try_set_from(other))
211 }
212
213 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 v.push_tag(other.var_instance_tag());
244 }
245 v.set_modify_importance(other.modify_importance());
247 });
248 }
249 })
250 }
251
252 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 pub fn hook(&self, on_update: impl FnMut(&AnyVarHookArgs) -> bool + Send + 'static) -> VarHandle {
272 self.0.hook(smallbox!(on_update))
273 }
274
275 #[allow(clippy::manual_async_fn)] 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 #[allow(clippy::manual_async_fn)] 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 pub fn last_update(&self) -> VarUpdateId {
307 self.0.last_update()
308 }
309
310 pub fn wait_update(&self) -> impl Future<Output = VarUpdateId> + Send + Sync {
324 crate::future::WaitUpdateFut::new(self)
325 }
326
327 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}
356impl AnyVar {
358 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 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 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 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 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 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 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 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 false
503 }
504 }
505 })
506 .perm();
507 output.hold(me).perm();
508
509 output.read_only()
510 }
511
512 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 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 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 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 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 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 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 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 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 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}
757impl AnyVar {
759 pub fn bind(&self, other: &AnyVar) -> VarHandle {
765 self.bind_map_any(other, |v| v.clone_boxed())
766 }
767
768 pub fn set_bind(&self, other: &AnyVar) -> VarHandle {
775 other.set_from(self);
776 self.bind(other)
777 }
778
779 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 v.push_tag(self_tag);
1073 }
1074 if update {
1075 v.update();
1077 }
1078 });
1079 true
1080 } else {
1081 false
1082 }
1083 })
1084 }
1085
1086 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 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 v.push_tag(self_.var_instance_tag());
1109 }
1110 if update {
1111 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 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 v.push_tag(self_tag);
1142 }
1143 if update {
1144 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}
1162impl AnyVar {
1164 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 let wk_target = target.downgrade();
1176 let animate = Arc::new(Mutex::new(animate));
1177
1178 return VARS.animate(move |args| {
1179 if let Some(target) = wk_target.upgrade() {
1182 if target.modify_importance() > VARS.current_modify().importance {
1185 args.stop();
1188 return;
1189 }
1190
1191 let r = target.try_modify(clmv!(animate, args, |value| {
1193 (animate.lock())(&args, value);
1194 }));
1195
1196 if let Err(VarIsReadOnlyError { .. }) = r {
1197 args.stop();
1199 }
1200 } else {
1201 args.stop();
1203 }
1204 });
1205 }
1206 }
1207 AnimationHandle::dummy()
1208 }
1209
1210 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 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 pub fn is_animating(&self) -> bool {
1266 self.0.is_animating()
1267 }
1268
1269 pub fn modify_importance(&self) -> usize {
1279 self.0.modify_importance()
1280 }
1281
1282 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 pub fn wait_animation(&self) -> impl Future<Output = ()> + Send + Sync {
1305 crate::future::WaitIsNotAnimatingFut::new(self)
1306 }
1307}
1308impl AnyVar {
1310 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 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 pub fn value_type(&self) -> TypeId {
1327 self.0.value_type()
1328 }
1329
1330 #[cfg(feature = "type_names")]
1334 pub fn value_type_name(&self) -> &'static str {
1335 self.0.value_type_name()
1336 }
1337
1338 pub fn value_is<T: VarValue>(&self) -> bool {
1340 self.value_type() == TypeId::of::<T>()
1341 }
1342}
1343impl AnyVar {
1345 pub fn capabilities(&self) -> VarCapability {
1347 self.0.capabilities()
1348 }
1349
1350 pub fn strong_count(&self) -> usize {
1357 self.0.strong_count()
1358 }
1359
1360 pub fn downgrade(&self) -> WeakAnyVar {
1367 WeakAnyVar(self.0.downgrade())
1368 }
1369
1370 pub fn var_eq(&self, other: &AnyVar) -> bool {
1383 self.0.var_eq(&other.0)
1384 }
1385
1386 pub fn var_instance_tag(&self) -> VarInstanceTag {
1394 self.0.var_instance_tag()
1395 }
1396
1397 pub fn read_only(&self) -> AnyVar {
1403 AnyVar(self.0.clone_dyn().into_read_only())
1404 }
1405
1406 pub fn cow(&self) -> AnyVar {
1412 let caps = self.capabilities();
1413
1414 if caps.is_contextual() {
1415 let me = self.clone();
1416 return any_contextual_var(move || me.clone().cow_tail(None), self.value_type());
1418 }
1419 self.cow_tail(Some(caps))
1420 }
1421 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 let _hold = &read_handle;
1440 a.contains_tag(&me.var_instance_tag())
1442 })
1443 .perm();
1444
1445 output
1446 }
1447
1448 pub fn perm(&self) {
1453 VARS.perm(self.clone());
1454 }
1455
1456 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 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 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
1508pub 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 pub fn strong_count(&self) -> usize {
1523 self.0.strong_count()
1524 }
1525
1526 pub fn upgrade(&self) -> Option<AnyVar> {
1528 self.0.upgrade().map(AnyVar)
1529 }
1530
1531 pub const fn new() -> Self {
1533 Self(crate::var_impl::DynWeakAnyVar::Const(crate::var_impl::const_var::WeakConstVar))
1534 }
1535
1536 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
1547pub 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 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 pub fn var_instance_tag(&self) -> VarInstanceTag {
1567 self.var_instance_tag
1568 }
1569
1570 pub fn value(&self) -> &'a dyn AnyVarValue {
1572 self.value
1573 }
1574
1575 pub fn update(&self) -> bool {
1579 self.update
1580 }
1581
1582 pub fn value_type(&self) -> TypeId {
1584 self.value.type_id()
1585 }
1586
1587 pub fn tags(&self) -> &[BoxAnyVarValue] {
1589 self.tags
1590 }
1591
1592 pub fn tags_vec(&self) -> Vec<BoxAnyVarValue> {
1594 self.tags.iter().map(|t| (*t).clone_boxed()).collect()
1595 }
1596
1597 pub fn downcast_value<T: VarValue>(&self) -> Option<&T> {
1599 self.value.downcast_ref()
1600 }
1601
1602 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 pub fn contains_tag<T: VarValue>(&self, tag: &T) -> bool {
1611 self.downcast_tags::<T>().any(|t| t == tag)
1612 }
1613
1614 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#[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 pub const NOT_SHARED: VarInstanceTag = VarInstanceTag(0);
1646}