Skip to main content

waft_winui/controls/items_view/
selector.rs

1//! `SelectorBase`, `NullSelector`, `SingleSelector`, `MultipleSelector` and `ExtendedSelector` (`controls/dev/ItemsView`): what a click, Space or Enter on an item (`OnInteractedAction`) and the keyboard moving the focus to it (`OnFocusedAction`) do to the selection, with Control and Shift.
2//!
3//! Each rule is the C++'s line for line; the selection model answers whether anything changed, and every rule answers the same, so a later editor who drops an answer loses a notification.
4
5use super::selection_model::SelectionModel;
6
7/// `ItemsViewSelectionMode`.
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
9pub enum ItemsViewSelectionMode {
10    /// No item can be selected.
11    None,
12    /// One item at a time; the default (`ItemsView::s_defaultSelectionMode`).
13    #[default]
14    Single,
15    /// Each click toggles an item; Shift extends from the anchor.
16    Multiple,
17    /// A click selects one item; Control toggles and Shift extends.
18    Extended,
19}
20
21/// The selector `ItemsView::UpdateSelector` makes for a selection mode.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub(crate) enum Selector {
24    Null,
25    /// `SingleSelector`, with `m_followFocus`.
26    Single {
27        follow_focus: bool,
28    },
29    Multiple,
30    Extended,
31}
32
33impl Selector {
34    /// `ItemsView::UpdateSelector`: the selector for `mode`, after setting the model's single-select mode and, for `None`, clearing it.
35    pub(crate) fn for_mode(
36        mode: ItemsViewSelectionMode,
37        model: &mut SelectionModel,
38    ) -> (Selector, bool) {
39        let mut changed = model.set_single_select(false);
40        let selector = match mode {
41            ItemsViewSelectionMode::None => {
42                changed |= model.clear_selection();
43                Selector::Null
44            }
45            ItemsViewSelectionMode::Single => {
46                changed |= model.set_single_select(true);
47                Selector::Single { follow_focus: true }
48            }
49            ItemsViewSelectionMode::Multiple => Selector::Multiple,
50            ItemsViewSelectionMode::Extended => Selector::Extended,
51        };
52        (selector, changed)
53    }
54
55    /// `OnInteractedAction`: a click, Space or Enter on `index`.
56    pub(crate) fn on_interacted_action(
57        self,
58        model: &mut SelectionModel,
59        index: usize,
60        ctrl: bool,
61        shift: bool,
62    ) -> bool {
63        match self {
64            Selector::Null => false,
65            Selector::Single { .. } => {
66                let mut changed = model.set_single_select(true);
67                changed |= if !ctrl || !model.is_selected(index) {
68                    model.select_at(index)
69                } else {
70                    model.deselect_at(index)
71                };
72                changed
73            }
74            Selector::Multiple => {
75                if shift {
76                    match model.anchor_index() {
77                        Some(anchor) => {
78                            let anchor_selected = model.is_selected(anchor);
79                            if anchor_selected == model.is_selected(index) {
80                                false
81                            } else if anchor_selected {
82                                model.select_range_from_anchor_to(index)
83                            } else {
84                                model.deselect_range_from_anchor_to(index)
85                            }
86                        }
87                        None => false,
88                    }
89                } else if model.is_selected(index) {
90                    model.deselect_at(index)
91                } else {
92                    model.select_at(index)
93                }
94            }
95            Selector::Extended => {
96                if shift {
97                    extend_from_anchor(model, index)
98                } else if ctrl {
99                    if model.is_selected(index) {
100                        model.deselect_at(index)
101                    } else {
102                        model.select_at(index)
103                    }
104                } else if !model.is_selected(index) {
105                    // Only clear selection if interacting with a different item.
106                    model.clear_selection();
107                    model.select_at(index);
108                    true
109                } else {
110                    false
111                }
112            }
113        }
114    }
115
116    /// `OnFocusedAction`: the keyboard moved the focus to `index`.
117    pub(crate) fn on_focused_action(
118        self,
119        model: &mut SelectionModel,
120        index: usize,
121        ctrl: bool,
122        shift: bool,
123    ) -> bool {
124        match self {
125            Selector::Null => false,
126            Selector::Single { follow_focus } => {
127                let mut changed = model.set_single_select(true);
128                if !ctrl && follow_focus {
129                    changed |= model.select_at(index);
130                }
131                changed
132            }
133            Selector::Multiple => {
134                if !shift {
135                    return false;
136                }
137                match model.anchor_index() {
138                    Some(anchor) if model.is_selected(anchor) => {
139                        model.select_range_from_anchor_to(index)
140                    }
141                    Some(_) => model.deselect_range_from_anchor_to(index),
142                    None => false,
143                }
144            }
145            Selector::Extended => {
146                if shift && ctrl {
147                    model.anchor_index().is_some() && model.select_range_from_anchor_to(index)
148                } else if shift {
149                    extend_from_anchor(model, index)
150                } else if !ctrl {
151                    model.clear_selection();
152                    model.select_at(index);
153                    true
154                } else {
155                    false
156                }
157            }
158        }
159    }
160
161    /// `SelectorBase::DeselectWithAnchorPreservation`.
162    pub(crate) fn deselect_with_anchor_preservation(
163        model: &mut SelectionModel,
164        index: usize,
165    ) -> bool {
166        let anchor = model.anchor_index();
167        let changed = model.deselect(index);
168        if anchor.is_some() {
169            model.set_anchor_index(anchor);
170        }
171        changed
172    }
173}
174
175/// Extended mode's Shift: the selection becomes the range from the anchor to `index`.
176fn extend_from_anchor(model: &mut SelectionModel, index: usize) -> bool {
177    match model.anchor_index() {
178        Some(anchor) => {
179            model.clear_selection();
180            model.set_anchor_index(Some(anchor));
181            model.select_range_from_anchor_to(index);
182            true
183        }
184        None => false,
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    fn with(mode: ItemsViewSelectionMode, count: usize) -> (Selector, SelectionModel) {
193        let mut model = SelectionModel::default();
194        model.set_source(count);
195        let (selector, _) = Selector::for_mode(mode, &mut model);
196        (selector, model)
197    }
198
199    fn selected(model: &SelectionModel) -> Vec<usize> {
200        model.selected_indices().collect()
201    }
202
203    #[test]
204    fn single_click_selects_and_control_click_deselects() {
205        let (selector, mut model) = with(ItemsViewSelectionMode::Single, 5);
206        selector.on_interacted_action(&mut model, 2, false, false);
207        selector.on_interacted_action(&mut model, 4, false, false);
208        assert_eq!(selected(&model), [4]);
209        selector.on_interacted_action(&mut model, 4, true, false);
210        assert_eq!(selected(&model), Vec::<usize>::new());
211        selector.on_interacted_action(&mut model, 1, true, false);
212        assert_eq!(
213            selected(&model),
214            [1],
215            "control on an unselected item selects it"
216        );
217    }
218
219    #[test]
220    fn single_selection_follows_the_focus_unless_control_is_held() {
221        let (selector, mut model) = with(ItemsViewSelectionMode::Single, 5);
222        selector.on_focused_action(&mut model, 3, false, false);
223        assert_eq!(selected(&model), [3]);
224        selector.on_focused_action(&mut model, 4, true, false);
225        assert_eq!(selected(&model), [3]);
226    }
227
228    #[test]
229    fn multiple_click_toggles_and_shift_follows_the_anchors_state() {
230        let (selector, mut model) = with(ItemsViewSelectionMode::Multiple, 8);
231        selector.on_interacted_action(&mut model, 1, false, false);
232        selector.on_interacted_action(&mut model, 3, false, false);
233        assert_eq!(selected(&model), [1, 3]);
234        // The anchor, 3, is selected: Shift selects from it to 6.
235        selector.on_interacted_action(&mut model, 6, false, true);
236        assert_eq!(selected(&model), [1, 3, 4, 5, 6]);
237        // Toggling 5 off makes it the anchor; Shift to 3 deselects 3 to 5.
238        selector.on_interacted_action(&mut model, 5, false, false);
239        selector.on_interacted_action(&mut model, 3, false, true);
240        assert_eq!(selected(&model), [1, 6]);
241        // Shift onto an item in the anchor's state changes nothing.
242        selector.on_interacted_action(&mut model, 2, false, true);
243        assert_eq!(selected(&model), [1, 6]);
244    }
245
246    #[test]
247    fn multiple_focus_moves_select_only_with_shift() {
248        let (selector, mut model) = with(ItemsViewSelectionMode::Multiple, 8);
249        selector.on_interacted_action(&mut model, 2, false, false);
250        selector.on_focused_action(&mut model, 3, false, false);
251        assert_eq!(selected(&model), [2]);
252        selector.on_focused_action(&mut model, 4, false, true);
253        assert_eq!(selected(&model), [2, 3, 4]);
254    }
255
256    #[test]
257    fn extended_click_control_and_shift() {
258        let (selector, mut model) = with(ItemsViewSelectionMode::Extended, 10);
259        selector.on_interacted_action(&mut model, 2, false, false);
260        selector.on_interacted_action(&mut model, 5, true, false);
261        assert_eq!(selected(&model), [2, 5]);
262        // Shift: the range from the anchor, 5, replaces the selection.
263        selector.on_interacted_action(&mut model, 7, false, true);
264        assert_eq!(selected(&model), [5, 6, 7]);
265        // A plain click on a selected item keeps the selection.
266        selector.on_interacted_action(&mut model, 6, false, false);
267        assert_eq!(selected(&model), [5, 6, 7]);
268        // On another item it selects only that one.
269        selector.on_interacted_action(&mut model, 0, false, false);
270        assert_eq!(selected(&model), [0]);
271    }
272
273    #[test]
274    fn extended_focus_moves() {
275        let (selector, mut model) = with(ItemsViewSelectionMode::Extended, 10);
276        selector.on_focused_action(&mut model, 2, false, false);
277        assert_eq!(selected(&model), [2]);
278        selector.on_focused_action(&mut model, 4, false, true);
279        assert_eq!(selected(&model), [2, 3, 4]);
280        // Control alone moves the focus and leaves the selection.
281        selector.on_focused_action(&mut model, 6, true, false);
282        assert_eq!(selected(&model), [2, 3, 4]);
283        // Control and Shift add the range from the anchor without clearing.
284        model.set_anchor_index(Some(8));
285        selector.on_focused_action(&mut model, 9, true, true);
286        assert_eq!(selected(&model), [2, 3, 4, 8, 9]);
287    }
288
289    #[test]
290    fn none_clears_and_ignores() {
291        let (_, mut model) = with(ItemsViewSelectionMode::Extended, 4);
292        model.select_all();
293        let (selector, _) = Selector::for_mode(ItemsViewSelectionMode::None, &mut model);
294        assert_eq!(selected(&model), Vec::<usize>::new());
295        assert!(!selector.on_interacted_action(&mut model, 1, false, false));
296    }
297
298    #[test]
299    fn deselecting_with_anchor_preservation_keeps_the_anchor() {
300        let (_, mut model) = with(ItemsViewSelectionMode::Extended, 6);
301        model.select_at(1);
302        model.select_range_from_anchor_to(4);
303        Selector::deselect_with_anchor_preservation(&mut model, 3);
304        assert_eq!(selected(&model), [1, 2, 4]);
305        assert_eq!(model.anchor_index(), Some(1));
306    }
307}