Skip to main content

waft_winui/controls/items_view/
selection.rs

1//! `ItemsView`'s selection and current item, held where the application reaches them: `Select`, `Deselect`, `IsSelected`, `SelectAll`, `DeselectAll`, `InvertSelection`, `SelectedItems` and `CurrentItemIndex` of `ItemsView.idl`, over its private `SelectionModel` and `m_currentElementSelectionModel`.
2//!
3//! Listeners hear every change of the selection or of the current item; each `ItemContainer` listens for its own index. A later editor who changes the model here without notifying leaves containers showing the old selection.
4
5use super::selection_model::SelectionModel;
6use super::selector::{ItemsViewSelectionMode, Selector};
7use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, Ref};
8
9/// What an `ItemsView` shows and what of it is selected: WinUI's `ItemsSource` and the `SelectionModel` and current-element model that `ItemsView` keeps over it, as one object the application holds.
10///
11/// The application makes one with [`ItemsViewSource::new`], giving the number of items, hands it to the `ItemsView`, and disposes it after the view. [`set_items`](Self::set_items) is assigning a new `ItemsSource`: `SelectionModel::Source(value)` clears the selection and the anchor and raises `SelectionChanged` (`controls/dev/Repeater/SelectionModel.cpp`, 44), and `ItemsView` does it when it is given an `ItemsSource` (`ItemsView.cpp`, `OnItemsSourceChanged`, or `OnItemsRepeaterItemsSourceChanged` once its repeater exists). A selection taken after that, before the view is built, is kept, as WinUI's is before `Loaded`; an index past the items is ignored, as `SelectionNode::Select` ignores it, and `SelectionChanged` raised all the same, as `SelectionModel::SelectImpl` raises it. Items added or removed in place (`SelectionNode::OnSourceListChanged`) are not ported: the application gives the new items with `set_items`.
12pub struct ItemsViewSource {
13    notifier: ChangeNotifierData,
14    model: SelectionModel,
15    selector: Selector,
16    /// `CurrentItemIndex`: the item that has, or last had, the focus.
17    current_item_index: Option<usize>,
18    /// Counts the selection's changes, which the view raises `SelectionChanged` for, apart from the current item's.
19    revision: u64,
20}
21
22impl ItemsViewSource {
23    /// Creates a source of `item_count` items with nothing selected, for `ItemsView`'s default `Single` mode.
24    pub fn new(app: &mut App, item_count: usize) -> Ref<Self> {
25        let mut model = SelectionModel::default();
26        model.set_source(item_count);
27        let (selector, _) = Selector::for_mode(ItemsViewSelectionMode::Single, &mut model);
28        app.create(Self {
29            notifier: ChangeNotifierData::new(),
30            model,
31            selector,
32            current_item_index: None,
33            revision: 0,
34        })
35    }
36
37    /// Releases the listeners; the selection is not used after.
38    pub fn dispose(self: Handle<Self>, app: &mut App) {
39        ChangeNotifierData::dispose(app, self);
40    }
41
42    /// `IsSelected`.
43    pub fn is_selected(self: Handle<Self>, app: &App, index: usize) -> bool {
44        app.get(self).model.is_selected(index)
45    }
46
47    /// The selected indices in ascending order: `SelectedItems` as positions.
48    pub fn selected_indices(self: Handle<Self>, app: &App) -> Vec<usize> {
49        app.get(self).model.selected_indices().collect()
50    }
51
52    /// `SelectedItem` as a position: the first selected index.
53    pub fn selected_index(self: Handle<Self>, app: &App) -> Option<usize> {
54        app.get(self).model.selected_index()
55    }
56
57    /// `CurrentItemIndex`.
58    pub fn current_item_index(self: Handle<Self>, app: &App) -> Option<usize> {
59        app.get(self).current_item_index
60    }
61
62    /// `Select`.
63    pub fn select(self: Handle<Self>, app: &mut App, index: usize) {
64        self.change(app, |model| model.select(index));
65    }
66
67    /// `Deselect`.
68    pub fn deselect(self: Handle<Self>, app: &mut App, index: usize) {
69        self.change(app, |model| model.deselect(index));
70    }
71
72    /// `SelectAll` (`SelectAllFlat`): every item, whatever the mode, as WinUI's model does.
73    pub fn select_all(self: Handle<Self>, app: &mut App) {
74        self.change(app, SelectionModel::select_all);
75    }
76
77    /// `DeselectAll`.
78    pub fn deselect_all(self: Handle<Self>, app: &mut App) {
79        self.change(app, SelectionModel::clear_selection);
80    }
81
82    /// `InvertSelection`: the selected items become unselected and the others selected.
83    pub fn invert_selection(self: Handle<Self>, app: &mut App) {
84        self.change(app, |model| {
85            let selected: Vec<usize> = model.selected_indices().collect();
86            let mut index_end = model.item_count() as isize - 1;
87            for index in selected.into_iter().rev() {
88                if (index as isize) < index_end {
89                    model.select_range(index + 1, index_end as usize);
90                }
91                model.deselect_at(index);
92                index_end = index as isize - 1;
93            }
94            if index_end >= 0 {
95                model.select_range(0, index_end as usize);
96            }
97            true
98        });
99    }
100
101    pub(crate) fn selector(self: Handle<Self>, app: &App) -> Selector {
102        app.get(self).selector
103    }
104
105    /// `ItemsView::OnSelectionModeChanged` and `UpdateSelector`.
106    pub(crate) fn set_selection_mode(
107        self: Handle<Self>,
108        app: &mut App,
109        mode: ItemsViewSelectionMode,
110    ) {
111        let mut selector = Selector::Null;
112        self.change(app, |model| {
113            let (made, changed) = Selector::for_mode(mode, model);
114            selector = made;
115            changed
116        });
117        app.get_mut(self).selector = selector;
118    }
119
120    /// The number of items: `ItemsSource`'s count.
121    pub fn item_count(self: Handle<Self>, app: &App) -> usize {
122        app.get(self).model.item_count()
123    }
124
125    /// Assigns new items: `ItemsView.ItemsSource` set, which sets the selection model's `Source`. The selection and the anchor are cleared and `SelectionChanged` raised once (`SelectionModel.cpp`, 44).
126    pub fn set_items(self: Handle<Self>, app: &mut App, count: usize) {
127        self.change(app, |model| model.set_source(count));
128    }
129
130    /// `ItemsView::SetCurrentElementIndex`.
131    pub(crate) fn set_current_item_index(self: Handle<Self>, app: &mut App, index: Option<usize>) {
132        if app.get(self).current_item_index != index {
133            app.get_mut(self).current_item_index = index;
134            self.notify_listeners(app);
135        }
136    }
137
138    /// `OnInteractedAction` of the selector for the view's mode.
139    pub(crate) fn interacted(
140        self: Handle<Self>,
141        app: &mut App,
142        index: usize,
143        ctrl: bool,
144        shift: bool,
145    ) {
146        let selector = self.selector(app);
147        self.change(app, |model| {
148            selector.on_interacted_action(model, index, ctrl, shift)
149        });
150    }
151
152    /// `OnFocusedAction` of the selector for the view's mode.
153    pub(crate) fn focused(
154        self: Handle<Self>,
155        app: &mut App,
156        index: usize,
157        ctrl: bool,
158        shift: bool,
159    ) {
160        let selector = self.selector(app);
161        self.change(app, |model| {
162            selector.on_focused_action(model, index, ctrl, shift)
163        });
164    }
165
166    /// `SelectorBase::DeselectWithAnchorPreservation`.
167    pub(crate) fn deselect_with_anchor_preservation(
168        self: Handle<Self>,
169        app: &mut App,
170        index: usize,
171    ) {
172        self.change(app, |model| {
173            Selector::deselect_with_anchor_preservation(model, index)
174        });
175    }
176
177    /// How many times the selection has changed.
178    pub(crate) fn revision(self: Handle<Self>, app: &App) -> u64 {
179        app.get(self).revision
180    }
181
182    /// Tells the containers that something they show besides the selection changed: which item Tab stops at.
183    pub(crate) fn notify_items(self: Handle<Self>, app: &mut App) {
184        self.notify_listeners(app);
185    }
186
187    /// Runs `change` on the model and notifies when it says the selection changed.
188    fn change(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut SelectionModel) -> bool) {
189        if change(&mut app.get_mut(self).model) {
190            app.get_mut(self).revision += 1;
191            self.notify_listeners(app);
192        }
193    }
194}
195
196impl ChangeNotifier for ItemsViewSource {
197    fn change_notifier_data(&self) -> &ChangeNotifierData {
198        &self.notifier
199    }
200
201    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
202        &mut self.notifier
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use waft_foundation::AppCell;
210
211    // `ItemsView.cpp`, `OnItemsSourceChanged`: a selection taken once `ItemsSource` is set is kept,
212    // before the view is shown.
213    #[test]
214    fn a_selection_taken_after_the_items_are_given_is_kept() {
215        let cell = AppCell::new();
216        let mut app = cell.borrow_mut();
217        let source = ItemsViewSource::new(&mut app, 5);
218        source.select(&mut app, 3);
219        assert_eq!(source.selected_indices(&app), [3]);
220        assert_eq!(source.item_count(&app), 5);
221    }
222
223    // `SelectionModel::Source(value)` clears the selection and raises `SelectionChanged`, once.
224    #[test]
225    fn giving_the_items_clears_the_selection_and_notifies_once() {
226        let cell = AppCell::new();
227        let mut app = cell.borrow_mut();
228        let source = ItemsViewSource::new(&mut app, 5);
229        source.select(&mut app, 3);
230        let revision = source.revision(&app);
231
232        source.set_items(&mut app, 7);
233        assert_eq!(source.selected_indices(&app), Vec::<usize>::new());
234        assert_eq!(source.item_count(&app), 7);
235        assert_eq!(source.revision(&app), revision + 1);
236    }
237
238    // `SelectionNode::Select` refuses an index past the items, and `SelectionModel::SelectImpl`
239    // raises `SelectionChanged` all the same.
240    #[test]
241    fn a_select_past_the_items_is_refused_and_raised() {
242        let cell = AppCell::new();
243        let mut app = cell.borrow_mut();
244        let source = ItemsViewSource::new(&mut app, 5);
245        let revision = source.revision(&app);
246
247        source.select(&mut app, 5);
248        assert_eq!(source.selected_indices(&app), Vec::<usize>::new());
249        assert_eq!(source.revision(&app), revision + 1, "SelectionChanged");
250    }
251}