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 loader_mount: OnceCell<crate::LoaderMount>,
329 signal: OnceCell<ChangeSignal>,
330 pub(crate) weak: crate::event_loop::WeakRegistration,
331}
332
333impl ComponentLifetime {
334 #[doc(hidden)]
335 pub fn loader_mount(&self) -> &crate::LoaderMount {
336 self.loader_mount.get_or_init(crate::LoaderMount::default)
337 }
338
339 pub fn track(&self) {
340 self.signal.get_or_init(ChangeSignal::default).track();
341 }
342
343 #[doc(hidden)]
345 pub fn try_input_state<E>(
346 &self,
347 selector: &str,
348 read: impl FnOnce() -> Result<i64, E>,
349 ) -> Result<i64, E> {
350 let component = &self.signal.get_or_init(ChangeSignal::default).0;
351 let cached = INPUT_PATHS.with(|paths| {
352 paths.borrow().last()?.states.iter().find_map(|entry| {
353 (entry.component.as_ptr() == Rc::as_ptr(component)
354 && entry.selector.as_ref() == selector)
355 .then_some(entry.selected)
356 })
357 });
358 if let Some(selected) = cached {
359 return Ok(selected);
360 }
361 let selected = read()?;
362 INPUT_PATHS.with(|paths| {
363 if let Some(path) = paths.borrow_mut().last_mut() {
364 path.states.push(InputState {
365 component: Rc::downgrade(component),
366 selector: selector.into(),
367 selected,
368 });
369 }
370 });
371 Ok(selected)
372 }
373
374 #[doc(hidden)]
375 pub fn input_state(&self, selector: &str, read: impl FnOnce() -> i64) -> i64 {
376 self.try_input_state(selector, || Ok::<_, std::convert::Infallible>(read()))
377 .unwrap_or_else(|error| match error {})
378 }
379
380 pub(crate) fn record_input_root_override(&self) {
381 let signal = self.signal.get_or_init(ChangeSignal::default);
382 INPUT_PATHS.with(|paths| {
383 if let Some(path) = paths.borrow_mut().last_mut() {
384 path.root_overrides.push(Rc::downgrade(&signal.0));
385 }
386 });
387 }
388
389 #[doc(hidden)]
391 pub fn try_input_root_visible<E>(
392 &self,
393 visible: impl FnOnce() -> Result<bool, E>,
394 ) -> Result<bool, E> {
395 let overridden = self.signal.get().is_some_and(|signal| {
396 INPUT_PATHS.with(|paths| {
397 paths.borrow().last().is_some_and(|path| {
398 path.root_overrides
399 .iter()
400 .any(|owner| owner.as_ptr() == Rc::as_ptr(&signal.0))
401 })
402 })
403 });
404 if overridden { Ok(true) } else { visible() }
405 }
406
407 #[doc(hidden)]
408 pub fn input_root_visible(&self, visible: impl FnOnce() -> bool) -> bool {
409 self.try_input_root_visible(|| Ok::<_, std::convert::Infallible>(visible()))
410 .unwrap_or_else(|error| match error {})
411 }
412}
413
414enum Stored<T> {
415 Unset,
416 Explicit(T),
417 Cached(T),
418}
419
420pub struct Property<T> {
424 value: RefCell<Stored<T>>,
425 binding: Option<Box<dyn Fn() -> T>>,
426 dependency: Rc<DependencyNode>,
427}
428
429impl<T> Default for Property<T> {
430 fn default() -> Self {
431 Self::new(None)
432 }
433}
434
435impl<T> Property<T> {
436 pub fn new(binding: Option<Box<dyn Fn() -> T>>) -> Self {
437 Self {
438 value: RefCell::new(Stored::Unset),
439 binding,
440 dependency: Rc::default(),
441 }
442 }
443
444 pub fn set(&self, value: T) {
445 self.replace(Stored::Explicit(value), true);
446 }
447
448 pub fn is_dirty(&self) -> bool {
450 self.dependency.dirty.get()
451 }
452
453 pub(crate) fn matches_current(&self, predicate: impl FnOnce(&T) -> bool) -> bool {
455 match &*self.value.borrow() {
456 Stored::Explicit(value) => predicate(value),
457 Stored::Cached(value) if !self.dependency.dirty.get() => predicate(value),
458 _ => false,
459 }
460 }
461
462 pub fn reset(&self) {
463 if matches!(*self.value.borrow(), Stored::Explicit(_)) {
464 self.replace(Stored::Unset, true);
465 }
466 }
467
468 fn replace(&self, value: Stored<T>, changed: bool) {
469 let previous = self.value.replace(value);
470 self.dependency.detach();
471 self.dependency.dirty.set(true);
472 if changed {
473 self.dependency.notify();
474 }
475 drop(previous);
476 }
477 #[doc(hidden)]
478 pub fn set_if_changed_by(&self, value: T, equal: impl FnOnce(&T, &T) -> bool) {
479 let changed = match &*self.value.borrow() {
480 Stored::Explicit(current) => {
481 if equal(current, &value) {
482 return;
483 }
484 true
485 }
486 Stored::Cached(current) if !self.dependency.dirty.get() => !equal(current, &value),
487 Stored::Unset | Stored::Cached(_) => true,
488 };
489 self.replace(Stored::Explicit(value), changed);
490 }
491}
492
493impl<T: PartialEq> Property<T> {
494 pub fn set_if_changed(&self, value: T) {
496 self.set_if_changed_by(value, T::eq);
497 }
498}
499
500impl<T: Clone> Property<T> {
501 #[doc(hidden)]
503 pub fn cached_value(&self) -> Option<T> {
504 match &*self.value.borrow() {
505 Stored::Explicit(value) => Some(value.clone()),
506 Stored::Cached(value) if !self.dependency.dirty.get() => Some(value.clone()),
507 _ => None,
508 }
509 }
510
511 pub fn explicit_value(&self) -> Option<T> {
513 self.dependency.track();
514 match &*self.value.borrow() {
515 Stored::Explicit(value) => Some(value.clone()),
516 _ => None,
517 }
518 }
519
520 pub fn get(&self, default: impl FnOnce() -> T) -> T {
521 self.try_get(|| Ok::<_, std::convert::Infallible>(default()))
522 .unwrap_or_else(|error| match error {})
523 }
524
525 #[doc(hidden)]
527 pub fn try_get<E>(&self, default: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
528 self.try_get_with(|| match &self.binding {
529 Some(binding) => Ok(binding()),
530 None => default(),
531 })
532 }
533
534 fn try_get_with<E>(&self, read: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
535 assert!(
536 !self.dependency.evaluating.get(),
537 "cyclic property evaluation"
538 );
539 self.dependency.track();
540 match &*self.value.borrow() {
541 Stored::Explicit(value) => return Ok(value.clone()),
542 Stored::Cached(value) if !self.dependency.dirty.get() => {
543 crate::update_profile::property(false);
544 return Ok(value.clone());
545 }
546 Stored::Unset | Stored::Cached(_) => {}
547 }
548
549 crate::update_profile::property(true);
550 let value = self.dependency.evaluate(read);
551 let value = match value {
552 Ok(value) => value,
553 Err(error) => {
554 if !self.dependency.dirty.replace(true) {
555 self.dependency.notify();
556 }
557 return Err(error);
558 }
559 };
560 if !self.dependency.dirty.get() {
561 let cached = value.clone();
562 if !self.dependency.dirty.get() {
563 self.value.replace(Stored::Cached(cached));
564 }
565 }
566 Ok(value)
567 }
568}
569
570impl<T: Clone, E: Clone> Property<Result<T, E>> {
571 fn get_result(&self, default: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
572 self.try_get_with(|| {
573 match &self.binding {
574 Some(binding) => binding(),
575 None => default(),
576 }
577 .map(Ok)
578 })?
579 }
580}
581
582#[doc(hidden)]
585pub enum InputProperty<T> {
586 Local(Property<T>),
587 Linked {
588 read: Box<dyn Fn() -> Option<T>>,
589 write: Box<dyn Fn(T)>,
590 },
591 State {
592 value: Property<T>,
593 read: Box<dyn Fn() -> Option<T>>,
594 base: Box<Self>,
595 },
596}
597
598impl<T> Default for InputProperty<T> {
599 fn default() -> Self {
600 Self::Local(Property::default())
601 }
602}
603
604impl<T> InputProperty<T> {
605 pub fn bound(read: impl Fn() -> T + 'static) -> Self {
606 Self::Local(Property::new(Some(Box::new(read))))
607 }
608
609 #[doc(hidden)]
612 pub fn bound_optional(read: impl Fn() -> Option<T> + 'static) -> Self {
613 Self::default().with_state(read)
614 }
615
616 pub fn linked(read: impl Fn() -> Option<T> + 'static, write: impl Fn(T) + 'static) -> Self {
617 Self::Linked {
618 read: Box::new(read),
619 write: Box::new(write),
620 }
621 }
622
623 pub fn with_state(self, read: impl Fn() -> Option<T> + 'static) -> Self {
626 Self::State {
627 value: Property::default(),
628 read: Box::new(read),
629 base: Box::new(self),
630 }
631 }
632
633 pub fn reset(&self) {
634 match self {
635 Self::Local(value) | Self::State { value, .. } => value.reset(),
636 Self::Linked { .. } => {}
637 }
638 }
639
640 #[doc(hidden)]
641 pub fn set_if_changed_by(&self, value: T, equal: impl FnOnce(&T, &T) -> bool) {
642 match self {
643 Self::Local(property)
644 | Self::State {
645 value: property, ..
646 } => property.set_if_changed_by(value, equal),
647 Self::Linked { write, .. } => write(value),
648 }
649 }
650}
651
652impl<T: Clone> InputProperty<T> {
653 pub fn get(&self, default: impl FnOnce() -> T) -> T {
654 match self {
655 Self::Local(property) => property.get(default),
656 Self::Linked { read, .. } => read().unwrap_or_else(default),
657 Self::State { value, read, base } => {
658 value.get(|| read().unwrap_or_else(|| base.get(default)))
659 }
660 }
661 }
662}
663
664impl<T: Clone, E: Clone> InputProperty<Result<T, E>> {
665 #[doc(hidden)]
667 pub fn get_result(&self, default: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
668 match self {
669 Self::Local(property) => property.get_result(default),
670 Self::Linked { read, .. } => read().unwrap_or_else(default),
671 Self::State { value, read, base } => {
672 value.get_result(|| read().unwrap_or_else(|| base.get_result(default)))
673 }
674 }
675 }
676}
677
678impl<T: PartialEq> InputProperty<T> {
679 pub fn set_if_changed(&self, value: T) {
680 self.set_if_changed_by(value, T::eq);
681 }
682}
683
684#[cfg(test)]
685mod tests {
686 use super::*;
687 use std::panic::{AssertUnwindSafe, catch_unwind};
688
689 #[test]
690 fn read_watch_keeps_live_inputs_of_a_dropped_cached_binding() {
691 let input = Rc::new(Property::default());
692 input.set(1);
693 let sampled = Property::new(Some(Box::new({
694 let input = input.clone();
695 move || input.get(|| 0)
696 })));
697 assert_eq!(sampled.get(|| 0), 1);
698
699 watch_reads(|reads| {
700 assert_eq!(sampled.get(|| 0), 1);
701 drop(sampled);
702 assert!(!reads.changed());
703 input.set(2);
704 assert!(reads.changed());
705 });
706 }
707
708 #[test]
709 fn state_input_restores_the_live_fallback_after_reset() {
710 let active = Rc::new(Property::default());
711 active.set(true);
712 let base = Property::default();
713 base.set(1);
714 let state = active.clone();
715 let input = InputProperty::default().with_state(move || state.get(|| false).then_some(2));
716 let read = || input.get(|| base.get(|| 0));
717
718 assert_eq!(read(), 2);
719 input.set_if_changed(2);
720 active.set(false);
721 base.set(3);
722 assert_eq!(read(), 2);
723 input.reset();
724 assert_eq!(read(), 3);
725 active.set(true);
726 assert_eq!(read(), 2);
727 }
728
729 #[test]
730 fn invalidation_reaches_a_diamond_once() {
731 let source = Property::default();
732 let left = Property::default();
733 let right = Property::default();
734 let total = Property::default();
735 let evaluations = Cell::new(0);
736
737 source.set(1);
738 let value = || {
739 total.get(|| {
740 evaluations.set(evaluations.get() + 1);
741 let left = left.get(|| source.get(|| 0) + source.get(|| 0));
742 left + right.get(|| source.get(|| 0) * 3)
743 })
744 };
745 assert_eq!(value(), 5);
746 source.set(2);
747 source.set(3);
748 assert_eq!(evaluations.get(), 1);
749 assert_eq!(value(), 15);
750 assert_eq!(value(), 15);
751 assert_eq!(evaluations.get(), 2);
752 }
753
754 #[test]
755 fn unwinding_a_nested_evaluation_allows_retry_and_restores_tracking() {
756 let source = Property::default();
757 let inner = Property::default();
758 let outer = Property::default();
759 let first = Cell::new(true);
760 source.set(7);
761
762 let value = || {
763 outer.get(|| {
764 catch_unwind(AssertUnwindSafe(|| {
765 inner.get(|| {
766 let number = source.get(|| 0);
767 assert!(!first.replace(false), "transient failure");
768 number
769 })
770 }))
771 .unwrap_or(0)
772 })
773 };
774 assert_eq!(value(), 0);
775 assert_eq!(value(), 7);
776 source.set(9);
777 assert_eq!(value(), 9);
778 }
779
780 #[test]
781 fn invalidation_during_evaluation_does_not_cache_an_obsolete_result() {
782 let source = Property::default();
783 let derived = Property::default();
784 source.set(1);
785
786 assert_eq!(
787 derived.get(|| {
788 let previous = source.get(|| 0);
789 source.set(2);
790 previous
791 }),
792 1
793 );
794 assert_eq!(derived.get(|| source.get(|| 0)), 2);
795 assert_eq!(derived.get(|| panic!("cache should be valid")), 2);
796 }
797
798 #[test]
799 fn dropping_a_source_invalidates_bindings_that_read_through_weak_references() {
800 let source = Rc::new(Property::default());
801 source.set(8);
802 let weak = Rc::downgrade(&source);
803 let derived = Property::default();
804 let value = || derived.get(|| weak.upgrade().map_or(0, |source| source.get(|| 0)));
805 assert_eq!(value(), 8);
806 drop(source);
807 assert_eq!(value(), 0);
808 }
809}