retroglyph-window 0.4.1

Shared winit windowing layer for retroglyph's windowed backends
Documentation
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
//! winit-event -> retroglyph-event converters.
//!
//! Pure functions, unit-testable without a window.

use retroglyph_core::event::{
    Event, KeyCode, KeyEvent, KeyEventKind, KeyLocation, KeyModifiers, ModifierKey, MouseButton,
    PhysicalPos,
};
use retroglyph_core::grid::Pos;

/// Maps a winit logical [`Key`](winit::keyboard::Key) plus modifiers to a [`KeyCode`].
///
/// Split out from [`translate_key`] so this (the actual key-identity logic) is unit-testable
/// directly: `winit::event::KeyEvent` (the type `translate_key` takes) has a private
/// platform-specific field in the pinned winit version, so it can't be constructed in test code,
/// but `winit::keyboard::Key`/`NamedKey` are plain public enums a test can build directly.
fn key_code_from_logical(key: &winit::keyboard::Key, modifiers: KeyModifiers) -> Option<KeyCode> {
    use winit::keyboard::{Key, NamedKey};

    Some(match key {
        Key::Named(NamedKey::Enter) => KeyCode::Enter,
        Key::Named(NamedKey::Escape) => KeyCode::Escape,
        Key::Named(NamedKey::Backspace) => KeyCode::Backspace,
        Key::Named(NamedKey::Delete) => KeyCode::Delete,
        Key::Named(NamedKey::Insert) => KeyCode::Insert,
        // winit has no distinct "Shift+Tab" key value: `Tab` is reported with `modifiers.shift()`
        // set instead. Normalize that to `KeyCode::BackTab` here (rather than making every
        // consumer separately check `code == Tab && modifiers.contains(SHIFT)`) so the same
        // "Shift+Tab" gesture always arrives as one canonical code, matching the crossterm
        // backend's legacy `ESC[Z` -> `BackTab` behavior.
        Key::Named(NamedKey::Tab) if modifiers.contains(KeyModifiers::SHIFT) => KeyCode::BackTab,
        Key::Named(NamedKey::Tab) => KeyCode::Tab,
        // winit 0.30 still reports the spacebar as `NamedKey::Space` (a later winit version is
        // expected to switch to `Key::Character(" ")` per the UI Events spec, but that hasn't
        // shipped in the pinned 0.30 line): without this arm, every Space press silently falls
        // through to `_ => return None` and is dropped.
        Key::Named(NamedKey::Space) => KeyCode::Char(' '),
        Key::Named(NamedKey::ArrowUp) => KeyCode::Up,
        Key::Named(NamedKey::ArrowDown) => KeyCode::Down,
        Key::Named(NamedKey::ArrowLeft) => KeyCode::Left,
        Key::Named(NamedKey::ArrowRight) => KeyCode::Right,
        Key::Named(NamedKey::Home) => KeyCode::Home,
        Key::Named(NamedKey::End) => KeyCode::End,
        Key::Named(NamedKey::PageUp) => KeyCode::PageUp,
        Key::Named(NamedKey::PageDown) => KeyCode::PageDown,
        Key::Named(NamedKey::F1) => KeyCode::F(1),
        Key::Named(NamedKey::F2) => KeyCode::F(2),
        Key::Named(NamedKey::F3) => KeyCode::F(3),
        Key::Named(NamedKey::F4) => KeyCode::F(4),
        Key::Named(NamedKey::F5) => KeyCode::F(5),
        Key::Named(NamedKey::F6) => KeyCode::F(6),
        Key::Named(NamedKey::F7) => KeyCode::F(7),
        Key::Named(NamedKey::F8) => KeyCode::F(8),
        Key::Named(NamedKey::F9) => KeyCode::F(9),
        Key::Named(NamedKey::F10) => KeyCode::F(10),
        Key::Named(NamedKey::F11) => KeyCode::F(11),
        Key::Named(NamedKey::F12) => KeyCode::F(12),
        // Bare modifier presses. Side (left/right) is not carried here: it comes from winit's
        // own `KeyLocation` on the surrounding event, consulted once in `translate_key` via
        // `translate_key_location` rather than re-derived per key.
        Key::Named(NamedKey::Shift) => KeyCode::Modifier(ModifierKey::Shift),
        Key::Named(NamedKey::Control) => KeyCode::Modifier(ModifierKey::Control),
        Key::Named(NamedKey::Alt) => KeyCode::Modifier(ModifierKey::Alt),
        Key::Named(NamedKey::Super) => KeyCode::Modifier(ModifierKey::Super),
        Key::Named(NamedKey::CapsLock) => KeyCode::CapsLock,
        Key::Named(NamedKey::ScrollLock) => KeyCode::ScrollLock,
        Key::Named(NamedKey::NumLock) => KeyCode::NumLock,
        Key::Named(NamedKey::PrintScreen) => KeyCode::PrintScreen,
        Key::Named(NamedKey::Pause) => KeyCode::Pause,
        Key::Named(NamedKey::ContextMenu) => KeyCode::Menu,
        Key::Character(s) => KeyCode::Char(s.chars().next()?),
        _ => return None,
    })
}

