Skip to main content

xrack_runtime/
record.rs

1use crate::{
2    ChangeSignal, RowKey, TableHistoryPayload, TableRowPatch, Value, VecModel, model::RowObserver,
3};
4use std::{
5    cell::RefCell,
6    collections::BTreeMap,
7    fmt,
8    rc::{Rc, Weak},
9};
10
11#[derive(Clone, Debug)]
12pub struct RecordValue {
13    name: Rc<str>,
14    fields: Rc<BTreeMap<String, Value>>,
15}
16
17impl PartialEq for RecordValue {
18    fn eq(&self, other: &Self) -> bool {
19        self.name == other.name
20            && self.fields.len() == other.fields.len()
21            && self.fields.iter().zip(other.fields.iter()).all(
22                |((left_name, left), (right_name, right))| {
23                    left_name == right_name && left.eq_with_image_assets(right)
24                },
25            )
26    }
27}
28
29impl RecordValue {
30    pub fn new(name: impl Into<Rc<str>>, fields: BTreeMap<String, Value>) -> Self {
31        Self {
32            name: name.into(),
33            fields: Rc::new(fields),
34        }
35    }
36
37    pub fn name(&self) -> &str {
38        &self.name
39    }
40
41    pub fn field(&self, name: &str) -> Option<&Value> {
42        self.fields.get(name)
43    }
44
45    pub fn fields(&self) -> impl ExactSizeIterator<Item = (&str, &Value)> {
46        self.fields
47            .iter()
48            .map(|(name, value)| (name.as_str(), value))
49    }
50
51    pub fn field_path(&self, path: &[String]) -> Option<&Value> {
52        let (name, rest) = path.split_first()?;
53        let field = self.field(name)?;
54        if rest.is_empty() {
55            Some(field)
56        } else if let Value::Record(record) = field {
57            record.field_path(rest)
58        } else {
59            None
60        }
61    }
62
63    pub fn with_field(&self, path: &[String], value: Value) -> Option<Self> {
64        let (name, rest) = path.split_first()?;
65        let mut record = self.clone();
66        let target = Rc::make_mut(&mut record.fields).get_mut(name)?;
67        if rest.is_empty() {
68            *target = value;
69        } else if let Value::Record(nested) = target {
70            *nested = nested.with_field(rest, value)?;
71        } else {
72            return None;
73        }
74        Some(record)
75    }
76}
77
78impl TableRowPatch<RecordValue> {
79    /// Save changed leaf fields so replay preserves independent changes to the same record.
80    pub fn record_changes(&mut self, before: &RecordValue, after: &RecordValue) {
81        self.record_record(before, after, &mut Vec::new());
82    }
83
84    fn record_record(&mut self, before: &RecordValue, after: &RecordValue, path: &mut Vec<String>) {
85        if Rc::ptr_eq(&before.fields, &after.fields) {
86            return;
87        }
88        for (name, before) in before.fields.iter() {
89            let Some(after) = after.field(name) else {
90                continue;
91            };
92            path.push(name.clone());
93            if let (Value::Record(before), Value::Record(after)) = (before, after) {
94                self.record_record(before, after, path);
95            } else if !same_field(before, after) {
96                let field = path.clone();
97                self.record_with(
98                    before,
99                    after,
100                    same_field,
101                    field_bytes,
102                    path,
103                    move |row, expected, value| {
104                        if !row
105                            .field_path(&field)
106                            .is_some_and(|current| same_field(current, expected))
107                        {
108                            return false;
109                        }
110                        let Some(next) = row.with_field(&field, value.clone()) else {
111                            return false;
112                        };
113                        *row = next;
114                        true
115                    },
116                );
117            }
118            path.pop();
119        }
120    }
121}
122
123fn same_field(before: &Value, after: &Value) -> bool {
124    before.eq_with_image_assets(after)
125        || match (before, after) {
126            (Value::Float(before), Value::Float(after)) => before.to_bits() == after.to_bits(),
127            (Value::Length(before), Value::Length(after)) => {
128                before.0.to_bits() == after.0.to_bits()
129            }
130            _ => false,
131        }
132}
133
134fn field_bytes(value: &Value) -> usize {
135    match value {
136        Value::String(value) => value.history_payload_bytes(),
137        Value::Font(value) => value.history_payload_bytes(),
138        Value::KeyEvent(value) => value.history_payload_bytes(),
139        Value::StyledText(value) => value.history_payload_bytes(),
140        Value::Brush(value) => value.history_payload_bytes(),
141        _ => 0,
142    }
143}
144
145#[doc(hidden)]
146pub type RecordRowValidator = dyn Fn(&str, &RecordValue) -> Result<(), String>;
147
148#[derive(Default)]
149struct ValidationState {
150    failures: RefCell<BTreeMap<RowKey, String>>,
151    changed: ChangeSignal,
152}
153
154struct RecordValidation {
155    validator: Weak<RecordRowValidator>,
156    state: Rc<ValidationState>,
157    _observer: Rc<RowObserver<RecordValue>>,
158}
159
160impl RecordValidation {
161    fn new(list: &RecordList, validator: &Rc<RecordRowValidator>) -> Self {
162        let state = Rc::new(ValidationState::default());
163        let mut failures = state.failures.borrow_mut();
164        list.model.visit_rows_untracked(usize::MAX, |_, key, row| {
165            if let Err(error) = validator(&list.name, row) {
166                failures.insert(key, error);
167            }
168        });
169        drop(failures);
170
171        let validator = Rc::downgrade(validator);
172        let observer: Rc<RowObserver<RecordValue>> = Rc::new({
173            let state = state.clone();
174            let validator = validator.clone();
175            let name = list.name.clone();
176            move |key, row| {
177                let Some(validator) = validator.upgrade() else {
178                    return;
179                };
180                let error = row.and_then(|row| validator(&name, row).err());
181                let mut failures = state.failures.borrow_mut();
182                if failures.get(&key) != error.as_ref() {
183                    if let Some(error) = error {
184                        failures.insert(key, error);
185                    } else {
186                        failures.remove(&key);
187                    }
188                    state.changed.notify();
189                }
190            }
191        });
192        list.model.observe_rows(&observer);
193        Self {
194            validator,
195            state,
196            _observer: observer,
197        }
198    }
199}
200
201#[derive(Clone)]
202pub struct RecordList {
203    name: Rc<str>,
204    model: VecModel<RecordValue>,
205    validations: Rc<RefCell<Vec<RecordValidation>>>,
206}
207
208impl PartialEq for RecordList {
209    fn eq(&self, other: &Self) -> bool {
210        self.name == other.name && self.model == other.model
211    }
212}
213
214impl RecordList {
215    pub fn new(name: impl Into<Rc<str>>, rows: Vec<RecordValue>) -> Self {
216        Self::from_model(name, VecModel::from(rows))
217    }
218
219    /// Use an existing model, preserving the row identities of the supplied handle.
220    pub fn from_model(name: impl Into<Rc<str>>, model: VecModel<RecordValue>) -> Self {
221        Self {
222            name: name.into(),
223            model,
224            validations: Rc::default(),
225        }
226    }
227
228    pub fn name(&self) -> &str {
229        &self.name
230    }
231
232    pub fn model(&self) -> &VecModel<RecordValue> {
233        &self.model
234    }
235
236    #[doc(hidden)]
237    pub fn into_snapshot(self) -> (Rc<str>, Vec<RecordValue>) {
238        (self.name, self.model.into_snapshot())
239    }
240
241    #[doc(hidden)]
242    pub fn values_eq_owned(
243        self,
244        other: Self,
245        validator: &Rc<RecordRowValidator>,
246    ) -> Result<bool, String> {
247        for list in [&self, &other] {
248            list.check_rows(validator, list.model.is_shared())
249                .map_err(|error| format!("model {}{error}", list.name))?;
250        }
251        Ok(self.name == other.name && self.model.values_eq_owned(other.model))
252    }
253
254    /// Check the current row shapes and track changes to their validity.
255    #[doc(hidden)]
256    pub fn validate_rows(&self, validator: &Rc<RecordRowValidator>) -> Result<(), String> {
257        self.check_rows(validator, true)
258    }
259
260    #[doc(hidden)]
261    pub fn validate_rows_untracked(
262        &self,
263        validator: &Rc<RecordRowValidator>,
264    ) -> Result<(), String> {
265        self.check_rows(validator, false)
266    }
267
268    fn check_rows(&self, validator: &Rc<RecordRowValidator>, tracked: bool) -> Result<(), String> {
269        let mut validations = self.validations.borrow_mut();
270        validations.retain(|entry| entry.validator.strong_count() != 0);
271        let key = Rc::downgrade(validator);
272        let index = validations
273            .iter()
274            .position(|entry| entry.validator.ptr_eq(&key))
275            .unwrap_or_else(|| {
276                validations.push(RecordValidation::new(self, validator));
277                validations.len() - 1
278            });
279        let state = &validations[index].state;
280        if tracked {
281            state.changed.track();
282        }
283        let failures = state.failures.borrow();
284        let Some((&row, error)) = failures.first_key_value() else {
285            return Ok(());
286        };
287        let index = if tracked {
288            self.model.row_index(row)
289        } else {
290            self.model.row_index_untracked(row)
291        };
292        Err(index.map_or_else(|| error.clone(), |index| format!("[{index}]{error}")))
293    }
294}
295
296impl fmt::Debug for RecordList {
297    fn fmt(&self, output: &mut fmt::Formatter<'_>) -> fmt::Result {
298        output
299            .debug_struct("RecordList")
300            .field("name", &self.name)
301            .finish_non_exhaustive()
302    }
303}