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