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