Skip to main content

xrack_runtime/
table_selection.rs

1use crate::table_clipboard::{MAX_CLIPBOARD_BYTES, MAX_CLIPBOARD_CELLS};
2use crate::{
3    ChangeSignal, ControlAction, KeyModifiers, ListModel, Node, RowKey, TableColumnOrder,
4    TableRows, table_rows::with_table_rows_in_view,
5};
6use std::{
7    cell::{Cell, OnceCell, RefCell},
8    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
9    ops::Range,
10    rc::Rc,
11    sync::Arc,
12};
13
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum SelectionTarget {
16    #[default]
17    Rows,
18    Cells,
19    Columns,
20}
21
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23pub enum SelectionGesture {
24    #[default]
25    Auto,
26    Drag,
27    PressAndHold,
28}
29
30impl SelectionGesture {
31    #[doc(hidden)]
32    pub fn uses_hold(self, touch: bool) -> bool {
33        match self {
34            Self::Auto => touch,
35            Self::Drag => false,
36            Self::PressAndHold => true,
37        }
38    }
39}
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum RowSelection {
43    Replace,
44    Toggle,
45    Extend,
46    AddRange,
47    Move,
48}
49
50impl RowSelection {
51    #[doc(hidden)]
52    pub fn from_modifiers(modifiers: KeyModifiers, keyboard: bool) -> Self {
53        match (modifiers.shift, modifiers.control || modifiers.meta) {
54            (true, true) => Self::AddRange,
55            (true, false) => Self::Extend,
56            (false, true) if keyboard => Self::Move,
57            (false, true) => Self::Toggle,
58            (false, false) => Self::Replace,
59        }
60    }
61}
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub enum TableSelectionAction {
65    Row {
66        index: usize,
67        operation: RowSelection,
68    },
69    Cell {
70        row: usize,
71        column: usize,
72        operation: RowSelection,
73    },
74    Column {
75        column: usize,
76        operation: RowSelection,
77    },
78    DragRange {
79        anchor: (usize, usize),
80        end: (usize, usize),
81        additive: bool,
82    },
83    All,
84    Clear,
85}
86
87impl TableSelectionAction {
88    /// Resolve a selection against the table column order seen by the input event.
89    #[doc(hidden)]
90    pub fn from_control(
91        table: &Node,
92        live_order: &TableColumnOrder,
93        action: ControlAction,
94    ) -> Option<Self> {
95        if table.table_selection.is_none() || &table.table_column_order != live_order {
96            return None;
97        }
98        let selection = match action {
99            ControlAction::Select(index) => Self::Row {
100                index,
101                operation: RowSelection::Replace,
102            },
103            ControlAction::TableSelection(selection) => selection,
104            _ => return None,
105        };
106        (!matches!(selection, Self::DragRange { .. }) || table.boolean("drag-select", false))
107            .then_some(selection)
108    }
109}
110
111/// Selection commands with signed positions from XR dialect operands.
112#[derive(Clone, Copy, Debug)]
113#[doc(hidden)]
114pub enum TableSelectionMethod {
115    SelectAll,
116    ClearSelection,
117    SelectRow,
118    ToggleRow,
119    SelectColumn,
120    SelectCell,
121    MoveCell,
122    ToggleCell,
123    SelectRange,
124}
125
126impl TableSelectionMethod {
127    pub fn parse(name: &str) -> Option<Self> {
128        Some(match name {
129            "select-all" => Self::SelectAll,
130            "clear-selection" => Self::ClearSelection,
131            "select-row" => Self::SelectRow,
132            "toggle-row" => Self::ToggleRow,
133            "select-column" => Self::SelectColumn,
134            "select-cell" => Self::SelectCell,
135            "set-current-cell" => Self::MoveCell,
136            "toggle-cell" => Self::ToggleCell,
137            "select-range" => Self::SelectRange,
138            _ => return None,
139        })
140    }
141
142    pub fn action(self, args: &[i64]) -> Option<TableSelectionAction> {
143        use TableSelectionAction as Action;
144        let index = |value| usize::try_from(value).ok();
145        Some(match (self, args) {
146            (Self::SelectAll, []) => Action::All,
147            (Self::ClearSelection, []) => Action::Clear,
148            (Self::SelectRow | Self::ToggleRow, [row]) => Action::Row {
149                index: index(*row)?,
150                operation: if matches!(self, Self::ToggleRow) {
151                    RowSelection::Toggle
152                } else {
153                    RowSelection::Replace
154                },
155            },
156            (Self::SelectColumn, [column]) => Action::Column {
157                column: index(*column)?,
158                operation: RowSelection::Replace,
159            },
160            (Self::SelectCell | Self::MoveCell | Self::ToggleCell, [row, column]) => Action::Cell {
161                row: index(*row)?,
162                column: index(*column)?,
163                operation: match self {
164                    Self::MoveCell => RowSelection::Move,
165                    Self::ToggleCell => RowSelection::Toggle,
166                    _ => RowSelection::Replace,
167                },
168            },
169            (Self::SelectRange, [row, column, end_row, end_column]) => Action::DragRange {
170                anchor: (index(*row)?, index(*column)?),
171                end: (index(*end_row)?, index(*end_column)?),
172                additive: false,
173            },
174            _ => return None,
175        })
176    }
177}
178
179type RowKeys = Arc<BTreeSet<RowKey>>;
180type ColumnCells = BTreeMap<usize, RowKeys>;
181
182#[derive(Clone, Debug)]
183enum Selected {
184    Rows(RowKeys),
185    Columns(Arc<BTreeSet<usize>>),
186    Cells(Arc<ColumnCells>),
187}
188
189impl PartialEq for Selected {
190    fn eq(&self, other: &Self) -> bool {
191        match (self, other) {
192            (Self::Rows(a), Self::Rows(b)) => a == b,
193            (Self::Columns(a), Self::Columns(b)) => a == b,
194            (Self::Cells(a), Self::Cells(b)) => {
195                let mut compared = HashSet::new();
196                Arc::ptr_eq(a, b)
197                    || a.len() == b.len()
198                        && a.iter()
199                            .zip(b.iter())
200                            .all(|((a_col, a_rows), (b_col, b_rows))| {
201                                a_col == b_col
202                                    && (!compared
203                                        .insert((Arc::as_ptr(a_rows), Arc::as_ptr(b_rows)))
204                                        || a_rows == b_rows)
205                            })
206            }
207            _ => false,
208        }
209    }
210}
211
212impl Eq for Selected {}
213
214impl Selected {
215    fn empty(target: SelectionTarget) -> Self {
216        match target {
217            SelectionTarget::Rows => Self::Rows(Arc::default()),
218            SelectionTarget::Cells => Self::Cells(Arc::default()),
219            SelectionTarget::Columns => Self::Columns(Arc::default()),
220        }
221    }
222
223    fn len(&self) -> usize {
224        match self {
225            Self::Rows(rows) => rows.len(),
226            Self::Columns(columns) => columns.len(),
227            Self::Cells(cells) => cells.values().map(|rows| rows.len()).sum(),
228        }
229    }
230
231    fn retain_live(&mut self, model: &impl ListModel) {
232        if matches!(self, Self::Columns(_)) || self.len() == 0 {
233            return;
234        }
235        match self {
236            Self::Rows(rows) => {
237                let mut live = BTreeSet::new();
238                model.visit_source_row_keys(|key| {
239                    if rows.contains(&key) {
240                        live.insert(key);
241                    }
242                });
243                if live.len() != rows.len() {
244                    *rows = Arc::new(live);
245                }
246            }
247            Self::Cells(cells) => {
248                let mut live = BTreeSet::new();
249                model.visit_source_row_keys(|key| {
250                    live.insert(key);
251                });
252                // A rectangular range can share a single row set across many columns.
253                let mut pruned = HashMap::<_, RowKeys>::new();
254                let cells = Arc::make_mut(cells);
255                cells.retain(|_, rows| {
256                    *rows = pruned
257                        .entry(Arc::as_ptr(rows))
258                        .or_insert_with(|| {
259                            if rows.is_subset(&live) {
260                                rows.clone()
261                            } else {
262                                Arc::new(rows.intersection(&live).copied().collect())
263                            }
264                        })
265                        .clone();
266                    !rows.is_empty()
267                });
268            }
269            Self::Columns(_) => {}
270        }
271    }
272}
273
274fn row_keys(model: &impl ListModel, range: Range<usize>) -> BTreeSet<RowKey> {
275    let mut keys = BTreeSet::new();
276    model.visit_row_keys(range, |key| {
277        keys.insert(key);
278    });
279    keys
280}
281
282fn span(a: usize, b: usize) -> Range<usize> {
283    a.min(b)..a.max(b) + 1
284}
285
286/// Selection in a table snapshot, including units outside the viewport.
287#[derive(Clone, Debug, PartialEq, Eq)]
288pub struct TableSelectionSnapshot {
289    stamp: (u64, u64),
290    target: SelectionTarget,
291    column_count: usize,
292    order: crate::TableColumnOrder,
293    multiple: bool,
294    current_column: Option<usize>,
295    selected: Selected,
296    drag_range: Option<CommittedRange>,
297}
298
299#[derive(Clone, Debug, PartialEq, Eq)]
300struct CommittedRange {
301    endpoints: [(usize, usize); 2],
302    order: crate::TableColumnOrder,
303}
304
305impl TableSelectionSnapshot {
306    #[doc(hidden)]
307    pub fn with_column_order(mut self, order: crate::TableColumnOrder) -> Self {
308        self.order = order;
309        self
310    }
311
312    pub fn target(&self) -> SelectionTarget {
313        self.target
314    }
315
316    pub fn current_column(&self) -> Option<usize> {
317        self.current_column
318    }
319
320    #[doc(hidden)]
321    pub fn current_column_index(&self) -> i64 {
322        self.current_column().map_or(-1, |column| column as i64)
323    }
324
325    #[doc(hidden)]
326    pub fn selection_count(&self) -> i64 {
327        self.len() as i64
328    }
329
330    pub fn multiple(&self) -> bool {
331        self.multiple
332    }
333
334    #[doc(hidden)]
335    pub fn structure_stamp(&self) -> (u64, u64) {
336        self.stamp
337    }
338
339    /// Endpoints of the last replacement drag, in row and logical column indices.
340    pub fn drag_range(&self) -> Option<[(usize, usize); 2]> {
341        let range = self.drag_range.as_ref()?;
342        (range.order == self.order).then_some(range.endpoints)
343    }
344
345    /// Number of selected rows, cells, or columns, depending on the target.
346    pub fn len(&self) -> usize {
347        self.selected.len()
348    }
349
350    pub fn is_empty(&self) -> bool {
351        self.len() == 0
352    }
353
354    pub fn keys(&self) -> &BTreeSet<RowKey> {
355        static EMPTY: BTreeSet<RowKey> = BTreeSet::new();
356        match &self.selected {
357            Selected::Rows(rows) => rows,
358            _ => &EMPTY,
359        }
360    }
361
362    pub fn columns(&self) -> &BTreeSet<usize> {
363        static EMPTY: BTreeSet<usize> = BTreeSet::new();
364        match &self.selected {
365            Selected::Columns(columns) => columns,
366            _ => &EMPTY,
367        }
368    }
369
370    /// Explicit cell selection in a column, without expanding whole-row or whole-column selections.
371    pub fn cell_keys(&self, column: usize) -> Option<&BTreeSet<RowKey>> {
372        match &self.selected {
373            Selected::Cells(cells) => cells.get(&column).map(Arc::as_ref),
374            _ => None,
375        }
376    }
377
378    pub fn contains_cell(&self, row: RowKey, column: usize) -> bool {
379        column < self.column_count
380            && row.model == self.stamp.0
381            && match &self.selected {
382                Selected::Rows(rows) => rows.contains(&row),
383                Selected::Columns(columns) => columns.contains(&column),
384                Selected::Cells(cells) => {
385                    cells.get(&column).is_some_and(|rows| rows.contains(&row))
386                }
387            }
388    }
389
390    pub fn row_header_selected(&self, row: RowKey) -> bool {
391        match &self.selected {
392            Selected::Rows(rows) => rows.contains(&row),
393            Selected::Cells(cells) => whole_row_selected(cells, self.column_count, row),
394            Selected::Columns(_) => false,
395        }
396    }
397
398    pub fn row_header_action(&self, index: usize, operation: RowSelection) -> TableSelectionAction {
399        match self.target {
400            SelectionTarget::Cells if !self.multiple => {
401                let column = self
402                    .current_column
403                    .filter(|column| *column < self.column_count)
404                    .or_else(|| self.order.iter(self.column_count).next())
405                    .unwrap_or_default();
406                TableSelectionAction::Cell {
407                    row: index,
408                    column,
409                    operation,
410                }
411            }
412            SelectionTarget::Columns => TableSelectionAction::Row {
413                index,
414                operation: RowSelection::Move,
415            },
416            _ => TableSelectionAction::Row { index, operation },
417        }
418    }
419
420    /// Resolve selected rows in the model's current order with one model pass.
421    pub fn indices(&self, model: &impl ListModel) -> Vec<usize> {
422        let keys = self.keys();
423        if keys.is_empty() || self.stamp.0 != model.structure_stamp().0 {
424            return Vec::new();
425        }
426        let mut indices = Vec::with_capacity(keys.len());
427        let mut index = 0;
428        model.visit_row_keys(0..model.row_count(), |key| {
429            if keys.contains(&key) {
430                indices.push(index);
431            }
432            index += 1;
433        });
434        indices
435    }
436}
437
438/// Serialize the selected model rows in the supplied visual column order.
439#[doc(hidden)]
440pub fn copy_table_text_in_order<M: ListModel>(
441    rows: &crate::TableRows<M>,
442    table: &Node,
443    columns: &[usize],
444    mut cell: impl FnMut(usize, usize, &M::Item) -> Option<String>,
445) -> Option<String> {
446    try_copy_table_text_in_order(rows, table, columns, |row, column, item| {
447        Ok::<_, std::convert::Infallible>(cell(row, column, item))
448    })
449    .unwrap_or_else(|error| match error {})
450}
451
452/// Serialize a selection, stopping before evaluating any cells after an error.
453#[doc(hidden)]
454pub fn try_copy_table_text_in_order<M: ListModel, E>(
455    rows: &TableRows<M>,
456    table: &Node,
457    columns: &[usize],
458    mut cell: impl FnMut(usize, usize, &M::Item) -> Result<Option<String>, E>,
459) -> Result<Option<String>, E> {
460    if table.standard_list_stamp != Some(rows.positions().stamp()) {
461        return Ok(None);
462    }
463    let source = rows.source();
464    let stamp = source.contents_stamp();
465    try_copy_table_rows(
466        rows,
467        table,
468        columns,
469        || source.contents_stamp() == stamp,
470        |row, column, _, item| cell(row, column, item),
471    )
472}
473
474#[doc(hidden)]
475pub fn copy_table_text_in_view<M: ListModel>(
476    table: &Node,
477    columns: &[usize],
478    rows: impl FnOnce() -> TableRows<M>,
479    cell: impl FnMut(usize, usize, RowKey, &M::Item) -> Option<String>,
480) -> Option<String> {
481    copy_table_text_in_view_if(table, columns, || Some(rows()), cell)
482}
483
484#[doc(hidden)]
485pub fn copy_table_text_in_view_if<M: ListModel>(
486    table: &Node,
487    columns: &[usize],
488    rows: impl FnOnce() -> Option<TableRows<M>>,
489    mut cell: impl FnMut(usize, usize, RowKey, &M::Item) -> Option<String>,
490) -> Option<String> {
491    try_copy_table_text_in_view(
492        table,
493        columns,
494        || Ok::<_, std::convert::Infallible>(rows()),
495        |row, column, key, item| Ok(cell(row, column, key, item)),
496    )
497    .unwrap_or_else(|error| match error {})
498}
499
500/// Copy cells only while the model and the dependencies read by the projection stay current.
501#[doc(hidden)]
502pub fn try_copy_table_text_in_view<M: ListModel, E>(
503    table: &Node,
504    columns: &[usize],
505    rows: impl FnOnce() -> Result<Option<TableRows<M>>, E>,
506    cell: impl FnMut(usize, usize, RowKey, &M::Item) -> Result<Option<String>, E>,
507) -> Result<Option<String>, E> {
508    try_copy_table_text_while_current(table, columns, || true, rows, cell)
509}
510
511#[doc(hidden)]
512pub fn copy_table_text_while_current<M: ListModel>(
513    table: &Node,
514    columns: &[usize],
515    available: impl Fn() -> bool,
516    rows: impl FnOnce() -> Option<TableRows<M>>,
517    mut cell: impl FnMut(usize, usize, RowKey, &M::Item) -> Option<String>,
518) -> Option<String> {
519    try_copy_table_text_while_current(
520        table,
521        columns,
522        available,
523        || Ok::<_, std::convert::Infallible>(rows()),
524        |row, column, key, item| Ok(cell(row, column, key, item)),
525    )
526    .unwrap_or_else(|error| match error {})
527}
528
529#[doc(hidden)]
530pub fn try_copy_table_text_while_current<M: ListModel, E>(
531    table: &Node,
532    columns: &[usize],
533    available: impl Fn() -> bool,
534    rows: impl FnOnce() -> Result<Option<TableRows<M>>, E>,
535    cell: impl FnMut(usize, usize, RowKey, &M::Item) -> Result<Option<String>, E>,
536) -> Result<Option<String>, E> {
537    with_table_rows_in_view(table, available, rows, |rows, current| {
538        try_copy_table_rows(rows, table, columns, current, cell)
539    })
540}
541
542fn try_copy_table_rows<M: ListModel, E>(
543    rows: &TableRows<M>,
544    table: &Node,
545    columns: &[usize],
546    current: impl Fn() -> bool,
547    mut cell: impl FnMut(usize, usize, RowKey, &M::Item) -> Result<Option<String>, E>,
548) -> Result<Option<String>, E> {
549    try_copy_table_text(rows, table, columns, current, |row, column, key, item| {
550        let Some(source) = rows.positions().source_index(row) else {
551            return Ok(None);
552        };
553        cell(source, column, key, item)
554    })
555}
556
557#[doc(hidden)]
558pub fn copy_table_text<M: ListModel>(
559    model: &M,
560    table: &Node,
561    displayed_columns: &[usize],
562    mut cell: impl FnMut(usize, usize, &M::Item) -> Option<String>,
563) -> Option<String> {
564    let stamp = model.contents_stamp();
565    try_copy_table_text(
566        model,
567        table,
568        displayed_columns,
569        || model.contents_stamp() == stamp,
570        |row, column, _, item| Ok::<_, std::convert::Infallible>(cell(row, column, item)),
571    )
572    .unwrap_or_else(|error| match error {})
573}
574
575struct ClipboardSelection<'a> {
576    rows: Vec<usize>,
577    range: Range<usize>,
578    columns: Vec<usize>,
579    cells: Option<&'a TableSelectionSnapshot>,
580}
581
582fn clipboard_selection<'a>(
583    model: &impl ListModel,
584    table: &'a Node,
585    displayed_columns: &[usize],
586) -> Option<ClipboardSelection<'a>> {
587    let count = model.row_count();
588    let column_count = table.table_header.as_ref()?.columns.len();
589    let mut columns: Vec<_> = displayed_columns
590        .iter()
591        .copied()
592        .filter(|&column| column < column_count)
593        .collect();
594    let mut rows = Vec::new();
595    let mut range = 0..count;
596    let mut cells = None;
597    if let Some(selection) = table.table_selection.as_deref() {
598        if selection.stamp.0 != model.structure_stamp().0 {
599            return None;
600        }
601        match &selection.selected {
602            Selected::Rows(selected) => {
603                if selected.len().checked_mul(columns.len())? > MAX_CLIPBOARD_CELLS {
604                    return None;
605                }
606                let current = table
607                    .int("current-row")
608                    .and_then(|row| usize::try_from(row).ok());
609                if let Some(row) = current.filter(|&row| {
610                    selected.len() == 1 && row < count && selected.contains(&model.row_key(row))
611                }) {
612                    rows.push(row);
613                } else {
614                    rows = selection.indices(model);
615                }
616                range = 0..0;
617            }
618            Selected::Columns(selected) => columns.retain(|column| selected.contains(column)),
619            Selected::Cells(selected) => {
620                let start = columns
621                    .iter()
622                    .position(|column| selected.contains_key(column))?;
623                let end = columns
624                    .iter()
625                    .rposition(|column| selected.contains_key(column))?
626                    + 1;
627                columns = columns[start..end].to_vec();
628                let selected_count = columns
629                    .iter()
630                    .filter_map(|column| selected.get(column))
631                    .try_fold(0usize, |count, keys| count.checked_add(keys.len()))?;
632                if selected_count > MAX_CLIPBOARD_CELLS {
633                    return None;
634                }
635                let mut seen = HashSet::new();
636                let row_sets: Vec<_> = columns
637                    .iter()
638                    .filter_map(|column| selected.get(column))
639                    .filter(|keys| seen.insert(Arc::as_ptr(keys)))
640                    .collect();
641                let union: HashSet<_> = if row_sets.len() > 1 {
642                    row_sets
643                        .iter()
644                        .flat_map(|rows| rows.iter().copied())
645                        .collect()
646                } else {
647                    HashSet::new()
648                };
649                let mut index = 0;
650                let mut first = count;
651                let mut last = 0;
652                model.visit_row_keys(0..count, |key| {
653                    let included = if let [keys] = row_sets.as_slice() {
654                        keys.contains(&key)
655                    } else {
656                        union.contains(&key)
657                    };
658                    if included {
659                        first = first.min(index);
660                        last = index + 1;
661                    }
662                    index += 1;
663                });
664                range = first..last;
665                cells = Some(selection);
666            }
667        }
668    } else {
669        let row = usize::try_from(table.int("current-row")?).ok()?;
670        if row >= count {
671            return None;
672        }
673        range = row..row + 1;
674    }
675
676    let size = rows
677        .len()
678        .checked_add(range.len())?
679        .checked_mul(columns.len())?;
680    if size == 0 || size > MAX_CLIPBOARD_CELLS {
681        return None;
682    }
683    Some(ClipboardSelection {
684        rows,
685        range,
686        columns,
687        cells,
688    })
689}
690
691fn try_copy_table_text<M: ListModel, E>(
692    model: &M,
693    table: &Node,
694    displayed_columns: &[usize],
695    current: impl Fn() -> bool,
696    mut cell: impl FnMut(usize, usize, RowKey, &M::Item) -> Result<Option<String>, E>,
697) -> Result<Option<String>, E> {
698    let Some(ClipboardSelection {
699        rows,
700        range,
701        columns,
702        cells,
703    }) = clipboard_selection(model, table, displayed_columns)
704    else {
705        return Ok(None);
706    };
707    let mut text = String::new();
708    for (line, row) in rows.into_iter().chain(range).enumerate() {
709        if line != 0 {
710            text.push('\n');
711        }
712        let line_start = text.len();
713        let key = model.row_key(row);
714        let item = model.item(row);
715        for (slot, &column) in columns.iter().enumerate() {
716            if slot != 0 {
717                text.push('\t');
718            }
719            if cells.is_none_or(|selection| selection.contains_cell(key, column)) {
720                let value = cell(row, column, key, &item)?;
721                if !current() {
722                    return Ok(None);
723                }
724                if let Some(value) = value {
725                    let Some(()) = append_cell(&mut text, &value) else {
726                        return Ok(None);
727                    };
728                }
729            }
730            if text.len() > MAX_CLIPBOARD_BYTES {
731                return Ok(None);
732            }
733        }
734        if text.len() == line_start {
735            // A blank final single-column row would otherwise look like a trailing newline.
736            if text.len().saturating_add(2) > MAX_CLIPBOARD_BYTES {
737                return Ok(None);
738            }
739            text.push_str("\"\"");
740        }
741    }
742    Ok(Some(text))
743}
744
745fn append_cell(text: &mut String, value: &str) -> Option<()> {
746    let quoted = value.contains(['\t', '\n', '\r', '"']);
747    let extra = if quoted {
748        value.bytes().filter(|&byte| byte == b'"').count() + 2
749    } else {
750        0
751    };
752    if text.len().saturating_add(value.len()).saturating_add(extra) > MAX_CLIPBOARD_BYTES {
753        return None;
754    }
755    if quoted {
756        text.push('"');
757        for (index, part) in value.split('"').enumerate() {
758            if index != 0 {
759                text.push_str("\"\"");
760            }
761            text.push_str(part);
762        }
763        text.push('"');
764    } else {
765        text.push_str(value);
766    }
767    Some(())
768}
769
770#[doc(hidden)]
771pub struct TableSelectionChange {
772    pub current: Option<usize>,
773    pub column_changed: bool,
774    pub selected_count: Option<usize>,
775}
776
777#[doc(hidden)]
778pub enum TableSelectionEvent {
779    CurrentRowChanged(usize),
780    CurrentCellChanged,
781    SelectionChanged(usize),
782}
783
784impl TableSelectionChange {
785    /// Publish the cursor before resolving the cell notification. The row
786    /// handler can change bindings that the cell handler will read.
787    pub fn try_notify<E>(
788        self,
789        notify_cell: bool,
790        mut notify: impl FnMut(TableSelectionEvent) -> Result<(), E>,
791    ) -> Result<bool, E> {
792        if let Some(row) = self.current {
793            notify(TableSelectionEvent::CurrentRowChanged(row))?;
794        }
795        let cursor_changed = self.current.is_some() || self.column_changed;
796        if notify_cell && cursor_changed {
797            notify(TableSelectionEvent::CurrentCellChanged)?;
798        }
799        if let Some(count) = self.selected_count {
800            notify(TableSelectionEvent::SelectionChanged(count))?;
801        }
802        Ok(cursor_changed || self.selected_count.is_some())
803    }
804
805    pub fn notify(self, notify_cell: bool, mut notify: impl FnMut(TableSelectionEvent)) -> bool {
806        self.try_notify(notify_cell, |event| {
807            notify(event);
808            Ok::<_, std::convert::Infallible>(())
809        })
810        .unwrap_or_else(|error| match error {})
811    }
812}
813
814#[doc(hidden)]
815pub struct TableSelectionOptions {
816    pub target: SelectionTarget,
817    pub multiple: bool,
818    pub order: TableColumnOrder,
819    pub drag_select: bool,
820}
821
822/// Address a table selection by its displayed position or source row.
823#[doc(hidden)]
824pub enum TableSelectionCommand {
825    Visual(TableSelectionAction),
826    Source { row: usize, column: Option<usize> },
827}
828
829#[derive(Clone, Copy)]
830#[doc(hidden)]
831pub enum ListSelectionCommand {
832    Visual(TableSelectionAction),
833    Source(usize),
834    Key(i64),
835}
836
837#[derive(Default)]
838struct Selection {
839    stamp: Option<(u64, u64)>,
840    source_stamp: Option<(u64, u64)>,
841    target: SelectionTarget,
842    multiple: bool,
843    selected: Option<Selected>,
844    row_anchor: Option<(usize, RowKey)>,
845    column_anchor: Option<usize>,
846    current_column: Option<usize>,
847    drag_range: Option<CommittedRange>,
848}
849
850impl Selection {
851    fn refresh(
852        &mut self,
853        model: &impl ListModel,
854        stamp: (u64, u64),
855        target: SelectionTarget,
856        multiple: bool,
857    ) {
858        let source = model.source_structure_stamp();
859        if self.target != target || self.multiple != multiple {
860            *self = Self {
861                target,
862                multiple,
863                stamp: Some(stamp),
864                source_stamp: Some(source),
865                ..Self::default()
866            };
867            return;
868        }
869        if self.stamp == Some(stamp) {
870            return;
871        }
872        self.drag_range = None;
873        let source_changed = self.source_stamp.replace(source) != Some(source);
874        if let Some(previous) = self.stamp.replace(stamp) {
875            if previous.0 != stamp.0 && target != SelectionTarget::Columns {
876                self.selected = Some(Selected::empty(target));
877                self.row_anchor = None;
878            } else if source_changed && let Some(selected) = &mut self.selected {
879                selected.retain_live(model);
880            }
881        }
882    }
883
884    fn selected(&self, model: &impl ListModel, current: Option<usize>) -> Selected {
885        self.selected.clone().unwrap_or_else(|| {
886            if self.target == SelectionTarget::Rows {
887                Selected::Rows(Arc::new(
888                    current
889                        .filter(|&index| index < model.row_count())
890                        .map(|index| model.row_key(index))
891                        .into_iter()
892                        .collect(),
893                ))
894            } else {
895                Selected::empty(self.target)
896            }
897        })
898    }
899
900    fn row_range(
901        &mut self,
902        model: &impl ListModel,
903        current: Option<usize>,
904        row: usize,
905    ) -> Range<usize> {
906        let count = model.row_count();
907        let anchor = self
908            .row_anchor
909            .and_then(|(old, key)| {
910                if old < count && model.row_key(old) == key {
911                    Some(old)
912                } else {
913                    model.index_of_key(key)
914                }
915            })
916            .or(current.filter(|&index| index < count))
917            .unwrap_or(row);
918        self.row_anchor = Some((anchor, model.row_key(anchor)));
919        span(anchor, row)
920    }
921
922    fn column_range<'a>(
923        &mut self,
924        column: usize,
925        view: &'a TableSelectionSnapshot,
926    ) -> impl Iterator<Item = usize> + use<'a> {
927        let anchor = self
928            .column_anchor
929            .or(self.current_column)
930            .filter(|&column| column < view.column_count)
931            .unwrap_or(column);
932        self.column_anchor = Some(anchor);
933        column_span(view, anchor, column)
934    }
935}
936
937fn column_span(
938    view: &TableSelectionSnapshot,
939    anchor: usize,
940    column: usize,
941) -> impl Iterator<Item = usize> + use<'_> {
942    let index = |column| view.order.visual_index(view.column_count, column);
943    let range = span(index(anchor).unwrap_or(0), index(column).unwrap_or(0));
944    view.order
945        .iter(view.column_count)
946        .skip(range.start)
947        .take(range.len())
948}
949
950fn select_cells(
951    cells: &mut Arc<ColumnCells>,
952    columns: impl Iterator<Item = usize>,
953    rows: RowKeys,
954    additive: bool,
955) {
956    if !additive {
957        *cells = Arc::new(columns.map(|column| (column, rows.clone())).collect());
958        return;
959    }
960    let cells = Arc::make_mut(cells);
961    let mut merged = HashMap::<_, RowKeys>::new();
962    for column in columns {
963        let keys = cells.entry(column).or_insert_with(|| rows.clone());
964        if !rows.is_subset(keys) {
965            *keys = merged
966                .entry(Arc::as_ptr(keys))
967                .or_insert_with(|| Arc::new(keys.union(&rows).copied().collect()))
968                .clone();
969        }
970    }
971}
972
973fn whole_row_selected(cells: &ColumnCells, column_count: usize, row: RowKey) -> bool {
974    column_count > 0
975        && cells.len() == column_count
976        && cells.values().all(|keys| keys.contains(&row))
977}
978
979fn remove_row_from_cells(cells: &mut Arc<ColumnCells>, row: RowKey) {
980    let mut trimmed = HashMap::new();
981    Arc::make_mut(cells).retain(|_, keys| {
982        *keys = trimmed
983            .entry(Arc::as_ptr(keys))
984            .or_insert_with(|| {
985                let mut remaining = (**keys).clone();
986                remaining.remove(&row);
987                Arc::new(remaining)
988            })
989            .clone();
990        !keys.is_empty()
991    });
992}
993
994fn toggle<T: Ord>(set: &mut BTreeSet<T>, key: T) {
995    if !set.remove(&key) {
996        set.insert(key);
997    }
998}
999
1000#[doc(hidden)]
1001#[derive(Clone, Default)]
1002pub struct TableSelectionDragHandle(Rc<TableSelectionDragState>);
1003
1004#[derive(Default)]
1005struct TableSelectionDragState {
1006    claims: Cell<usize>,
1007    signal: ChangeSignal,
1008}
1009
1010impl std::fmt::Debug for TableSelectionDragHandle {
1011    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1012        formatter
1013            .debug_tuple("TableSelectionDragHandle")
1014            .field(&self.0.claims.get())
1015            .finish()
1016    }
1017}
1018
1019impl PartialEq for TableSelectionDragHandle {
1020    fn eq(&self, other: &Self) -> bool {
1021        Rc::ptr_eq(&self.0, &other.0)
1022    }
1023}
1024
1025#[doc(hidden)]
1026#[derive(Debug)]
1027pub struct TableSelectionDrag(TableSelectionDragHandle);
1028
1029impl TableSelectionDragHandle {
1030    pub fn claim(&self) -> Rc<TableSelectionDrag> {
1031        let count = self.0.claims.get();
1032        self.0.claims.set(count + 1);
1033        if count == 0 {
1034            self.0.signal.notify();
1035        }
1036        Rc::new(TableSelectionDrag(self.clone()))
1037    }
1038
1039    pub fn dragging(&self) -> bool {
1040        self.0.signal.track();
1041        self.0.claims.get() != 0
1042    }
1043}
1044
1045impl Drop for TableSelectionDrag {
1046    fn drop(&mut self) {
1047        let state = &self.0.0;
1048        let previous = state.claims.get();
1049        state.claims.set(previous - 1);
1050        if previous == 1 {
1051            state.signal.notify();
1052        }
1053    }
1054}
1055
1056/// Generated per table so gestures and data changes share the same selection.
1057#[doc(hidden)]
1058#[derive(Default)]
1059pub struct TableSelection {
1060    state: RefCell<Selection>,
1061    changed: ChangeSignal,
1062    drag: OnceCell<TableSelectionDragHandle>,
1063}
1064
1065impl TableSelection {
1066    fn drag_handle(&self) -> &TableSelectionDragHandle {
1067        self.drag.get_or_init(Default::default)
1068    }
1069
1070    #[doc(hidden)]
1071    pub fn dragging(&self) -> bool {
1072        self.drag_handle().dragging()
1073    }
1074
1075    #[doc(hidden)]
1076    pub fn try_list_selected_keys<M: ListModel, E>(
1077        selection: Option<&Self>,
1078        rows: impl FnOnce() -> Result<TableRows<M>, E>,
1079        current: impl FnOnce() -> Result<i64, E>,
1080        multiple: impl FnOnce() -> Result<bool, E>,
1081        keys: impl FnOnce(&TableRows<M>, &BTreeSet<RowKey>) -> Vec<i64>,
1082    ) -> Result<Vec<i64>, E> {
1083        let prepared = crate::try_prepare_action_view(|| {
1084            let rows = rows()?;
1085            let current = usize::try_from(current()?)
1086                .ok()
1087                .filter(|&index| index < rows.row_count());
1088            let multiple = multiple()?;
1089            Ok(Some((rows, current, multiple)))
1090        })?;
1091        let Some((rows, current, multiple)) = prepared else {
1092            return Ok(Vec::new());
1093        };
1094        if let Some(selection) = selection.filter(|_| multiple) {
1095            let snapshot = selection.snapshot(&rows, current, SelectionTarget::Rows, 0, true);
1096            return Ok(keys(&rows, snapshot.keys()));
1097        }
1098        Ok(current.map_or_else(Vec::new, |index| {
1099            keys(&rows, &BTreeSet::from([rows.row_key(index)]))
1100        }))
1101    }
1102
1103    /// Replace the row selection after resolving every requested key against one source.
1104    #[doc(hidden)]
1105    pub fn try_replace_list_keys<M: ListModel, E>(
1106        &self,
1107        rows: impl FnOnce() -> Result<TableRows<M>, E>,
1108        current: impl FnOnce() -> Result<i64, E>,
1109        multiple: impl FnOnce() -> Result<bool, E>,
1110        resolve: impl FnOnce(&TableRows<M>) -> Option<BTreeSet<RowKey>>,
1111    ) -> Result<Option<TableSelectionChange>, E> {
1112        let prepared = crate::try_prepare_action_view(|| {
1113            if !multiple()? {
1114                return Ok(None);
1115            }
1116            let rows = rows()?;
1117            let Some(keys) = resolve(&rows) else {
1118                return Ok(None);
1119            };
1120            let current = usize::try_from(current()?).ok();
1121            Ok(Some((rows, current, keys)))
1122        })?;
1123        let Some((rows, current, keys)) = prepared else {
1124            return Ok(None);
1125        };
1126        let mut state = self.state.borrow_mut();
1127        state.refresh(&rows, rows.structure_stamp(), SelectionTarget::Rows, true);
1128        let previous = state.selected(&rows, current);
1129        let next = Selected::Rows(Arc::new(keys));
1130        let selected_count = (previous != next).then_some(next.len());
1131        let was_implicit = state.selected.is_none();
1132        state.selected = Some(next);
1133        state.row_anchor = None;
1134        state.column_anchor = None;
1135        let had_range = state.drag_range.take().is_some();
1136        drop(state);
1137        if selected_count.is_some() || was_implicit || had_range {
1138            self.changed.notify();
1139        }
1140        Ok(Some(TableSelectionChange {
1141            current: None,
1142            column_changed: false,
1143            selected_count,
1144        }))
1145    }
1146
1147    #[doc(hidden)]
1148    pub fn try_list_info<M: ListModel, E>(
1149        selection: Option<&Self>,
1150        rows: impl FnOnce() -> Result<TableRows<M>, E>,
1151        current: impl FnOnce() -> Result<i64, E>,
1152        multiple: impl FnOnce() -> Result<bool, E>,
1153        query: i64,
1154    ) -> Result<(i64, bool), E> {
1155        let prepared = crate::property::watch_reads(|reads| {
1156            let rows = rows()?;
1157            let count = rows.row_count();
1158            let current = usize::try_from(current()?)
1159                .ok()
1160                .filter(|&index| index < count);
1161            let multiple = multiple()?;
1162            Ok((!reads.changed()).then_some((rows, count, current, multiple)))
1163        })?;
1164        let Some((rows, count, current, multiple)) = prepared else {
1165            return Ok((0, false));
1166        };
1167        let query = usize::try_from(query).ok().filter(|&index| index < count);
1168        if let Some(selection) = selection.filter(|_| multiple) {
1169            let snapshot = selection.snapshot(&rows, current, SelectionTarget::Rows, 0, true);
1170            Ok((
1171                snapshot.selection_count(),
1172                query.is_some_and(|index| snapshot.keys().contains(&rows.row_key(index))),
1173            ))
1174        } else {
1175            Ok((
1176                i64::from(current.is_some()),
1177                query.is_some() && query == current,
1178            ))
1179        }
1180    }
1181
1182    #[doc(hidden)]
1183    pub fn try_apply_list_command<M: ListModel, E>(
1184        &self,
1185        command: ListSelectionCommand,
1186        rows: impl FnOnce() -> Result<TableRows<M>, E>,
1187        current: impl FnOnce() -> Result<i64, E>,
1188        multiple: impl FnOnce() -> Result<bool, E>,
1189        key_source: impl FnOnce(&TableRows<M>, i64) -> Option<usize>,
1190    ) -> Result<Option<TableSelectionChange>, E> {
1191        let prepared = crate::property::watch_reads(|reads| {
1192            let rows = rows()?;
1193            let replace = |index| TableSelectionAction::Row {
1194                index,
1195                operation: RowSelection::Replace,
1196            };
1197            let action = match command {
1198                ListSelectionCommand::Visual(action) => Some(action),
1199                ListSelectionCommand::Source(source) => {
1200                    rows.positions().visual_index(source).map(replace)
1201                }
1202                ListSelectionCommand::Key(key) if key >= 0 => key_source(&rows, key)
1203                    .and_then(|source| rows.positions().visual_index(source))
1204                    .map(replace),
1205                ListSelectionCommand::Key(_) => None,
1206            };
1207            let Some(action) = action else {
1208                return Ok(None);
1209            };
1210            let current = usize::try_from(current()?).ok();
1211            let multiple = multiple()?;
1212            Ok((!reads.changed()).then_some((rows, current, multiple, action)))
1213        })?;
1214        let Some((rows, current, multiple, action)) = prepared else {
1215            return Ok(None);
1216        };
1217        if !multiple {
1218            return Ok(match action {
1219                TableSelectionAction::Row {
1220                    index,
1221                    operation: RowSelection::Replace,
1222                } if index < rows.row_count() && Some(index) != current => {
1223                    Some(TableSelectionChange {
1224                        current: Some(index),
1225                        column_changed: false,
1226                        selected_count: None,
1227                    })
1228                }
1229                _ => None,
1230            });
1231        }
1232        if !matches!(
1233            action,
1234            TableSelectionAction::Row { .. }
1235                | TableSelectionAction::All
1236                | TableSelectionAction::Clear
1237        ) {
1238            return Ok(None);
1239        }
1240        let view = self.snapshot(&rows, current, SelectionTarget::Rows, 0, true);
1241        Ok(self.apply(&rows, &view, current, action))
1242    }
1243
1244    pub fn has_explicit_selection(&self) -> bool {
1245        self.changed.track();
1246        self.state.borrow().selected.is_some()
1247    }
1248
1249    pub fn snapshot(
1250        &self,
1251        model: &impl ListModel,
1252        current: Option<usize>,
1253        target: SelectionTarget,
1254        column_count: usize,
1255        multiple: bool,
1256    ) -> TableSelectionSnapshot {
1257        self.changed.track();
1258        let stamp = model.structure_stamp();
1259        let mut state = self.state.borrow_mut();
1260        state.refresh(model, stamp, target, multiple);
1261        TableSelectionSnapshot {
1262            stamp,
1263            target,
1264            column_count,
1265            order: crate::TableColumnOrder::default(),
1266            multiple,
1267            current_column: state.current_column,
1268            selected: state.selected(model, current),
1269            drag_range: state.drag_range.clone(),
1270        }
1271    }
1272
1273    /// Read the live cursor and selection bindings in the same order for both backends.
1274    #[doc(hidden)]
1275    pub fn try_snapshot_with<E>(
1276        &self,
1277        model: &impl ListModel,
1278        column_count: usize,
1279        current: impl FnOnce() -> Result<i64, E>,
1280        target: impl FnOnce() -> Result<SelectionTarget, E>,
1281        multiple: impl FnOnce() -> Result<bool, E>,
1282        order: impl FnOnce() -> TableColumnOrder,
1283    ) -> Result<TableSelectionSnapshot, E> {
1284        let current = usize::try_from(current()?).ok();
1285        Ok(self
1286            .snapshot(model, current, target()?, column_count, multiple()?)
1287            .with_column_order(order()))
1288    }
1289
1290    #[doc(hidden)]
1291    pub fn snapshot_with(
1292        &self,
1293        model: &impl ListModel,
1294        column_count: usize,
1295        current: impl FnOnce() -> i64,
1296        target: impl FnOnce() -> SelectionTarget,
1297        multiple: impl FnOnce() -> bool,
1298        order: impl FnOnce() -> TableColumnOrder,
1299    ) -> TableSelectionSnapshot {
1300        self.try_snapshot_with(
1301            model,
1302            column_count,
1303            || Ok::<_, std::convert::Infallible>(current()),
1304            || Ok(target()),
1305            || Ok(multiple()),
1306            order,
1307        )
1308        .unwrap_or_else(|error| match error {})
1309    }
1310
1311    /// Build the rendered selection from the same row projection and bindings as the scene.
1312    #[doc(hidden)]
1313    pub fn populate_scene(&self, table: &mut Node, model: &impl ListModel) {
1314        let current = table
1315            .int("current-row")
1316            .and_then(|row| usize::try_from(row).ok());
1317        let target = table.selection_target();
1318        let columns = table
1319            .table_header
1320            .as_ref()
1321            .map_or(0, |header| header.columns.len());
1322        let multiple = table.boolean("multi-select", false);
1323        if multiple && table.boolean("drag-select", false) {
1324            table.table_selection_drag = Some(self.drag_handle().clone());
1325        }
1326        let snapshot = self
1327            .snapshot(model, current, target, columns, multiple)
1328            .with_column_order(table.table_column_order.clone());
1329        table.table_selection =
1330            (multiple || target != SelectionTarget::Rows || self.has_explicit_selection())
1331                .then(|| Box::new(snapshot));
1332    }
1333
1334    #[doc(hidden)]
1335    pub fn populate_list_scene(&self, list: &mut Node, model: &impl ListModel) {
1336        let multiple = list.boolean("multi-select", false);
1337        let current = list
1338            .int("current-index")
1339            .and_then(|index| usize::try_from(index).ok());
1340        let snapshot = self.snapshot(model, current, SelectionTarget::Rows, 0, multiple);
1341        list.table_selection = multiple.then(|| Box::new(snapshot));
1342    }
1343
1344    /// Apply a scene's selection only while its row order and selection mode still apply.
1345    #[doc(hidden)]
1346    pub fn try_apply_control<M: ListModel, E>(
1347        &self,
1348        table: &Node,
1349        input: crate::InputRoute<'_>,
1350        available: impl FnOnce() -> Result<bool, E>,
1351        rows: impl FnOnce() -> Result<M, E>,
1352        options: impl FnOnce() -> Result<TableSelectionOptions, E>,
1353        current: impl FnOnce() -> Result<i64, E>,
1354    ) -> Result<Option<TableSelectionChange>, E> {
1355        let crate::RoutedEvent::Control(action) = *input.event() else {
1356            return Ok(None);
1357        };
1358        let prepared = crate::property::watch_reads(|reads| {
1359            if !available()? || reads.changed() {
1360                return Ok(None);
1361            }
1362            let rows = rows()?;
1363            if table.standard_list_stamp != Some(rows.structure_stamp()) || reads.changed() {
1364                return Ok(None);
1365            }
1366            let row_count = rows.row_count();
1367            let options = options()?;
1368            if options.target != table.selection_target()
1369                || options.multiple != table.boolean("multi-select", false)
1370                || reads.changed()
1371            {
1372                return Ok(None);
1373            }
1374            let selection = if table.table_selection.is_some() {
1375                let Some(selection) =
1376                    TableSelectionAction::from_control(table, &options.order, action)
1377                else {
1378                    return Ok(None);
1379                };
1380                if table.table_header.is_none()
1381                    && !matches!(
1382                        selection,
1383                        TableSelectionAction::Row { .. }
1384                            | TableSelectionAction::All
1385                            | TableSelectionAction::Clear
1386                    )
1387                {
1388                    return Ok(None);
1389                }
1390                if matches!(selection, TableSelectionAction::DragRange { .. })
1391                    && !options.drag_select
1392                {
1393                    return Ok(None);
1394                }
1395                Some(selection)
1396            } else {
1397                if !matches!(action, ControlAction::Select(index) if index < row_count)
1398                    || self.has_explicit_selection()
1399                {
1400                    return Ok(None);
1401                }
1402                None
1403            };
1404            let current = usize::try_from(current()?).ok();
1405            Ok((input.is_current() && !reads.changed())
1406                .then_some((rows, options, current, selection)))
1407        })?;
1408        let Some((rows, options, current, selection)) = prepared else {
1409            return Ok(None);
1410        };
1411        if let Some(selection) = selection {
1412            let column_count = table
1413                .table_header
1414                .as_ref()
1415                .map_or(0, |header| header.columns.len());
1416            let view = self
1417                .snapshot(
1418                    &rows,
1419                    current,
1420                    options.target,
1421                    column_count,
1422                    options.multiple,
1423                )
1424                .with_column_order(options.order);
1425            return Ok(self.apply(&rows, &view, current, selection));
1426        }
1427        Ok(match action {
1428            ControlAction::Select(index) if Some(index) != current => Some(TableSelectionChange {
1429                current: Some(index),
1430                column_changed: false,
1431                selected_count: None,
1432            }),
1433            _ => None,
1434        })
1435    }
1436
1437    #[doc(hidden)]
1438    pub fn apply_control<M: ListModel>(
1439        &self,
1440        table: &Node,
1441        input: crate::InputRoute<'_>,
1442        available: impl FnOnce() -> bool,
1443        rows: impl FnOnce() -> M,
1444        options: impl FnOnce() -> TableSelectionOptions,
1445        current: impl FnOnce() -> i64,
1446    ) -> Option<TableSelectionChange> {
1447        self.try_apply_control(
1448            table,
1449            input,
1450            || Ok::<_, std::convert::Infallible>(available()),
1451            || Ok(rows()),
1452            || Ok(options()),
1453            || Ok(current()),
1454        )
1455        .unwrap_or_else(|error| match error {})
1456    }
1457
1458    /// Apply a command using one live model and cursor snapshot.
1459    #[doc(hidden)]
1460    pub fn try_apply_command<M: ListModel, E>(
1461        &self,
1462        command: TableSelectionCommand,
1463        column_count: usize,
1464        rows: impl FnOnce() -> Result<TableRows<M>, E>,
1465        current: impl FnOnce() -> Result<i64, E>,
1466        options: impl FnOnce() -> Result<TableSelectionOptions, E>,
1467    ) -> Result<Option<TableSelectionChange>, E> {
1468        self.try_apply_command_for(column_count, rows, current, options, |_| Some(command))
1469    }
1470
1471    /// Resolve commands against the same model projection that will receive them.
1472    #[doc(hidden)]
1473    pub fn try_apply_command_for<M: ListModel, E>(
1474        &self,
1475        column_count: usize,
1476        rows: impl FnOnce() -> Result<TableRows<M>, E>,
1477        current: impl FnOnce() -> Result<i64, E>,
1478        options: impl FnOnce() -> Result<TableSelectionOptions, E>,
1479        command: impl FnOnce(&TableRows<M>) -> Option<TableSelectionCommand>,
1480    ) -> Result<Option<TableSelectionChange>, E> {
1481        let prepared = crate::property::watch_reads(|reads| {
1482            let rows = rows()?;
1483            let Some(command) = command(&rows) else {
1484                return Ok(None);
1485            };
1486            let command = match command {
1487                TableSelectionCommand::Source { row, column } => {
1488                    let Some(row) = rows.positions().visual_index(row) else {
1489                        return Ok(None);
1490                    };
1491                    TableSelectionCommand::Source { row, column }
1492                }
1493                command => command,
1494            };
1495            let current = usize::try_from(current()?).ok();
1496            let options = options()?;
1497            Ok((!reads.changed()).then_some((rows, current, options, command)))
1498        })?;
1499        let Some((rows, current, options, command)) = prepared else {
1500            return Ok(None);
1501        };
1502        let action = match command {
1503            TableSelectionCommand::Visual(action) => action,
1504            TableSelectionCommand::Source {
1505                row,
1506                column: Some(column),
1507            } => TableSelectionAction::Cell {
1508                row,
1509                column,
1510                operation: RowSelection::Replace,
1511            },
1512            TableSelectionCommand::Source { row, column: None } => {
1513                let operation = match options.target {
1514                    SelectionTarget::Rows => RowSelection::Replace,
1515                    SelectionTarget::Cells if options.multiple => RowSelection::Replace,
1516                    _ => RowSelection::Move,
1517                };
1518                TableSelectionAction::Row {
1519                    index: row,
1520                    operation,
1521                }
1522            }
1523        };
1524        let view = self
1525            .snapshot(
1526                &rows,
1527                current,
1528                options.target,
1529                column_count,
1530                options.multiple,
1531            )
1532            .with_column_order(options.order);
1533        Ok(self.apply(&rows, &view, current, action))
1534    }
1535
1536    #[doc(hidden)]
1537    pub fn apply_command<M: ListModel>(
1538        &self,
1539        command: TableSelectionCommand,
1540        column_count: usize,
1541        rows: impl FnOnce() -> TableRows<M>,
1542        current: impl FnOnce() -> i64,
1543        options: impl FnOnce() -> TableSelectionOptions,
1544    ) -> Option<TableSelectionChange> {
1545        self.try_apply_command(
1546            command,
1547            column_count,
1548            || Ok::<_, std::convert::Infallible>(rows()),
1549            || Ok(current()),
1550            || Ok(options()),
1551        )
1552        .unwrap_or_else(|error| match error {})
1553    }
1554
1555    pub fn apply(
1556        &self,
1557        model: &impl ListModel,
1558        view: &TableSelectionSnapshot,
1559        current: Option<usize>,
1560        action: TableSelectionAction,
1561    ) -> Option<TableSelectionChange> {
1562        let stamp = model.structure_stamp();
1563        let mut state = self.state.borrow_mut();
1564        if stamp != view.stamp || state.target != view.target || state.multiple != view.multiple {
1565            return None;
1566        }
1567        let count = model.row_count();
1568        let column_count = view.column_count;
1569        state.refresh(model, stamp, view.target, view.multiple);
1570        let previous = state.selected(model, current);
1571        let mut next = previous.clone();
1572        let mut cursor = None;
1573        let mut drag_range = None;
1574        let old_column = state.current_column;
1575        let operation_for = |operation| {
1576            if view.multiple || operation == RowSelection::Move {
1577                operation
1578            } else {
1579                RowSelection::Replace
1580            }
1581        };
1582        match action {
1583            TableSelectionAction::Row { index, operation } if index < count => {
1584                let operation = operation_for(operation);
1585                cursor = Some(index);
1586                if let Selected::Rows(rows) = &mut next {
1587                    let key = model.row_key(index);
1588                    match operation {
1589                        RowSelection::Replace => {
1590                            state.row_anchor = Some((index, key));
1591                            *rows = Arc::new(BTreeSet::from([key]));
1592                        }
1593                        RowSelection::Toggle => {
1594                            state.row_anchor = Some((index, key));
1595                            toggle(Arc::make_mut(rows), key);
1596                        }
1597                        RowSelection::Extend | RowSelection::AddRange => {
1598                            let keys = row_keys(model, state.row_range(model, current, index));
1599                            if operation == RowSelection::Extend {
1600                                *rows = Arc::new(keys);
1601                            } else {
1602                                Arc::make_mut(rows).extend(keys);
1603                            }
1604                        }
1605                        RowSelection::Move => {}
1606                    }
1607                } else if let Selected::Cells(cells) = &mut next
1608                    && view.multiple
1609                    && column_count > 0
1610                {
1611                    match operation {
1612                        RowSelection::Replace | RowSelection::Toggle => {
1613                            let key = model.row_key(index);
1614                            state.row_anchor = Some((index, key));
1615                            state.column_anchor = state
1616                                .current_column
1617                                .or_else(|| view.order.iter(column_count).next());
1618                            state.current_column = state.column_anchor;
1619                            if operation == RowSelection::Toggle
1620                                && whole_row_selected(cells, column_count, key)
1621                            {
1622                                remove_row_from_cells(cells, key);
1623                            } else {
1624                                select_cells(
1625                                    cells,
1626                                    0..column_count,
1627                                    Arc::new(BTreeSet::from([key])),
1628                                    operation == RowSelection::Toggle,
1629                                );
1630                            }
1631                        }
1632                        RowSelection::Extend | RowSelection::AddRange => {
1633                            let rows =
1634                                Arc::new(row_keys(model, state.row_range(model, current, index)));
1635                            select_cells(
1636                                cells,
1637                                0..column_count,
1638                                rows,
1639                                operation == RowSelection::AddRange,
1640                            );
1641                        }
1642                        RowSelection::Move => {}
1643                    }
1644                } else if operation != RowSelection::Move {
1645                    return None;
1646                }
1647            }
1648            TableSelectionAction::Column { column, operation } if column < column_count => {
1649                let operation = operation_for(operation);
1650                let Selected::Columns(columns) = &mut next else {
1651                    return None;
1652                };
1653                match operation {
1654                    RowSelection::Replace => {
1655                        state.column_anchor = Some(column);
1656                        *columns = Arc::new(BTreeSet::from([column]));
1657                    }
1658                    RowSelection::Toggle => {
1659                        state.column_anchor = Some(column);
1660                        toggle(Arc::make_mut(columns), column);
1661                    }
1662                    RowSelection::Extend | RowSelection::AddRange => {
1663                        let range = state.column_range(column, view);
1664                        if operation == RowSelection::Extend {
1665                            *columns = Arc::new(range.collect());
1666                        } else {
1667                            Arc::make_mut(columns).extend(range);
1668                        }
1669                    }
1670                    RowSelection::Move => {}
1671                }
1672                state.current_column = Some(column);
1673            }
1674            TableSelectionAction::Cell {
1675                row,
1676                column,
1677                operation,
1678            } if row < count && column < column_count => {
1679                let operation = operation_for(operation);
1680                let Selected::Cells(cells) = &mut next else {
1681                    return None;
1682                };
1683                cursor = Some(row);
1684                match operation {
1685                    RowSelection::Replace | RowSelection::Toggle => {
1686                        let key = model.row_key(row);
1687                        state.row_anchor = Some((row, key));
1688                        state.column_anchor = Some(column);
1689                        if operation == RowSelection::Replace {
1690                            *cells = Arc::new(BTreeMap::from([(
1691                                column,
1692                                Arc::new(BTreeSet::from([key])),
1693                            )]));
1694                        } else {
1695                            let cells = Arc::make_mut(cells);
1696                            let rows = cells.entry(column).or_default();
1697                            toggle(Arc::make_mut(rows), key);
1698                            if rows.is_empty() {
1699                                cells.remove(&column);
1700                            }
1701                        }
1702                    }
1703                    RowSelection::Extend | RowSelection::AddRange => {
1704                        let range = state.column_range(column, view);
1705                        let rows = Arc::new(row_keys(model, state.row_range(model, current, row)));
1706                        select_cells(cells, range, rows, operation == RowSelection::AddRange);
1707                    }
1708                    RowSelection::Move => {}
1709                }
1710                state.current_column = Some(column);
1711            }
1712            TableSelectionAction::DragRange {
1713                anchor: (first_row, first_column),
1714                end: (row, column),
1715                additive,
1716            } if view.multiple
1717                && first_row < count
1718                && row < count
1719                && first_column < column_count
1720                && column < column_count =>
1721            {
1722                drag_range = (!additive).then(|| CommittedRange {
1723                    endpoints: [(first_row, first_column), (row, column)],
1724                    order: view.order.clone(),
1725                });
1726                match &mut next {
1727                    Selected::Rows(rows) => {
1728                        let range = row_keys(model, span(first_row, row));
1729                        if additive {
1730                            Arc::make_mut(rows).extend(range);
1731                        } else {
1732                            *rows = Arc::new(range);
1733                        }
1734                    }
1735                    Selected::Columns(columns) => {
1736                        let range = column_span(view, first_column, column);
1737                        if additive {
1738                            Arc::make_mut(columns).extend(range);
1739                        } else {
1740                            *columns = Arc::new(range.collect());
1741                        }
1742                    }
1743                    Selected::Cells(cells) => select_cells(
1744                        cells,
1745                        column_span(view, first_column, column),
1746                        Arc::new(row_keys(model, span(first_row, row))),
1747                        additive,
1748                    ),
1749                }
1750                if view.target != SelectionTarget::Columns {
1751                    state.row_anchor = Some((first_row, model.row_key(first_row)));
1752                    cursor = Some(row);
1753                }
1754                if view.target != SelectionTarget::Rows {
1755                    state.column_anchor = Some(first_column);
1756                    state.current_column = Some(column);
1757                }
1758            }
1759            TableSelectionAction::All if view.multiple => {
1760                let total = match view.target {
1761                    SelectionTarget::Rows => count,
1762                    SelectionTarget::Columns => column_count,
1763                    SelectionTarget::Cells => count.saturating_mul(column_count),
1764                };
1765                if previous.len() == total
1766                    && match &previous {
1767                        Selected::Rows(keys) => {
1768                            let mut complete = true;
1769                            model.visit_row_keys(0..count, |key| complete &= keys.contains(&key));
1770                            complete
1771                        }
1772                        _ => true,
1773                    }
1774                {
1775                    if state.drag_range.take().is_some() {
1776                        self.changed.notify();
1777                    }
1778                    return Some(TableSelectionChange {
1779                        current: None,
1780                        column_changed: false,
1781                        selected_count: None,
1782                    });
1783                }
1784                next = match view.target {
1785                    SelectionTarget::Rows => Selected::Rows(Arc::new(row_keys(model, 0..count))),
1786                    SelectionTarget::Columns => {
1787                        Selected::Columns(Arc::new((0..column_count).collect()))
1788                    }
1789                    SelectionTarget::Cells => {
1790                        if count == 0 {
1791                            Selected::empty(view.target)
1792                        } else {
1793                            let rows = Arc::new(row_keys(model, 0..count));
1794                            Selected::Cells(Arc::new(
1795                                (0..column_count)
1796                                    .map(|column| (column, rows.clone()))
1797                                    .collect(),
1798                            ))
1799                        }
1800                    }
1801                };
1802            }
1803            TableSelectionAction::Clear => {
1804                state.row_anchor = None;
1805                state.column_anchor = None;
1806                next = Selected::empty(view.target);
1807            }
1808            _ => return None,
1809        }
1810        let selected_count = (next != previous).then_some(next.len());
1811        let column_changed = state.current_column != old_column;
1812        let range_changed = state.drag_range != drag_range;
1813        state.drag_range = drag_range;
1814        state.selected = Some(next);
1815        if selected_count.is_some() || column_changed || range_changed {
1816            self.changed.notify();
1817        }
1818        Some(TableSelectionChange {
1819            current: cursor.filter(|index| Some(*index) != current),
1820            column_changed,
1821            selected_count,
1822        })
1823    }
1824}
1825
1826#[cfg(test)]
1827mod tests {
1828    use super::*;
1829
1830    #[test]
1831    fn drag_ranges_use_the_explicit_anchor_in_each_selection_mode() {
1832        let selection = TableSelection::default();
1833        let model = 6_i64;
1834        let rows = selection.snapshot(&model, Some(0), SelectionTarget::Rows, 3, true);
1835        let action = TableSelectionAction::DragRange {
1836            anchor: (4, 2),
1837            end: (1, 0),
1838            additive: false,
1839        };
1840        let change = selection.apply(&model, &rows, Some(0), action).unwrap();
1841        assert_eq!(change.current, Some(1));
1842        assert_eq!(change.selected_count, Some(4));
1843        assert_eq!(
1844            selection
1845                .snapshot(&model, Some(1), SelectionTarget::Rows, 3, true)
1846                .indices(&model),
1847            [1, 2, 3, 4],
1848        );
1849
1850        let (_, order) = crate::TableColumnOrder::default().moved(3, 2, 0).unwrap();
1851        let columns = selection
1852            .snapshot(&model, Some(1), SelectionTarget::Columns, 3, true)
1853            .with_column_order(order.clone());
1854        let change = selection.apply(&model, &columns, Some(1), action).unwrap();
1855        assert_eq!(change.current, None);
1856        assert_eq!(change.selected_count, Some(2));
1857        let view = selection.snapshot(&model, Some(1), SelectionTarget::Columns, 3, true);
1858        assert_eq!(view.columns().iter().copied().collect::<Vec<_>>(), [0, 2]);
1859        assert_eq!(view.current_column(), Some(0));
1860        assert_eq!(view.drag_range(), None);
1861        assert_eq!(
1862            view.with_column_order(order).drag_range(),
1863            Some([(4, 2), (1, 0)])
1864        );
1865        let single = selection.snapshot(&model, Some(1), SelectionTarget::Columns, 3, false);
1866        assert!(selection.apply(&model, &single, Some(1), action).is_none());
1867    }
1868
1869    #[test]
1870    fn whole_column_copy_is_ordered_and_checks_the_budget_before_projecting() {
1871        let selection = TableSelection::default();
1872        let model = 3_i64;
1873        let mut table = Node::new("TableView", None);
1874        table.table_header = Some(Box::new(crate::TableHeader {
1875            columns: (0..3).map(|_| Node::new("TableColumn", None)).collect(),
1876            sort: None,
1877            column_widths: Vec::new(),
1878        }));
1879        for (column, operation) in [(1, RowSelection::Replace), (2, RowSelection::Toggle)] {
1880            let view = selection.snapshot(&model, None, SelectionTarget::Columns, 3, true);
1881            assert!(
1882                selection
1883                    .apply(
1884                        &model,
1885                        &view,
1886                        None,
1887                        TableSelectionAction::Column { column, operation }
1888                    )
1889                    .is_some()
1890            );
1891        }
1892        table.table_selection = Some(Box::new(selection.snapshot(
1893            &model,
1894            None,
1895            SelectionTarget::Columns,
1896            3,
1897            true,
1898        )));
1899        let text = copy_table_text(&model, &table, &[2, 0, 1], |_, column, value| {
1900            Some(format!("{value}:{column}"))
1901        });
1902        assert_eq!(text.as_deref(), Some("0:2\t0:1\n1:2\t1:1\n2:2\t2:1"));
1903        assert!(
1904            copy_table_text(&600_000_i64, &table, &[2, 0, 1], |_, _, _| panic!(
1905                "oversized selection must be rejected before projection"
1906            ))
1907            .is_none()
1908        );
1909    }
1910
1911    #[test]
1912    fn numeric_models_prune_removed_positions_and_reject_stale_actions() {
1913        let selection = TableSelection::default();
1914        let view = selection.snapshot(&5_i64, Some(1), SelectionTarget::Rows, 1, true);
1915        assert_eq!(view.indices(&5_i64), [1]);
1916        let change = selection
1917            .apply(
1918                &5_i64,
1919                &view,
1920                Some(1),
1921                TableSelectionAction::Row {
1922                    index: 4,
1923                    operation: RowSelection::Extend,
1924                },
1925            )
1926            .unwrap();
1927        assert_eq!(change.selected_count, Some(4));
1928        assert_eq!(change.current, Some(4));
1929        let stale = selection.snapshot(&5_i64, Some(4), SelectionTarget::Rows, 1, true);
1930        assert!(
1931            selection
1932                .apply(&3_i64, &stale, None, TableSelectionAction::All)
1933                .is_none()
1934        );
1935        assert_eq!(
1936            selection
1937                .snapshot(&3_i64, None, SelectionTarget::Rows, 1, true)
1938                .indices(&3_i64),
1939            [1, 2]
1940        );
1941    }
1942
1943    #[test]
1944    fn cell_select_all_shares_row_keys_across_columns() {
1945        let selection = TableSelection::default();
1946        let model = crate::VecModel::from((0..10_000).collect::<Vec<_>>());
1947        let view = selection.snapshot(&model, None, SelectionTarget::Cells, 128, true);
1948        selection
1949            .apply(&model, &view, None, TableSelectionAction::All)
1950            .unwrap();
1951        let view = selection.snapshot(&model, None, SelectionTarget::Cells, 128, true);
1952        assert_eq!(view.len(), 1_280_000);
1953        assert!(std::ptr::eq(
1954            view.cell_keys(0).unwrap(),
1955            view.cell_keys(127).unwrap()
1956        ));
1957        let removed = model.row_key(0).unwrap();
1958        model.remove(0);
1959        let view = selection.snapshot(&model, None, SelectionTarget::Cells, 128, true);
1960        assert_eq!(view.len(), 1_279_872);
1961        assert!(!view.contains_cell(removed, 0));
1962        assert!(std::ptr::eq(
1963            view.cell_keys(0).unwrap(),
1964            view.cell_keys(127).unwrap()
1965        ));
1966    }
1967
1968    #[test]
1969    fn grid_selection_can_be_single_and_mode_changes_reject_old_gestures() {
1970        let selection = TableSelection::default();
1971        let view = selection.snapshot(&5_i64, None, SelectionTarget::Cells, 2, false);
1972        assert!(
1973            selection
1974                .apply(&5_i64, &view, None, TableSelectionAction::All)
1975                .is_none()
1976        );
1977        for (row, column, operation) in
1978            [(0, 0, RowSelection::Replace), (4, 1, RowSelection::Extend)]
1979        {
1980            selection
1981                .apply(
1982                    &5_i64,
1983                    &view,
1984                    None,
1985                    TableSelectionAction::Cell {
1986                        row,
1987                        column,
1988                        operation,
1989                    },
1990                )
1991                .unwrap();
1992        }
1993        let view = selection.snapshot(&5_i64, None, SelectionTarget::Cells, 2, false);
1994        assert_eq!(view.len(), 1);
1995        assert!(view.contains_cell(5_i64.row_key(4), 1));
1996        let columns = selection.snapshot(&5_i64, None, SelectionTarget::Columns, 2, true);
1997        assert!(columns.is_empty());
1998        assert!(
1999            selection
2000                .apply(&5_i64, &view, None, TableSelectionAction::Clear)
2001                .is_none()
2002        );
2003    }
2004}