Skip to main content

nadir_debug/
input.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The debug UI's input: window events in their order, taken a frame at a
16//! time.
17
18use std::collections::VecDeque;
19
20use nadir_core::{Key, MouseButton, Vec2};
21
22/// The most events kept. Past it the oldest go, so that a debug UI that is
23/// not drawn still uses bounded memory.
24const MAX_EVENTS: usize = 4096;
25
26/// One window event, as the debug UI keeps it.
27#[derive(Clone, Copy, Debug, PartialEq)]
28enum Event {
29    Moved(Vec2),
30    Button(bool),
31    Wheel(Vec2),
32    Key { key: Key, pressed: bool },
33    Text(char),
34    FocusLost,
35}
36
37/// The modifier keys that are down.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39struct Modifiers {
40    /// Left and right Shift, Control, Alt and Super, in that order.
41    down: [bool; 8],
42}
43
44impl Modifiers {
45    /// Records `key` going down or up, if it is a modifier.
46    fn set(&mut self, key: Key, pressed: bool) {
47        let slot = match key {
48            Key::LeftShift => 0,
49            Key::RightShift => 1,
50            Key::LeftControl => 2,
51            Key::RightControl => 3,
52            Key::LeftAlt => 4,
53            Key::RightAlt => 5,
54            Key::LeftSuper => 6,
55            Key::RightSuper => 7,
56            _ => return,
57        };
58        self.down[slot] = pressed;
59    }
60
61    fn shift(&self) -> bool {
62        self.down[0] || self.down[1]
63    }
64
65    /// Control or Super, with no Alt: AltGr arrives on Windows as Control
66    /// and Alt, and types text.
67    fn command(&self) -> bool {
68        let alt = self.down[4] || self.down[5];
69        (self.down[2] || self.down[3] || self.down[6] || self.down[7]) && !alt
70    }
71}
72
73/// An edit of the focused text field, in the order typed.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub(crate) enum Edit {
76    /// A character typed.
77    Char(char),
78    /// A key pressed, or repeated, with Shift, and with Control or Super
79    /// and no Alt (`command`).
80    Key {
81        key: Key,
82        shift: bool,
83        command: bool,
84    },
85}
86
87/// What a frame takes from the input: where the pointer was at each edge
88/// of the left button, in output pixels, and the edits in order.
89#[derive(Clone, Debug, Default, PartialEq)]
90pub(crate) struct Taken {
91    /// Where the pointer is after the frame's events.
92    pub(crate) pointer: Vec2,
93    /// Where the button went down, if it did.
94    pub(crate) press: Option<Vec2>,
95    /// Where it went up, if it did, and whether that was the window losing
96    /// the focus, which clicks nothing.
97    pub(crate) release: Option<(Vec2, bool)>,
98    /// Whether it is down after the frame's events.
99    pub(crate) down: bool,
100    /// The wheel's turn, in lines; +y is away from the user.
101    pub(crate) wheel: Vec2,
102    pub(crate) edits: Vec<Edit>,
103}
104
105/// The debug UI's input: the window's events, fed in their order, by the
106/// engine from its window (roadmap M7.10) or by a test.
107///
108/// [`DebugUi::frame`](crate::DebugUi::frame) takes the events of one frame:
109/// at most one press and one release of the left button, so that a click is
110/// judged where it was pressed and where it was released, however late the
111/// frame. The frame ends at the release, so that a drag ends where the
112/// button went up; a press after a release, or after text or keys, waits for
113/// the next frame, so that what was typed goes to the field that had the
114/// keyboard. It ends too at a press of a key whose meaning a text field
115/// leaves to its caller, Enter (and the keypad's), Tab, Up, Down, PageUp
116/// and PageDown, which the caller handles after the field: a console then
117/// runs a line with the text typed before its Enter only, and goes back in
118/// its history before an Enter that follows. Pointer moves in a row are
119/// kept as the last one, and past 4096
120/// events the oldest go: a debug UI not drawn for a while should
121/// [`clear`](DebugInput::clear) its input when it is drawn again.
122#[derive(Clone, Debug, Default)]
123pub struct DebugInput {
124    events: VecDeque<Event>,
125    /// As the events taken so far left them.
126    pointer: Vec2,
127    down: bool,
128    modifiers: Modifiers,
129}
130
131impl DebugInput {
132    /// An input with no events, the pointer at (0, 0) and nothing down.
133    pub fn new() -> Self {
134        Self::default()
135    }
136
137    /// The pointer moved to `position`: the output's pixels from its
138    /// top-left corner, as `nadir_input::Input::pointer` gives it.
139    pub fn pointer_moved(&mut self, position: Vec2) {
140        if let Some(Event::Moved(last)) = self.events.back_mut() {
141            *last = position;
142        } else {
143            self.push(Event::Moved(position));
144        }
145    }
146
147    /// A mouse button went down or up. The debug UI uses the left one only.
148    pub fn button(&mut self, button: MouseButton, pressed: bool) {
149        if button == MouseButton::Left {
150            self.push(Event::Button(pressed));
151        }
152    }
153
154    /// The wheel turned by `lines`: +y is away from the user, which
155    /// scrolls toward the top.
156    pub fn wheel(&mut self, lines: Vec2) {
157        self.push(Event::Wheel(lines));
158    }
159
160    /// A key went down, up, or repeated while held (`repeat`): a repeat is
161    /// a press again, as editing wants.
162    pub fn key(&mut self, key: Key, pressed: bool, repeat: bool) {
163        let _ = repeat;
164        self.push(Event::Key { key, pressed });
165    }
166
167    /// Text was typed. Control characters, a tab and newlines among them,
168    /// are left out: the keys that make them are seen as keys.
169    pub fn text(&mut self, text: &str) {
170        for character in text.chars().filter(|c| !c.is_control()) {
171            self.push(Event::Text(character));
172        }
173    }
174
175    /// The window lost the focus: the button and the modifiers are let go,
176    /// and a widget held is released without a click.
177    pub fn focus_lost(&mut self) {
178        self.push(Event::FocusLost);
179    }
180
181    /// Whether events wait to be taken.
182    pub fn is_empty(&self) -> bool {
183        self.events.is_empty()
184    }
185
186    /// Drops the events not taken, keeping where they leave the pointer and
187    /// what they leave held: for a debug UI drawn again after frames it was
188    /// not, so that the clicks the game had then are not replayed on it.
189    pub fn clear(&mut self) {
190        for event in self.events.drain(..) {
191            match event {
192                Event::Moved(position) => self.pointer = position,
193                Event::Button(pressed) => self.down = pressed,
194                Event::Key { key, pressed } => self.modifiers.set(key, pressed),
195                Event::FocusLost => {
196                    self.down = false;
197                    self.modifiers = Modifiers::default();
198                }
199                Event::Wheel(_) | Event::Text(_) => {}
200            }
201        }
202    }
203
204    fn push(&mut self, event: Event) {
205        if self.events.len() == MAX_EVENTS {
206            self.events.pop_front();
207        }
208        self.events.push_back(event);
209    }
210
211    /// Takes the events of one frame into `out`.
212    pub(crate) fn take(&mut self, out: &mut Taken) {
213        out.press = None;
214        out.release = None;
215        out.wheel = Vec2::ZERO;
216        out.edits.clear();
217        while let Some(&event) = self.events.front() {
218            // A frame ends at its release, and a press waits for the next
219            // frame after a release or after text and keys, which go to the
220            // field that had the keyboard before it.
221            match event {
222                Event::Button(true)
223                    if out.press.is_some() || out.release.is_some() || !out.edits.is_empty() =>
224                {
225                    break;
226                }
227                Event::Button(false) | Event::Moved(_) if out.release.is_some() => break,
228                _ => {}
229            }
230            self.events.pop_front();
231            match event {
232                Event::Moved(position) => self.pointer = position,
233                Event::Button(true) => {
234                    if !self.down {
235                        self.down = true;
236                        out.press = Some(self.pointer);
237                    }
238                }
239                Event::Button(false) => {
240                    if self.down {
241                        self.down = false;
242                        out.release = Some((self.pointer, false));
243                    }
244                }
245                Event::Wheel(lines) => out.wheel += lines,
246                Event::Key { key, pressed } => {
247                    self.modifiers.set(key, pressed);
248                    if pressed {
249                        out.edits.push(Edit::Key {
250                            key,
251                            shift: self.modifiers.shift(),
252                            command: self.modifiers.command(),
253                        });
254                        if ends_frame(key) {
255                            break;
256                        }
257                    }
258                }
259                Event::Text(character) => out.edits.push(Edit::Char(character)),
260                Event::FocusLost => {
261                    if self.down {
262                        self.down = false;
263                        out.release = Some((self.pointer, true));
264                    }
265                    self.modifiers = Modifiers::default();
266                }
267            }
268        }
269        out.pointer = self.pointer;
270        out.down = self.down;
271    }
272}
273
274/// Whether a press of `key` ends a frame's events: a key whose meaning a
275/// text field leaves to its caller, who handles it after the field.
276fn ends_frame(key: Key) -> bool {
277    matches!(
278        key,
279        Key::Enter
280            | Key::NumpadEnter
281            | Key::Tab
282            | Key::Up
283            | Key::Down
284            | Key::PageUp
285            | Key::PageDown
286    )
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    #[test]
294    fn a_frame_ends_at_a_press_of_a_key_a_field_leaves_to_its_caller() {
295        let mut input = DebugInput::new();
296        input.text("tp");
297        input.key(Key::Enter, true, false);
298        input.text("5");
299        input.key(Key::Enter, false, false);
300        input.key(Key::Up, true, false);
301        input.key(Key::Up, true, true);
302        input.key(Key::A, true, false);
303        let keys = |taken: &Taken| -> Vec<Edit> { taken.edits.clone() };
304        let edit = |key| Edit::Key {
305            key,
306            shift: false,
307            command: false,
308        };
309        let first = take(&mut input);
310        assert_eq!(
311            keys(&first),
312            [Edit::Char('t'), Edit::Char('p'), edit(Key::Enter)]
313        );
314        // What came after waits: the text, then the next such key.
315        assert_eq!(keys(&take(&mut input)), [Edit::Char('5'), edit(Key::Up)]);
316        // A repeat is a press again.
317        assert_eq!(keys(&take(&mut input)), [edit(Key::Up)]);
318        assert_eq!(keys(&take(&mut input)), [edit(Key::A)]);
319        assert!(input.is_empty());
320        // Left, Right and the rest are the field's: they end nothing.
321        for key in [
322            Key::Left,
323            Key::Right,
324            Key::Home,
325            Key::End,
326            Key::Backspace,
327            Key::Escape,
328        ] {
329            input.key(key, true, false);
330        }
331        assert_eq!(take(&mut input).edits.len(), 6);
332        for key in [
333            Key::NumpadEnter,
334            Key::Tab,
335            Key::Down,
336            Key::PageUp,
337            Key::PageDown,
338        ] {
339            input.key(key, true, false);
340            input.text("x");
341            assert_eq!(keys(&take(&mut input)), [edit(key)], "{key:?}");
342            assert_eq!(keys(&take(&mut input)), [Edit::Char('x')]);
343        }
344    }
345
346    fn take(input: &mut DebugInput) -> Taken {
347        let mut taken = Taken::default();
348        input.take(&mut taken);
349        taken
350    }
351
352    #[test]
353    fn a_press_and_its_release_are_judged_where_they_happened() {
354        let mut input = DebugInput::new();
355        input.pointer_moved(Vec2::new(1.0, 1.0));
356        input.button(MouseButton::Left, true);
357        input.pointer_moved(Vec2::new(5.0, 1.0));
358        input.pointer_moved(Vec2::new(9.0, 1.0));
359        input.button(MouseButton::Left, false);
360        input.pointer_moved(Vec2::new(20.0, 1.0));
361        // Not the left button: not seen.
362        input.button(MouseButton::Right, true);
363        let taken = take(&mut input);
364        assert_eq!(taken.press, Some(Vec2::new(1.0, 1.0)));
365        assert_eq!(taken.release, Some((Vec2::new(9.0, 1.0), false)));
366        // The frame ends at the release: a drag ends where it went up.
367        assert_eq!((taken.pointer, taken.down), (Vec2::new(9.0, 1.0), false));
368        assert!(!input.is_empty());
369        assert_eq!(take(&mut input).pointer, Vec2::new(20.0, 1.0));
370        assert!(input.is_empty());
371    }
372
373    #[test]
374    fn a_press_after_typing_waits_for_the_next_frame() {
375        let mut input = DebugInput::new();
376        input.text("ab");
377        input.key(Key::Enter, true, false);
378        input.button(MouseButton::Left, true);
379        input.text("c");
380        let first = take(&mut input);
381        assert_eq!((first.press, first.edits.len()), (None, 3));
382        let second = take(&mut input);
383        assert!(second.press.is_some());
384        assert_eq!(second.edits, [Edit::Char('c')]);
385    }
386
387    #[test]
388    fn clearing_drops_the_events_and_keeps_what_they_hold() {
389        let mut input = DebugInput::new();
390        input.key(Key::LeftShift, true, false);
391        input.pointer_moved(Vec2::new(4.0, 5.0));
392        input.button(MouseButton::Left, true);
393        input.button(MouseButton::Left, false);
394        input.button(MouseButton::Left, true);
395        input.text("lost");
396        input.clear();
397        assert!(input.is_empty());
398        // Held, with no press to judge; Shift still down.
399        input.key(Key::Left, true, false);
400        input.button(MouseButton::Left, false);
401        let taken = take(&mut input);
402        assert_eq!(taken.press, None);
403        assert_eq!(taken.release, Some((Vec2::new(4.0, 5.0), false)));
404        assert_eq!(
405            taken.edits,
406            [Edit::Key {
407                key: Key::Left,
408                shift: true,
409                command: false
410            }]
411        );
412    }
413
414    #[test]
415    fn a_press_after_a_release_waits_for_the_next_frame() {
416        let mut input = DebugInput::new();
417        input.button(MouseButton::Left, true);
418        let first = take(&mut input);
419        assert!(first.press.is_some() && first.down);
420        // The drag ends, and a new press starts, in one frame.
421        input.button(MouseButton::Left, false);
422        input.pointer_moved(Vec2::new(3.0, 0.0));
423        input.button(MouseButton::Left, true);
424        input.text("a");
425        let second = take(&mut input);
426        assert_eq!(second.release, Some((Vec2::ZERO, false)));
427        assert_eq!((second.press, second.down), (None, false));
428        assert!(second.edits.is_empty(), "after the cut");
429        let third = take(&mut input);
430        assert_eq!(third.press, Some(Vec2::new(3.0, 0.0)));
431        assert_eq!(third.edits, [Edit::Char('a')]);
432        // Two clicks in one frame are two frames.
433        input.button(MouseButton::Left, false);
434        input.button(MouseButton::Left, true);
435        input.button(MouseButton::Left, false);
436        assert!(take(&mut input).release.is_some());
437        let last = take(&mut input);
438        assert!(last.press.is_some() && last.release.is_some());
439    }
440
441    #[test]
442    fn edits_keep_their_order_with_the_modifiers_of_their_time() {
443        let mut input = DebugInput::new();
444        input.text("c");
445        input.key(Key::LeftShift, true, false);
446        input.key(Key::Left, true, false);
447        input.key(Key::Left, true, true);
448        input.key(Key::LeftShift, false, false);
449        input.key(Key::Backspace, true, false);
450        input.key(Key::RightControl, true, false);
451        input.key(Key::A, true, false);
452        // AltGr: Control and Alt, which types text, selects nothing.
453        input.key(Key::RightAlt, true, false);
454        input.key(Key::A, true, false);
455        input.text("\tą\n");
456        let key = |key, shift, command| Edit::Key {
457            key,
458            shift,
459            command,
460        };
461        assert_eq!(
462            take(&mut input).edits,
463            [
464                Edit::Char('c'),
465                key(Key::LeftShift, true, false),
466                key(Key::Left, true, false),
467                key(Key::Left, true, false),
468                key(Key::Backspace, false, false),
469                key(Key::RightControl, false, true),
470                key(Key::A, false, true),
471                key(Key::RightAlt, false, false),
472                key(Key::A, false, false),
473                Edit::Char('ą'),
474            ]
475        );
476    }
477
478    #[test]
479    fn losing_the_focus_lets_go_without_a_click() {
480        let mut input = DebugInput::new();
481        input.key(Key::LeftShift, true, false);
482        input.button(MouseButton::Left, true);
483        take(&mut input);
484        input.focus_lost();
485        input.key(Key::Left, true, false);
486        let taken = take(&mut input);
487        assert_eq!(taken.release, Some((Vec2::ZERO, true)));
488        assert!(!taken.down);
489        assert_eq!(
490            taken.edits,
491            [Edit::Key {
492                key: Key::Left,
493                shift: false,
494                command: false
495            }]
496        );
497    }
498
499    #[test]
500    fn moves_in_a_row_are_one_and_the_events_are_bounded() {
501        let mut input = DebugInput::new();
502        for x in 0..10_000 {
503            input.pointer_moved(Vec2::new(x as f32, 0.0));
504        }
505        assert_eq!(input.events.len(), 1);
506        for _ in 0..10_000 {
507            input.wheel(Vec2::new(0.0, 1.0));
508        }
509        assert_eq!(input.events.len(), MAX_EVENTS);
510        assert_eq!(take(&mut input).wheel, Vec2::new(0.0, MAX_EVENTS as f32));
511    }
512}