/// Translates a winit [`Ime`](winit::event::Ime) event into an [`Event`].
///
/// Only [`Ime::Commit`](winit::event::Ime) carries a complete, atomic block of text: the same
/// shape as the crossterm backend's `Event::Paste` (see its handling of `crossterm::event::Event
/// ::Paste` in `crates/crossterm/src/lib.rs`), so a commit is mapped to [`Event::Paste`] rather
/// than adding a new `Event` variant: `Event` is `#[non_exhaustive]`, so a new variant would be
/// backward-compatible for exhaustive-matching consumers (per issue #267), but there is no need
/// for a new one when an existing variant already fits the shape of the data. `Ime::Enabled`,
/// `Ime::Preedit` (in-progress composition, not yet committed), and `Ime::Disabled` have no
/// existing-`Event` equivalent and are intentionally dropped: an app that wants live preedit
/// rendering is out of scope for this landable-sized change (see issue #296). An empty commit
/// (`Ime::Commit(String::new())`) is also dropped: winit can send an empty commit as part of
/// clearing composition state, and forwarding it would deliver a spurious empty paste.
#[must_use]
pub fn translate_ime(ime: winit::event::Ime) -> Option<Event> {
    match ime {
        winit::event::Ime::Commit(text) if !text.is_empty() => Some(Event::Paste(text)),
        _ => None,
    }
}

/// Translates a winit key event into an [`Event`].
///
/// Reports [`KeyEventKind::Press`], [`KeyEventKind::Repeat`] (winit's `repeat` flag), and
/// [`KeyEventKind::Release`]. Returns `None` only for keys we don't map.
#[must_use]
#[allow(clippy::needless_pass_by_value)]
pub fn translate_key(input: winit::event::KeyEvent, modifiers: KeyModifiers) -> Option<Event> {
    let kind = key_event_kind(input.state, input.repeat);
    let code = key_code_from_logical(&input.logical_key, modifiers)?;
    let location = translate_key_location(input.location);
    Some(Event::Key(KeyEvent::with_location(
        code, modifiers, kind, location,
    )))
}

/// Maps winit's [`KeyLocation`](winit::keyboard::KeyLocation) 1:1 onto our [`KeyLocation`].
#[must_use]
pub const fn translate_key_location(location: winit::keyboard::KeyLocation) -> KeyLocation {
    use winit::keyboard::KeyLocation as WL;
    match location {
        WL::Standard => KeyLocation::Standard,
        WL::Left => KeyLocation::Left,
        WL::Right => KeyLocation::Right,
        WL::Numpad => KeyLocation::Numpad,
    }
}

/// Converts a raw f64 cursor position to a [`PhysicalPos`].
///
/// `f64.max(0.0) as u32`: the `.max(0.0)` clamp makes sign loss intentional. Truncation of the
/// fractional part is also intentional: pixel coordinates are always integers.
#[must_use]
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
pub const fn physical_pos_from(x: f64, y: f64) -> PhysicalPos {
    PhysicalPos {
        x: x.max(0.0) as u32,
        y: y.max(0.0) as u32,
    }
}

