1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
use gilrs::{Axis, Button, Event, Gilrs};
use winit::event::{ElementState, MouseButton, WindowEvent};
use winit::keyboard::{Key, NamedKey};
// ── Direction index constants ──────────────────────────────────────────────────
const LEFT: usize = 0;
const RIGHT: usize = 1;
const UP: usize = 2;
const DOWN: usize = 3;
// ── ArrowRepeat ───────────────────────────────────────────────────────────────
/// Held-state and auto-repeat timer for a single arrow direction.
///
/// Kept private to `Input`; the public pulse bools (`arrow_left` etc.) are the
/// outward-facing API.
#[derive(Clone, Copy)]
struct ArrowRepeat {
/// Whether the key/button is currently held down.
held: bool,
/// Seconds the key has been held; drives the initial-delay / repeat-rate logic.
timer: f32,
}
impl ArrowRepeat {
const fn new() -> Self {
Self {
held: false,
timer: 0.0,
}
}
}
// ── Input ─────────────────────────────────────────────────────────────────────
/// Raw input state in grid units (1080-unit tall coordinate space).
///
/// Updated every frame from winit events via [`Input::handle_event`] and from
/// gilrs events via [`Input::poll_gamepad`] or [`Input::handle_gamepad_event`].
/// Single-frame pulse fields (`left_just_pressed`, `arrow_left`, …) are cleared
/// by [`Input::begin_frame`] at the end of each frame.
pub struct Input {
/// Optional owned gilrs instance. Present in standalone mode; `None` in
/// overlay mode where the caller drives [`Input::handle_gamepad_event`] directly.
pub gilrs: Option<Gilrs>,
/// Cursor X position in grid units (origin at screen centre, right = +).
pub mouse_x: f32,
/// Cursor Y position in grid units (origin at screen centre, down = +).
pub mouse_y: f32,
/// `true` while the left mouse button is held.
pub left_pressed: bool,
/// `true` on the first frame the left mouse button goes down.
pub left_just_pressed: bool,
/// `true` on the first frame the left mouse button is released.
pub left_just_released: bool,
/// Lines scrolled this frame; positive = scroll down.
pub scroll_delta: f32,
/// Printable characters typed this frame (from `event.text`, handles IME / dead keys).
pub text_input: Vec<char>,
/// `true` if backspace was pressed this frame.
pub backspace: bool,
/// `true` if Enter/Return was pressed this frame.
pub enter: bool,
/// `true` if Escape was pressed this frame.
pub escape: bool,
/// `true` if Tab was pressed this frame.
pub tab: bool,
/// Arrow-left pulse this frame (fires on key-down and during auto-repeat).
pub arrow_left: bool,
/// Arrow-right pulse this frame (fires on key-down and during auto-repeat).
pub arrow_right: bool,
/// Arrow-up pulse this frame (fires on key-down and during auto-repeat).
pub arrow_up: bool,
/// Arrow-down pulse this frame (fires on key-down and during auto-repeat).
pub arrow_down: bool,
/// `true` while Shift is held.
pub shift: bool,
/// `true` while Ctrl is held.
pub ctrl: bool,
/// `true` if the 'A' key was pressed this frame (regardless of modifiers).
pub key_a: bool,
/// `true` if the 'C' key was pressed this frame.
pub key_c: bool,
/// `true` if the 'X' key was pressed this frame.
pub key_x: bool,
/// `true` if the 'V' key was pressed this frame.
pub key_v: bool,
/// `true` if Space or the gamepad South button was pressed this frame.
pub space: bool,
/// `true` if the gamepad Mode/Guide button was pressed this frame.
pub home: bool,
/// Timestamp of the last hardware keyboard event; used by [`Input::keyboard_present`].
pub last_hw_key: Option<std::time::Instant>,
/// Held-state and repeat timers for the four arrow directions.
/// Indexed by the `LEFT / RIGHT / UP / DOWN` constants.
arrows: [ArrowRepeat; 4],
}
impl Default for Input {
fn default() -> Self {
Self::new()
}
}
impl Input {
/// Create a zeroed `Input` with no gilrs instance.
#[must_use]
pub const fn new() -> Self {
Self {
gilrs: None,
mouse_x: 0.0,
mouse_y: 0.0,
left_pressed: false,
left_just_pressed: false,
left_just_released: false,
scroll_delta: 0.0,
text_input: Vec::new(),
backspace: false,
enter: false,
escape: false,
tab: false,
arrow_left: false,
arrow_right: false,
arrow_up: false,
arrow_down: false,
shift: false,
ctrl: false,
key_a: false,
key_c: false,
key_x: false,
key_v: false,
space: false,
home: false,
last_hw_key: None,
arrows: [ArrowRepeat::new(); 4],
}
}
/// Like [`Input::new`], but attempts to initialise gilrs for automatic gamepad polling.
#[must_use]
pub fn new_with_gilrs() -> Self {
let mut s = Self::new();
s.gilrs = Gilrs::new().ok();
s
}
/// Poll the owned gilrs instance (if any) and map events onto input flags.
///
/// Uses `take` / put-back to avoid borrowing `self.gilrs` while dispatching
/// to `handle_gamepad_event`, eliminating the per-frame `Vec` allocation the
/// naive approach would require.
pub fn poll_gamepad(&mut self) {
let Some(mut g) = self.gilrs.take() else {
return;
};
while let Some(event) = g.next_event() {
self.handle_gamepad_event(event);
}
self.gilrs = Some(g);
}
/// Feed a single gilrs event in manually.
///
/// Used in overlay mode where the caller owns the `Gilrs` instance and
/// drains it themselves, or in tests.
pub fn handle_gamepad_event(&mut self, event: Event) {
use gilrs::EventType::{AxisChanged, ButtonPressed, ButtonReleased};
match event.event {
ButtonPressed(Button::DPadLeft, _) => {
if !self.arrows[LEFT].held {
self.arrow_left = true;
}
self.arrows[LEFT].held = true;
}
ButtonPressed(Button::DPadRight, _) => {
if !self.arrows[RIGHT].held {
self.arrow_right = true;
}
self.arrows[RIGHT].held = true;
}
ButtonPressed(Button::DPadUp, _) => {
if !self.arrows[UP].held {
self.arrow_up = true;
}
self.arrows[UP].held = true;
}
ButtonPressed(Button::DPadDown, _) => {
if !self.arrows[DOWN].held {
self.arrow_down = true;
}
self.arrows[DOWN].held = true;
}
ButtonReleased(Button::DPadLeft, _) => {
self.arrows[LEFT].held = false;
self.arrows[LEFT].timer = 0.0;
}
ButtonReleased(Button::DPadRight, _) => {
self.arrows[RIGHT].held = false;
self.arrows[RIGHT].timer = 0.0;
}
ButtonReleased(Button::DPadUp, _) => {
self.arrows[UP].held = false;
self.arrows[UP].timer = 0.0;
}
ButtonReleased(Button::DPadDown, _) => {
self.arrows[DOWN].held = false;
self.arrows[DOWN].timer = 0.0;
}
ButtonPressed(Button::South, _) => {
self.space = true;
}
ButtonPressed(Button::East, _) => {
self.escape = true;
}
ButtonPressed(Button::Start, _) => {
self.enter = true;
}
ButtonPressed(Button::Mode, _) => {
self.home = true;
}
ButtonPressed(Button::LeftTrigger, _) => {
self.tab = true;
self.shift = true;
}
ButtonPressed(Button::RightTrigger, _) => {
self.tab = true;
}
ButtonReleased(Button::LeftTrigger, _) => {
self.shift = false;
}
AxisChanged(Axis::LeftStickX | Axis::DPadX, v, _) => self.axis_horizontal(v),
AxisChanged(Axis::LeftStickY, v, _) => self.axis_vertical_stick(v),
AxisChanged(Axis::DPadY, v, _) => self.axis_dpad_y(v),
_ => {}
}
}
/// Clear all single-frame pulse flags and advance arrow auto-repeat timers.
///
/// Call exactly once per frame, **after** all widgets have read input but
/// **before** the next frame's events are collected. Note that `shift` and
/// `ctrl` are *not* cleared here — they are held-modifier flags updated on
/// key press/release, not single-frame pulses.
pub fn begin_frame(&mut self, dt: f32) {
const INITIAL_DELAY: f32 = 0.4;
const REPEAT_RATE: f32 = 0.08;
self.left_just_pressed = false;
self.left_just_released = false;
self.scroll_delta = 0.0;
self.text_input.clear();
self.backspace = false;
self.enter = false;
self.escape = false;
self.tab = false;
self.arrow_left = false;
self.arrow_right = false;
self.arrow_up = false;
self.arrow_down = false;
self.space = false;
self.home = false;
self.key_a = false;
self.key_c = false;
self.key_x = false;
self.key_v = false;
// Auto-repeat: after INITIAL_DELAY seconds held, pulse at REPEAT_RATE Hz.
Self::tick_repeat(
self.arrows[LEFT].held,
&mut self.arrows[LEFT].timer,
&mut self.arrow_left,
dt,
INITIAL_DELAY,
REPEAT_RATE,
);
Self::tick_repeat(
self.arrows[RIGHT].held,
&mut self.arrows[RIGHT].timer,
&mut self.arrow_right,
dt,
INITIAL_DELAY,
REPEAT_RATE,
);
Self::tick_repeat(
self.arrows[UP].held,
&mut self.arrows[UP].timer,
&mut self.arrow_up,
dt,
INITIAL_DELAY,
REPEAT_RATE,
);
Self::tick_repeat(
self.arrows[DOWN].held,
&mut self.arrows[DOWN].timer,
&mut self.arrow_down,
dt,
INITIAL_DELAY,
REPEAT_RATE,
);
}
/// Returns `true` if a hardware keyboard key was pressed within the last 3 seconds.
///
/// Used to decide whether to show the on-screen keyboard: if a physical
/// keyboard is present and recently active, suppress the OSK.
#[must_use]
pub fn keyboard_present(&self) -> bool {
self.last_hw_key
.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(3))
}
/// Feed a raw winit `WindowEvent` into the input state.
///
/// `pw` and `ph` are the current window pixel dimensions; they are needed to
/// convert cursor pixel coordinates into the 1080-unit grid space.
pub fn handle_event(&mut self, event: &WindowEvent, pw: f32, ph: f32) {
match event {
WindowEvent::CursorMoved { position, .. } => {
let unit = ph / 1080.0;
let ox = ((pw / ph) * 1080.0).mul_add(-unit, pw) * 0.5;
self.mouse_x = ((pw / ph) * 1080.0).mul_add(-0.5, (position.x as f32 - ox) / unit);
self.mouse_y = position.y as f32 / unit - 540.0;
}
WindowEvent::MouseWheel { delta, .. } => {
self.scroll_delta += match delta {
winit::event::MouseScrollDelta::LineDelta(_, y) => *y,
winit::event::MouseScrollDelta::PixelDelta(pos) => pos.y as f32 / 20.0,
};
}
WindowEvent::MouseInput {
button: MouseButton::Left,
state,
..
} => match state {
ElementState::Pressed => {
self.left_pressed = true;
self.left_just_pressed = true;
}
ElementState::Released => {
self.left_pressed = false;
self.left_just_released = true;
}
},
WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => {
self.handle_key_press(event);
}
WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Released => {
match &event.logical_key {
Key::Named(NamedKey::Shift) => {
self.shift = false;
}
Key::Named(NamedKey::Control) => {
self.ctrl = false;
}
Key::Named(NamedKey::ArrowLeft) => {
self.arrows[LEFT].held = false;
self.arrows[LEFT].timer = 0.0;
}
Key::Named(NamedKey::ArrowRight) => {
self.arrows[RIGHT].held = false;
self.arrows[RIGHT].timer = 0.0;
}
Key::Named(NamedKey::ArrowUp) => {
self.arrows[UP].held = false;
self.arrows[UP].timer = 0.0;
}
Key::Named(NamedKey::ArrowDown) => {
self.arrows[DOWN].held = false;
self.arrows[DOWN].timer = 0.0;
}
_ => {}
}
}
_ => {}
}
}
// ── Private helpers ────────────────────────────────────────────────────────
/// Process a winit key-press event: update modifier flags, arrow held-state,
/// named-key pulses, printable-character list, and `last_hw_key` timestamp.
///
/// `last_hw_key` is only updated for keys that a physical keyboard uniquely
/// provides — printable characters and Backspace. Arrow keys, Space, Enter,
/// Escape, Tab, Shift, and Control are all producible by a gamepad or the OSK
/// itself, so they must not suppress the OSK.
fn handle_key_press(&mut self, event: &winit::event::KeyEvent) {
match &event.logical_key {
Key::Named(NamedKey::Backspace) => {
self.last_hw_key = Some(std::time::Instant::now());
self.backspace = true;
}
Key::Named(NamedKey::Enter) => {
self.enter = true;
}
Key::Named(NamedKey::Escape) => {
self.escape = true;
}
Key::Named(NamedKey::Tab) => {
self.tab = true;
}
Key::Named(NamedKey::Shift) => {
self.shift = true;
}
Key::Named(NamedKey::Control) => {
self.ctrl = true;
}
Key::Named(NamedKey::Space) => {
self.space = true;
}
Key::Named(NamedKey::ArrowLeft) => {
if !self.arrows[LEFT].held {
self.arrow_left = true;
}
self.arrows[LEFT].held = true;
}
Key::Named(NamedKey::ArrowRight) => {
if !self.arrows[RIGHT].held {
self.arrow_right = true;
}
self.arrows[RIGHT].held = true;
}
Key::Named(NamedKey::ArrowUp) => {
if !self.arrows[UP].held {
self.arrow_up = true;
}
self.arrows[UP].held = true;
}
Key::Named(NamedKey::ArrowDown) => {
if !self.arrows[DOWN].held {
self.arrow_down = true;
}
self.arrows[DOWN].held = true;
}
Key::Character(s) => {
self.last_hw_key = Some(std::time::Instant::now());
match s.to_lowercase().as_str() {
"a" => self.key_a = true,
"c" => self.key_c = true,
"x" => self.key_x = true,
"v" => self.key_v = true,
_ => {}
}
}
_ => {}
}
if let Some(text) = &event.text {
for ch in text.chars() {
if !ch.is_control() {
self.text_input.push(ch);
}
}
}
}
/// Set held-state for one arrow direction and emit a pulse on the first frame.
/// Shared helper for a 1-D axis with a deadzone.
///
/// Maps the signed axis value `v` onto two arrow directions (`neg_idx` fires
/// when `v < -DEADZONE`, `pos_idx` fires when `v > +DEADZONE`). Returns
/// `(neg_pulse, pos_pulse)` so callers can set the corresponding public bool.
fn axis_2d(&mut self, v: f32, neg_idx: usize, pos_idx: usize) -> (bool, bool) {
const DEADZONE: f32 = 0.3;
if v < -DEADZONE {
let pulse = !self.arrows[neg_idx].held;
self.arrows[neg_idx].held = true;
self.arrows[pos_idx].held = false;
self.arrows[pos_idx].timer = 0.0;
(pulse, false)
} else if v > DEADZONE {
let pulse = !self.arrows[pos_idx].held;
self.arrows[pos_idx].held = true;
self.arrows[neg_idx].held = false;
self.arrows[neg_idx].timer = 0.0;
(false, pulse)
} else {
self.arrows[neg_idx].held = false;
self.arrows[neg_idx].timer = 0.0;
self.arrows[pos_idx].held = false;
self.arrows[pos_idx].timer = 0.0;
(false, false)
}
}
/// Map `LeftStickX` / `DPadX` to left/right arrows.
fn axis_horizontal(&mut self, v: f32) {
let (l, r) = self.axis_2d(v, LEFT, RIGHT);
if l {
self.arrow_left = true;
}
if r {
self.arrow_right = true;
}
}
/// Map `LeftStickY` to up/down arrows. Positive Y = up on this axis.
fn axis_vertical_stick(&mut self, v: f32) {
// LeftStickY: positive = up, negative = down — so pos_idx = UP, neg_idx = DOWN.
let (d, u) = self.axis_2d(v, DOWN, UP);
if u {
self.arrow_up = true;
}
if d {
self.arrow_down = true;
}
}
/// Map `DPadY` to up/down arrows. Polarity is reversed vs. the stick: negative = up.
fn axis_dpad_y(&mut self, v: f32) {
// DPadY: negative = up, positive = down — opposite polarity to LeftStickY.
let (u, d) = self.axis_2d(v, UP, DOWN);
if u {
self.arrow_up = true;
}
if d {
self.arrow_down = true;
}
}
/// Advance one auto-repeat timer and set `pulse` if a repeat tick fires this frame.
///
/// After `initial` seconds held, a pulse fires every `rate` seconds. The
/// edge-detection uses floor division so the rate is constant regardless of
/// variable frame times.
fn tick_repeat(
held: bool,
timer: &mut f32,
pulse: &mut bool,
dt: f32,
initial: f32,
rate: f32,
) {
if !held {
*timer = 0.0;
return;
}
*timer += dt;
if *timer >= initial {
let repeat_t = *timer - initial;
let prev = (repeat_t - dt).max(0.0);
if (repeat_t / rate).floor() > (prev / rate).floor() {
*pulse = true;
}
}
}
}