Skip to main content

egui_pop_core/
keys.rs

1//! The key dispatcher: egui key events become chords, chords resolve
2//! through the keymap in the focus chain's context (ADR 0007), and the
3//! keys that resolve are consumed before widgets see them, and so is what such
4//! a key sends while it is held.
5//!
6//! A focused widget that reads keys itself
7//! ([`crate::focus::reads_keys`]: a list's or a grid's arrows) gets them
8//! before a global binding of theirs pressed without Ctrl or Alt: the
9//! dispatcher names them in the context
10//! ([`CONTEXT_WIDGET_KEYS`](egui_pop_model::keymap::CONTEXT_WIDGET_KEYS)),
11//! and such a binding resolves nothing. Bindings scoped to the widget's
12//! surface, panel or window were declared for that place and go first.
13//!
14//! While a text input owns the keyboard
15//! ([`crate::focus::text_input_owns_keyboard`]: a text field has the
16//! focus, or an open input such as a slider's typed entry claimed it),
17//! Escape and Enter without Ctrl or Alt are left to the input: they
18//! resolve nothing and stay in the input. A host with a dispatcher of its
19//! own should ask the same before it reads those keys.
20//!
21//! On macOS the Command key counts as `Ctrl` in chords, so one keymap
22//! serves every platform (as egui's `Modifiers::command`).
23
24use std::collections::VecDeque;
25
26use egui::{Context, Event, Key, Modifiers};
27use egui_pop_model::ids::CommandId;
28use egui_pop_model::keymap::{Chord, Keymap, Keys, Resolution, Trace};
29use egui_pop_model::when::WhenContext;
30use serde::Serialize;
31
32/// The chord of a key press.
33pub fn chord_of(key: Key, modifiers: Modifiers) -> Chord {
34    let mut c = Chord::key(key.name());
35    c.ctrl = modifiers.ctrl || modifiers.mac_cmd || modifiers.command;
36    c.alt = modifiers.alt;
37    c.shift = modifiers.shift;
38    c
39}
40
41/// The egui key and modifiers of a chord (for tests and display).
42pub fn key_of(chord: &Chord) -> Option<(Modifiers, Key)> {
43    let key = Key::ALL
44        .iter()
45        .copied()
46        .find(|k| k.name().eq_ignore_ascii_case(&chord.key))?;
47    let modifiers = Modifiers {
48        alt: chord.alt,
49        ctrl: chord.ctrl,
50        shift: chord.shift,
51        mac_cmd: false,
52        command: chord.ctrl,
53    };
54    Some((modifiers, key))
55}
56
57/// Whether a key press is left to a text input that owns the keyboard:
58/// Escape and Enter, without Ctrl or Alt.
59pub fn left_to_input(key: Key, modifiers: Modifiers) -> bool {
60    matches!(key, Key::Escape | Key::Enter)
61        && !modifiers.ctrl
62        && !modifiers.alt
63        && !modifiers.command
64        && !modifiers.mac_cmd
65}
66
67/// A command a key asked for.
68#[derive(Clone, Debug, PartialEq, Serialize)]
69pub struct Dispatch {
70    pub command: CommandId,
71    pub keys: String,
72    pub trace: Trace,
73}
74
75/// How many traces the dispatcher keeps.
76pub const TRACES: usize = 32;
77
78/// Turns key events into commands, keeping the chords of a shortcut in
79/// progress and a trace of each resolution.
80#[derive(Debug)]
81pub struct KeyDispatcher {
82    pending: Vec<Chord>,
83    pending_since: f64,
84    /// Seconds before a shortcut in progress is dropped.
85    pub timeout: f64,
86    traces: VecDeque<Trace>,
87    /// The keys a binding took and that are still down: what a held key sends
88    /// goes with its press, not to the widgets.
89    held: Vec<Key>,
90    /// The text a consumed plain key types, when it did not come in the
91    /// same pass as the press, and the pass of the press: it is taken when
92    /// it comes in the next two.
93    typed: Vec<(String, u64)>,
94}
95
96impl Default for KeyDispatcher {
97    fn default() -> Self {
98        Self {
99            pending: Vec::new(),
100            pending_since: 0.0,
101            timeout: 2.0,
102            traces: VecDeque::new(),
103            held: Vec::new(),
104            typed: Vec::new(),
105        }
106    }
107}
108
109impl KeyDispatcher {
110    pub fn new() -> Self {
111        Self::default()
112    }
113
114    /// The chords of a shortcut in progress (`Ctrl+K` waiting for more).
115    pub fn pending(&self) -> Option<Keys> {
116        (!self.pending.is_empty()).then(|| Keys(self.pending.clone()))
117    }
118
119    /// Drops the shortcut in progress, if any: the next key starts a new
120    /// one (the window it began in is no longer the one worked in).
121    pub fn cancel_pending(&mut self) {
122        self.pending.clear();
123    }
124
125    /// The last resolutions, oldest first.
126    pub fn traces(&self) -> impl Iterator<Item = &Trace> {
127        self.traces.iter()
128    }
129
130    fn keep(&mut self, trace: Trace) {
131        if self.traces.len() == TRACES {
132            self.traces.pop_front();
133        }
134        self.traces.push_back(trace);
135    }
136
137    /// Reads this pass's key presses, resolves them and consumes the ones
138    /// that did something (ran a command, or started or broke a
139    /// shortcut). Returns the commands to run, in order.
140    pub fn process(&mut self, ctx: &Context, keymap: &Keymap, cx: &WhenContext) -> Vec<Dispatch> {
141        let now = ctx.input(|i| i.time);
142        if !self.pending.is_empty() && now - self.pending_since > self.timeout {
143            self.pending.clear();
144        }
145        let owned = crate::focus::text_input_owns_keyboard(ctx);
146        let read = crate::focus::keys_read_by_focus(ctx);
147        let widened;
148        let cx = if read.is_empty() {
149            cx
150        } else {
151            let names: Vec<String> = read
152                .iter()
153                .map(|k| chord_of(*k, Modifiers::NONE).key)
154                .collect();
155            let mut c = cx.clone();
156            c.set(
157                egui_pop_model::keymap::CONTEXT_WIDGET_KEYS,
158                &names.join(" "),
159            );
160            widened = c;
161            &widened
162        };
163        let presses: Vec<(usize, Key, Modifiers)> = ctx.input(|i| {
164            i.events
165                .iter()
166                .enumerate()
167                .filter_map(|(n, e)| match e {
168                    Event::Key {
169                        key,
170                        pressed: true,
171                        repeat: false,
172                        modifiers,
173                        ..
174                    } => Some((n, *key, *modifiers)),
175                    _ => None,
176                })
177                .filter(|(_, key, modifiers)| !(owned && left_to_input(*key, *modifiers)))
178                .collect()
179        });
180        let mut out = Vec::new();
181        let mut consumed: Vec<(usize, Chord)> = Vec::new();
182        ctx.input(|i| {
183            for (n, e) in i.events.iter().enumerate() {
184                match e {
185                    Event::Key {
186                        key,
187                        pressed: false,
188                        ..
189                    } => self.held.retain(|k| k != key),
190                    Event::Key {
191                        key,
192                        pressed: true,
193                        repeat: true,
194                        modifiers,
195                        ..
196                    } if self.held.contains(key) => consumed.push((n, chord_of(*key, *modifiers))),
197                    _ => {}
198                }
199            }
200        });
201        for (n, key, modifiers) in presses {
202            let chord = chord_of(key, modifiers);
203            // A new press: the release of the last one may have gone elsewhere.
204            self.held.retain(|k| *k != key);
205            let mut keys = self.pending.clone();
206            keys.push(chord.clone());
207            let keys = Keys(keys);
208            let (resolution, trace) = keymap.resolve_traced(&keys, cx);
209            let had_pending = !self.pending.is_empty();
210            let interesting = had_pending || !trace.candidates.is_empty();
211            match resolution {
212                Resolution::Run(command) => {
213                    self.pending.clear();
214                    consumed.push((n, chord));
215                    self.held.push(key);
216                    out.push(Dispatch {
217                        command,
218                        keys: keys.to_string(),
219                        trace: trace.clone(),
220                    });
221                }
222                Resolution::Pending => {
223                    self.pending = keys.0;
224                    self.pending_since = now;
225                    consumed.push((n, chord));
226                }
227                Resolution::Nothing => {
228                    if had_pending {
229                        // A broken shortcut swallows its last key.
230                        consumed.push((n, chord));
231                    }
232                    self.pending.clear();
233                }
234            }
235            if interesting {
236                self.keep(trace);
237            }
238        }
239        let pass = ctx.cumulative_pass_nr();
240        self.typed.retain(|(_, p)| p + 2 >= pass);
241        // Its name (`a`), or its symbol for a key named otherwise (`/` for
242        // `slash`).
243        let texts: Vec<String> = consumed
244            .iter()
245            .filter(|(_, c)| !c.ctrl && !c.alt && !c.meta)
246            .flat_map(|(_, c)| {
247                let symbol = key_of(c).map(|(_, k)| k.symbol_or_name().to_string());
248                std::iter::once(c.key.clone()).chain(symbol)
249            })
250            .collect();
251        if !consumed.is_empty() || !self.typed.is_empty() {
252            let mut seen = false;
253            let typed = &mut self.typed;
254            ctx.input_mut(|i| {
255                let mut index = 0;
256                i.events.retain(|e| {
257                    let n = index;
258                    index += 1;
259                    if consumed.iter().any(|(c, _)| *c == n) {
260                        return false;
261                    }
262                    let Event::Text(t) = e else { return true };
263                    // The text a consumed plain key types.
264                    if texts.iter().any(|k| t.eq_ignore_ascii_case(k)) {
265                        seen = true;
266                        return false;
267                    }
268                    // Or typed, a pass or two after its press.
269                    match typed.iter().position(|(k, _)| t.eq_ignore_ascii_case(k)) {
270                        Some(at) => {
271                            typed.remove(at);
272                            false
273                        }
274                        None => true,
275                    }
276                });
277            });
278            // A symbol key whose text did not come with it: it may come next.
279            if !seen {
280                for (_, c) in consumed
281                    .iter()
282                    .filter(|(_, c)| !c.ctrl && !c.alt && !c.meta)
283                {
284                    if let Some((_, k)) = key_of(c)
285                        && k.symbol_or_name() != k.name()
286                    {
287                        self.typed.push((k.symbol_or_name().to_string(), pass));
288                    }
289                }
290            }
291        }
292        quiet_plain_clicks(ctx);
293        out
294    }
295}
296
297/// Enter and Space click a focused plain widget only when pressed alone and
298/// once: with Ctrl, Alt, Shift or Command, or repeated while held, they are
299/// taken out of the input before the widget reads them, as a native button
300/// does. A binding on such a key has already run and taken it (this comes
301/// after the keymap), and a widget sensing drags (a slider, a splitter, a
302/// text field) reads its own keys and is left alone.
303///
304/// upstream: egui clicks a focused widget sensing clicks on any press of
305/// Enter or Space, whatever the modifiers, at each repeat
306/// (docs/upstream.md, "egui: Enter and Space click whatever the modifiers").
307fn quiet_plain_clicks(ctx: &Context) {
308    let Some(id) = ctx.memory(|m| m.focused()) else {
309        return;
310    };
311    let plain = ctx.viewport(|v| {
312        v.prev_pass
313            .widgets
314            .get(id)
315            .is_some_and(|w| w.enabled && w.sense.senses_click() && !w.sense.senses_drag())
316    });
317    if !plain {
318        return;
319    }
320    ctx.input_mut(|i| {
321        i.events.retain(|e| {
322            !matches!(
323                e,
324                Event::Key {
325                    key: Key::Enter | Key::Space,
326                    pressed: true,
327                    repeat,
328                    modifiers,
329                    ..
330                } if *repeat || modifiers.any()
331            )
332        });
333    });
334}