damascene_winit/lib.rs
1//! Pure winit → damascene input mappers.
2//!
3//! Leaf translation functions with no host state — a custom
4//! `ApplicationHandler` calls these from its own `window_event` to
5//! produce the values `damascene_core`'s runtime input methods expect.
6//! They are render-backend-neutral: the in-tree wgpu host routes every
7//! event through these same functions, and vulkano / ash / out-of-tree
8//! hosts use them without pulling in any GPU stack (this crate depends
9//! on `damascene-core` and `winit` only — see issue #121).
10//!
11//! Since the three-facet key model (#114) the mappings are total tables
12//! over the W3C named-key and physical-code vocabularies; the tests here
13//! assert that coverage against `damascene_core`'s `ALL` consts, so a
14//! new core variant fails this crate's tests instead of silently
15//! degrading to `Unidentified` in every host.
16//!
17//! Note the winit version coupling: these signatures take this crate's
18//! winit types, so a host must use the same winit major version
19//! (re-check `Cargo.toml` on upgrades).
20
21#![warn(missing_docs)]
22
23use damascene_core::{Cursor, KeyModifiers, LogicalKey, NamedKey, PhysicalKey, PointerButton};
24use winit::event::{Force, MouseButton};
25use winit::keyboard::{Key, KeyCode, NamedKey as WinitNamedKey, PhysicalKey as WinitPhysicalKey};
26use winit::window::CursorIcon;
27
28/// X-macro table of the named keys winit and damascene share — every
29/// entry is a same-named pair (both vocabularies mirror the W3C `key`
30/// spec), applied by [`map_key`]'s translation match and re-applied by
31/// the totality test to prove the table reaches all of
32/// [`NamedKey::ALL`].
33macro_rules! for_each_named_key {
34 ($apply:ident) => {
35 $apply! {
36 // Modifier keys.
37 Alt,
38 AltGraph,
39 CapsLock,
40 Control,
41 Fn,
42 FnLock,
43 Meta,
44 NumLock,
45 ScrollLock,
46 Shift,
47 Super,
48 Hyper,
49 Symbol,
50 // Whitespace / editing / navigation.
51 Enter,
52 Tab,
53 Space,
54 ArrowDown,
55 ArrowLeft,
56 ArrowRight,
57 ArrowUp,
58 End,
59 Home,
60 PageDown,
61 PageUp,
62 Backspace,
63 Clear,
64 Copy,
65 CrSel,
66 Cut,
67 Delete,
68 EraseEof,
69 ExSel,
70 Insert,
71 Paste,
72 Redo,
73 Undo,
74 // General-purpose / UI.
75 Accept,
76 Again,
77 Cancel,
78 ContextMenu,
79 Escape,
80 Execute,
81 Find,
82 Help,
83 Pause,
84 Play,
85 Props,
86 Select,
87 ZoomIn,
88 ZoomOut,
89 // Device.
90 Eject,
91 Power,
92 PrintScreen,
93 WakeUp,
94 // Common media keys.
95 AudioVolumeDown,
96 AudioVolumeMute,
97 AudioVolumeUp,
98 MediaPlayPause,
99 MediaStop,
100 MediaTrackNext,
101 MediaTrackPrevious,
102 // Function keys.
103 F1,
104 F2,
105 F3,
106 F4,
107 F5,
108 F6,
109 F7,
110 F8,
111 F9,
112 F10,
113 F11,
114 F12,
115 F13,
116 F14,
117 F15,
118 F16,
119 F17,
120 F18,
121 F19,
122 F20,
123 F21,
124 F22,
125 F23,
126 F24,
127 }
128 };
129}
130
131/// X-macro table of the physical codes winit and damascene spell
132/// identically (both follow the W3C `code` spec). The few codes whose
133/// spellings differ are bridged explicitly in [`map_physical`], and the
134/// totality test proves table + bridges reach all of
135/// [`PhysicalKey::ALL`].
136macro_rules! for_each_physical_key {
137 ($apply:ident) => {
138 $apply! {
139 // Writing-system keys.
140 Backquote,
141 Backslash,
142 BracketLeft,
143 BracketRight,
144 Comma,
145 Digit0,
146 Digit1,
147 Digit2,
148 Digit3,
149 Digit4,
150 Digit5,
151 Digit6,
152 Digit7,
153 Digit8,
154 Digit9,
155 Equal,
156 IntlBackslash,
157 IntlRo,
158 IntlYen,
159 KeyA,
160 KeyB,
161 KeyC,
162 KeyD,
163 KeyE,
164 KeyF,
165 KeyG,
166 KeyH,
167 KeyI,
168 KeyJ,
169 KeyK,
170 KeyL,
171 KeyM,
172 KeyN,
173 KeyO,
174 KeyP,
175 KeyQ,
176 KeyR,
177 KeyS,
178 KeyT,
179 KeyU,
180 KeyV,
181 KeyW,
182 KeyX,
183 KeyY,
184 KeyZ,
185 Minus,
186 Period,
187 Quote,
188 Semicolon,
189 Slash,
190 // Functional keys.
191 AltLeft,
192 AltRight,
193 Backspace,
194 CapsLock,
195 ContextMenu,
196 ControlLeft,
197 ControlRight,
198 Enter,
199 ShiftLeft,
200 ShiftRight,
201 Space,
202 Tab,
203 // Control pad / arrows.
204 Delete,
205 End,
206 Help,
207 Home,
208 Insert,
209 PageDown,
210 PageUp,
211 ArrowDown,
212 ArrowLeft,
213 ArrowRight,
214 ArrowUp,
215 // Numpad.
216 NumLock,
217 Numpad0,
218 Numpad1,
219 Numpad2,
220 Numpad3,
221 Numpad4,
222 Numpad5,
223 Numpad6,
224 Numpad7,
225 Numpad8,
226 Numpad9,
227 NumpadAdd,
228 NumpadBackspace,
229 NumpadClear,
230 NumpadComma,
231 NumpadDecimal,
232 NumpadDivide,
233 NumpadEnter,
234 NumpadEqual,
235 NumpadMultiply,
236 NumpadParenLeft,
237 NumpadParenRight,
238 NumpadSubtract,
239 // System / function.
240 Escape,
241 PrintScreen,
242 ScrollLock,
243 Pause,
244 F1,
245 F2,
246 F3,
247 F4,
248 F5,
249 F6,
250 F7,
251 F8,
252 F9,
253 F10,
254 F11,
255 F12,
256 F13,
257 F14,
258 F15,
259 F16,
260 F17,
261 F18,
262 F19,
263 F20,
264 F21,
265 F22,
266 F23,
267 F24,
268 }
269 };
270}
271
272/// Translate a winit logical [`Key`] to a damascene [`LogicalKey`] — the
273/// key's layout-dependent meaning.
274///
275/// Named keys map onto [`NamedKey`] (the W3C `key` named set), printable
276/// input becomes [`LogicalKey::Character`], and anything without a logical
277/// meaning damascene models — dead keys, unmapped/rare named keys —
278/// becomes [`LogicalKey::Unidentified`]. The mapping is total (no `None`):
279/// a key with no logical identity can still carry a useful
280/// [physical][`map_physical`] one, so the caller decides whether to
281/// dispatch based on both facets rather than dropping the event here.
282pub fn map_key(key: &Key) -> LogicalKey {
283 match key {
284 Key::Named(named) => match map_named(named) {
285 Some(n) => LogicalKey::Named(n),
286 None => LogicalKey::Unidentified,
287 },
288 Key::Character(s) => LogicalKey::Character(s.to_string()),
289 _ => LogicalKey::Unidentified,
290 }
291}
292
293/// Map a winit [`NamedKey`](WinitNamedKey) to damascene's [`NamedKey`].
294/// The shared names map 1:1 through [`for_each_named_key!`]; names
295/// damascene does not (yet) model return `None` and surface as
296/// [`LogicalKey::Unidentified`].
297fn map_named(named: &WinitNamedKey) -> Option<NamedKey> {
298 macro_rules! same {
299 ($($v:ident),+ $(,)?) => {
300 Some(match named {
301 $( WinitNamedKey::$v => NamedKey::$v, )+
302 _ => return None,
303 })
304 };
305 }
306 for_each_named_key!(same)
307}
308
309/// Translate a winit [`PhysicalKey`](WinitPhysicalKey) to a damascene
310/// [`PhysicalKey`] — the layout-independent board position (W3C `code`).
311///
312/// winit's [`KeyCode`] follows the same W3C `code` spec, so the shared
313/// names map 1:1 through `for_each_physical_key!`; the few that differ
314/// in spelling (winit's `SuperLeft`/`SuperRight` are the W3C
315/// `MetaLeft`/`MetaRight`; `NumpadStar` is `NumpadMultiply`) are bridged
316/// explicitly. Native / unmapped codes become
317/// [`PhysicalKey::Unidentified`].
318pub fn map_physical(physical: WinitPhysicalKey) -> PhysicalKey {
319 let code = match physical {
320 WinitPhysicalKey::Code(code) => code,
321 WinitPhysicalKey::Unidentified(_) => return PhysicalKey::Unidentified,
322 };
323 macro_rules! same {
324 ($($v:ident),+ $(,)?) => {
325 match code {
326 $( KeyCode::$v => PhysicalKey::$v, )+
327 // Spelling bridges (winit → W3C `code`).
328 KeyCode::SuperLeft => PhysicalKey::MetaLeft,
329 KeyCode::SuperRight => PhysicalKey::MetaRight,
330 KeyCode::NumpadStar => PhysicalKey::NumpadMultiply,
331 _ => PhysicalKey::Unidentified,
332 }
333 };
334 }
335 for_each_physical_key!(same)
336}
337
338/// Translate a winit [`MouseButton`] to a damascene [`PointerButton`].
339pub fn pointer_button(b: MouseButton) -> Option<PointerButton> {
340 match b {
341 MouseButton::Left => Some(PointerButton::Primary),
342 MouseButton::Right => Some(PointerButton::Secondary),
343 MouseButton::Middle => Some(PointerButton::Middle),
344 // Back / Forward / Other → not surfaced; apps that need them can
345 // grow the enum.
346 _ => None,
347 }
348}
349
350/// Normalize a winit touch [`Force`] to the `[0, 1]` pressure value
351/// `Pointer::with_pressure` expects. `None` in, `None` out — winit
352/// reports no force on platforms/devices without a pressure sensor.
353pub fn touch_pressure(force: Option<Force>) -> Option<f32> {
354 match force? {
355 Force::Calibrated {
356 force,
357 max_possible_force,
358 ..
359 } if max_possible_force > 0.0 => Some((force / max_possible_force).clamp(0.0, 1.0) as f32),
360 Force::Calibrated { force, .. } => Some(force.clamp(0.0, 1.0) as f32),
361 Force::Normalized(v) => Some(v.clamp(0.0, 1.0) as f32),
362 }
363}
364
365/// Translate a damascene [`Cursor`] to winit's [`CursorIcon`]. The
366/// damascene enum is a subset of winit's so this stays a 1:1 map; the
367/// wildcard arm is a forward-compat safety net (damascene's `Cursor` is
368/// `non_exhaustive` — add a new variant in core, add the matching arm
369/// here, otherwise it falls back to the platform default; the test
370/// against [`Cursor::ALL`] catches the gap).
371///
372/// Equivalent alternative without this crate: `Cursor::css_name()` in
373/// damascene-core parses straight into winit's `CursorIcon`
374/// (`cursor.css_name().parse::<CursorIcon>().unwrap_or_default()`).
375pub fn winit_cursor(cursor: Cursor) -> CursorIcon {
376 match cursor {
377 Cursor::Default => CursorIcon::Default,
378 Cursor::Pointer => CursorIcon::Pointer,
379 Cursor::Text => CursorIcon::Text,
380 Cursor::NotAllowed => CursorIcon::NotAllowed,
381 Cursor::Grab => CursorIcon::Grab,
382 Cursor::Grabbing => CursorIcon::Grabbing,
383 Cursor::Move => CursorIcon::Move,
384 Cursor::EwResize => CursorIcon::EwResize,
385 Cursor::NsResize => CursorIcon::NsResize,
386 Cursor::NwseResize => CursorIcon::NwseResize,
387 Cursor::NeswResize => CursorIcon::NeswResize,
388 Cursor::ColResize => CursorIcon::ColResize,
389 Cursor::RowResize => CursorIcon::RowResize,
390 Cursor::Crosshair => CursorIcon::Crosshair,
391 _ => CursorIcon::Default,
392 }
393}
394
395/// Translate winit's [`ModifiersState`](winit::keyboard::ModifiersState)
396/// to damascene [`KeyModifiers`].
397pub fn key_modifiers(mods: winit::keyboard::ModifiersState) -> KeyModifiers {
398 KeyModifiers {
399 shift: mods.shift_key(),
400 ctrl: mods.control_key(),
401 alt: mods.alt_key(),
402 logo: mods.super_key(),
403 }
404}
405
406#[cfg(test)]
407mod tests {
408 use super::*;
409
410 /// Every named key core models must be reachable from the winit key
411 /// of the same W3C name. When core grows a variant, `NamedKey::ALL`
412 /// grows with it (same macro listing) and this fails until the
413 /// [`for_each_named_key!`] table gains the entry — instead of the
414 /// key silently degrading to `Unidentified` in every winit host.
415 #[test]
416 fn map_named_covers_every_core_named_key() {
417 macro_rules! as_slice {
418 ($($v:ident),+ $(,)?) => { &[ $(NamedKey::$v),+ ] };
419 }
420 let table: &[NamedKey] = for_each_named_key!(as_slice);
421 for k in NamedKey::ALL {
422 assert!(
423 table.contains(k),
424 "NamedKey::{k:?} is unreachable from winit — extend for_each_named_key!"
425 );
426 }
427 }
428
429 /// Every physical key core models must be reachable from some winit
430 /// `KeyCode` — via the same-spelling table, a spelling bridge, or
431 /// the no-position fallback. Same rot guard as the named-key test.
432 #[test]
433 fn map_physical_covers_every_core_physical_key() {
434 macro_rules! as_slice {
435 ($($v:ident),+ $(,)?) => { &[ $(PhysicalKey::$v),+ ] };
436 }
437 let table: &[PhysicalKey] = for_each_physical_key!(as_slice);
438 for k in PhysicalKey::ALL {
439 let covered = table.contains(k)
440 || matches!(
441 k,
442 // Bridged from winit's `SuperLeft`/`SuperRight` spelling.
443 PhysicalKey::MetaLeft | PhysicalKey::MetaRight
444 // Produced by the `WinitPhysicalKey::Unidentified` arm.
445 | PhysicalKey::Unidentified
446 );
447 assert!(
448 covered,
449 "PhysicalKey::{k:?} is unreachable from winit — extend for_each_physical_key! (or the bridges in map_physical)"
450 );
451 }
452 }
453
454 /// `winit_cursor` and `Cursor::css_name()` are two spellings of
455 /// the same mapping — winit's `CursorIcon` parses CSS cursor
456 /// names, so the table here must agree with core's names or the
457 /// wgpu-free path drifts. Iterating `Cursor::ALL` also makes this
458 /// the totality guard: a new core cursor variant hits the
459 /// wildcard `Default` arm and mismatches its parsed CSS name.
460 #[test]
461 fn winit_cursor_agrees_with_css_name_parsing() {
462 for cursor in Cursor::ALL {
463 let parsed: CursorIcon = cursor
464 .css_name()
465 .parse()
466 .unwrap_or_else(|_| panic!("css_name {:?} should parse", cursor.css_name()));
467 assert_eq!(parsed, winit_cursor(*cursor), "variant {cursor:?}");
468 }
469 }
470
471 /// winit's `KeyCode` and damascene's `PhysicalKey` both mirror the W3C
472 /// `code` set, but a few names differ in spelling — those bridges are
473 /// the only thing that can silently rot, so pin them.
474 #[test]
475 fn map_physical_bridges_winit_spelling_to_w3c() {
476 let code = |c| map_physical(WinitPhysicalKey::Code(c));
477 assert_eq!(code(KeyCode::SuperLeft), PhysicalKey::MetaLeft);
478 assert_eq!(code(KeyCode::SuperRight), PhysicalKey::MetaRight);
479 assert_eq!(code(KeyCode::NumpadStar), PhysicalKey::NumpadMultiply);
480 // 1:1 names pass straight through, and numpad vs main row stay
481 // distinct (the whole point of exposing physical identity).
482 assert_eq!(code(KeyCode::KeyA), PhysicalKey::KeyA);
483 assert_eq!(code(KeyCode::Numpad1), PhysicalKey::Numpad1);
484 assert_ne!(code(KeyCode::Digit1), code(KeyCode::Numpad1));
485 // A native scancode with no W3C `code` is Unidentified, never a
486 // host-formatted string.
487 assert_eq!(
488 map_physical(WinitPhysicalKey::Unidentified(
489 winit::keyboard::NativeKeyCode::Unidentified
490 )),
491 PhysicalKey::Unidentified
492 );
493 }
494
495 /// A named key damascene does not model must surface as
496 /// `Unidentified`, never the old `Debug`-string fallback.
497 #[test]
498 fn map_key_unmapped_named_is_unidentified() {
499 assert_eq!(
500 map_key(&Key::Named(WinitNamedKey::LaunchMail)),
501 LogicalKey::Unidentified
502 );
503 assert_eq!(
504 map_key(&Key::Named(WinitNamedKey::Enter)),
505 LogicalKey::Named(NamedKey::Enter)
506 );
507 }
508}