1use std::collections::VecDeque;
19
20use nadir_core::{Key, MouseButton, Vec2};
21
22const MAX_EVENTS: usize = 4096;
25
26#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39struct Modifiers {
40 down: [bool; 8],
42}
43
44impl Modifiers {
45 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub(crate) enum Edit {
76 Char(char),
78 Key {
81 key: Key,
82 shift: bool,
83 command: bool,
84 },
85}
86
87#[derive(Clone, Debug, Default, PartialEq)]
90pub(crate) struct Taken {
91 pub(crate) pointer: Vec2,
93 pub(crate) press: Option<Vec2>,
95 pub(crate) release: Option<(Vec2, bool)>,
98 pub(crate) down: bool,
100 pub(crate) wheel: Vec2,
102 pub(crate) edits: Vec<Edit>,
103}
104
105#[derive(Clone, Debug, Default)]
123pub struct DebugInput {
124 events: VecDeque<Event>,
125 pointer: Vec2,
127 down: bool,
128 modifiers: Modifiers,
129}
130
131impl DebugInput {
132 pub fn new() -> Self {
134 Self::default()
135 }
136
137 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 pub fn button(&mut self, button: MouseButton, pressed: bool) {
149 if button == MouseButton::Left {
150 self.push(Event::Button(pressed));
151 }
152 }
153
154 pub fn wheel(&mut self, lines: Vec2) {
157 self.push(Event::Wheel(lines));
158 }
159
160 pub fn key(&mut self, key: Key, pressed: bool, repeat: bool) {
163 let _ = repeat;
164 self.push(Event::Key { key, pressed });
165 }
166
167 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 pub fn focus_lost(&mut self) {
178 self.push(Event::FocusLost);
179 }
180
181 pub fn is_empty(&self) -> bool {
183 self.events.is_empty()
184 }
185
186 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 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 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
274fn 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 assert_eq!(keys(&take(&mut input)), [Edit::Char('5'), edit(Key::Up)]);
316 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 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 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 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 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 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 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 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}