Skip to main content

waft_winui/controls/table_view/
selection.rs

1//! `TableView`'s row selection (`controls/dev/TableView/TableView_Selection.cpp`): the table's gestures and `SelectionChanged`, and the selection held where the application reaches it: `Select`, `Deselect`, `IsSelected`, `DeselectAll`, `SelectedIndex` and `SelectedItem` of `TableView.idl`, over the single-select `SelectionModel` the control keeps.
2//!
3//! The selection is resolved only while a `TableView` holds it: the table gives it the number of rows, whether its mode allows selection, and how a row maps to an item. Every change of the selected row notifies, and nothing else does, for the table binds the selection while it builds and a listener above the table may rebuild; the table raises `SelectionChanged` from the item reported last, and each row listens for its own index. A later editor who changes the model without notifying leaves rows showing the old selection.
4
5use super::super::items_view::selection_model::SelectionModel;
6use super::source::{TableViewSource, ViewChange};
7use super::*;
8use std::fmt;
9use std::rc::Rc;
10use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Ref};
11
12/// The index in the source's items of a row of the view.
13pub(crate) type ItemOfRow = Rc<dyn Fn(&App, usize) -> Option<usize>>;
14
15/// Adds a listener to an items source.
16type AddSourceListener = Rc<dyn Fn(&mut App, Listener)>;
17/// Removes a listener from an items source.
18type RemoveSourceListener = Rc<dyn Fn(&mut App, &Listener)>;
19/// Reads the changes an items source last made.
20type ReadSourceChanges = Rc<dyn Fn(&App) -> Vec<ViewChange>>;
21/// Reads the number of rows in an items source's view.
22type ReadSourceRowCount = Rc<dyn Fn(&App) -> usize>;
23
24/// The items source a selection follows, erased from the source's item type: how to listen to it,
25/// and how to read the changes it last made and the number of rows in its view.
26#[derive(Clone)]
27pub(crate) struct SelectionSource {
28    id: HandleId,
29    add_listener: AddSourceListener,
30    remove_listener: RemoveSourceListener,
31    changes: ReadSourceChanges,
32    row_count: ReadSourceRowCount,
33}
34
35impl SelectionSource {
36    /// The subscription a selection makes to `source`.
37    pub(crate) fn new<T: 'static>(source: &Ref<TableViewSource<T>>) -> SelectionSource {
38        let for_adding = source.clone();
39        let for_removing = source.clone();
40        let for_changes = source.clone();
41        let for_rows = source.clone();
42        SelectionSource {
43            id: source.handle().id(),
44            add_listener: Rc::new(move |app, listener| for_adding.add_listener(app, listener)),
45            remove_listener: Rc::new(move |app, listener| {
46                for_removing.remove_listener(app, listener)
47            }),
48            changes: Rc::new(move |app| for_changes.changes(app).to_vec()),
49            row_count: Rc::new(move |app| for_rows.view(app).len()),
50        }
51    }
52}
53
54/// What the table holding a selection tells it.
55struct SelectionBinding {
56    /// The table.
57    owner: HandleId,
58    /// `CanSelectRows`: the selection mode is not `None`.
59    can_select: bool,
60    /// The index in the source's items of a row of the view.
61    item_of_row: ItemOfRow,
62}
63
64/// The selected row of a `TableView`: at most one, as WinUI's v1 has it.
65///
66/// The application makes one with [`TableViewSelection::new`], gives it to the table with `TableView::selection`, and disposes it after the table. A table given none selects nothing.
67pub struct TableViewSelection {
68    notifier: ChangeNotifierData,
69    model: SelectionModel,
70    binding: Option<SelectionBinding>,
71    /// The items source the selection follows, kept across tables and heard from whether or not a
72    /// table holds the selection; a table adopting it again changes nothing.
73    source: Option<SelectionSource>,
74    /// The listener the selection has on its source.
75    source_listener: Option<Listener>,
76    /// `m_lastRaisedSelectedItem`: the item `SelectionChanged` last reported.
77    last_raised_item: Option<usize>,
78}
79
80impl TableViewSelection {
81    /// Creates a selection with nothing selected.
82    pub fn new(app: &mut App) -> Ref<Self> {
83        let mut model = SelectionModel::default();
84        model.set_single_select(true);
85        app.create(Self {
86            notifier: ChangeNotifierData::new(),
87            model,
88            binding: None,
89            source: None,
90            source_listener: None,
91            last_raised_item: None,
92        })
93    }
94
95    /// Releases the listeners, including the one on the source it follows; the selection is not
96    /// used after.
97    pub fn dispose(self: Handle<Self>, app: &mut App) {
98        self.stop_following_source(app);
99        ChangeNotifierData::dispose(app, self);
100    }
101
102    /// `Select`: the row `index` of the view becomes the selection. Nothing while no table holds the selection, while its mode is `None`, or for an index past the rows: an existing selection is never cleared to signal a refusal.
103    pub fn select(self: Handle<Self>, app: &mut App, index: usize) {
104        if !self.can_select(app) || index >= self.row_count(app) {
105            return;
106        }
107        self.apply(app, Some(index));
108    }
109
110    /// `Deselect`: clears the selection only when `index` is the selected row, so a stale call cannot clear a newer one.
111    pub fn deselect(self: Handle<Self>, app: &mut App, index: usize) {
112        if self.is_selected(app, index) {
113            self.apply(app, None);
114        }
115    }
116
117    /// `IsSelected`.
118    pub fn is_selected(self: Handle<Self>, app: &App, index: usize) -> bool {
119        index < self.row_count(app) && app.get(self).model.is_selected(index)
120    }
121
122    /// `DeselectAll`, whatever the selection mode.
123    pub fn deselect_all(self: Handle<Self>, app: &mut App) {
124        self.apply(app, None);
125    }
126
127    /// `SelectedIndex`: the selected row of the view.
128    pub fn selected_index(self: Handle<Self>, app: &App) -> Option<usize> {
129        app.get(self)
130            .model
131            .selected_index()
132            .filter(|index| *index < self.row_count(app))
133    }
134
135    /// `SelectedItem`: the selected row's index in the source's items.
136    pub fn selected_item(self: Handle<Self>, app: &App) -> Option<usize> {
137        let index = self.selected_index(app)?;
138        let binding = app.get(self).binding.as_ref()?;
139        (binding.item_of_row)(app, index)
140    }
141}
142
143// MARK: The holding table's view of the selection
144
145impl TableViewSelection {
146    /// The table `owner` holds the selection over `source`; a selection set to a different source starts over on its rows, as `SelectionModel::Source` clears. Adopting the same source again keeps the selection. Answers whether the selected row was cleared, which the table defers to its listener until after the frame.
147    pub(crate) fn bind(
148        self: Handle<Self>,
149        app: &mut App,
150        owner: HandleId,
151        can_select: bool,
152        row_count: usize,
153        source: SelectionSource,
154        item_of_row: ItemOfRow,
155    ) -> bool {
156        let source_changed = app
157            .get(self)
158            .source
159            .as_ref()
160            .is_none_or(|bound| bound.id != source.id);
161        if source_changed {
162            // The selection follows its source itself, as WinUI's model does, so rows that change
163            // while no table holds the selection still move it.
164            self.stop_following_source(app);
165            let listener = Listener::handle_method(self, Self::source_heard);
166            (source.add_listener)(app, listener.clone());
167            let selection = app.get_mut(self);
168            selection.source = Some(source);
169            selection.source_listener = Some(listener);
170        }
171        app.get_mut(self).binding = Some(SelectionBinding {
172            owner,
173            can_select,
174            item_of_row,
175        });
176        let cleared = if source_changed {
177            app.get_mut(self).start_over(row_count)
178        } else {
179            false
180        };
181        if !can_select {
182            // `OnSelectionModePropertyChanged`: turning selection off clears it.
183            self.apply(app, None);
184        }
185        cleared
186    }
187
188    /// Stops listening to the source the selection follows, if any.
189    fn stop_following_source(self: Handle<Self>, app: &mut App) {
190        let (source, listener) = {
191            let selection = app.get_mut(self);
192            (selection.source.take(), selection.source_listener.take())
193        };
194        if let (Some(source), Some(listener)) = (source, listener) {
195            (source.remove_listener)(app, &listener);
196        }
197    }
198
199    /// The source the selection follows changed its view: `SelectionNode::OnSourceListChanged`,
200    /// which the model hears whether or not a table is attached.
201    fn source_heard(self: Handle<Self>, app: &mut App) {
202        let (changes, row_count) = {
203            let selection = app.get(self);
204            let Some(source) = &selection.source else {
205                return;
206            };
207            ((source.changes)(app), (source.row_count)(app))
208        };
209        self.source_changed(app, &changes, row_count);
210    }
211
212    /// The table `owner` lets the selection go.
213    pub(crate) fn unbind(self: Handle<Self>, app: &mut App, owner: HandleId) {
214        let selection = app.get_mut(self);
215        if selection
216            .binding
217            .as_ref()
218            .is_some_and(|binding| binding.owner == owner)
219        {
220            selection.binding = None;
221        }
222    }
223
224    /// `SelectionNode::OnSourceListChanged` for each change the source made, in order, notifying once: the item `SelectionChanged` last reported keeps naming the same item as the items move, a row inserted or removed moves the selection with its row and a removed selected row is deselected, a row moved keeps its selection, and a rebuilt view starts over. The view has `row_count` rows after the changes.
225    pub(crate) fn source_changed(
226        self: Handle<Self>,
227        app: &mut App,
228        changes: &[ViewChange],
229        row_count: usize,
230    ) {
231        let mut invalidated = false;
232        for &change in changes {
233            let selection = app.get_mut(self);
234            invalidated |= match change {
235                ViewChange::ItemInserted(index) => {
236                    if let Some(item) = &mut selection.last_raised_item
237                        && *item >= index
238                    {
239                        *item += 1;
240                    }
241                    false
242                }
243                ViewChange::ItemRemoved(index) => {
244                    // The removed item keeps its old index, to be reported as removed.
245                    if let Some(item) = &mut selection.last_raised_item
246                        && *item > index
247                    {
248                        *item -= 1;
249                    }
250                    false
251                }
252                ViewChange::RowInserted(row) => selection.model.on_items_added(row, 1),
253                ViewChange::RowRemoved(row) => selection.model.on_items_removed(row, 1),
254                ViewChange::RowMoved(from, to) => {
255                    // The row's item is the same, so the selection moves with it.
256                    let was_selected = selection.model.is_selected(from);
257                    selection.model.on_items_removed(from, 1);
258                    selection.model.on_items_added(to, 1);
259                    if was_selected {
260                        selection.model.select(to);
261                    }
262                    true
263                }
264                ViewChange::RowReplaced(row) => {
265                    let removed = selection.model.on_items_removed(row, 1);
266                    selection.model.on_items_added(row, 1) | removed
267                }
268                ViewChange::Reset => selection.start_over(row_count),
269            };
270        }
271        debug_assert_eq!(app.get(self).model.item_count(), row_count);
272        // Once, after the last change: a listener reads rows of the view the changes ended with.
273        if invalidated {
274            self.notify_listeners(app);
275        }
276    }
277
278    /// `SelectRowIndexFromInteraction`: a pointer or keyboard gesture selects the row; with `toggle` (Control) a selected row is deselected.
279    pub(crate) fn select_from_interaction(
280        self: Handle<Self>,
281        app: &mut App,
282        index: usize,
283        toggle: bool,
284    ) {
285        if !self.can_select(app) {
286            return;
287        }
288        if toggle && self.is_selected(app, index) {
289            self.apply(app, None);
290        } else {
291            self.apply(app, Some(index));
292        }
293    }
294
295    /// The item `SelectionChanged` should now report as removed and added, if it changed since the last report (`RaiseSelectionChanged`).
296    pub(crate) fn take_change(
297        self: Handle<Self>,
298        app: &mut App,
299    ) -> Option<(Option<usize>, Option<usize>)> {
300        let added = self.selected_item(app);
301        let removed = app.get(self).last_raised_item;
302        if removed == added {
303            return None;
304        }
305        app.get_mut(self).last_raised_item = added;
306        Some((removed, added))
307    }
308
309    /// `SelectionModel::Source`: the selection starts over on `row_count` rows. Answers whether a row was selected, the only change a listener can read: WinUI's model raises `SelectionChanged` whatever it cleared, and `TableView::PushSelectionProperties` republishes `SelectedIndex` and `SelectedItem` only when they differ.
310    fn start_over(&mut self, row_count: usize) -> bool {
311        let cleared = self.model.selected_index().is_some();
312        self.model.set_source(row_count);
313        cleared
314    }
315
316    fn can_select(self: Handle<Self>, app: &App) -> bool {
317        app.get(self)
318            .binding
319            .as_ref()
320            .is_some_and(|binding| binding.can_select)
321    }
322
323    fn row_count(self: Handle<Self>, app: &App) -> usize {
324        app.get(self).model.item_count()
325    }
326
327    /// `ApplySelection`: the single writer.
328    fn apply(self: Handle<Self>, app: &mut App, index: Option<usize>) {
329        let index = index.filter(|index| self.can_select(app) && *index < self.row_count(app));
330        let model = &mut app.get_mut(self).model;
331        let changed = match index {
332            Some(index) => model.select(index),
333            None => model.selected_index().is_some() && model.clear_selection(),
334        };
335        if changed {
336            self.notify_listeners(app);
337        }
338    }
339}
340
341impl ChangeNotifier for TableViewSelection {
342    fn change_notifier_data(&self) -> &ChangeNotifierData {
343        &self.notifier
344    }
345
346    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
347        &mut self.notifier
348    }
349}
350
351impl fmt::Debug for TableViewSelection {
352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353        f.debug_struct("TableViewSelection")
354            .field("selected_index", &self.model.selected_index())
355            .field("bound", &self.binding.is_some())
356            .finish_non_exhaustive()
357    }
358}
359
360// MARK: The table's selection
361
362impl<T: 'static> TableViewState<T> {
363    /// Gives the selection the table's rows and mode, and listens to it.
364    pub(super) fn sync_selection(self: Handle<Self>, app: &mut App) {
365        let id = self.id_of();
366        let selection = self.widget(app).selection.clone();
367        let held = app
368            .get(self)
369            .selection
370            .as_ref()
371            .map(|(held, _)| held.handle());
372        if held != selection.as_ref().map(|selection| selection.handle()) {
373            if let Some((old, listener)) = app.get_mut(self).selection.take() {
374                old.remove_listener(app, &listener);
375                old.unbind(app, id);
376            }
377            if let Some(selection) = &selection {
378                let listener = Listener::new(move |app| self.selection_heard(app));
379                selection.add_listener(app, listener.clone());
380                app.get_mut(self).selection = Some((selection.clone(), listener));
381            }
382        }
383        if let Some(selection) = selection {
384            let can_select = self.widget(app).selection_mode != TableViewSelectionMode::None;
385            let count = self.row_count(app);
386            let item_of_row: selection::ItemOfRow = Rc::new(move |app, row| {
387                if !app.contains(self) {
388                    return None;
389                }
390                self.source_handle(app).view(app).get(row).copied()
391            });
392            let source = SelectionSource::new(&self.widget(app).items_source);
393            // A replaced source clears the selected row while the table builds; its listener hears
394            // of it once the frame is over, as a rebuild of the table during build must not dirty
395            // a widget above it.
396            if selection.bind(app, id, can_select, count, source, item_of_row) {
397                let selection = selection.clone();
398                self.after_frame(app, move |app| {
399                    if app.contains(selection.handle()) {
400                        selection.handle().notify_listeners(app);
401                    }
402                });
403            }
404        }
405    }
406
407    /// `OnSelectionModelSelectionChanged`'s `RaiseSelectionChanged`: one event for the change of the selected item.
408    pub(super) fn selection_heard(self: Handle<Self>, app: &mut App) {
409        if !self.alive(app) {
410            return;
411        }
412        let Some(selection) = self.selection_handle(app) else {
413            return;
414        };
415        let Some((removed, added)) = selection.take_change(app) else {
416            return;
417        };
418        if let Some(changed) = self.widget(app).selection_changed.clone() {
419            let args = TableViewSelectionChangedEventArgs {
420                removed_items: removed.into_iter().collect(),
421                added_items: added.into_iter().collect(),
422            };
423            changed(app, &args);
424        }
425    }
426
427    pub(super) fn can_select_rows(self: Handle<Self>, app: &App) -> bool {
428        self.widget(app).selection.is_some()
429            && self.widget(app).selection_mode != TableViewSelectionMode::None
430    }
431
432    /// `SelectRowIndexFromInteraction`: Control toggles.
433    pub(super) fn select_row_from_interaction(self: Handle<Self>, app: &mut App, index: usize) {
434        let control = HardwareKeyboard::instance(app).is_control_pressed(app);
435        if let Some(selection) = self.selection_handle(app) {
436            selection.select_from_interaction(app, index, control);
437        }
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444    use waft_foundation::AppCell;
445
446    fn bound(app: &mut App, rows: usize, can_select: bool) -> Ref<TableViewSelection> {
447        let source = TableViewSource::from(app, vec![0u8; rows]);
448        bound_to(app, rows, can_select, &source)
449    }
450
451    fn bound_to(
452        app: &mut App,
453        rows: usize,
454        can_select: bool,
455        source: &Ref<TableViewSource<u8>>,
456    ) -> Ref<TableViewSelection> {
457        let selection = TableViewSelection::new(app);
458        let owner = app.create(0u8);
459        selection.bind(
460            app,
461            owner.handle().id(),
462            can_select,
463            rows,
464            SelectionSource::new(source),
465            Rc::new(|_, row| Some(row + 10)),
466        );
467        selection
468    }
469
470    // `TableView::Select` is a no-op before a source exists, while the mode is None, and past the
471    // rows; it never clears an existing selection to signal a refusal.
472    #[test]
473    fn a_select_that_cannot_be_resolved_does_nothing() {
474        let cell = AppCell::new();
475        let mut app = cell.borrow_mut();
476        let unbound = TableViewSelection::new(&mut app);
477        unbound.select(&mut app, 0);
478        assert_eq!(unbound.selected_index(&app), None);
479
480        let selection = bound(&mut app, 3, true);
481        selection.select(&mut app, 1);
482        selection.select(&mut app, 9);
483        assert_eq!(selection.selected_index(&app), Some(1));
484        assert_eq!(selection.selected_item(&app), Some(11));
485
486        let off = bound(&mut app, 3, false);
487        off.select(&mut app, 1);
488        assert_eq!(off.selected_index(&app), None);
489    }
490
491    #[test]
492    fn deselect_clears_only_the_selected_row_and_control_toggles() {
493        let cell = AppCell::new();
494        let mut app = cell.borrow_mut();
495        let selection = bound(&mut app, 3, true);
496        selection.select(&mut app, 2);
497        selection.deselect(&mut app, 1);
498        assert_eq!(selection.selected_index(&app), Some(2));
499        selection.select_from_interaction(&mut app, 2, true);
500        assert_eq!(selection.selected_index(&app), None);
501        selection.select_from_interaction(&mut app, 0, false);
502        selection.select_from_interaction(&mut app, 1, false);
503        assert_eq!(selection.selected_index(&app), Some(1));
504    }
505
506    #[test]
507    fn a_change_is_reported_once_from_the_item_reported_last() {
508        let cell = AppCell::new();
509        let mut app = cell.borrow_mut();
510        let selection = bound(&mut app, 3, true);
511        selection.select(&mut app, 0);
512        assert_eq!(selection.take_change(&mut app), Some((None, Some(10))));
513        assert_eq!(selection.take_change(&mut app), None);
514        // A replaced source clears the row and the clear is reported from the item last raised.
515        let owner = app.create(0u8);
516        let other_source = TableViewSource::from(&mut app, vec![0u8; 3]);
517        assert!(selection.bind(
518            &mut app,
519            owner.handle().id(),
520            true,
521            3,
522            SelectionSource::new(&other_source),
523            Rc::new(|_, row| Some(row)),
524        ));
525        assert_eq!(selection.take_change(&mut app), Some((Some(10), None)));
526    }
527
528    /// A table adopting the same source again changes nothing: the selected row stays and no
529    /// listener hears of it.
530    #[test]
531    fn rebinding_the_same_source_keeps_the_selection() {
532        let cell = AppCell::new();
533        let mut app = cell.borrow_mut();
534        let source = TableViewSource::from(&mut app, vec![0u8; 3]);
535        let selection = bound_to(&mut app, 3, true, &source);
536        selection.select(&mut app, 1);
537        assert_eq!(selection.selected_index(&app), Some(1));
538
539        let heard = Rc::new(std::cell::Cell::new(0));
540        let heard_here = Rc::clone(&heard);
541        selection.add_listener(
542            &mut app,
543            Listener::new(move |_app| heard_here.set(heard_here.get() + 1)),
544        );
545
546        let owner = app.create(0u8);
547        let cleared = selection.bind(
548            &mut app,
549            owner.handle().id(),
550            true,
551            3,
552            SelectionSource::new(&source),
553            Rc::new(|_, row| Some(row)),
554        );
555        assert!(!cleared);
556        assert_eq!(selection.selected_index(&app), Some(1));
557        assert_eq!(heard.get(), 0);
558    }
559
560    /// The selection follows its source with no table holding it, as WinUI's model does: a row
561    /// inserted above moves the selected row down, and removing the selected row clears it.
562    #[test]
563    fn the_selection_follows_its_source_with_no_table_holding_it() {
564        let cell = AppCell::new();
565        let mut app = cell.borrow_mut();
566        let source = TableViewSource::from(&mut app, vec![10u8, 20, 30, 40]);
567        let owner = app.create(0u8);
568        let selection = TableViewSelection::new(&mut app);
569        let rows_of = source.clone();
570        selection.bind(
571            &mut app,
572            owner.handle().id(),
573            true,
574            4,
575            SelectionSource::new(&source),
576            Rc::new(move |app, row| rows_of.view(app).get(row).copied()),
577        );
578        selection.select(&mut app, 2);
579        assert_eq!(selection.selected_index(&app), Some(2));
580
581        // The table goes away; the source inserts a row above the selected one.
582        selection.unbind(&mut app, owner.handle().id());
583        source.insert(&mut app, 0, 5);
584        assert_eq!(selection.selected_index(&app), Some(3));
585
586        // Rows leave from the end down to the selected row, which clears it.
587        source.remove(&mut app, 4);
588        source.remove(&mut app, 3);
589        assert_eq!(selection.selected_index(&app), None);
590    }
591
592    // A row the source moved keeps its selection; one moved across it shifts it.
593    #[test]
594    fn a_moved_row_keeps_its_selection() {
595        let cell = AppCell::new();
596        let mut app = cell.borrow_mut();
597        let selection = bound(&mut app, 3, true);
598        selection.select(&mut app, 2);
599        selection.source_changed(&mut app, &[ViewChange::RowMoved(2, 0)], 3);
600        assert_eq!(selection.selected_index(&app), Some(0));
601        selection.source_changed(&mut app, &[ViewChange::RowMoved(2, 0)], 3);
602        assert_eq!(selection.selected_index(&app), Some(1));
603    }
604}