Skip to main content

xrack_runtime/
list.rs

1use crate::{Date, Node, Orientation, Property, TableRows, Time, Value, VecModel};
2use std::{
3    cell::Cell,
4    collections::HashMap,
5    fmt,
6    ops::Range,
7    rc::{Rc, Weak},
8    sync::atomic::{AtomicU64, Ordering},
9};
10
11pub(crate) const MAX_ROWS: usize = 1_000_000;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct RowKey {
15    pub(crate) model: u64,
16    pub(crate) row: u64,
17    pub(crate) scope: u64,
18}
19
20impl RowKey {
21    pub(crate) fn in_view(self, scope: u64) -> Self {
22        Self { scope, ..self }
23    }
24
25    #[doc(hidden)]
26    pub fn has_view_scope(self) -> bool {
27        self.scope != 0
28    }
29}
30
31type RenderRows = dyn Fn(Range<usize>, &TableColumnWindow) -> Vec<Node>;
32
33struct RowRenderer {
34    scope: u64,
35    rows: Box<RenderRows>,
36    offsets: [Property<Option<f32>>; 2],
37    selection: Cell<Option<(Option<usize>, usize)>>,
38    tree_root: Cell<Option<(i64, Option<RowKey>)>>,
39}
40
41/// Materializes a single view in its component instance, including views in delegates.
42#[doc(hidden)]
43#[derive(Clone)]
44pub struct ListRowRenderer(Rc<RowRenderer>);
45
46impl ListRowRenderer {
47    pub fn new(rows: impl Fn(Range<usize>) -> Vec<Node> + 'static) -> Self {
48        Self::with_columns(move |range, _| rows(range))
49    }
50
51    pub fn with_columns(
52        rows: impl Fn(Range<usize>, &TableColumnWindow) -> Vec<Node> + 'static,
53    ) -> Self {
54        static NEXT_VIEW: AtomicU64 = AtomicU64::new(1);
55        let scope = NEXT_VIEW
56            .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
57            .expect("virtual view identities exhausted");
58        Self(Rc::new(RowRenderer {
59            scope,
60            rows: Box::new(rows),
61            offsets: Default::default(),
62            selection: Cell::default(),
63            tree_root: Cell::default(),
64        }))
65    }
66
67    pub fn render(&self, rows: Range<usize>) -> Vec<Node> {
68        self.render_in_columns(rows, &TableColumnWindow::default())
69    }
70
71    pub fn render_in_columns(&self, rows: Range<usize>, columns: &TableColumnWindow) -> Vec<Node> {
72        (self.0.rows)(rows, columns)
73    }
74
75    pub fn scope(&self) -> u64 {
76        self.0.scope
77    }
78
79    pub fn offset(&self, axis: Orientation) -> Option<f32> {
80        self.0.offsets[usize::from(axis == Orientation::Vertical)].get(|| None)
81    }
82
83    pub fn set_offset(&self, axis: Orientation, offset: f32) {
84        self.0.offsets[usize::from(axis == Orientation::Vertical)].set_if_changed(Some(offset));
85    }
86
87    pub fn selection_changed(&self, selected: Option<usize>, columns: usize) -> bool {
88        self.0
89            .selection
90            .get()
91            .is_some_and(|previous| previous != (selected, columns))
92    }
93
94    pub fn remember_selection(&self, selected: Option<usize>, columns: usize) {
95        self.0.selection.set(Some((selected, columns)));
96    }
97
98    pub fn tree_root_changed(&self, root: (i64, Option<RowKey>)) -> bool {
99        self.0
100            .tree_root
101            .get()
102            .is_some_and(|previous| previous != root)
103    }
104
105    pub fn remember_tree_root(&self, root: (i64, Option<RowKey>)) {
106        self.0.tree_root.set(Some(root));
107    }
108}
109
110/// Visible columns in declaration order. The default requests every column.
111#[doc(hidden)]
112#[derive(Clone, Debug, Default, PartialEq, Eq)]
113pub struct TableColumnWindow(Option<Rc<VisibleColumns>>);
114
115#[derive(Debug, PartialEq, Eq)]
116struct VisibleColumns {
117    indices: Box<[usize]>,
118    count: usize,
119}
120
121impl TableColumnWindow {
122    pub fn new(visible: impl IntoIterator<Item = bool>) -> Self {
123        let mut indices = Vec::new();
124        let mut count = 0;
125        for (index, visible) in visible.into_iter().enumerate() {
126            if visible {
127                indices.push(index);
128            }
129            count = index + 1;
130        }
131        Self((indices.len() != count).then(|| {
132            Rc::new(VisibleColumns {
133                indices: indices.into_boxed_slice(),
134                count,
135            })
136        }))
137    }
138
139    pub fn includes(&self, column: usize) -> bool {
140        self.dense_index(column).is_some()
141    }
142
143    pub fn dense_index(&self, column: usize) -> Option<usize> {
144        self.0.as_ref().map_or(Some(column), |visible| {
145            visible.indices.binary_search(&column).ok()
146        })
147    }
148
149    pub fn logical_index(&self, index: usize) -> usize {
150        self.0
151            .as_ref()
152            .map_or(index, |visible| visible.indices[index])
153    }
154
155    pub fn logical_len(&self, materialized: usize) -> usize {
156        self.0
157            .as_ref()
158            .map_or(materialized, |visible| visible.count)
159    }
160
161    pub fn columns(&self, count: usize) -> impl Iterator<Item = usize> + '_ {
162        self.0
163            .iter()
164            .flat_map(move |visible| {
165                visible
166                    .indices
167                    .iter()
168                    .copied()
169                    .take_while(move |&index| index < count)
170            })
171            .chain(0..if self.0.is_none() { count } else { 0 })
172    }
173}
174
175impl PartialEq for ListRowRenderer {
176    fn eq(&self, other: &Self) -> bool {
177        Rc::ptr_eq(&self.0, &other.0)
178    }
179}
180
181impl fmt::Debug for ListRowRenderer {
182    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
183        formatter
184            .debug_struct("ListRowRenderer")
185            .finish_non_exhaustive()
186    }
187}
188
189pub struct RowLifetime(pub(crate) Option<Weak<()>>);
190
191impl RowLifetime {
192    pub(crate) fn is_live(&self, key: RowKey, model: u64, count: usize) -> bool {
193        key.model == model
194            && match &self.0 {
195                Some(lifetime) => lifetime.strong_count() != 0,
196                None => key.row < count as u64,
197            }
198    }
199}
200
201#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
202pub struct ListMetrics {
203    pub row_count: usize,
204    pub first_row: usize,
205}
206
207impl ListMetrics {
208    pub fn row_height(node: &Node) -> f32 {
209        Self::clamp_row_height(node.length("row-height").unwrap_or(32.0))
210    }
211
212    pub fn clamp_row_height(height: f32) -> f32 {
213        height.clamp(12.0, 512.0)
214    }
215
216    pub fn row_height_at(node: &Node, index: usize) -> f32 {
217        node.row_heights
218            .as_ref()
219            .map_or_else(|| Self::row_height(node), |heights| heights.height(index))
220    }
221
222    pub fn selection(node: &Node) -> Option<i64> {
223        if let Some(tree) = &node.tree {
224            return tree
225                .visible_index(node.int("current-key")?)
226                .map(|index| index as i64);
227        }
228        node.int(if node.kind == "TableView" {
229            "current-row"
230        } else {
231            "current-index"
232        })
233    }
234}
235
236/// Resolves stable model row identities without constructing their delegates.
237#[derive(Clone)]
238#[doc(hidden)]
239pub struct ListRowLocator(Rc<dyn RowPositions>);
240
241trait RowPositions {
242    fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)>;
243    fn key_at(&self, index: usize) -> Option<RowKey>;
244    fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize>;
245}
246
247impl<M: ListModel> RowPositions for M {
248    fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
249        self.index_of_source_key(key, source_index)
250    }
251
252    fn key_at(&self, index: usize) -> Option<RowKey> {
253        (index < self.row_count()).then(|| self.row_key(index))
254    }
255
256    fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)> {
257        let &(first, hint) = candidates.first()?;
258        let count = self.row_count();
259        if count == 0 || self.row_key(0).model != first.model {
260            return None;
261        }
262        if hint < count && self.row_key(hint) == first {
263            return Some((0, hint));
264        }
265        // Nearby insertions and removals are common, including in deep lists.
266        let nearby = hint.saturating_sub(4)..count.min(hint.saturating_add(5));
267        if let Some(index) = nearby
268            .into_iter()
269            .find(|&index| self.row_key(index) == first)
270        {
271            return Some((0, index));
272        }
273
274        // Resolve all fallback rows in one pass when a whole page was removed.
275        let priorities: HashMap<_, _> = candidates
276            .iter()
277            .enumerate()
278            .map(|(priority, &(key, _))| (key, priority))
279            .collect();
280        let mut best = None;
281        let mut index = 0;
282        self.visit_row_keys(0..count, |key| {
283            if let Some(&priority) = priorities.get(&key)
284                && best.is_none_or(|(previous, _)| priority < previous)
285            {
286                best = Some((priority, index));
287            }
288            index += 1;
289        });
290        best
291    }
292}
293
294impl ListRowLocator {
295    pub fn new(model: Rc<impl ListModel + 'static>) -> Self {
296        Self(model)
297    }
298
299    pub fn first_position(&self, candidates: &[(RowKey, usize)]) -> Option<(usize, usize)> {
300        self.0.first_position(candidates)
301    }
302
303    pub fn key_at(&self, index: usize) -> Option<RowKey> {
304        self.0.key_at(index)
305    }
306
307    pub(crate) fn position_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
308        self.0.position_of_source_key(key, source_index)
309    }
310}
311
312impl PartialEq for ListRowLocator {
313    fn eq(&self, other: &Self) -> bool {
314        Rc::ptr_eq(&self.0, &other.0)
315    }
316}
317
318impl fmt::Debug for ListRowLocator {
319    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
320        formatter
321            .debug_struct("ListRowLocator")
322            .finish_non_exhaustive()
323    }
324}
325
326#[doc(hidden)]
327pub fn standard_list_rows<T: Clone + PartialEq>(
328    model: &VecModel<T>,
329    range: Range<usize>,
330    label: impl FnMut(T) -> String,
331) -> Vec<Node> {
332    standard_list_rows_at(model, range, label)
333}
334
335#[doc(hidden)]
336pub fn standard_list_rows_in_view<T: Clone + PartialEq>(
337    rows: &TableRows<VecModel<T>>,
338    range: Range<usize>,
339    label: impl FnMut(T) -> String,
340) -> Vec<Node> {
341    standard_list_rows_at(
342        rows.source(),
343        range.filter_map(|row| rows.positions().source_index(row)),
344        label,
345    )
346}
347
348fn standard_list_rows_at<T: Clone + PartialEq>(
349    model: &VecModel<T>,
350    indices: impl Iterator<Item = usize>,
351    mut label: impl FnMut(T) -> String,
352) -> Vec<Node> {
353    indices
354        .filter_map(|index| {
355            let value = model.row(index)?;
356            let key = model.row_key(index)?;
357            let mut item = Node::new("StandardListItem", None);
358            item.row_key = Some(key);
359            item.properties.insert("text", label(value).into());
360            Some(item)
361        })
362        .collect()
363}
364
365#[doc(hidden)]
366pub fn standard_table_rows<T, const COLUMNS: usize>(
367    model: &VecModel<T>,
368    range: Range<usize>,
369    project: impl Fn(&T) -> [String; COLUMNS],
370) -> Vec<Node> {
371    standard_table_rows_with_header(model, range, |item| (None, project(item)))
372}
373
374#[doc(hidden)]
375pub fn standard_table_rows_with_header<T, const COLUMNS: usize>(
376    model: &VecModel<T>,
377    range: Range<usize>,
378    project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
379) -> Vec<Node> {
380    standard_table_rows_at(model, range, [None; COLUMNS], project)
381}
382
383#[doc(hidden)]
384pub fn standard_table_rows_in_order<T, const COLUMNS: usize>(
385    rows: &TableRows<VecModel<T>>,
386    range: Range<usize>,
387    project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
388) -> Vec<Node> {
389    standard_table_rows_with_editors_in_order(rows, range, [None; COLUMNS], project)
390}
391
392#[doc(hidden)]
393pub fn standard_table_rows_with_editors_in_order<T, const COLUMNS: usize>(
394    rows: &TableRows<VecModel<T>>,
395    range: Range<usize>,
396    editors: [Option<TableCellEditor>; COLUMNS],
397    project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
398) -> Vec<Node> {
399    standard_table_rows_at(
400        rows.source(),
401        range.filter_map(|index| rows.positions().source_index(index)),
402        editors,
403        project,
404    )
405}
406
407/// Build only the visible cells and retain their declaration-order addresses.
408#[doc(hidden)]
409pub fn project_standard_table_rows<T>(
410    rows: &TableRows<VecModel<T>>,
411    range: Range<usize>,
412    columns: &TableColumnWindow,
413    column_count: usize,
414    header: impl Fn(&T) -> Option<String>,
415    cell: impl Fn(&T, usize) -> String,
416    editor: impl Fn(usize) -> Option<TableCellEditor>,
417) -> Vec<Node> {
418    let model = rows.source();
419    let visible: Vec<_> = columns
420        .columns(column_count)
421        .map(|column| (column, editor(column)))
422        .collect();
423    range
424        .filter_map(|index| {
425            let index = rows.positions().source_index(index)?;
426            let key = model.row_key(index)?;
427            model.project_row(index, |item| {
428                let mut row = projected_table_row(key, header(item));
429                row.table_column_window = columns.clone();
430                row.children.extend(
431                    visible
432                        .iter()
433                        .map(|&(column, editor)| projected_table_cell(cell(item, column), editor)),
434                );
435                row
436            })
437        })
438        .collect()
439}
440
441/// The model field type used to validate a projected cell's text draft.
442#[doc(hidden)]
443#[derive(Clone, Copy, Debug, PartialEq, Eq)]
444pub enum TableCellEditor {
445    String,
446    Int,
447    Float,
448    Bool,
449    Date,
450    Time,
451}
452
453impl TableCellEditor {
454    pub fn parse(self, text: &str) -> Option<Value> {
455        let trimmed = text.trim();
456        match self {
457            Self::String => Some(Value::String(text.into())),
458            Self::Int => trimmed.parse().ok().map(Value::Int),
459            Self::Float => trimmed
460                .parse::<f64>()
461                .ok()
462                .filter(|number| number.is_finite())
463                .map(Value::Float),
464            Self::Bool => crate::table_paste_bool(text).map(Value::Bool),
465            Self::Date => {
466                let [year, month, day] = parse_cell_parts(trimmed, '-')?;
467                Date::new(year, month, day).map(Value::Date)
468            }
469            Self::Time => {
470                let [hour, minute, second] = parse_cell_parts(trimmed, ':')?;
471                Time::new(hour, minute, second).map(Value::Time)
472            }
473        }
474    }
475
476    pub fn accepts(self, text: &str) -> bool {
477        self == Self::String || self.parse(text).is_some()
478    }
479}
480
481fn parse_cell_parts(text: &str, separator: char) -> Option<[i64; 3]> {
482    let mut parts = text.split(separator);
483    let values = [
484        parts.next()?.parse().ok()?,
485        parts.next()?.parse().ok()?,
486        parts.next()?.parse().ok()?,
487    ];
488    parts.next().is_none().then_some(values)
489}
490
491fn standard_table_rows_at<T, const COLUMNS: usize>(
492    model: &VecModel<T>,
493    indices: impl Iterator<Item = usize>,
494    editors: [Option<TableCellEditor>; COLUMNS],
495    project: impl Fn(&T) -> (Option<String>, [String; COLUMNS]),
496) -> Vec<Node> {
497    indices
498        .filter_map(|index| {
499            let key = model.row_key(index)?;
500            let (header, cells) = model.project_row(index, &project)?;
501            let mut row = projected_table_row(key, header);
502            row.children.extend(
503                cells
504                    .into_iter()
505                    .zip(editors)
506                    .map(|(text, editor)| projected_table_cell(text, editor)),
507            );
508            Some(row)
509        })
510        .collect()
511}
512
513fn projected_table_row(key: RowKey, header: Option<String>) -> Node {
514    let mut row = Node::new("TableRow", None);
515    row.row_key = Some(key);
516    if let Some(header) = header {
517        row.properties.insert("row-header-text", header.into());
518    }
519    row
520}
521
522fn projected_table_cell(text: String, editor: Option<TableCellEditor>) -> Node {
523    let mut cell = Node::new("TableCell", None);
524    cell.properties.insert("text", text.into());
525    if editor.is_some() {
526        cell.properties.insert("editable", true.into());
527        cell.table_cell_editor = editor;
528    }
529    cell
530}
531
532pub trait ListModel {
533    type Item: Clone + PartialEq;
534
535    fn row_count(&self) -> usize;
536    fn item(&self, row: usize) -> Self::Item;
537    fn row_key(&self, row: usize) -> RowKey;
538    fn visit_items(&self, mut visit: impl FnMut(usize, RowKey, &Self::Item)) {
539        for index in 0..self.row_count() {
540            visit(index, self.row_key(index), &self.item(index));
541        }
542    }
543    fn visit_row_keys(&self, range: Range<usize>, mut visit: impl FnMut(RowKey)) {
544        for index in range {
545            visit(self.row_key(index));
546        }
547    }
548    fn index_of_key(&self, key: RowKey) -> Option<usize> {
549        (0..self.row_count()).find(|&index| self.row_key(index) == key)
550    }
551    #[doc(hidden)]
552    fn index_of_source_key(&self, key: RowKey, source_index: usize) -> Option<usize> {
553        if source_index < self.row_count() && self.row_key(source_index) == key {
554            Some(source_index)
555        } else {
556            self.index_of_key(key)
557        }
558    }
559    fn row_lifetime(&self, key: RowKey) -> RowLifetime;
560    fn structure_stamp(&self) -> (u64, u64);
561    #[doc(hidden)]
562    fn source_structure_stamp(&self) -> (u64, u64) {
563        self.structure_stamp()
564    }
565    #[doc(hidden)]
566    fn visit_source_row_keys(&self, visit: impl FnMut(RowKey)) {
567        self.visit_row_keys(0..self.row_count(), visit);
568    }
569}
570
571impl ListModel for i64 {
572    type Item = i64;
573
574    fn row_count(&self) -> usize {
575        (*self).clamp(0, MAX_ROWS as i64) as usize
576    }
577
578    fn item(&self, row: usize) -> Self::Item {
579        row as i64
580    }
581
582    fn row_key(&self, row: usize) -> RowKey {
583        RowKey {
584            model: 0,
585            row: row as u64,
586            scope: 0,
587        }
588    }
589    fn row_lifetime(&self, _: RowKey) -> RowLifetime {
590        RowLifetime(None)
591    }
592    fn index_of_key(&self, key: RowKey) -> Option<usize> {
593        let index = usize::try_from(key.row).ok()?;
594        (key.model == 0 && index < self.row_count()).then_some(index)
595    }
596    fn structure_stamp(&self) -> (u64, u64) {
597        (0, self.row_count() as u64)
598    }
599}
600
601impl<T: Clone + PartialEq> ListModel for VecModel<T> {
602    type Item = T;
603
604    fn row_count(&self) -> usize {
605        self.len().min(MAX_ROWS)
606    }
607    fn visit_items(&self, visit: impl FnMut(usize, RowKey, &Self::Item)) {
608        self.visit_row_data(self.row_count(), visit);
609    }
610
611    fn item(&self, row: usize) -> Self::Item {
612        self.row(row).expect("row is inside the model range")
613    }
614
615    fn row_key(&self, row: usize) -> RowKey {
616        self.row_key(row).expect("row is inside the model range")
617    }
618
619    fn row_lifetime(&self, key: RowKey) -> RowLifetime {
620        self.row_lifetime(key)
621    }
622    fn index_of_key(&self, key: RowKey) -> Option<usize> {
623        self.row_index(key).filter(|&index| index < MAX_ROWS)
624    }
625    fn visit_row_keys(&self, range: Range<usize>, visit: impl FnMut(RowKey)) {
626        self.visit_row_keys(range, visit);
627    }
628    fn structure_stamp(&self) -> (u64, u64) {
629        self.structure_stamp()
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636
637    #[test]
638    fn standard_table_projects_values_and_editor_flags_only_for_requested_columns() {
639        use std::cell::RefCell;
640
641        let model = Rc::new(VecModel::from(vec!["A".to_owned(), "B".to_owned()]));
642        let rows = crate::TableRowOrder::default().rows(model.clone());
643        let values = RefCell::new(Vec::new());
644        let flags = RefCell::new(Vec::new());
645        let view = project_standard_table_rows(
646            &rows,
647            0..2,
648            &TableColumnWindow::new(vec![true, false, true, false]),
649            4,
650            |item| Some(item.clone()),
651            |item, column| {
652                values.borrow_mut().push((item.clone(), column));
653                format!("{item}:{column}")
654            },
655            |column| {
656                flags.borrow_mut().push(column);
657                Some(TableCellEditor::String)
658            },
659        );
660        assert_eq!(*flags.borrow(), [0, 2]);
661        assert_eq!(
662            values
663                .borrow()
664                .iter()
665                .map(|(_, column)| *column)
666                .collect::<Vec<_>>(),
667            [0, 2, 0, 2]
668        );
669        assert_eq!(view[1].row_key, model.row_key(1));
670        assert_eq!(view[1].text("row-header-text"), Some("B"));
671        assert_eq!(view[1].child_at(2).unwrap().text("text"), Some("B:2"));
672        assert_eq!(
673            view[1].child_at(2).unwrap().table_cell_editor,
674            Some(TableCellEditor::String)
675        );
676        assert!(view[1].child_at(1).is_none());
677        assert_eq!(view[1].children.len(), 2);
678    }
679
680    #[test]
681    fn projected_cell_values_validate_scalar_ranges_and_preserve_strings() {
682        use TableCellEditor::*;
683        assert_eq!(
684            String.parse("  device  "),
685            Some(Value::String("  device  ".into()))
686        );
687        assert_eq!(Int.parse(" -42 "), Some(Value::Int(-42)));
688        assert!(!Int.accepts("9223372036854775808"));
689        assert_eq!(Float.parse("1.25e2"), Some(Value::Float(125.0)));
690        for text in ["NaN", "inf", "1e500"] {
691            assert!(!Float.accepts(text));
692        }
693        assert_eq!(Bool.parse("true"), Some(Value::Bool(true)));
694        assert_eq!(Bool.parse("0"), Some(Value::Bool(false)));
695        assert!(!Bool.accepts("2"));
696        assert_eq!(
697            Date.parse("2000-02-29"),
698            crate::Date::new(2000, 2, 29).map(Value::Date)
699        );
700        assert!(!Date.accepts("1900-02-29"));
701        assert!(!Date.accepts("2000-02-29-01"));
702        assert_eq!(
703            Time.parse("23:59:59"),
704            crate::Time::new(23, 59, 59).map(Value::Time)
705        );
706        assert!(!Time.accepts("24:00:00"));
707        assert!(!Time.accepts("12:34"));
708    }
709}