/// Converts physical pixel coordinates to a grid cell [`Pos`].
///
/// Clamps to `u16::MAX` so out-of-bounds cursor positions (negative or extremely large) don't
/// panic: the game loop is responsible for bounds-checking against the terminal size.
#[must_use]
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
pub fn pixel_to_cell(px_x: f64, px_y: f64, cell_w: u32, cell_h: u32) -> Pos {
    // .max(0.0) guards against negatives before the f64→u32 cast.
    // .min(u16::MAX as u32) guarantees the u32→u16 cast never truncates.
    let col =
        u32::checked_div(px_x.max(0.0) as u32, cell_w).map_or(0, |v| v.min(u32::from(u16::MAX)));
    let col = u16::try_from(col).unwrap_or(u16::MAX);
    let row =
        u32::checked_div(px_y.max(0.0) as u32, cell_h).map_or(0, |v| v.min(u32::from(u16::MAX)));
    let row = u16::try_from(row).unwrap_or(u16::MAX);
    Pos { x: col, y: row }
}

/// Translates a winit [`winit::event::MouseButton`] into our [`MouseButton`].
///
/// Returns `None` for side buttons and other unrecognized buttons.
#[must_use]
pub const fn translate_mouse_button(button: winit::event::MouseButton) -> Option<MouseButton> {
    match button {
        winit::event::MouseButton::Left => Some(MouseButton::Left),
        winit::event::MouseButton::Right => Some(MouseButton::Right),
        winit::event::MouseButton::Middle => Some(MouseButton::Middle),
        _ => None,
    }
}

/// Maps a winit key `state`/`repeat` pair to a [`KeyEventKind`].
#[must_use]
pub const fn key_event_kind(state: winit::event::ElementState, repeat: bool) -> KeyEventKind {
    use winit::event::ElementState;
    match (state, repeat) {
        (ElementState::Pressed, false) => KeyEventKind::Press,
        (ElementState::Pressed, true) => KeyEventKind::Repeat,
        (ElementState::Released, _) => KeyEventKind::Release,
    }
}

