1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
use crate::{observable::ObservableInternalFns, static_state};
use std::{
    cell::{Cell, Ref, RefCell},
    rc::{Rc, Weak},
};

pub trait IsUnchanged {
    fn is_unchanged(&self, _other: &Self) -> bool {
        false
    }
}

impl<T> IsUnchanged for T {
    default fn is_unchanged(&self, _other: &Self) -> bool {
        false
    }
}

pub(crate) trait ObserverInternalFns {
    fn send_stale(&self);
    fn send_ready(&self, changed: bool);
    fn update(&self);
    fn get_unique_data_address(&self) -> *const ();
}

/// Helper struct which stores observers that should be notified whenever an observable object
/// changes. Used by both Observable and Derivation.
#[derive(Default)]
pub(crate) struct ObserverList {
    observers: Cell<Vec<Weak<dyn ObserverInternalFns>>>,
}

impl ObserverList {
    pub fn broadcast_stale(&self) {
        let list = self.observers.take();
        for observer in &list {
            observer.upgrade().unwrap().send_stale();
        }
        self.observers.set(list);
    }

    pub fn broadcast_ready(&self, changed: bool) {
        let list = self.observers.take();
        for observer in &list {
            observer.upgrade().unwrap().send_ready(changed);
        }
        self.observers.set(list);
    }

    pub fn add(&self, observer: Weak<dyn ObserverInternalFns>) {
        let mut list = self.observers.take();
        if list.iter().any(|item| Weak::ptr_eq(&observer, item)) {
            panic!("Tried to subscribe the same observer twice.");
        }
        list.push(observer);
        self.observers.set(list);
    }

    pub fn remove(&self, observer: &Weak<dyn ObserverInternalFns>) {
        let mut list = self.observers.take();
        let index = list.iter().position(|item| Weak::ptr_eq(item, observer));
        let index = index.expect(
            "(Internal error) Tried to unsubscribe an observer that was already unsubscribed.",
        );
        list.remove(index);
        self.observers.set(list);
    }
}

#[repr(C)]
struct DerivationData<T: IsUnchanged + 'static, F: FnMut() -> T + 'static> {
    this_ptr: Weak<dyn ObserverInternalFns>,
    observers: ObserverList,
    observing: Cell<Vec<Rc<dyn ObservableInternalFns>>>,
    num_stale_notifications: Cell<usize>,
    /// True if fields we are observing have changed and we need to update once
    /// num_stale_notifications reaches zero.
    should_update: Cell<bool>,
    compute_value: RefCell<F>,
    value: RefCell<T>,
}

impl<T: IsUnchanged + 'static, F: FnMut() -> T + 'static> ObserverInternalFns
    for DerivationData<T, F>
{
    /// Called when a value this observer depends on becomes stale.
    fn send_stale(&self) {
        let old = self
            .num_stale_notifications
            .replace(self.num_stale_notifications.get() + 1);
        // Don't send multiple stale notifications when we receive multiple stale notifications.
        if old == 0 {
            self.observers.broadcast_stale();
        }
    }

    /// Called when a value this observer depends on finishes updating. `changed` is false if the
    /// value has not changed.
    fn send_ready(&self, changed: bool) {
        let nsn = self.num_stale_notifications.get() - 1;
        self.num_stale_notifications.set(nsn);
        let should_update = self.should_update.get() || changed;
        self.should_update.set(should_update);
        if nsn == 0 {
            if should_update {
                self.update();
            } else {
                self.observers.broadcast_ready(false);
            }
        }
    }

    fn update(&self) {
        assert!(self.should_update.get());
        self.should_update.set(false);

        static_state::push_observing_stack();
        let new_value = (self.compute_value.borrow_mut())();
        let now_observing = static_state::pop_observing_stack();
        let was_observing = self.observing.take();
        for observable in &was_observing {
            let uda = observable.get_unique_data_address();
            // If we are no longer observing something we used to...
            if !now_observing
                .iter()
                .any(|other| uda == other.get_unique_data_address())
            {
                observable.remove_observer(&self.this_ptr)
            }
        }
        for observable in &now_observing {
            let uda = observable.get_unique_data_address();
            // If we are observing something we weren't observing before...
            if !was_observing
                .iter()
                .any(|other| uda == other.get_unique_data_address())
            {
                observable.add_observer(Weak::clone(&self.this_ptr));
            }
        }
        self.observing.set(now_observing);

        let changed = !(&*self.value.borrow()).is_unchanged(&new_value);
        if changed {
            self.value.replace(new_value);
        }

        self.observers.broadcast_ready(changed);
    }

    fn get_unique_data_address(&self) -> *const () {
        self.value.as_ptr() as _
    }
}

impl<T: IsUnchanged, F: FnMut() -> T> Drop for DerivationData<T, F> {
    fn drop(&mut self) {
        for observable in self.observing.take() {
            observable.remove_observer(&self.this_ptr);
        }
    }
}

impl<T: IsUnchanged, F: FnMut() -> T> ObservableInternalFns for DerivationData<T, F> {
    fn add_observer(&self, observer: Weak<dyn ObserverInternalFns>) {
        self.observers.add(observer);
    }

    fn remove_observer(&self, observer: &Weak<dyn ObserverInternalFns>) {
        self.observers.remove(observer);
    }

    fn get_unique_data_address(&self) -> *const () {
        self.value.as_ptr() as _
    }
}

pub struct DerivationPtr<T: IsUnchanged + 'static, F: FnMut() -> T + 'static> {
    ptr: Rc<DerivationData<T, F>>,
}

impl<T: IsUnchanged + 'static, F: FnMut() -> T + 'static> Clone for DerivationPtr<T, F> {
    fn clone(&self) -> Self {
        Self {
            ptr: Rc::clone(&self.ptr),
        }
    }
}

impl<T: IsUnchanged + 'static, F: FnMut() -> T + 'static> DerivationPtr<T, F> {
    pub fn new(mut compute_value: F) -> Self {
        static_state::push_observing_stack();
        let initial_value = compute_value();
        let observing = static_state::pop_observing_stack();
        let ptr = Rc::new_cyclic(|weak| DerivationData {
            this_ptr: Weak::clone(weak) as _,
            num_stale_notifications: Cell::new(0),
            observers: Default::default(),
            observing: Cell::new(observing.clone()),
            should_update: Cell::new(false),
            compute_value: RefCell::new(compute_value),
            value: RefCell::new(initial_value),
        });
        let weak = &ptr.this_ptr;
        for observable in &observing {
            observable.add_observer(Weak::clone(weak) as _);
        }
        Self { ptr }
    }

    pub fn new_dyn(compute_value: F) -> DerivationPtr<T, Box<dyn FnMut() -> T + 'static>> {
        let f = Box::new(compute_value) as _;
        DerivationPtr::new(f)
    }

    pub fn computed(compute_value: F) -> Self {
        Self::new(compute_value)
    }

    pub fn borrow(&self) -> Ref<T> {
        static_state::note_observed(Rc::clone(&self.ptr) as _);
        self.ptr.value.borrow()
    }

    pub fn borrow_untracked(&self) -> Ref<T> {
        self.ptr.value.borrow()
    }
}