Skip to main content

pushrod/cache/
focus.rs

1// Focus
2// Pushrod
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Keyboard focus for the [`WidgetCache`]: which `Widget` receives key presses, how Tab and the
17//! arrow keys move it, and how Return and Escape activate the default and cancel `Widget`s.
18//!
19//! **Focus groups.** `Widget`s that are [`Behavior::EXCLUSIVE`] and share a parent form one group
20//! (a radio group).  Tab and Shift-Tab visit each group once, at its checked member (or its
21//! first member if none is checked); the arrow keys move within the group.  Every other
22//! focusable `Widget` is a group of one.  Order is by `WidgetId`, which is the order the form was
23//! designed in.
24
25use super::WidgetCache;
26use crate::event::{EngineEvent, Event, EventCtx, EventPhase, Propagation};
27use crate::input::{Key, Modifiers};
28use crate::widget::{Behavior, ROOT_WIDGET_ID, VisualState, WidgetId};
29
30/// The modifier keys that stop a Tab or arrow key from moving focus (Shift is allowed).
31const COMMAND_MODS: Modifiers = Modifiers::CTRL.union(Modifiers::ALT).union(Modifiers::GUI);
32
33impl WidgetCache {
34    /// Returns the `Widget` that has the keyboard focus.
35    ///
36    /// # Returns
37    ///
38    /// The ID of the focused `Widget`, or `None` if nothing has focus.
39    pub fn focused(&self) -> Option<WidgetId> {
40        self.focused_widget_id
41    }
42
43    /// Gives the keyboard focus to a `Widget`.
44    ///
45    /// The `Widget` that had focus receives [`Event::FocusLost`], then the new one receives
46    /// [`Event::FocusGained`] (both are also queued for the application), the two `Widget`s'
47    /// [`VisualState::FOCUSED`] flags are updated, and [`EngineEvent::FocusChanged`] is queued.
48    /// Nothing happens if the `Widget` already has focus.
49    ///
50    /// # Arguments
51    ///
52    /// * `id` - The `Widget` to focus.
53    ///
54    /// # Returns
55    ///
56    /// `true` if the `Widget` has focus afterward; `false` if it does not exist or cannot take
57    /// focus (not [`Behavior::FOCUSABLE`], disabled, or hidden, itself or through a parent).
58    pub fn set_focus(&mut self, id: WidgetId) -> bool {
59        if !self.can_focus(id) {
60            return false;
61        }
62
63        self.move_focus(Some(id));
64
65        true
66    }
67
68    /// Removes the keyboard focus, so no `Widget` has it.
69    pub fn clear_focus(&mut self) {
70        self.move_focus(None);
71    }
72
73    /// Returns whether a `Widget` can take focus now.
74    fn can_focus(&self, id: WidgetId) -> bool {
75        self.get(id).is_some_and(|w| w.is_focusable()) && !self.hidden_above(id)
76    }
77
78    /// Returns whether any ancestor of a `Widget` is hidden.
79    fn hidden_above(&self, id: WidgetId) -> bool {
80        self.ancestors(id)
81            .iter()
82            .any(|&a| self.get(a).is_some_and(|w| w.is_hidden()))
83    }
84
85    /// Returns whether the `Widget` is a focusable member of a radio group.
86    fn is_group_member(&self, id: WidgetId) -> bool {
87        self.can_focus(id)
88            && self
89                .get(id)
90                .is_some_and(|w| w.behavior().contains(Behavior::EXCLUSIVE))
91    }
92
93    /// Moves focus, delivering the focus events and updating the visual states.
94    fn move_focus(&mut self, new: Option<WidgetId>) {
95        let old = self.focused_widget_id;
96
97        if old == new {
98            return;
99        }
100
101        self.focused_widget_id = new;
102
103        if let Some(id) = old {
104            self.set_focused_state(id, false);
105            self.notify(id, Event::FocusLost { id });
106        }
107
108        if let Some(id) = new {
109            self.set_focused_state(id, true);
110            self.notify(id, Event::FocusGained { id });
111            // A scrolling container above brings the focused `Widget` into view.
112            self.notify_ancestors(id);
113        }
114
115        self.text_input_wanted = new
116            .and_then(|id| self.get(id))
117            .is_some_and(|w| w.accepts_text_input());
118
119        self.queue_event(Event::Engine(EngineEvent::FocusChanged { old, new }));
120    }
121
122    /// Sets or clears [`VisualState::FOCUSED`] on a `Widget`.
123    fn set_focused_state(&mut self, id: WidgetId, focused: bool) {
124        if let Some(widget) = self.get_mut(id) {
125            let mut state = widget.state();
126
127            state.set(VisualState::FOCUSED, focused);
128            widget.set_state(state);
129        }
130    }
131
132    /// Delivers a focus event to its `Widget`, then queues it, and what the `Widget` generated,
133    /// for the application.
134    fn notify(&mut self, id: WidgetId, event: Event) {
135        let mut ctx = EventCtx::default();
136
137        self.send(id, &event, EventPhase::Target, &mut ctx);
138        self.queue_event(event);
139
140        for generated in self.finish(ctx) {
141            self.queue_event(generated);
142        }
143    }
144
145    /// Returns whether the engine should ask the OS for text input.
146    ///
147    /// # Returns
148    ///
149    /// `true` while the focused `Widget` accepts typed text.
150    pub fn text_input_wanted(&self) -> bool {
151        self.text_input_wanted
152    }
153
154    /// Focuses the nearest focusable `Widget` at or above the one that was clicked.
155    ///
156    /// For each `Widget` that cannot take focus, its container's layout is asked first through
157    /// [`Layout::focus_target`](crate::layout::Layout::focus_target), so a click on a form
158    /// label focuses its field.  A click on something that cannot take focus leaves the focus
159    /// where it is.
160    ///
161    /// # Arguments
162    ///
163    /// * `target` - The `Widget` that was clicked.
164    pub(super) fn focus_for_click(&mut self, target: WidgetId) {
165        let mut candidates = vec![target];
166
167        candidates.extend(self.ancestors(target));
168
169        let found = candidates.iter().find_map(|&id| {
170            if self.can_focus(id) {
171                Some(id)
172            } else {
173                self.layout_focus_target(id)
174            }
175        });
176
177        if let Some(id) = found {
178            self.move_focus(Some(id));
179        }
180    }
181
182    /// Asks a `Widget`'s container's layout which `Widget` a click on it should focus.
183    ///
184    /// # Arguments
185    ///
186    /// * `id` - The clicked `Widget`, or one of its ancestors.
187    ///
188    /// # Returns
189    ///
190    /// The `Widget` the layout names, if it can take focus now; `None` for the root, a container
191    /// without a layout, or a layout with no answer.
192    fn layout_focus_target(&self, id: WidgetId) -> Option<WidgetId> {
193        if id == ROOT_WIDGET_ID {
194            return None;
195        }
196
197        let parent = self.get(id)?.get_parent();
198
199        self.get(parent)?
200            .core()
201            .layout_ref()?
202            .focus_target(id)
203            .filter(|&target| self.can_focus(target))
204    }
205
206    /// Returns the `Widget` that receives keys.
207    ///
208    /// # Returns
209    ///
210    /// The focused `Widget`, or the root with no focus.
211    pub(super) fn key_target(&self) -> WidgetId {
212        self.focused_widget_id
213            .filter(|&id| self.can_focus(id))
214            .unwrap_or(ROOT_WIDGET_ID)
215    }
216
217    /// The members of the radio group a `Widget` belongs to, in ID order.
218    fn group_of(&self, id: WidgetId) -> Vec<WidgetId> {
219        let Some(widget) = self.get(id) else {
220            return Vec::new();
221        };
222
223        if !self.is_group_member(id) {
224            return vec![id];
225        }
226
227        self.children_of(widget.get_parent())
228            .iter()
229            .copied()
230            .filter(|&c| self.is_group_member(c))
231            .collect()
232    }
233
234    /// The one `Widget` Tab visits for a group: its checked member, or its first.
235    fn group_stop(&self, id: WidgetId) -> WidgetId {
236        let group = self.group_of(id);
237
238        group
239            .iter()
240            .copied()
241            .find(|&m| {
242                self.get(m)
243                    .is_some_and(|w| w.state().contains(VisualState::CHECKED))
244            })
245            .or_else(|| group.first().copied())
246            .unwrap_or(id)
247    }
248
249    /// Every `Widget` Tab visits, in ID order.
250    fn tab_stops(&self) -> Vec<WidgetId> {
251        (0..self.cache.len() as WidgetId)
252            .filter(|&id| self.can_focus(id) && self.group_stop(id) == id)
253            .collect()
254    }
255
256    /// Moves focus to the next (or previous) group, wrapping at the ends.
257    ///
258    /// # Arguments
259    ///
260    /// * `backward` - `true` for Shift-Tab.
261    ///
262    /// # Returns
263    ///
264    /// `true` if a `Widget` has focus afterward.
265    pub fn focus_next(&mut self, backward: bool) -> bool {
266        let stops = self.tab_stops();
267
268        if stops.is_empty() {
269            return false;
270        }
271
272        let current = self
273            .focused_widget_id
274            .filter(|&id| self.can_focus(id))
275            .map(|id| self.group_stop(id))
276            .and_then(|stop| stops.iter().position(|&s| s == stop));
277        let last = stops.len() - 1;
278        let index = match (current, backward) {
279            (None, false) => 0,
280            (None, true) => last,
281            (Some(i), false) => (i + 1) % stops.len(),
282            (Some(0), true) => last,
283            (Some(i), true) => i - 1,
284        };
285
286        self.move_focus(Some(stops[index]));
287
288        true
289    }
290
291    /// Moves focus within the focused `Widget`'s radio group, wrapping at the ends.
292    ///
293    /// # Arguments
294    ///
295    /// * `forward` - `true` for the next member (Right, Down), `false` for the previous.
296    ///
297    /// # Returns
298    ///
299    /// `true` if focus moved; `false` if the focused `Widget` is not in a group of two or more.
300    pub fn focus_in_group(&mut self, forward: bool) -> bool {
301        let Some(current) = self.focused_widget_id else {
302            return false;
303        };
304        let group = self.group_of(current);
305        let Some(index) = group.iter().position(|&m| m == current) else {
306            return false;
307        };
308
309        if group.len() < 2 {
310            return false;
311        }
312
313        let next = if forward {
314            (index + 1) % group.len()
315        } else {
316            (index + group.len() - 1) % group.len()
317        };
318
319        self.move_focus(Some(group[next]));
320
321        true
322    }
323
324    /// Moves focus within the radio group and activates the member that received it, so an
325    /// arrow key selects as well as moves (a radio group's checked member follows the focus).
326    ///
327    /// # Arguments
328    ///
329    /// * `forward` - `true` for the next member, `false` for the previous.
330    /// * `ctx` - The context collecting generated events.
331    fn select_in_group(&mut self, forward: bool, ctx: &mut EventCtx) {
332        if self.focus_in_group(forward)
333            && let Some(id) = self.focused_widget_id
334        {
335            self.send(id, &Event::Activated { id }, EventPhase::Target, ctx);
336        }
337    }
338
339    /// Returns the checked member of the radio group under `parent`.
340    ///
341    /// A group is the [`Behavior::EXCLUSIVE`] children of one parent.
342    ///
343    /// # Arguments
344    ///
345    /// * `parent` - The `Widget` the group's members are children of.
346    ///
347    /// # Returns
348    ///
349    /// The ID of the checked member, or `None` if none is checked.
350    pub fn checked_in_group(&self, parent: WidgetId) -> Option<WidgetId> {
351        self.children_of(parent).iter().copied().find(|&c| {
352            self.get(c).is_some_and(|w| {
353                w.behavior().contains(Behavior::EXCLUSIVE)
354                    && w.state().contains(VisualState::CHECKED)
355            })
356        })
357    }
358
359    /// Keeps radio groups to one checked member.  For each `Toggled { checked: true }` from an
360    /// [`Behavior::EXCLUSIVE`] `Widget`, every other checked exclusive sibling is cleared and a
361    /// `Toggled { checked: false }` for it follows the event that caused it.
362    ///
363    /// # Arguments
364    ///
365    /// * `events` - The events `Widget`s generated.
366    ///
367    /// # Returns
368    ///
369    /// The same events, with the clearing `Toggled` events added.
370    pub(super) fn apply_exclusive(&mut self, events: Vec<Event>) -> Vec<Event> {
371        let mut out = Vec::with_capacity(events.len());
372
373        for event in events {
374            let checked_id = match &event {
375                Event::Toggled { id, checked: true } => Some(*id),
376                _ => None,
377            };
378
379            out.push(event);
380
381            if let Some(id) = checked_id {
382                out.extend(self.clear_siblings(id));
383            }
384        }
385
386        out
387    }
388
389    /// Clears the checked exclusive siblings of `id`, returning a `Toggled(false)` for each.
390    fn clear_siblings(&mut self, id: WidgetId) -> Vec<Event> {
391        let Some(widget) = self.get(id) else {
392            return Vec::new();
393        };
394
395        if !widget.behavior().contains(Behavior::EXCLUSIVE) {
396            return Vec::new();
397        }
398
399        let parent = widget.get_parent();
400        let siblings: Vec<WidgetId> = self
401            .children_of(parent)
402            .iter()
403            .copied()
404            .filter(|&c| c != id)
405            .collect();
406        let mut cleared = Vec::new();
407
408        for sibling in siblings {
409            let Some(w) = self.get_mut(sibling) else {
410                continue;
411            };
412
413            if w.behavior().contains(Behavior::EXCLUSIVE)
414                && w.state().contains(VisualState::CHECKED)
415            {
416                let mut state = w.state();
417
418                state.set(VisualState::CHECKED, false);
419                w.set_state(state);
420                w.set_invalidated(true);
421                cleared.push(Event::Toggled {
422                    id: sibling,
423                    checked: false,
424                });
425            }
426        }
427
428        cleared
429    }
430
431    /// Finds the `Widget` with `flag` that Return or Escape activates.
432    ///
433    /// The form is the nearest ancestor of the focused `Widget` (or the root) that contains an
434    /// enabled, visible `Widget` with the flag; the first one in ID order wins.
435    fn find_action(&self, flag: Behavior) -> Option<WidgetId> {
436        let start = self.key_target();
437        let mut forms = vec![start];
438
439        forms.extend(self.ancestors(start));
440
441        forms
442            .into_iter()
443            .find_map(|form| self.action_in(form, flag))
444    }
445
446    /// Searches the subtree under `form` for an actionable `Widget` with `flag`.
447    fn action_in(&self, form: WidgetId, flag: Behavior) -> Option<WidgetId> {
448        let mut stack = vec![form];
449        let mut found: Option<WidgetId> = None;
450
451        while let Some(id) = stack.pop() {
452            let Some(widget) = self.get(id) else {
453                continue;
454            };
455
456            if widget.is_hidden() {
457                continue;
458            }
459
460            if widget.is_enabled()
461                && widget.behavior().contains(flag)
462                && found.is_none_or(|f| id < f)
463            {
464                found = Some(id);
465            }
466
467            stack.extend(self.children_of(id));
468        }
469
470        found
471    }
472
473    /// Queues the activation of the default or cancel `Widget`, if the form has one, and delivers
474    /// [`Event::Activated`] to that `Widget` so it can act.
475    fn trigger_action(&mut self, cancel: bool, ctx: &mut EventCtx) -> bool {
476        let flag = if cancel {
477            Behavior::CANCEL_ACTION
478        } else {
479            Behavior::DEFAULT_ACTION
480        };
481
482        let Some(id) = self.find_action(flag) else {
483            return false;
484        };
485
486        // The application hears of the activation first; then the widget itself is told, so a
487        // button can respond as if it had been clicked.
488        ctx.emit(Event::Activated { id });
489        self.send(id, &Event::Activated { id }, EventPhase::Target, ctx);
490        self.queue_event(Event::Engine(EngineEvent::ActionTriggered { id, cancel }));
491
492        true
493    }
494
495    /// Delivers a key press to the focused `Widget`, then, if nothing stopped it, applies the
496    /// keyboard rules: Tab and Shift-Tab, the arrow keys within a group, Return for the default
497    /// `Widget`, and Escape (or Cmd-. on macOS) for the cancel `Widget`.
498    ///
499    /// # Arguments
500    ///
501    /// * `key` - The key pressed.
502    /// * `modifiers` - The modifier keys held.
503    /// * `repeat` - `true` if this is an auto-repeat.
504    /// * `ctx` - The context collecting generated events.
505    pub(super) fn handle_key_down(
506        &mut self,
507        key: Key,
508        modifiers: Modifiers,
509        repeat: bool,
510        ctx: &mut EventCtx,
511    ) {
512        let target = self.key_target();
513        let event = Event::KeyPressed {
514            id: target,
515            key,
516            modifiers,
517            repeat,
518        };
519
520        if self.propagate_with(target, &event, ctx) == Propagation::Stop {
521            return;
522        }
523
524        let command = modifiers.intersects(COMMAND_MODS);
525        let shift = modifiers.intersects(Modifiers::SHIFT);
526
527        match key {
528            Key::Tab if !command => {
529                self.focus_next(shift);
530            }
531            Key::Right | Key::Down if !command => {
532                self.select_in_group(true, ctx);
533            }
534            Key::Left | Key::Up if !command => {
535                self.select_in_group(false, ctx);
536            }
537            Key::Return | Key::KpEnter if !repeat && !command => {
538                self.trigger_action(false, ctx);
539            }
540            Key::Escape if !repeat && !command => {
541                self.trigger_action(true, ctx);
542            }
543            Key::Char('.')
544                if cfg!(target_os = "macos") && !repeat && modifiers.intersects(Modifiers::GUI) =>
545            {
546                self.trigger_action(true, ctx);
547            }
548            _ => {}
549        }
550    }
551}