Skip to main content

xrack_runtime/
model.rs

1use crate::{ChangeSignal, RowKey, RowLifetime};
2use std::{
3    cell::{Cell, RefCell},
4    cmp::Ordering as Comparison,
5    collections::BTreeMap,
6    fmt,
7    ops::Range,
8    rc::{Rc, Weak},
9    sync::atomic::{AtomicU64, Ordering},
10};
11
12static NEXT_MODEL: AtomicU64 = AtomicU64::new(1);
13
14struct Entry<T> {
15    id: u64,
16    value: T,
17}
18
19#[derive(Default)]
20struct RowSignals {
21    signals: BTreeMap<usize, ChangeSignal>,
22    next_prune: usize,
23}
24
25impl RowSignals {
26    fn track(&mut self, index: usize) {
27        if !self.signals.contains_key(&index) && self.signals.len() >= self.next_prune {
28            self.signals.retain(|_, signal| signal.has_observers());
29            self.next_prune = (self.signals.len() * 2).max(64);
30        }
31        self.signals.entry(index).or_default().track();
32    }
33}
34
35type ProjectionDiff<T> = dyn Fn(usize, &T, &T) -> bool;
36pub(crate) type RowObserver<T> = dyn Fn(RowKey, Option<&T>);
37
38struct RowProjection<T> {
39    signal: Weak<ChangeSignal>,
40    limit: usize,
41    changed: Box<ProjectionDiff<T>>,
42}
43
44struct ModelData<T> {
45    id: u64,
46    rows: RefCell<Vec<Entry<T>>>,
47    next_row: Cell<u64>,
48    revision: Cell<u64>,
49    edit_revision: Cell<u64>,
50    lifetimes: RefCell<BTreeMap<u64, Rc<()>>>,
51    count: ChangeSignal,
52    structure: ChangeSignal,
53    values: ChangeSignal,
54    row_signals: RefCell<RowSignals>,
55    projections: RefCell<Vec<RowProjection<T>>>,
56    row_observers: RefCell<Vec<Weak<RowObserver<T>>>>,
57}
58
59/// A shared UI-thread model with separately tracked row and length reads.
60/// Cloning the handle shares its data and subscriptions.
61pub struct VecModel<T>(Rc<ModelData<T>>);
62
63impl<T> fmt::Debug for VecModel<T> {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.debug_struct("VecModel")
66            .field("id", &self.0.id)
67            .finish_non_exhaustive()
68    }
69}
70
71impl<T> Clone for VecModel<T> {
72    fn clone(&self) -> Self {
73        Self(self.0.clone())
74    }
75}
76
77impl<T> From<Vec<T>> for VecModel<T> {
78    fn from(rows: Vec<T>) -> Self {
79        let id = NEXT_MODEL
80            .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
81            .expect("model identity exhausted");
82        let next_row = rows.len() as u64;
83        Self(Rc::new(ModelData {
84            id,
85            rows: RefCell::new(
86                rows.into_iter()
87                    .enumerate()
88                    .map(|(id, value)| Entry {
89                        id: id as u64,
90                        value,
91                    })
92                    .collect(),
93            ),
94            next_row: Cell::new(next_row),
95            revision: Cell::default(),
96            edit_revision: Cell::default(),
97            lifetimes: RefCell::default(),
98            count: ChangeSignal::default(),
99            structure: ChangeSignal::default(),
100            values: ChangeSignal::default(),
101            row_signals: RefCell::default(),
102            projections: RefCell::default(),
103            row_observers: RefCell::default(),
104        }))
105    }
106}
107
108impl<T> Default for VecModel<T> {
109    fn default() -> Self {
110        Self::from(Vec::new())
111    }
112}
113
114impl<T> PartialEq for VecModel<T> {
115    fn eq(&self, other: &Self) -> bool {
116        Rc::ptr_eq(&self.0, &other.0)
117    }
118}
119
120impl<T> Eq for VecModel<T> {}
121
122impl<T> VecModel<T> {
123    pub(crate) fn is_shared(&self) -> bool {
124        Rc::strong_count(&self.0) > 1
125    }
126
127    fn entry(&self, value: T) -> Entry<T> {
128        let id = self.0.next_row.get();
129        self.0
130            .next_row
131            .set(id.checked_add(1).expect("model row identity exhausted"));
132        Entry { id, value }
133    }
134
135    /// A stable identity that survives edits, inserts, removes of other rows, and sorting.
136    pub fn row_key(&self, index: usize) -> Option<RowKey> {
137        self.0.structure.track();
138        self.0.rows.borrow().get(index).map(|entry| RowKey {
139            model: self.0.id,
140            row: entry.id,
141            scope: 0,
142        })
143    }
144
145    /// Find a record's current index by its stable identity.
146    pub fn row_index(&self, key: RowKey) -> Option<usize> {
147        self.0.structure.track();
148        self.row_index_untracked(key)
149    }
150
151    pub(crate) fn row_index_untracked(&self, key: RowKey) -> Option<usize> {
152        if key.model != self.0.id {
153            return None;
154        }
155        self.0
156            .rows
157            .borrow()
158            .iter()
159            .position(|entry| entry.id == key.row)
160    }
161
162    pub(crate) fn visit_row_keys(&self, range: Range<usize>, mut visit: impl FnMut(RowKey)) {
163        self.0.structure.track();
164        for entry in &self.0.rows.borrow()[range] {
165            visit(RowKey {
166                model: self.0.id,
167                row: entry.id,
168                scope: 0,
169            });
170        }
171    }
172
173    pub(crate) fn visit_row_data(&self, count: usize, visit: impl FnMut(usize, RowKey, &T)) {
174        self.0.values.track();
175        self.visit_rows_untracked(count, visit);
176    }
177
178    /// Borrow the rows after the caller has established the appropriate dependencies.
179    pub(crate) fn visit_rows_untracked(
180        &self,
181        count: usize,
182        mut visit: impl FnMut(usize, RowKey, &T),
183    ) {
184        for (index, entry) in self.0.rows.borrow().iter().take(count).enumerate() {
185            visit(
186                index,
187                RowKey {
188                    model: self.0.id,
189                    row: entry.id,
190                    scope: 0,
191                },
192                &entry.value,
193            );
194        }
195    }
196
197    /// Locate a row after the caller has established the appropriate dependencies.
198    pub(crate) fn position_untracked(
199        &self,
200        range: std::ops::Range<usize>,
201        mut predicate: impl FnMut(&T) -> bool,
202    ) -> Option<usize> {
203        let start = range.start;
204        self.0
205            .rows
206            .borrow()
207            .get(range)?
208            .iter()
209            .position(|entry| predicate(&entry.value))
210            .map(|offset| start + offset)
211    }
212
213    /// Check an editor's field against the identified row without watching other fields.
214    #[doc(hidden)]
215    pub fn row_matches(&self, index: usize, key: RowKey, matches: impl FnOnce(&T) -> bool) -> bool {
216        key.model == self.0.id
217            && self
218                .0
219                .rows
220                .borrow()
221                .get(index)
222                .is_some_and(|entry| entry.id == key.row && matches(&entry.value))
223    }
224
225    pub(crate) fn project_row_untracked<R>(
226        &self,
227        index: usize,
228        project: impl FnOnce(&T) -> R,
229    ) -> Option<R> {
230        self.0
231            .rows
232            .borrow()
233            .get(index)
234            .map(|entry| project(&entry.value))
235    }
236
237    /// Subscribe to changes in the projected value of existing rows. The caller also tracks
238    /// structure changes and keeps the returned signal alive for as long as it uses the projection.
239    pub(crate) fn observe_projection<P: PartialEq>(
240        &self,
241        limit: usize,
242        project: impl Fn(&T) -> P + 'static,
243    ) -> Rc<ChangeSignal> {
244        self.observe_projection_changes(limit, move |_, before, after| {
245            project(before) != project(after)
246        })
247    }
248
249    pub(crate) fn observe_projection_changes(
250        &self,
251        limit: usize,
252        changed: impl Fn(usize, &T, &T) -> bool + 'static,
253    ) -> Rc<ChangeSignal> {
254        let signal = Rc::new(ChangeSignal::default());
255        let mut projections = self.0.projections.borrow_mut();
256        projections.retain(|projection| projection.signal.strong_count() != 0);
257        projections.push(RowProjection {
258            signal: Rc::downgrade(&signal),
259            limit,
260            changed: Box::new(changed),
261        });
262        signal
263    }
264
265    /// Observe row contents by stable key. Observers run while the model may be borrowed.
266    pub(crate) fn observe_rows(&self, observer: &Rc<RowObserver<T>>) {
267        let mut observers = self.0.row_observers.borrow_mut();
268        observers.retain(|observer| observer.strong_count() != 0);
269        observers.push(Rc::downgrade(observer));
270    }
271
272    fn row_changed(&self, id: u64, value: Option<&T>) {
273        let key = RowKey {
274            model: self.0.id,
275            row: id,
276            scope: 0,
277        };
278        self.0.row_observers.borrow_mut().retain(|observer| {
279            if let Some(observer) = observer.upgrade() {
280                observer(key, value);
281                true
282            } else {
283                false
284            }
285        });
286    }
287
288    pub(crate) fn row_lifetime(&self, key: RowKey) -> RowLifetime {
289        let mut lifetimes = self.0.lifetimes.borrow_mut();
290        RowLifetime(Some(Rc::downgrade(lifetimes.entry(key.row).or_default())))
291    }
292
293    pub(crate) fn structure_stamp(&self) -> (u64, u64) {
294        self.0.structure.track();
295        (self.0.id, self.0.revision.get())
296    }
297
298    /// Identify the exact model contents and order seen by an asynchronous edit.
299    #[doc(hidden)]
300    pub fn edit_stamp(&self) -> (u64, u64) {
301        (self.0.id, self.0.edit_revision.get())
302    }
303
304    pub(crate) fn contents_stamp(&self) -> (u64, u64) {
305        self.0.values.track();
306        self.edit_stamp()
307    }
308
309    pub fn len(&self) -> usize {
310        self.0.count.track();
311        self.0.rows.borrow().len()
312    }
313
314    pub fn is_empty(&self) -> bool {
315        self.len() == 0
316    }
317
318    pub fn push(&self, value: T) {
319        let index = {
320            let mut rows = self.0.rows.borrow_mut();
321            let index = rows.len();
322            let entry = self.entry(value);
323            self.row_changed(entry.id, Some(&entry.value));
324            rows.push(entry);
325            index
326        };
327        self.structure_changed(index, true);
328    }
329
330    /// Insert at a model index. An index beyond the end leaves the model unchanged.
331    pub fn insert(&self, index: usize, value: T) -> bool {
332        {
333            let mut rows = self.0.rows.borrow_mut();
334            if index > rows.len() {
335                return false;
336            }
337            let entry = self.entry(value);
338            self.row_changed(entry.id, Some(&entry.value));
339            rows.insert(index, entry);
340        }
341        self.structure_changed(index, true);
342        true
343    }
344
345    pub fn remove(&self, index: usize) -> Option<T> {
346        let removed = {
347            let mut rows = self.0.rows.borrow_mut();
348            if index >= rows.len() {
349                return None;
350            }
351            rows.remove(index)
352        };
353        self.row_changed(removed.id, None);
354        self.0.lifetimes.borrow_mut().remove(&removed.id);
355        self.structure_changed(index, true);
356        Some(removed.value)
357    }
358
359    pub(crate) fn sorted_indices_untracked(
360        &self,
361        limit: usize,
362        compare: impl FnMut(&T, &T) -> Comparison,
363    ) -> Vec<usize> {
364        self.projected_indices_untracked(limit, None, |_| true, Some(compare))
365    }
366
367    pub(crate) fn projected_indices_untracked(
368        &self,
369        limit: usize,
370        base_order: Option<&[usize]>,
371        include: impl Fn(&T) -> bool,
372        compare: Option<impl FnMut(&T, &T) -> Comparison>,
373    ) -> Vec<usize> {
374        let rows = self.0.rows.borrow();
375        let mut order: Vec<_> = (0..rows.len().min(limit))
376            .map(|index| base_order.map_or(index, |order| order[index]))
377            .filter(|&index| include(&rows[index].value))
378            .collect();
379        if let Some(mut compare) = compare {
380            order.sort_by(|&a, &b| compare(&rows[a].value, &rows[b].value));
381        }
382        order
383    }
384
385    /// Stably reorder rows, retaining their keys and delegate lifetimes.
386    pub fn sort_by(&self, compare: impl FnMut(&T, &T) -> Comparison) -> bool {
387        let order = self.sorted_indices_untracked(usize::MAX, compare);
388        let Some(first_changed) = order.iter().enumerate().position(|(new, old)| new != *old)
389        else {
390            return false;
391        };
392        {
393            let mut rows = self.0.rows.borrow_mut();
394            let mut source: Vec<_> = rows.drain(first_changed..).map(Some).collect();
395            rows.extend(order.into_iter().skip(first_changed).map(|index| {
396                source[index - first_changed]
397                    .take()
398                    .expect("sort permutation contains each row once")
399            }));
400        }
401        self.structure_changed(first_changed, false);
402        true
403    }
404
405    fn structure_changed(&self, index: usize, count_changed: bool) {
406        self.0.revision.set(self.0.revision.get().wrapping_add(1));
407        // Notify readers before discarding signals for indices whose rows have shifted.
408        let shifted = self.0.row_signals.borrow_mut().signals.split_off(&index);
409        for signal in shifted.into_values() {
410            signal.notify();
411        }
412        if count_changed {
413            self.0.count.notify();
414        }
415        self.0.structure.notify();
416        self.values_changed();
417    }
418
419    fn values_changed(&self) {
420        self.0
421            .edit_revision
422            .set(self.0.edit_revision.get().wrapping_add(1));
423        self.0.values.notify();
424    }
425}
426
427impl<T> VecModel<T> {
428    pub(crate) fn project_row<R>(&self, index: usize, project: impl FnOnce(&T) -> R) -> Option<R> {
429        let rows = self.0.rows.borrow();
430        if let Some(entry) = rows.get(index) {
431            if ChangeSignal::is_tracking() {
432                self.0.row_signals.borrow_mut().track(index);
433            }
434            Some(project(&entry.value))
435        } else {
436            self.0.count.track();
437            None
438        }
439    }
440}
441
442impl<T: Clone> VecModel<T> {
443    pub fn row(&self, index: usize) -> Option<T> {
444        self.project_row(index, T::clone)
445    }
446
447    /// Resolve a DSL model index with the same dependency tracking as a row read.
448    #[doc(hidden)]
449    pub fn row_at(&self, index: i64) -> Option<T> {
450        self.row(usize::try_from(index).ok()?)
451    }
452
453    pub fn snapshot(&self) -> Vec<T> {
454        self.0.values.track();
455        self.snapshot_untracked()
456    }
457
458    /// Copy rows that the caller has already sampled from the live model.
459    #[doc(hidden)]
460    pub fn snapshot_untracked(&self) -> Vec<T> {
461        self.0
462            .rows
463            .borrow()
464            .iter()
465            .map(|entry| entry.value.clone())
466            .collect()
467    }
468
469    /// Transfer an owned model's rows at a by-value boundary. A shared model
470    /// still needs a tracked read because its other owners can edit it.
471    #[doc(hidden)]
472    pub fn into_snapshot(self) -> Vec<T> {
473        match Rc::try_unwrap(self.0) {
474            Ok(data) => data
475                .rows
476                .into_inner()
477                .into_iter()
478                .map(|entry| entry.value)
479                .collect(),
480            Err(data) => Self(data).snapshot(),
481        }
482    }
483}
484
485impl<T: PartialEq> VecModel<T> {
486    /// Commit a value against the row and value observed by an editor.
487    pub fn set_row_if_current(&self, index: usize, key: RowKey, expected: &T, value: T) -> bool {
488        self.update_row_if_key(index, key, |current| (current == expected).then_some(value))
489    }
490
491    /// Update an identified record from its latest value. Returning None declines the edit.
492    pub fn update_row_if_key(
493        &self,
494        index: usize,
495        key: RowKey,
496        update: impl FnOnce(&T) -> Option<T>,
497    ) -> bool {
498        let next = {
499            let rows = self.0.rows.borrow();
500            let Some(entry) = rows
501                .get(index)
502                .filter(|entry| key.model == self.0.id && entry.id == key.row)
503            else {
504                return false;
505            };
506            update(&entry.value)
507        };
508        next.is_some_and(|value| self.set_row(index, value))
509    }
510
511    /// Replace one row. Returns false for an invalid index or equal value.
512    pub fn set_row(&self, index: usize, value: T) -> bool {
513        let mut value = value;
514        let changed = {
515            let mut rows = self.0.rows.borrow_mut();
516            let Some(current) = rows.get_mut(index) else {
517                return false;
518            };
519            self.swap_row(index, current, &mut value)
520        };
521        if changed {
522            self.values_changed();
523        }
524        changed
525    }
526
527    pub(crate) fn replace_rows_if_current(
528        &self,
529        stamp: (u64, u64),
530        mut values: Vec<(usize, T)>,
531    ) -> bool {
532        if self.edit_stamp() != stamp {
533            return false;
534        }
535        let mut rows = self.0.rows.borrow_mut();
536        if values.iter().any(|(index, _)| *index >= rows.len()) {
537            return false;
538        }
539        let mut changed = false;
540        for (index, value) in &mut values {
541            changed |= self.swap_row(*index, &mut rows[*index], value);
542        }
543        drop(rows);
544        if changed {
545            self.values_changed();
546        }
547        changed
548    }
549
550    fn swap_row(&self, index: usize, entry: &mut Entry<T>, next: &mut T) -> bool {
551        if &entry.value == next {
552            return false;
553        }
554        self.0.projections.borrow_mut().retain(|projection| {
555            let Some(signal) = projection.signal.upgrade() else {
556                return false;
557            };
558            if index < projection.limit && (projection.changed)(index, &entry.value, next) {
559                signal.notify();
560            }
561            true
562        });
563        std::mem::swap(&mut entry.value, next);
564        self.row_changed(entry.id, Some(&entry.value));
565        if let Some(signal) = self.0.row_signals.borrow().signals.get(&index) {
566            signal.notify();
567        }
568        true
569    }
570
571    /// Compare the current values, independently of handle identity.
572    pub fn values_eq(&self, other: &Self) -> bool {
573        self.compare_values(other, |model| model.0.values.track())
574    }
575
576    /// Compare expression operands, tracking only models that can outlive
577    /// the comparison and be changed by another owner.
578    #[doc(hidden)]
579    pub fn values_eq_owned(self, other: Self) -> bool {
580        self.compare_values(&other, |model| {
581            if model.is_shared() {
582                model.0.values.track();
583            }
584        })
585    }
586
587    fn compare_values(&self, other: &Self, track: impl Fn(&Self)) -> bool {
588        if self == other {
589            return true;
590        }
591        track(self);
592        track(other);
593        self.0.rows.borrow().iter().map(|row| &row.value).eq(other
594            .0
595            .rows
596            .borrow()
597            .iter()
598            .map(|row| &row.value))
599    }
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605    use crate::Property;
606    use std::cell::Cell;
607
608    #[test]
609    fn sorting_retains_stable_keys_and_invalidates_only_affected_reads() {
610        let model = VecModel::from(vec![(0, 'a'), (2, 'b'), (1, 'c'), (2, 'd')]);
611        let keys: Vec<_> = (0..4).map(|index| model.row_key(index).unwrap()).collect();
612        let lifetime = model.row_lifetime(keys[2]);
613        let len = Property::default();
614        let first = Property::default();
615        let second = Property::default();
616        let count_reads = Cell::new(0);
617        let prefix_reads = Cell::new(0);
618        let count = || {
619            len.get(|| {
620                count_reads.set(count_reads.get() + 1);
621                model.len()
622            })
623        };
624        let prefix = || {
625            first.get(|| {
626                prefix_reads.set(prefix_reads.get() + 1);
627                model.row(0)
628            })
629        };
630        let row = || second.get(|| model.row(1));
631        assert_eq!(
632            (count(), prefix(), row()),
633            (4, Some((0, 'a')), Some((2, 'b')))
634        );
635        assert!(model.sort_by(|a, b| a.0.cmp(&b.0)));
636        assert_eq!(
637            (count(), prefix(), row()),
638            (4, Some((0, 'a')), Some((1, 'c')))
639        );
640        assert_eq!((count_reads.get(), prefix_reads.get()), (1, 1));
641        assert_eq!(model.snapshot(), [(0, 'a'), (1, 'c'), (2, 'b'), (2, 'd')]);
642        assert_eq!(model.row_key(1), Some(keys[2]));
643        assert_eq!(model.row_key(2), Some(keys[1]));
644        assert_eq!(model.row_key(3), Some(keys[3]));
645        assert!(lifetime.is_live(keys[2], model.structure_stamp().0, 4));
646        assert!(!model.sort_by(|a, b| a.0.cmp(&b.0)));
647    }
648
649    #[test]
650    fn watched_model_rows_survive_pruning_and_detect_shifts() {
651        use crate::property::watch_reads;
652
653        let model = VecModel::from((0..128).collect::<Vec<_>>());
654        watch_reads(|reads| {
655            for index in 0..100 {
656                assert_eq!(model.row(index), Some(index));
657            }
658            assert!(model.set_row(120, 0));
659            assert!(!reads.changed());
660            assert!(model.set_row(0, 120));
661            assert!(reads.changed());
662        });
663        watch_reads(|reads| {
664            assert_eq!(model.row(1), Some(1));
665            assert_eq!(model.remove(0), Some(120));
666            assert!(reads.changed());
667        });
668    }
669
670    #[test]
671    fn consuming_snapshot_tracks_only_models_with_a_live_owner() {
672        let temporary = Property::default();
673        assert_eq!(
674            temporary.get(|| VecModel::from(vec![1]).into_snapshot()),
675            [1]
676        );
677        assert!(!temporary.is_dirty());
678
679        let shared = VecModel::from(vec![2]);
680        let snapshot = Property::default();
681        let read = || snapshot.get(|| shared.clone().into_snapshot());
682        assert_eq!(read(), [2]);
683        assert!(!snapshot.is_dirty());
684        assert!(shared.set_row(0, 3));
685        assert!(snapshot.is_dirty());
686        assert_eq!(read(), [3]);
687    }
688
689    #[test]
690    fn model_tracks_rows_length_and_snapshots_independently() {
691        let model = VecModel::from(vec![10, 20, 30]);
692        let count = Property::default();
693        let second = Property::default();
694        let missing = Property::default();
695        let snapshot = Property::default();
696        let reads = Cell::new(0);
697        let len = || {
698            count.get(|| {
699                reads.set(reads.get() + 1);
700                model.len()
701            })
702        };
703        let row = || second.get(|| model.row(1));
704        let tail = || missing.get(|| model.row(3));
705        let values = || snapshot.get(|| model.snapshot());
706
707        assert_eq!((len(), row(), tail()), (3, Some(20), None));
708        assert_eq!(values(), [10, 20, 30]);
709        assert!(model.set_row(0, 11));
710        assert_eq!((len(), row()), (3, Some(20)));
711        assert_eq!(reads.get(), 1);
712        assert_eq!(values(), [11, 20, 30]);
713        assert!(!model.set_row(0, 11));
714        assert!(!model.set_row(9, 11));
715        model.push(40);
716        assert_eq!((len(), row(), tail()), (4, Some(20), Some(40)));
717        assert!(model.insert(0, 5));
718        assert_eq!((len(), row(), tail()), (5, Some(11), Some(30)));
719        assert_eq!(model.remove(0), Some(5));
720        assert_eq!((len(), row(), tail()), (4, Some(20), Some(40)));
721    }
722}