Skip to main content

xrack_runtime/
property.rs

1//! Lazy property bindings with dynamically tracked dependencies.
2use std::{
3    cell::{Cell, OnceCell, RefCell},
4    collections::HashMap,
5    rc::{Rc, Weak},
6};
7
8thread_local! {
9    static EVALUATING: RefCell<EvaluationContext> = const {
10        RefCell::new(EvaluationContext { binding: None, watches: Vec::new() })
11    };
12}
13
14struct EvaluationContext {
15    binding: Option<Rc<DependencyNode>>,
16    watches: Vec<Rc<ReadWatch>>,
17}
18
19/// Observe writes to dependencies read while preparing a transaction.
20#[derive(Default)]
21pub(crate) struct ReadWatch {
22    sources: RefCell<HashMap<*const DependencyNode, Weak<DependencyNode>>>,
23    next_prune: Cell<usize>,
24    changed: Cell<bool>,
25}
26
27impl ReadWatch {
28    fn observe(&self, node: &Rc<DependencyNode>) {
29        let mut sources = self.sources.borrow_mut();
30        if sources.contains_key(&Rc::as_ptr(node)) {
31            return;
32        }
33        if sources.len() >= self.next_prune.get() {
34            sources.retain(|_, source| source.strong_count() != 0);
35            self.next_prune.set(sources.len().saturating_mul(2).max(64));
36        }
37        // Clean bindings may use their cached value without reading their inputs again.
38        let mut pending = Vec::new();
39        let mut next = Some(node.clone());
40        while let Some(node) = next {
41            if let std::collections::hash_map::Entry::Vacant(source) =
42                sources.entry(Rc::as_ptr(&node))
43            {
44                source.insert(Rc::downgrade(&node));
45                if !node.dirty.get() {
46                    pending.extend(node.sources.borrow().iter().filter_map(Weak::upgrade));
47                }
48            }
49            next = pending.pop();
50        }
51    }
52
53    pub(crate) fn changed(&self) -> bool {
54        self.changed.get()
55    }
56}
57
58pub(crate) fn watch_reads<T>(operation: impl FnOnce(&ReadWatch) -> T) -> T {
59    struct Scope;
60    impl Drop for Scope {
61        fn drop(&mut self) {
62            EVALUATING.with(|context| context.borrow_mut().watches.pop());
63        }
64    }
65
66    let watch = Rc::new(ReadWatch::default());
67    EVALUATING.with(|context| context.borrow_mut().watches.push(watch.clone()));
68    let _scope = Scope;
69    operation(&watch)
70}
71
72#[derive(Default)]
73struct DependencyNode {
74    dirty: Cell<bool>,
75    evaluating: Cell<bool>,
76    sources: RefCell<Vec<Weak<Self>>>,
77    dependents: RefCell<Vec<Weak<Self>>>,
78}
79
80impl DependencyNode {
81    fn track(self: &Rc<Self>) {
82        EVALUATING.with(|current| {
83            let current = current.borrow();
84            for watch in &current.watches {
85                watch.observe(self);
86            }
87            let Some(binding) = current.binding.as_ref() else {
88                return;
89            };
90            if Rc::ptr_eq(self, binding) {
91                return;
92            }
93            let mut sources = binding.sources.borrow_mut();
94            let source = Rc::downgrade(self);
95            if !sources.iter().any(|existing| existing.ptr_eq(&source)) {
96                sources.push(source);
97                self.dependents.borrow_mut().push(Rc::downgrade(binding));
98            }
99        });
100    }
101
102    fn detach(&self) {
103        let address = self as *const Self;
104        for source in self.sources.take() {
105            if let Some(source) = source.upgrade() {
106                source
107                    .dependents
108                    .borrow_mut()
109                    .retain(|binding| binding.as_ptr() != address);
110            }
111        }
112    }
113
114    fn push_dependents(&self, pending: &mut Vec<Rc<Self>>) {
115        self.dependents.borrow_mut().retain(|weak| {
116            if let Some(binding) = weak.upgrade() {
117                pending.push(binding);
118                true
119            } else {
120                false
121            }
122        });
123    }
124
125    fn notify(&self) {
126        EVALUATING.with(|context| {
127            let address = std::ptr::from_ref(self);
128            for watch in &context.borrow().watches {
129                if watch.sources.borrow().contains_key(&address) {
130                    watch.changed.set(true);
131                }
132            }
133        });
134        self.invalidate_dependents();
135    }
136
137    fn invalidate_dependents(&self) {
138        let mut pending = Vec::new();
139        self.push_dependents(&mut pending);
140        while let Some(binding) = pending.pop() {
141            if !binding.dirty.replace(true) {
142                binding.push_dependents(&mut pending);
143            }
144        }
145    }
146
147    fn evaluate<T>(self: &Rc<Self>, binding: impl FnOnce() -> T) -> T {
148        self.detach();
149        self.evaluating.set(true);
150        self.dirty.set(false);
151        let mut evaluation = Evaluation {
152            node: self,
153            previous: EVALUATING.with(|current| current.borrow_mut().binding.replace(self.clone())),
154            completed: false,
155        };
156        let value = binding();
157        evaluation.completed = true;
158        value
159    }
160}
161
162impl Drop for DependencyNode {
163    fn drop(&mut self) {
164        self.detach();
165        // Ending a temporary binding is not a write to an input used by a transaction.
166        self.invalidate_dependents();
167    }
168}
169
170struct Evaluation<'a> {
171    node: &'a DependencyNode,
172    previous: Option<Rc<DependencyNode>>,
173    completed: bool,
174}
175
176impl Drop for Evaluation<'_> {
177    fn drop(&mut self) {
178        EVALUATING.with(|current| {
179            current.borrow_mut().binding = self.previous.take();
180        });
181        self.node.evaluating.set(false);
182        if !self.completed && !self.node.dirty.replace(true) {
183            self.node.notify();
184        }
185    }
186}
187
188/// A dependency on mutable state that is stored outside a property.
189#[derive(Default)]
190pub struct ChangeSignal(Rc<DependencyNode>);
191
192impl ChangeSignal {
193    pub(crate) fn is_tracking() -> bool {
194        EVALUATING.with(|current| {
195            let current = current.borrow();
196            current.binding.is_some() || !current.watches.is_empty()
197        })
198    }
199
200    pub(crate) fn has_observers(&self) -> bool {
201        !self.0.dependents.borrow().is_empty()
202            || EVALUATING.with(|context| {
203                let address = Rc::as_ptr(&self.0);
204                context
205                    .borrow()
206                    .watches
207                    .iter()
208                    .any(|watch| watch.sources.borrow().contains_key(&address))
209            })
210    }
211
212    pub fn track(&self) {
213        self.0.track();
214    }
215
216    pub fn notify(&self) {
217        self.0.notify();
218    }
219}
220
221/// A dependency on the lifetime of a component that owns a weak binding.
222#[doc(hidden)]
223#[derive(Default)]
224pub struct ComponentLifetime {
225    signal: OnceCell<ChangeSignal>,
226    pub(crate) weak: crate::event_loop::WeakRegistration,
227}
228
229impl ComponentLifetime {
230    pub fn track(&self) {
231        self.signal.get_or_init(ChangeSignal::default).track();
232    }
233}
234
235enum Stored<T> {
236    Unset,
237    Explicit(T),
238    Cached(T),
239}
240
241/// Stores an explicit value or a lazily computed binding result.
242///
243/// The default closure supplied to `get` describes the same binding on each read.
244pub struct Property<T> {
245    value: RefCell<Stored<T>>,
246    binding: Option<Box<dyn Fn() -> T>>,
247    dependency: Rc<DependencyNode>,
248}
249
250impl<T> Default for Property<T> {
251    fn default() -> Self {
252        Self::new(None)
253    }
254}
255
256impl<T> Property<T> {
257    pub fn new(binding: Option<Box<dyn Fn() -> T>>) -> Self {
258        Self {
259            value: RefCell::new(Stored::Unset),
260            binding,
261            dependency: Rc::default(),
262        }
263    }
264
265    pub fn set(&self, value: T) {
266        self.replace(Stored::Explicit(value), true);
267    }
268
269    /// Inspect whether a cached binding needs reevaluation without tracking a read.
270    pub fn is_dirty(&self) -> bool {
271        self.dependency.dirty.get()
272    }
273
274    /// Inspect the current explicit or clean cached value without evaluating a binding.
275    pub(crate) fn matches_current(&self, predicate: impl FnOnce(&T) -> bool) -> bool {
276        match &*self.value.borrow() {
277            Stored::Explicit(value) => predicate(value),
278            Stored::Cached(value) if !self.dependency.dirty.get() => predicate(value),
279            _ => false,
280        }
281    }
282
283    pub fn reset(&self) {
284        if matches!(*self.value.borrow(), Stored::Explicit(_)) {
285            self.replace(Stored::Unset, true);
286        }
287    }
288
289    fn replace(&self, value: Stored<T>, changed: bool) {
290        let previous = self.value.replace(value);
291        self.dependency.detach();
292        self.dependency.dirty.set(true);
293        if changed {
294            self.dependency.notify();
295        }
296        drop(previous);
297    }
298    #[doc(hidden)]
299    pub fn set_if_changed_by(&self, value: T, equal: impl FnOnce(&T, &T) -> bool) {
300        let changed = match &*self.value.borrow() {
301            Stored::Explicit(current) => {
302                if equal(current, &value) {
303                    return;
304                }
305                true
306            }
307            Stored::Cached(current) if !self.dependency.dirty.get() => !equal(current, &value),
308            Stored::Unset | Stored::Cached(_) => true,
309        };
310        self.replace(Stored::Explicit(value), changed);
311    }
312}
313
314impl<T: PartialEq> Property<T> {
315    /// Override the binding and invalidate dependents only when its known value changes.
316    pub fn set_if_changed(&self, value: T) {
317        self.set_if_changed_by(value, T::eq);
318    }
319}
320
321impl<T: Clone> Property<T> {
322    /// Observe an explicit override while leaving the default to the caller.
323    pub fn explicit_value(&self) -> Option<T> {
324        self.dependency.track();
325        match &*self.value.borrow() {
326            Stored::Explicit(value) => Some(value.clone()),
327            _ => None,
328        }
329    }
330
331    pub fn get(&self, default: impl FnOnce() -> T) -> T {
332        self.try_get(|| Ok::<_, std::convert::Infallible>(default()))
333            .unwrap_or_else(|error| match error {})
334    }
335
336    /// Evaluate a binding without caching a failed result.
337    #[doc(hidden)]
338    pub fn try_get<E>(&self, default: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
339        self.try_get_with(|| match &self.binding {
340            Some(binding) => Ok(binding()),
341            None => default(),
342        })
343    }
344
345    fn try_get_with<E>(&self, read: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
346        assert!(
347            !self.dependency.evaluating.get(),
348            "cyclic property evaluation"
349        );
350        self.dependency.track();
351        match &*self.value.borrow() {
352            Stored::Explicit(value) => return Ok(value.clone()),
353            Stored::Cached(value) if !self.dependency.dirty.get() => return Ok(value.clone()),
354            Stored::Unset | Stored::Cached(_) => {}
355        }
356
357        let value = self.dependency.evaluate(read);
358        let value = match value {
359            Ok(value) => value,
360            Err(error) => {
361                if !self.dependency.dirty.replace(true) {
362                    self.dependency.notify();
363                }
364                return Err(error);
365            }
366        };
367        if !self.dependency.dirty.get() {
368            let cached = value.clone();
369            if !self.dependency.dirty.get() {
370                self.value.replace(Stored::Cached(cached));
371            }
372        }
373        Ok(value)
374    }
375}
376
377impl<T: Clone, E: Clone> Property<Result<T, E>> {
378    fn get_result(&self, default: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
379        self.try_get_with(|| {
380            match &self.binding {
381                Some(binding) => binding(),
382                None => default(),
383            }
384            .map(Ok)
385        })?
386    }
387}
388
389/// Storage for a generated component input. Linked inputs track the actual
390/// source property and forward writes without allocating a second value slot.
391#[doc(hidden)]
392pub enum InputProperty<T> {
393    Local(Property<T>),
394    Linked {
395        read: Box<dyn Fn() -> Option<T>>,
396        write: Box<dyn Fn(T)>,
397    },
398    State {
399        value: Property<T>,
400        read: Box<dyn Fn() -> Option<T>>,
401        base: Box<Self>,
402    },
403}
404
405impl<T> Default for InputProperty<T> {
406    fn default() -> Self {
407        Self::Local(Property::default())
408    }
409}
410
411impl<T> InputProperty<T> {
412    pub fn bound(read: impl Fn() -> T + 'static) -> Self {
413        Self::Local(Property::new(Some(Box::new(read))))
414    }
415
416    /// Evaluate a supplied binding while it is available, then use the
417    /// component's own property default.
418    #[doc(hidden)]
419    pub fn bound_optional(read: impl Fn() -> Option<T> + 'static) -> Self {
420        Self::default().with_state(read)
421    }
422
423    pub fn linked(read: impl Fn() -> Option<T> + 'static, write: impl Fn(T) + 'static) -> Self {
424        Self::Linked {
425            read: Box::new(read),
426            write: Box::new(write),
427        }
428    }
429
430    /// Add a lazy state binding above an existing input. An explicit write
431    /// replaces this binding until reset, including when the value is equal.
432    pub fn with_state(self, read: impl Fn() -> Option<T> + 'static) -> Self {
433        Self::State {
434            value: Property::default(),
435            read: Box::new(read),
436            base: Box::new(self),
437        }
438    }
439
440    pub fn reset(&self) {
441        match self {
442            Self::Local(value) | Self::State { value, .. } => value.reset(),
443            Self::Linked { .. } => {}
444        }
445    }
446
447    #[doc(hidden)]
448    pub fn set_if_changed_by(&self, value: T, equal: impl FnOnce(&T, &T) -> bool) {
449        match self {
450            Self::Local(property)
451            | Self::State {
452                value: property, ..
453            } => property.set_if_changed_by(value, equal),
454            Self::Linked { write, .. } => write(value),
455        }
456    }
457}
458
459impl<T: Clone> InputProperty<T> {
460    pub fn get(&self, default: impl FnOnce() -> T) -> T {
461        match self {
462            Self::Local(property) => property.get(default),
463            Self::Linked { read, .. } => read().unwrap_or_else(default),
464            Self::State { value, read, base } => {
465                value.get(|| read().unwrap_or_else(|| base.get(default)))
466            }
467        }
468    }
469}
470
471impl<T: Clone, E: Clone> InputProperty<Result<T, E>> {
472    /// A failed input read leaves the binding dirty so it can be retried.
473    #[doc(hidden)]
474    pub fn get_result(&self, default: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
475        match self {
476            Self::Local(property) => property.get_result(default),
477            Self::Linked { read, .. } => read().unwrap_or_else(default),
478            Self::State { value, read, base } => {
479                value.get_result(|| read().unwrap_or_else(|| base.get_result(default)))
480            }
481        }
482    }
483}
484
485impl<T: PartialEq> InputProperty<T> {
486    pub fn set_if_changed(&self, value: T) {
487        self.set_if_changed_by(value, T::eq);
488    }
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494    use std::panic::{AssertUnwindSafe, catch_unwind};
495
496    #[test]
497    fn read_watch_keeps_live_inputs_of_a_dropped_cached_binding() {
498        let input = Rc::new(Property::default());
499        input.set(1);
500        let sampled = Property::new(Some(Box::new({
501            let input = input.clone();
502            move || input.get(|| 0)
503        })));
504        assert_eq!(sampled.get(|| 0), 1);
505
506        watch_reads(|reads| {
507            assert_eq!(sampled.get(|| 0), 1);
508            drop(sampled);
509            assert!(!reads.changed());
510            input.set(2);
511            assert!(reads.changed());
512        });
513    }
514
515    #[test]
516    fn state_input_restores_the_live_fallback_after_reset() {
517        let active = Rc::new(Property::default());
518        active.set(true);
519        let base = Property::default();
520        base.set(1);
521        let state = active.clone();
522        let input = InputProperty::default().with_state(move || state.get(|| false).then_some(2));
523        let read = || input.get(|| base.get(|| 0));
524
525        assert_eq!(read(), 2);
526        input.set_if_changed(2);
527        active.set(false);
528        base.set(3);
529        assert_eq!(read(), 2);
530        input.reset();
531        assert_eq!(read(), 3);
532        active.set(true);
533        assert_eq!(read(), 2);
534    }
535
536    #[test]
537    fn invalidation_reaches_a_diamond_once() {
538        let source = Property::default();
539        let left = Property::default();
540        let right = Property::default();
541        let total = Property::default();
542        let evaluations = Cell::new(0);
543
544        source.set(1);
545        let value = || {
546            total.get(|| {
547                evaluations.set(evaluations.get() + 1);
548                let left = left.get(|| source.get(|| 0) + source.get(|| 0));
549                left + right.get(|| source.get(|| 0) * 3)
550            })
551        };
552        assert_eq!(value(), 5);
553        source.set(2);
554        source.set(3);
555        assert_eq!(evaluations.get(), 1);
556        assert_eq!(value(), 15);
557        assert_eq!(value(), 15);
558        assert_eq!(evaluations.get(), 2);
559    }
560
561    #[test]
562    fn unwinding_a_nested_evaluation_allows_retry_and_restores_tracking() {
563        let source = Property::default();
564        let inner = Property::default();
565        let outer = Property::default();
566        let first = Cell::new(true);
567        source.set(7);
568
569        let value = || {
570            outer.get(|| {
571                catch_unwind(AssertUnwindSafe(|| {
572                    inner.get(|| {
573                        let number = source.get(|| 0);
574                        assert!(!first.replace(false), "transient failure");
575                        number
576                    })
577                }))
578                .unwrap_or(0)
579            })
580        };
581        assert_eq!(value(), 0);
582        assert_eq!(value(), 7);
583        source.set(9);
584        assert_eq!(value(), 9);
585    }
586
587    #[test]
588    fn invalidation_during_evaluation_does_not_cache_an_obsolete_result() {
589        let source = Property::default();
590        let derived = Property::default();
591        source.set(1);
592
593        assert_eq!(
594            derived.get(|| {
595                let previous = source.get(|| 0);
596                source.set(2);
597                previous
598            }),
599            1
600        );
601        assert_eq!(derived.get(|| source.get(|| 0)), 2);
602        assert_eq!(derived.get(|| panic!("cache should be valid")), 2);
603    }
604
605    #[test]
606    fn dropping_a_source_invalidates_bindings_that_read_through_weak_references() {
607        let source = Rc::new(Property::default());
608        source.set(8);
609        let weak = Rc::downgrade(&source);
610        let derived = Property::default();
611        let value = || derived.get(|| weak.upgrade().map_or(0, |source| source.get(|| 0)));
612        assert_eq!(value(), 8);
613        drop(source);
614        assert_eq!(value(), 0);
615    }
616}