1use std::{
3 cell::{Cell, OnceCell, RefCell},
4 collections::HashMap,
5 rc::{Rc, Weak},
6};
7
8thread_local! {
9 static INPUT_PATHS: RefCell<Vec<InputPath>> = const { RefCell::new(Vec::new()) };
10 static EVALUATING: RefCell<EvaluationContext> = const {
11 RefCell::new(EvaluationContext { binding: None, watches: Vec::new() })
12 };
13}
14
15#[derive(Default)]
16struct InputPath {
17 root_overrides: Vec<Weak<DependencyNode>>,
18 availability: Option<Rc<ReadWatch>>,
19 states: Vec<InputState>,
20}
21
22struct InputState {
23 component: Weak<DependencyNode>,
24 selector: Box<str>,
25 selected: i64,
26}
27
28struct EvaluationContext {
29 binding: Option<Rc<DependencyNode>>,
30 watches: Vec<Rc<ReadWatch>>,
31}
32
33#[derive(Default)]
35pub(crate) struct ReadWatch {
36 sources: RefCell<HashMap<*const DependencyNode, Weak<DependencyNode>>>,
37 next_prune: Cell<usize>,
38 changed: Cell<bool>,
39 frozen: Cell<bool>,
40}
41
42impl ReadWatch {
43 fn observe(&self, node: &Rc<DependencyNode>) {
44 if self.frozen.get() {
45 return;
46 }
47 let mut sources = self.sources.borrow_mut();
48 if sources.contains_key(&Rc::as_ptr(node)) {
49 return;
50 }
51 if sources.len() >= self.next_prune.get() {
52 sources.retain(|_, source| source.strong_count() != 0);
53 self.next_prune.set(sources.len().saturating_mul(2).max(64));
54 }
55 let mut pending = Vec::new();
57 let mut next = Some(node.clone());
58 while let Some(node) = next {
59 if let std::collections::hash_map::Entry::Vacant(source) =
60 sources.entry(Rc::as_ptr(&node))
61 {
62 source.insert(Rc::downgrade(&node));
63 if !node.dirty.get() {
64 pending.extend(node.sources.borrow().iter().filter_map(Weak::upgrade));
65 }
66 }
67 next = pending.pop();
68 }
69 }
70
71 fn invalidate(&self, source: *const DependencyNode) {
72 if self.sources.borrow().contains_key(&source) {
73 self.changed.set(true);
74 }
75 }
76
77 pub(crate) fn changed(&self) -> bool {
78 self.changed.get()
79 }
80
81 pub(crate) fn clear_changes(&self) {
82 self.changed.set(false);
83 }
84
85 pub(crate) fn freeze(&self) {
87 self.frozen.set(true);
88 }
89
90 pub(crate) fn without_new_reads<T>(&self, operation: impl FnOnce() -> T) -> T {
91 struct Restore<'a>(&'a Cell<bool>, bool);
92 impl Drop for Restore<'_> {
93 fn drop(&mut self) {
94 self.0.set(self.1);
95 }
96 }
97 let _restore = Restore(&self.frozen, self.frozen.replace(true));
98 operation()
99 }
100}
101
102pub(crate) fn watch_reads<T>(operation: impl FnOnce(&ReadWatch) -> T) -> T {
103 let watch = Rc::new(ReadWatch::default());
104 with_read_watch(&watch, || operation(&watch))
105}
106
107pub(crate) fn with_read_watch<T>(watch: &Rc<ReadWatch>, operation: impl FnOnce() -> T) -> T {
108 struct Scope;
109 impl Drop for Scope {
110 fn drop(&mut self) {
111 EVALUATING.with(|context| context.borrow_mut().watches.pop());
112 }
113 }
114
115 EVALUATING.with(|context| context.borrow_mut().watches.push(watch.clone()));
116 let _scope = Scope;
117 operation()
118}
119
120pub(crate) fn without_read_watches<T>(operation: impl FnOnce() -> T) -> T {
122 struct Restore(Vec<Rc<ReadWatch>>);
123 impl Drop for Restore {
124 fn drop(&mut self) {
125 EVALUATING.with(|context| context.borrow_mut().watches = std::mem::take(&mut self.0));
126 }
127 }
128 let _restore =
129 Restore(EVALUATING.with(|context| std::mem::take(&mut context.borrow_mut().watches)));
130 operation()
131}
132
133pub(crate) fn with_input_path<T>(operation: impl FnOnce() -> T) -> T {
134 struct Scope;
135 impl Drop for Scope {
136 fn drop(&mut self) {
137 INPUT_PATHS.with(|paths| paths.borrow_mut().pop());
138 }
139 }
140
141 INPUT_PATHS.with(|paths| paths.borrow_mut().push(InputPath::default()));
142 let _scope = Scope;
143 operation()
144}
145
146pub(crate) fn track_input_availability<T>(check: impl FnOnce() -> T) -> T {
147 let watch = INPUT_PATHS.with(|paths| {
148 paths
149 .borrow_mut()
150 .last_mut()
151 .map(|path| path.availability.get_or_insert_with(Rc::default).clone())
152 });
153 match watch {
154 Some(watch) => with_read_watch(&watch, check),
155 None => check(),
156 }
157}
158
159pub(crate) fn input_path_is_current() -> bool {
161 INPUT_PATHS.with(|paths| {
162 paths
163 .borrow()
164 .last()
165 .and_then(|path| path.availability.as_ref())
166 .is_none_or(|watch| !watch.changed())
167 })
168}
169
170#[derive(Default)]
171struct DependencyNode {
172 dirty: Cell<bool>,
173 evaluating: Cell<bool>,
174 sources: RefCell<Vec<Weak<Self>>>,
175 dependents: RefCell<Vec<Weak<Self>>>,
176}
177
178impl DependencyNode {
179 fn track(self: &Rc<Self>) {
180 EVALUATING.with(|current| {
181 let current = current.borrow();
182 for watch in ¤t.watches {
183 watch.observe(self);
184 }
185 let Some(binding) = current.binding.as_ref() else {
186 return;
187 };
188 if Rc::ptr_eq(self, binding) {
189 return;
190 }
191 let mut sources = binding.sources.borrow_mut();
192 let source = Rc::downgrade(self);
193 if !sources.iter().any(|existing| existing.ptr_eq(&source)) {
194 sources.push(source);
195 self.dependents.borrow_mut().push(Rc::downgrade(binding));
196 }
197 });
198 }
199
200 fn detach(&self) {
201 let address = self as *const Self;
202 for source in self.sources.take() {
203 if let Some(source) = source.upgrade() {
204 source
205 .dependents
206 .borrow_mut()
207 .retain(|binding| binding.as_ptr() != address);
208 }
209 }
210 }
211
212 fn push_dependents(&self, pending: &mut Vec<Rc<Self>>) {
213 self.dependents.borrow_mut().retain(|weak| {
214 if let Some(binding) = weak.upgrade() {
215 pending.push(binding);
216 true
217 } else {
218 false
219 }
220 });
221 }
222
223 fn notify(&self) {
224 EVALUATING.with(|context| {
225 let address = std::ptr::from_ref(self);
226 for watch in &context.borrow().watches {
227 watch.invalidate(address);
228 }
229 INPUT_PATHS.with(|paths| {
230 for path in paths.borrow().iter() {
231 if let Some(watch) = &path.availability {
232 watch.invalidate(address);
233 }
234 }
235 });
236 });
237 self.invalidate_dependents();
238 }
239
240 fn invalidate_dependents(&self) {
241 let mut pending = Vec::new();
242 self.push_dependents(&mut pending);
243 while let Some(binding) = pending.pop() {
244 if !binding.dirty.replace(true) {
245 binding.push_dependents(&mut pending);
246 }
247 }
248 }
249
250 fn evaluate<T>(self: &Rc<Self>, binding: impl FnOnce() -> T) -> T {
251 self.detach();
252 self.evaluating.set(true);
253 self.dirty.set(false);
254 let mut evaluation = Evaluation {
255 node: self,
256 previous: EVALUATING.with(|current| current.borrow_mut().binding.replace(self.clone())),
257 completed: false,
258 };
259 let value = binding();
260 evaluation.completed = true;
261 value
262 }
263}
264
265impl Drop for DependencyNode {
266 fn drop(&mut self) {
267 self.detach();
268 self.invalidate_dependents();
270 }
271}
272
273struct Evaluation<'a> {
274 node: &'a DependencyNode,
275 previous: Option<Rc<DependencyNode>>,
276 completed: bool,
277}
278
279impl Drop for Evaluation<'_> {
280 fn drop(&mut self) {
281 EVALUATING.with(|current| {
282 current.borrow_mut().binding = self.previous.take();
283 });
284 self.node.evaluating.set(false);
285 if !self.completed && !self.node.dirty.replace(true) {
286 self.node.notify();
287 }
288 }
289}
290
291#[derive(Default)]
293pub struct ChangeSignal(Rc<DependencyNode>);
294
295impl ChangeSignal {
296 pub(crate) fn is_tracking() -> bool {
297 EVALUATING.with(|current| {
298 let current = current.borrow();
299 current.binding.is_some() || !current.watches.is_empty()
300 })
301 }
302
303 pub(crate) fn has_observers(&self) -> bool {
304 !self.0.dependents.borrow().is_empty()
305 || EVALUATING.with(|context| {
306 let address = Rc::as_ptr(&self.0);
307 context
308 .borrow()
309 .watches
310 .iter()
311 .any(|watch| watch.sources.borrow().contains_key(&address))
312 })
313 }
314
315 pub fn track(&self) {
316 self.0.track();
317 }
318
319 pub fn notify(&self) {
320 self.0.notify();
321 }
322}
323
324#[doc(hidden)]
326#[derive(Default)]
327pub struct ComponentLifetime {
328 signal: OnceCell<ChangeSignal>,
329 pub(crate) weak: crate::event_loop::WeakRegistration,
330}
331
332impl ComponentLifetime {
333 pub fn track(&self) {
334 self.signal.get_or_init(ChangeSignal::default).track();
335 }
336
337 #[doc(hidden)]
339 pub fn try_input_state<E>(
340 &self,
341 selector: &str,
342 read: impl FnOnce() -> Result<i64, E>,
343 ) -> Result<i64, E> {
344 let component = &self.signal.get_or_init(ChangeSignal::default).0;
345 let cached = INPUT_PATHS.with(|paths| {
346 paths.borrow().last()?.states.iter().find_map(|entry| {
347 (entry.component.as_ptr() == Rc::as_ptr(component)
348 && entry.selector.as_ref() == selector)
349 .then_some(entry.selected)
350 })
351 });
352 if let Some(selected) = cached {
353 return Ok(selected);
354 }
355 let selected = read()?;
356 INPUT_PATHS.with(|paths| {
357 if let Some(path) = paths.borrow_mut().last_mut() {
358 path.states.push(InputState {
359 component: Rc::downgrade(component),
360 selector: selector.into(),
361 selected,
362 });
363 }
364 });
365 Ok(selected)
366 }
367
368 #[doc(hidden)]
369 pub fn input_state(&self, selector: &str, read: impl FnOnce() -> i64) -> i64 {
370 self.try_input_state(selector, || Ok::<_, std::convert::Infallible>(read()))
371 .unwrap_or_else(|error| match error {})
372 }
373
374 pub(crate) fn record_input_root_override(&self) {
375 let signal = self.signal.get_or_init(ChangeSignal::default);
376 INPUT_PATHS.with(|paths| {
377 if let Some(path) = paths.borrow_mut().last_mut() {
378 path.root_overrides.push(Rc::downgrade(&signal.0));
379 }
380 });
381 }
382
383 #[doc(hidden)]
385 pub fn try_input_root_visible<E>(
386 &self,
387 visible: impl FnOnce() -> Result<bool, E>,
388 ) -> Result<bool, E> {
389 let overridden = self.signal.get().is_some_and(|signal| {
390 INPUT_PATHS.with(|paths| {
391 paths.borrow().last().is_some_and(|path| {
392 path.root_overrides
393 .iter()
394 .any(|owner| owner.as_ptr() == Rc::as_ptr(&signal.0))
395 })
396 })
397 });
398 if overridden { Ok(true) } else { visible() }
399 }
400
401 #[doc(hidden)]
402 pub fn input_root_visible(&self, visible: impl FnOnce() -> bool) -> bool {
403 self.try_input_root_visible(|| Ok::<_, std::convert::Infallible>(visible()))
404 .unwrap_or_else(|error| match error {})
405 }
406}
407
408enum Stored<T> {
409 Unset,
410 Explicit(T),
411 Cached(T),
412}
413
414pub struct Property<T> {
418 value: RefCell<Stored<T>>,
419 binding: Option<Box<dyn Fn() -> T>>,
420 dependency: Rc<DependencyNode>,
421}
422
423impl<T> Default for Property<T> {
424 fn default() -> Self {
425 Self::new(None)
426 }
427}
428
429impl<T> Property<T> {
430 pub fn new(binding: Option<Box<dyn Fn() -> T>>) -> Self {
431 Self {
432 value: RefCell::new(Stored::Unset),
433 binding,
434 dependency: Rc::default(),
435 }
436 }
437
438 pub fn set(&self, value: T) {
439 self.replace(Stored::Explicit(value), true);
440 }
441
442 pub fn is_dirty(&self) -> bool {
444 self.dependency.dirty.get()
445 }
446
447 pub(crate) fn matches_current(&self, predicate: impl FnOnce(&T) -> bool) -> bool {
449 match &*self.value.borrow() {
450 Stored::Explicit(value) => predicate(value),
451 Stored::Cached(value) if !self.dependency.dirty.get() => predicate(value),
452 _ => false,
453 }
454 }
455
456 pub fn reset(&self) {
457 if matches!(*self.value.borrow(), Stored::Explicit(_)) {
458 self.replace(Stored::Unset, true);
459 }
460 }
461
462 fn replace(&self, value: Stored<T>, changed: bool) {
463 let previous = self.value.replace(value);
464 self.dependency.detach();
465 self.dependency.dirty.set(true);
466 if changed {
467 self.dependency.notify();
468 }
469 drop(previous);
470 }
471 #[doc(hidden)]
472 pub fn set_if_changed_by(&self, value: T, equal: impl FnOnce(&T, &T) -> bool) {
473 let changed = match &*self.value.borrow() {
474 Stored::Explicit(current) => {
475 if equal(current, &value) {
476 return;
477 }
478 true
479 }
480 Stored::Cached(current) if !self.dependency.dirty.get() => !equal(current, &value),
481 Stored::Unset | Stored::Cached(_) => true,
482 };
483 self.replace(Stored::Explicit(value), changed);
484 }
485}
486
487impl<T: PartialEq> Property<T> {
488 pub fn set_if_changed(&self, value: T) {
490 self.set_if_changed_by(value, T::eq);
491 }
492}
493
494impl<T: Clone> Property<T> {
495 #[doc(hidden)]
497 pub fn cached_value(&self) -> Option<T> {
498 match &*self.value.borrow() {
499 Stored::Explicit(value) => Some(value.clone()),
500 Stored::Cached(value) if !self.dependency.dirty.get() => Some(value.clone()),
501 _ => None,
502 }
503 }
504
505 pub fn explicit_value(&self) -> Option<T> {
507 self.dependency.track();
508 match &*self.value.borrow() {
509 Stored::Explicit(value) => Some(value.clone()),
510 _ => None,
511 }
512 }
513
514 pub fn get(&self, default: impl FnOnce() -> T) -> T {
515 self.try_get(|| Ok::<_, std::convert::Infallible>(default()))
516 .unwrap_or_else(|error| match error {})
517 }
518
519 #[doc(hidden)]
521 pub fn try_get<E>(&self, default: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
522 self.try_get_with(|| match &self.binding {
523 Some(binding) => Ok(binding()),
524 None => default(),
525 })
526 }
527
528 fn try_get_with<E>(&self, read: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
529 assert!(
530 !self.dependency.evaluating.get(),
531 "cyclic property evaluation"
532 );
533 self.dependency.track();
534 match &*self.value.borrow() {
535 Stored::Explicit(value) => return Ok(value.clone()),
536 Stored::Cached(value) if !self.dependency.dirty.get() => {
537 crate::update_profile::property(false);
538 return Ok(value.clone());
539 }
540 Stored::Unset | Stored::Cached(_) => {}
541 }
542
543 crate::update_profile::property(true);
544 let value = self.dependency.evaluate(read);
545 let value = match value {
546 Ok(value) => value,
547 Err(error) => {
548 if !self.dependency.dirty.replace(true) {
549 self.dependency.notify();
550 }
551 return Err(error);
552 }
553 };
554 if !self.dependency.dirty.get() {
555 let cached = value.clone();
556 if !self.dependency.dirty.get() {
557 self.value.replace(Stored::Cached(cached));
558 }
559 }
560 Ok(value)
561 }
562}
563
564impl<T: Clone, E: Clone> Property<Result<T, E>> {
565 fn get_result(&self, default: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
566 self.try_get_with(|| {
567 match &self.binding {
568 Some(binding) => binding(),
569 None => default(),
570 }
571 .map(Ok)
572 })?
573 }
574}
575
576#[doc(hidden)]
579pub enum InputProperty<T> {
580 Local(Property<T>),
581 Linked {
582 read: Box<dyn Fn() -> Option<T>>,
583 write: Box<dyn Fn(T)>,
584 },
585 State {
586 value: Property<T>,
587 read: Box<dyn Fn() -> Option<T>>,
588 base: Box<Self>,
589 },
590}
591
592impl<T> Default for InputProperty<T> {
593 fn default() -> Self {
594 Self::Local(Property::default())
595 }
596}
597
598impl<T> InputProperty<T> {
599 pub fn bound(read: impl Fn() -> T + 'static) -> Self {
600 Self::Local(Property::new(Some(Box::new(read))))
601 }
602
603 #[doc(hidden)]
606 pub fn bound_optional(read: impl Fn() -> Option<T> + 'static) -> Self {
607 Self::default().with_state(read)
608 }
609
610 pub fn linked(read: impl Fn() -> Option<T> + 'static, write: impl Fn(T) + 'static) -> Self {
611 Self::Linked {
612 read: Box::new(read),
613 write: Box::new(write),
614 }
615 }
616
617 pub fn with_state(self, read: impl Fn() -> Option<T> + 'static) -> Self {
620 Self::State {
621 value: Property::default(),
622 read: Box::new(read),
623 base: Box::new(self),
624 }
625 }
626
627 pub fn reset(&self) {
628 match self {
629 Self::Local(value) | Self::State { value, .. } => value.reset(),
630 Self::Linked { .. } => {}
631 }
632 }
633
634 #[doc(hidden)]
635 pub fn set_if_changed_by(&self, value: T, equal: impl FnOnce(&T, &T) -> bool) {
636 match self {
637 Self::Local(property)
638 | Self::State {
639 value: property, ..
640 } => property.set_if_changed_by(value, equal),
641 Self::Linked { write, .. } => write(value),
642 }
643 }
644}
645
646impl<T: Clone> InputProperty<T> {
647 pub fn get(&self, default: impl FnOnce() -> T) -> T {
648 match self {
649 Self::Local(property) => property.get(default),
650 Self::Linked { read, .. } => read().unwrap_or_else(default),
651 Self::State { value, read, base } => {
652 value.get(|| read().unwrap_or_else(|| base.get(default)))
653 }
654 }
655 }
656}
657
658impl<T: Clone, E: Clone> InputProperty<Result<T, E>> {
659 #[doc(hidden)]
661 pub fn get_result(&self, default: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
662 match self {
663 Self::Local(property) => property.get_result(default),
664 Self::Linked { read, .. } => read().unwrap_or_else(default),
665 Self::State { value, read, base } => {
666 value.get_result(|| read().unwrap_or_else(|| base.get_result(default)))
667 }
668 }
669 }
670}
671
672impl<T: PartialEq> InputProperty<T> {
673 pub fn set_if_changed(&self, value: T) {
674 self.set_if_changed_by(value, T::eq);
675 }
676}
677
678#[cfg(test)]
679mod tests {
680 use super::*;
681 use std::panic::{AssertUnwindSafe, catch_unwind};
682
683 #[test]
684 fn read_watch_keeps_live_inputs_of_a_dropped_cached_binding() {
685 let input = Rc::new(Property::default());
686 input.set(1);
687 let sampled = Property::new(Some(Box::new({
688 let input = input.clone();
689 move || input.get(|| 0)
690 })));
691 assert_eq!(sampled.get(|| 0), 1);
692
693 watch_reads(|reads| {
694 assert_eq!(sampled.get(|| 0), 1);
695 drop(sampled);
696 assert!(!reads.changed());
697 input.set(2);
698 assert!(reads.changed());
699 });
700 }
701
702 #[test]
703 fn state_input_restores_the_live_fallback_after_reset() {
704 let active = Rc::new(Property::default());
705 active.set(true);
706 let base = Property::default();
707 base.set(1);
708 let state = active.clone();
709 let input = InputProperty::default().with_state(move || state.get(|| false).then_some(2));
710 let read = || input.get(|| base.get(|| 0));
711
712 assert_eq!(read(), 2);
713 input.set_if_changed(2);
714 active.set(false);
715 base.set(3);
716 assert_eq!(read(), 2);
717 input.reset();
718 assert_eq!(read(), 3);
719 active.set(true);
720 assert_eq!(read(), 2);
721 }
722
723 #[test]
724 fn invalidation_reaches_a_diamond_once() {
725 let source = Property::default();
726 let left = Property::default();
727 let right = Property::default();
728 let total = Property::default();
729 let evaluations = Cell::new(0);
730
731 source.set(1);
732 let value = || {
733 total.get(|| {
734 evaluations.set(evaluations.get() + 1);
735 let left = left.get(|| source.get(|| 0) + source.get(|| 0));
736 left + right.get(|| source.get(|| 0) * 3)
737 })
738 };
739 assert_eq!(value(), 5);
740 source.set(2);
741 source.set(3);
742 assert_eq!(evaluations.get(), 1);
743 assert_eq!(value(), 15);
744 assert_eq!(value(), 15);
745 assert_eq!(evaluations.get(), 2);
746 }
747
748 #[test]
749 fn unwinding_a_nested_evaluation_allows_retry_and_restores_tracking() {
750 let source = Property::default();
751 let inner = Property::default();
752 let outer = Property::default();
753 let first = Cell::new(true);
754 source.set(7);
755
756 let value = || {
757 outer.get(|| {
758 catch_unwind(AssertUnwindSafe(|| {
759 inner.get(|| {
760 let number = source.get(|| 0);
761 assert!(!first.replace(false), "transient failure");
762 number
763 })
764 }))
765 .unwrap_or(0)
766 })
767 };
768 assert_eq!(value(), 0);
769 assert_eq!(value(), 7);
770 source.set(9);
771 assert_eq!(value(), 9);
772 }
773
774 #[test]
775 fn invalidation_during_evaluation_does_not_cache_an_obsolete_result() {
776 let source = Property::default();
777 let derived = Property::default();
778 source.set(1);
779
780 assert_eq!(
781 derived.get(|| {
782 let previous = source.get(|| 0);
783 source.set(2);
784 previous
785 }),
786 1
787 );
788 assert_eq!(derived.get(|| source.get(|| 0)), 2);
789 assert_eq!(derived.get(|| panic!("cache should be valid")), 2);
790 }
791
792 #[test]
793 fn dropping_a_source_invalidates_bindings_that_read_through_weak_references() {
794 let source = Rc::new(Property::default());
795 source.set(8);
796 let weak = Rc::downgrade(&source);
797 let derived = Property::default();
798 let value = || derived.get(|| weak.upgrade().map_or(0, |source| source.get(|| 0)));
799 assert_eq!(value(), 8);
800 drop(source);
801 assert_eq!(value(), 0);
802 }
803}