/// Translates winit modifier state into our [`KeyModifiers`].
#[must_use]
pub fn translate_modifiers(state: winit::keyboard::ModifiersState) -> KeyModifiers {
    let mut m = KeyModifiers::NONE;
    if state.shift_key() {
        m |= KeyModifiers::SHIFT;
    }
    if state.control_key() {
        m |= KeyModifiers::CONTROL;
    }
    if state.alt_key() {
        m |= KeyModifiers::ALT;
    }
    if state.super_key() {
        m |= KeyModifiers::SUPER;
    }
    m
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── key_code_from_logical ─────────────────────────────────────────────────

    #[test]
    fn space_maps_to_char_space() {
        // Regression test: winit 0.30 reports the spacebar as `NamedKey::Space`, not
        // `Key::Character(" ")`: without a dedicated arm this silently mapped to `None` and
        // every Space press was dropped.
        let key = winit::keyboard::Key::Named(winit::keyboard::NamedKey::Space);
        assert_eq!(
            key_code_from_logical(&key, KeyModifiers::NONE),
            Some(KeyCode::Char(' '))
        );
    }

    #[test]
    fn shift_tab_normalizes_to_backtab() {
        // Regression test: winit has no distinct "Shift+Tab" key value: it reports `Tab` with
        // the shift modifier set instead, which has to be normalized to `KeyCode::BackTab` here
        // (matching the crossterm backend's legacy `ESC[Z` -> `BackTab` behavior) or every
        // consumer of the event stream sees indistinguishable plain-Tab and Shift+Tab presses.
        let key = winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab);
        assert_eq!(
            key_code_from_logical(&key, KeyModifiers::SHIFT),
            Some(KeyCode::BackTab)
        );
    }

    #[test]
    fn plain_tab_is_unaffected() {
        let key = winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab);
        assert_eq!(
            key_code_from_logical(&key, KeyModifiers::NONE),
            Some(KeyCode::Tab)
        );
    }

    #[test]
    fn shift_modifier_on_non_tab_keys_is_unaffected() {
        let key = winit::keyboard::Key::Character("a".into());
        assert_eq!(
            key_code_from_logical(&key, KeyModifiers::SHIFT),
            Some(KeyCode::Char('a'))
        );
    }

    #[test]
    fn left_shift_alone_maps_to_modifier_shift_with_left_location() {
        // `translate_key` itself can't be constructed directly in tests (see this module's doc
        // comment on `key_code_from_logical`), so the round trip is exercised as its two parts:
        // the key-identity mapping here, and `translate_key_location` below.
        let key = winit::keyboard::Key::Named(winit::keyboard::NamedKey::Shift);
        assert_eq!(
            key_code_from_logical(&key, KeyModifiers::SHIFT),
            Some(KeyCode::Modifier(ModifierKey::Shift))
        );
        assert_eq!(
            translate_key_location(winit::keyboard::KeyLocation::Left),
            KeyLocation::Left
        );
    }

    #[test]
    fn caps_lock_maps_straight_through() {
        let key = winit::keyboard::Key::Named(winit::keyboard::NamedKey::CapsLock);
        assert_eq!(
            key_code_from_logical(&key, KeyModifiers::NONE),
            Some(KeyCode::CapsLock)
        );
    }

    #[test]
    fn unmapped_key_returns_none() {
        let key = winit::keyboard::Key::Named(winit::keyboard::NamedKey::AudioVolumeUp);
        assert_eq!(key_code_from_logical(&key, KeyModifiers::NONE), None);
    }

    // ── translate_ime ─────────────────────────────────────────────────────────

    #[test]
    fn ime_commit_maps_to_paste_event() {
        let ime = winit::event::Ime::Commit("hello".to_string());
        assert_eq!(translate_ime(ime), Some(Event::Paste("hello".to_string())));
    }

    #[test]
    fn ime_empty_commit_produces_no_event() {
        // winit can send an empty commit while clearing composition state; forwarding it would
        // deliver a spurious empty paste.
        let ime = winit::event::Ime::Commit(String::new());
        assert_eq!(translate_ime(ime), None);
    }

    #[test]
    fn ime_enabled_produces_no_event() {
        assert_eq!(translate_ime(winit::event::Ime::Enabled), None);
    }

    #[test]
    fn ime_disabled_produces_no_event() {
        assert_eq!(translate_ime(winit::event::Ime::Disabled), None);
    }

    #[test]
    fn ime_preedit_produces_no_event() {
        // In-progress composition text (not yet committed) has no `Event` equivalent; only a
        // completed `Commit` is forwarded.
        let ime = winit::event::Ime::Preedit("nihon".to_string(), Some((0, 5)));
        assert_eq!(translate_ime(ime), None);
    }

    // ── pixel_to_cell ─────────────────────────────────────────────────────────

    #[test]
    fn pixel_to_cell_basic() {
        // 8×16 cells: pixel (20, 48) → col 2, row 3
        let pos = pixel_to_cell(20.0, 48.0, 8, 16);
        assert_eq!(pos, Pos { x: 2, y: 3 });
    }

    #[test]
    fn pixel_to_cell_origin() {
        let pos = pixel_to_cell(0.0, 0.0, 8, 16);
        assert_eq!(pos, Pos { x: 0, y: 0 });
    }

    #[test]
    fn pixel_to_cell_negative_coords_clamp_to_zero() {
        // Cursor briefly outside the window can produce negative physical coords.
        let pos = pixel_to_cell(-5.0, -10.0, 8, 16);
        assert_eq!(pos, Pos { x: 0, y: 0 });
    }

    #[test]
    fn pixel_to_cell_zero_cell_size_returns_origin() {
        // Degenerate case: backend not yet initialised with a valid cell size.
        let pos = pixel_to_cell(100.0, 200.0, 0, 0);
        assert_eq!(pos, Pos { x: 0, y: 0 });
    }

    #[test]
    fn pixel_to_cell_clamps_to_u16_max() {
        // A huge pixel coordinate must not overflow u16.
        let pos = pixel_to_cell(f64::from(u32::MAX), f64::from(u32::MAX), 1, 1);
        assert_eq!(
            pos,
            Pos {
                x: u16::MAX,
                y: u16::MAX
            }
        );
    }

    // ── translate_modifiers ──────────────────────────────────────────────────

    #[test]
    fn translate_modifiers_none() {
        let state = winit::keyboard::ModifiersState::empty();
        assert_eq!(translate_modifiers(state), KeyModifiers::NONE);
    }

    #[test]
    fn translate_modifiers_super_only() {
        let state = winit::keyboard::ModifiersState::SUPER;
        let mods = translate_modifiers(state);
        assert!(mods.contains(KeyModifiers::SUPER));
        assert!(!mods.contains(KeyModifiers::SHIFT));
        assert!(!mods.contains(KeyModifiers::CONTROL));
        assert!(!mods.contains(KeyModifiers::ALT));
    }

    #[test]
    fn translate_modifiers_super_without_super_key() {
        let state = winit::keyboard::ModifiersState::SHIFT;
        let mods = translate_modifiers(state);
        assert!(!mods.contains(KeyModifiers::SUPER));
    }

    #[test]
    fn translate_modifiers_super_combined_with_shift() {
        let state = winit::keyboard::ModifiersState::SUPER | winit::keyboard::ModifiersState::SHIFT;
        let mods = translate_modifiers(state);
        assert!(mods.contains(KeyModifiers::SUPER));
        assert!(mods.contains(KeyModifiers::SHIFT));
        assert!(!mods.contains(KeyModifiers::CONTROL));
        assert!(!mods.contains(KeyModifiers::ALT));
    }

    #[test]
    fn translate_modifiers_all_together() {
        let state = winit::keyboard::ModifiersState::SHIFT
            | winit::keyboard::ModifiersState::CONTROL
            | winit::keyboard::ModifiersState::ALT
            | winit::keyboard::ModifiersState::SUPER;
        let mods = translate_modifiers(state);
        assert!(mods.contains(KeyModifiers::SHIFT));
        assert!(mods.contains(KeyModifiers::CONTROL));
        assert!(mods.contains(KeyModifiers::ALT));
        assert!(mods.contains(KeyModifiers::SUPER));
    }

    // ── key_event_kind ────────────────────────────────────────────────────────

    #[test]
    fn key_event_kind_press_repeat_release() {
        use winit::event::ElementState;
        assert_eq!(
            key_event_kind(ElementState::Pressed, false),
            KeyEventKind::Press
        );
        assert_eq!(
            key_event_kind(ElementState::Pressed, true),
            KeyEventKind::Repeat
        );
        assert_eq!(
            key_event_kind(ElementState::Released, false),
            KeyEventKind::Release
        );
        // A release is a release regardless of the repeat flag.
        assert_eq!(
            key_event_kind(ElementState::Released, true),
            KeyEventKind::Release
        );
    }

    // ── translate_key_location ────────────────────────────────────────────────

    #[test]
    fn translate_key_location_maps_all_variants() {
        use winit::keyboard::KeyLocation as WL;
        assert_eq!(translate_key_location(WL::Standard), KeyLocation::Standard);
        assert_eq!(translate_key_location(WL::Left), KeyLocation::Left);
        assert_eq!(translate_key_location(WL::Right), KeyLocation::Right);
        assert_eq!(translate_key_location(WL::Numpad), KeyLocation::Numpad);
    }

    // ── translate_mouse_button ────────────────────────────────────────────────

    #[test]
    fn translate_mouse_button_left() {
        assert_eq!(
            translate_mouse_button(winit::event::MouseButton::Left),
            Some(MouseButton::Left)
        );
    }

    #[test]
    fn translate_mouse_button_right() {
        assert_eq!(
            translate_mouse_button(winit::event::MouseButton::Right),
            Some(MouseButton::Right)
        );
    }

    #[test]
    fn translate_mouse_button_middle() {
        assert_eq!(
            translate_mouse_button(winit::event::MouseButton::Middle),
            Some(MouseButton::Middle)
        );
    }

    #[test]
    fn translate_mouse_button_other_is_none() {
        assert_eq!(
            translate_mouse_button(winit::event::MouseButton::Back),
            None
        );
        assert_eq!(
            translate_mouse_button(winit::event::MouseButton::Forward),
            None
        );
        assert_eq!(
            translate_mouse_button(winit::event::MouseButton::Other(7)),
            None
        );
    }
}