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