Skip to main content

repose_core/
input.rs

1use crate::Vec2;
2use std::cell::Cell;
3use std::collections::{HashMap, HashSet};
4use std::rc::Rc;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7pub struct PointerId(pub u64);
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum PointerKind {
11    Mouse,
12    Touch,
13    Pen,
14}
15
16/// What produced a scroll delta.
17///
18/// A wheel notch and a one-finger drag are the same `Vec2` by the time they
19/// reach a handler, which is why a canvas cannot decide "zoom" from the value
20/// alone. Two-finger pan and pinch are *not* scrolls: they arrive as
21/// [`crate::shortcuts::Gesture`] actions instead.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
23pub enum ScrollSource {
24    /// A mouse wheel or trackpad.
25    Wheel,
26    /// A single-finger drag across a surface.
27    Touch,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
31pub enum PointerButton {
32    Primary,   // Left mouse, touch
33    Secondary, // Right mouse
34    Tertiary,  // Middle mouse
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum PointerEventPass {
39    /// Top-down pass: ancestor -> descendant. Allows ancestors to preview or
40    /// intercept events before descendants see them.
41    Initial,
42    /// Bottom-up pass: descendant -> ancestor. The primary pass where gesture
43    /// handlers react to and consume events. A child that consumes its event
44    /// prevents the parent from reacting (Compose's requireUnconsumed).
45    Main,
46    /// Top-down pass: ancestor -> descendant. Allows descendants to learn
47    /// about events consumed by ancestors during the Main pass.
48    Final,
49}
50
51#[derive(Clone, Copy, Debug)]
52pub enum PointerEventKind {
53    Down(PointerButton),
54    Up(PointerButton),
55    Move,
56    Cancel,
57    Enter,
58    Leave,
59}
60
61#[derive(Clone, Debug)]
62pub struct PointerEvent {
63    pub id: PointerId,
64    pub kind: PointerKind,
65    pub event: PointerEventKind,
66    /// Position relative to `origin` (hit-region top-left), in physical px.
67    pub position: Vec2,
68    /// Top-left of the hit region this event is being delivered to (physical px).
69    pub origin: Vec2,
70    /// Absolute pointer position in window/surface physical pixels.
71    pub window_position: Vec2,
72    pub pressure: f32,
73    pub modifiers: Modifiers,
74    /// Shared consumed state -> every clone of this event points to the same
75    /// Cell. Calling `consume()` on any clone marks it consumed for all clones.
76    pub consumed: Rc<Cell<bool>>,
77}
78
79impl PointerEvent {
80    pub fn new(
81        id: PointerId,
82        kind: PointerKind,
83        event: PointerEventKind,
84        position: Vec2,
85        pressure: f32,
86        modifiers: Modifiers,
87    ) -> Self {
88        Self {
89            id,
90            kind,
91            event,
92            position,
93            origin: Vec2::ZERO,
94            window_position: position,
95            pressure,
96            modifiers,
97            consumed: Rc::new(Cell::new(false)),
98        }
99    }
100
101    /// Absolute position in window/surface physical pixels.
102    pub fn position_in_window(&self) -> Vec2 {
103        self.window_position
104    }
105
106    /// Mark this event as consumed. Once consumed, subsequent handlers in the
107    /// same pass should skip processing it (equivalent to Compose's
108    /// `PointerInputChange.consume()`).
109    pub fn consume(&self) {
110        self.consumed.set(true);
111    }
112
113    /// Returns `true` if `consume()` was called on this event or any clone of it.
114    pub fn is_consumed(&self) -> bool {
115        self.consumed.get()
116    }
117}
118
119#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
120pub struct Modifiers {
121    pub shift: bool,
122    pub ctrl: bool,
123    pub alt: bool,
124    pub meta: bool,    // Cmd on Mac, Win key on Windows
125    pub command: bool, // egui like (Cmd on macOS, Ctrl elsewhere)
126}
127
128/// Physical key position, layout-independent (W3C `KeyboardEvent.code`)
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
130pub enum PhysicalKey {
131    KeyA,
132    KeyB,
133    KeyC,
134    KeyD,
135    KeyE,
136    KeyF,
137    KeyG,
138    KeyH,
139    KeyI,
140    KeyJ,
141    KeyK,
142    KeyL,
143    KeyM,
144    KeyN,
145    KeyO,
146    KeyP,
147    KeyQ,
148    KeyR,
149    KeyS,
150    KeyT,
151    KeyU,
152    KeyV,
153    KeyW,
154    KeyX,
155    KeyY,
156    KeyZ,
157    Digit0,
158    Digit1,
159    Digit2,
160    Digit3,
161    Digit4,
162    Digit5,
163    Digit6,
164    Digit7,
165    Digit8,
166    Digit9,
167    Minus,
168    Equal,
169    BracketLeft,
170    BracketRight,
171    Backslash,
172    Semicolon,
173    Quote,
174    Backquote,
175    Comma,
176    Period,
177    Slash,
178    IntlBackslash,
179    IntlRo,
180    IntlYen,
181    Escape,
182    F1,
183    F2,
184    F3,
185    F4,
186    F5,
187    F6,
188    F7,
189    F8,
190    F9,
191    F10,
192    F11,
193    F12,
194    PrintScreen,
195    ScrollLock,
196    Pause,
197    Insert,
198    Home,
199    PageUp,
200    Delete,
201    End,
202    PageDown,
203    ArrowRight,
204    ArrowLeft,
205    ArrowDown,
206    ArrowUp,
207    NumLock,
208    NumpadDivide,
209    NumpadMultiply,
210    NumpadSubtract,
211    NumpadAdd,
212    NumpadEnter,
213    NumpadDecimal,
214    Numpad0,
215    Numpad1,
216    Numpad2,
217    Numpad3,
218    Numpad4,
219    Numpad5,
220    Numpad6,
221    Numpad7,
222    Numpad8,
223    Numpad9,
224    Backspace,
225    Tab,
226    Space,
227    CapsLock,
228    Enter,
229    ShiftLeft,
230    ShiftRight,
231    ControlLeft,
232    ControlRight,
233    AltLeft,
234    AltRight,
235    SuperLeft,
236    SuperRight,
237    ContextMenu,
238    Unidentified,
239}
240
241impl PhysicalKey {
242    /// W3C `code` name (`KeyW`, `Digit1`, `Space`, ...).
243    pub fn name(self) -> &'static str {
244        match self {
245            PhysicalKey::KeyA => "KeyA",
246            PhysicalKey::KeyB => "KeyB",
247            PhysicalKey::KeyC => "KeyC",
248            PhysicalKey::KeyD => "KeyD",
249            PhysicalKey::KeyE => "KeyE",
250            PhysicalKey::KeyF => "KeyF",
251            PhysicalKey::KeyG => "KeyG",
252            PhysicalKey::KeyH => "KeyH",
253            PhysicalKey::KeyI => "KeyI",
254            PhysicalKey::KeyJ => "KeyJ",
255            PhysicalKey::KeyK => "KeyK",
256            PhysicalKey::KeyL => "KeyL",
257            PhysicalKey::KeyM => "KeyM",
258            PhysicalKey::KeyN => "KeyN",
259            PhysicalKey::KeyO => "KeyO",
260            PhysicalKey::KeyP => "KeyP",
261            PhysicalKey::KeyQ => "KeyQ",
262            PhysicalKey::KeyR => "KeyR",
263            PhysicalKey::KeyS => "KeyS",
264            PhysicalKey::KeyT => "KeyT",
265            PhysicalKey::KeyU => "KeyU",
266            PhysicalKey::KeyV => "KeyV",
267            PhysicalKey::KeyW => "KeyW",
268            PhysicalKey::KeyX => "KeyX",
269            PhysicalKey::KeyY => "KeyY",
270            PhysicalKey::KeyZ => "KeyZ",
271            PhysicalKey::Digit0 => "Digit0",
272            PhysicalKey::Digit1 => "Digit1",
273            PhysicalKey::Digit2 => "Digit2",
274            PhysicalKey::Digit3 => "Digit3",
275            PhysicalKey::Digit4 => "Digit4",
276            PhysicalKey::Digit5 => "Digit5",
277            PhysicalKey::Digit6 => "Digit6",
278            PhysicalKey::Digit7 => "Digit7",
279            PhysicalKey::Digit8 => "Digit8",
280            PhysicalKey::Digit9 => "Digit9",
281            PhysicalKey::Minus => "Minus",
282            PhysicalKey::Equal => "Equal",
283            PhysicalKey::BracketLeft => "BracketLeft",
284            PhysicalKey::BracketRight => "BracketRight",
285            PhysicalKey::Backslash => "Backslash",
286            PhysicalKey::Semicolon => "Semicolon",
287            PhysicalKey::Quote => "Quote",
288            PhysicalKey::Backquote => "Backquote",
289            PhysicalKey::Comma => "Comma",
290            PhysicalKey::Period => "Period",
291            PhysicalKey::Slash => "Slash",
292            PhysicalKey::IntlBackslash => "IntlBackslash",
293            PhysicalKey::IntlRo => "IntlRo",
294            PhysicalKey::IntlYen => "IntlYen",
295            PhysicalKey::Escape => "Escape",
296            PhysicalKey::F1 => "F1",
297            PhysicalKey::F2 => "F2",
298            PhysicalKey::F3 => "F3",
299            PhysicalKey::F4 => "F4",
300            PhysicalKey::F5 => "F5",
301            PhysicalKey::F6 => "F6",
302            PhysicalKey::F7 => "F7",
303            PhysicalKey::F8 => "F8",
304            PhysicalKey::F9 => "F9",
305            PhysicalKey::F10 => "F10",
306            PhysicalKey::F11 => "F11",
307            PhysicalKey::F12 => "F12",
308            PhysicalKey::PrintScreen => "PrintScreen",
309            PhysicalKey::ScrollLock => "ScrollLock",
310            PhysicalKey::Pause => "Pause",
311            PhysicalKey::Insert => "Insert",
312            PhysicalKey::Home => "Home",
313            PhysicalKey::PageUp => "PageUp",
314            PhysicalKey::Delete => "Delete",
315            PhysicalKey::End => "End",
316            PhysicalKey::PageDown => "PageDown",
317            PhysicalKey::ArrowRight => "ArrowRight",
318            PhysicalKey::ArrowLeft => "ArrowLeft",
319            PhysicalKey::ArrowDown => "ArrowDown",
320            PhysicalKey::ArrowUp => "ArrowUp",
321            PhysicalKey::NumLock => "NumLock",
322            PhysicalKey::NumpadDivide => "NumpadDivide",
323            PhysicalKey::NumpadMultiply => "NumpadMultiply",
324            PhysicalKey::NumpadSubtract => "NumpadSubtract",
325            PhysicalKey::NumpadAdd => "NumpadAdd",
326            PhysicalKey::NumpadEnter => "NumpadEnter",
327            PhysicalKey::NumpadDecimal => "NumpadDecimal",
328            PhysicalKey::Numpad0 => "Numpad0",
329            PhysicalKey::Numpad1 => "Numpad1",
330            PhysicalKey::Numpad2 => "Numpad2",
331            PhysicalKey::Numpad3 => "Numpad3",
332            PhysicalKey::Numpad4 => "Numpad4",
333            PhysicalKey::Numpad5 => "Numpad5",
334            PhysicalKey::Numpad6 => "Numpad6",
335            PhysicalKey::Numpad7 => "Numpad7",
336            PhysicalKey::Numpad8 => "Numpad8",
337            PhysicalKey::Numpad9 => "Numpad9",
338            PhysicalKey::Backspace => "Backspace",
339            PhysicalKey::Tab => "Tab",
340            PhysicalKey::Space => "Space",
341            PhysicalKey::CapsLock => "CapsLock",
342            PhysicalKey::Enter => "Enter",
343            PhysicalKey::ShiftLeft => "ShiftLeft",
344            PhysicalKey::ShiftRight => "ShiftRight",
345            PhysicalKey::ControlLeft => "ControlLeft",
346            PhysicalKey::ControlRight => "ControlRight",
347            PhysicalKey::AltLeft => "AltLeft",
348            PhysicalKey::AltRight => "AltRight",
349            PhysicalKey::SuperLeft => "SuperLeft",
350            PhysicalKey::SuperRight => "SuperRight",
351            PhysicalKey::ContextMenu => "ContextMenu",
352            PhysicalKey::Unidentified => "Unidentified",
353        }
354    }
355
356    /// Parse a W3C `code` name. Unknown names map to `Unidentified`
357    /// (never `None`: every physical press has a position, even when
358    /// the platform cannot name it).
359    pub fn from_name(name: &str) -> Self {
360        match name {
361            "KeyA" => PhysicalKey::KeyA,
362            "KeyB" => PhysicalKey::KeyB,
363            "KeyC" => PhysicalKey::KeyC,
364            "KeyD" => PhysicalKey::KeyD,
365            "KeyE" => PhysicalKey::KeyE,
366            "KeyF" => PhysicalKey::KeyF,
367            "KeyG" => PhysicalKey::KeyG,
368            "KeyH" => PhysicalKey::KeyH,
369            "KeyI" => PhysicalKey::KeyI,
370            "KeyJ" => PhysicalKey::KeyJ,
371            "KeyK" => PhysicalKey::KeyK,
372            "KeyL" => PhysicalKey::KeyL,
373            "KeyM" => PhysicalKey::KeyM,
374            "KeyN" => PhysicalKey::KeyN,
375            "KeyO" => PhysicalKey::KeyO,
376            "KeyP" => PhysicalKey::KeyP,
377            "KeyQ" => PhysicalKey::KeyQ,
378            "KeyR" => PhysicalKey::KeyR,
379            "KeyS" => PhysicalKey::KeyS,
380            "KeyT" => PhysicalKey::KeyT,
381            "KeyU" => PhysicalKey::KeyU,
382            "KeyV" => PhysicalKey::KeyV,
383            "KeyW" => PhysicalKey::KeyW,
384            "KeyX" => PhysicalKey::KeyX,
385            "KeyY" => PhysicalKey::KeyY,
386            "KeyZ" => PhysicalKey::KeyZ,
387            "Digit0" => PhysicalKey::Digit0,
388            "Digit1" => PhysicalKey::Digit1,
389            "Digit2" => PhysicalKey::Digit2,
390            "Digit3" => PhysicalKey::Digit3,
391            "Digit4" => PhysicalKey::Digit4,
392            "Digit5" => PhysicalKey::Digit5,
393            "Digit6" => PhysicalKey::Digit6,
394            "Digit7" => PhysicalKey::Digit7,
395            "Digit8" => PhysicalKey::Digit8,
396            "Digit9" => PhysicalKey::Digit9,
397            "Minus" => PhysicalKey::Minus,
398            "Equal" => PhysicalKey::Equal,
399            "BracketLeft" => PhysicalKey::BracketLeft,
400            "BracketRight" => PhysicalKey::BracketRight,
401            "Backslash" => PhysicalKey::Backslash,
402            "Semicolon" => PhysicalKey::Semicolon,
403            "Quote" => PhysicalKey::Quote,
404            "Backquote" => PhysicalKey::Backquote,
405            "Comma" => PhysicalKey::Comma,
406            "Period" => PhysicalKey::Period,
407            "Slash" => PhysicalKey::Slash,
408            "IntlBackslash" => PhysicalKey::IntlBackslash,
409            "IntlRo" => PhysicalKey::IntlRo,
410            "IntlYen" => PhysicalKey::IntlYen,
411            "Escape" => PhysicalKey::Escape,
412            "F1" => PhysicalKey::F1,
413            "F2" => PhysicalKey::F2,
414            "F3" => PhysicalKey::F3,
415            "F4" => PhysicalKey::F4,
416            "F5" => PhysicalKey::F5,
417            "F6" => PhysicalKey::F6,
418            "F7" => PhysicalKey::F7,
419            "F8" => PhysicalKey::F8,
420            "F9" => PhysicalKey::F9,
421            "F10" => PhysicalKey::F10,
422            "F11" => PhysicalKey::F11,
423            "F12" => PhysicalKey::F12,
424            "PrintScreen" => PhysicalKey::PrintScreen,
425            "ScrollLock" => PhysicalKey::ScrollLock,
426            "Pause" => PhysicalKey::Pause,
427            "Insert" => PhysicalKey::Insert,
428            "Home" => PhysicalKey::Home,
429            "PageUp" => PhysicalKey::PageUp,
430            "Delete" => PhysicalKey::Delete,
431            "End" => PhysicalKey::End,
432            "PageDown" => PhysicalKey::PageDown,
433            "ArrowRight" => PhysicalKey::ArrowRight,
434            "ArrowLeft" => PhysicalKey::ArrowLeft,
435            "ArrowDown" => PhysicalKey::ArrowDown,
436            "ArrowUp" => PhysicalKey::ArrowUp,
437            "NumLock" => PhysicalKey::NumLock,
438            "NumpadDivide" => PhysicalKey::NumpadDivide,
439            "NumpadMultiply" => PhysicalKey::NumpadMultiply,
440            "NumpadSubtract" => PhysicalKey::NumpadSubtract,
441            "NumpadAdd" => PhysicalKey::NumpadAdd,
442            "NumpadEnter" => PhysicalKey::NumpadEnter,
443            "NumpadDecimal" => PhysicalKey::NumpadDecimal,
444            "Numpad0" => PhysicalKey::Numpad0,
445            "Numpad1" => PhysicalKey::Numpad1,
446            "Numpad2" => PhysicalKey::Numpad2,
447            "Numpad3" => PhysicalKey::Numpad3,
448            "Numpad4" => PhysicalKey::Numpad4,
449            "Numpad5" => PhysicalKey::Numpad5,
450            "Numpad6" => PhysicalKey::Numpad6,
451            "Numpad7" => PhysicalKey::Numpad7,
452            "Numpad8" => PhysicalKey::Numpad8,
453            "Numpad9" => PhysicalKey::Numpad9,
454            "Backspace" => PhysicalKey::Backspace,
455            "Tab" => PhysicalKey::Tab,
456            "Space" => PhysicalKey::Space,
457            "CapsLock" => PhysicalKey::CapsLock,
458            "Enter" => PhysicalKey::Enter,
459            "ShiftLeft" => PhysicalKey::ShiftLeft,
460            "ShiftRight" => PhysicalKey::ShiftRight,
461            "ControlLeft" => PhysicalKey::ControlLeft,
462            "ControlRight" => PhysicalKey::ControlRight,
463            "AltLeft" => PhysicalKey::AltLeft,
464            "AltRight" => PhysicalKey::AltRight,
465            "SuperLeft" | "MetaLeft" => PhysicalKey::SuperLeft,
466            "SuperRight" | "MetaRight" => PhysicalKey::SuperRight,
467            "ContextMenu" => PhysicalKey::ContextMenu,
468            _ => PhysicalKey::Unidentified,
469        }
470    }
471}
472
473#[derive(Clone, Debug, PartialEq, Eq, Hash)]
474pub enum Key {
475    Character(char),
476    Enter,
477    Tab,
478    Backspace,
479    Delete,
480    Insert,
481    Escape,
482    ArrowLeft,
483    ArrowRight,
484    ArrowUp,
485    ArrowDown,
486    Home,
487    End,
488    PageUp,
489    PageDown,
490    Space,
491    ShiftLeft,
492    ShiftRight,
493    ControlLeft,
494    ControlRight,
495    AltLeft,
496    AltRight,
497    MetaLeft,
498    MetaRight,
499    CapsLock,
500    NumLock,
501    ScrollLock,
502    Pause,
503    PrintScreen,
504    ContextMenu,
505    Numpad(char),
506    NumpadEnter,
507    MediaPlay,
508    MediaPause,
509    MediaPlayPause,
510    MediaStop,
511    MediaNext,
512    MediaPrevious,
513    VolumeUp,
514    VolumeDown,
515    VolumeMute,
516    F(u8), // F1-F12
517    Unknown,
518}
519
520#[derive(Clone, Copy, Debug, PartialEq, Eq)]
521pub enum KeyEventType {
522    /// Key pressed down.
523    Down,
524    /// Key released.
525    Up,
526    /// Unknown or unsupported event type.
527    Unknown,
528}
529
530#[derive(Clone, Debug)]
531pub struct KeyEvent {
532    pub key: Key,
533    pub modifiers: Modifiers,
534    pub is_repeat: bool,
535    /// Whether this is a key-down or key-up event.
536    pub event_type: KeyEventType,
537    /// UTF-16 code point for character keys, or 0 for non-characters.
538    /// Matches Compose's `utf16CodePoint`.
539    pub utf16_code_point: u16,
540    /// Physical key position, layout-independent. `None` for synthetic events.
541    pub physical: Option<PhysicalKey>,
542}
543
544impl KeyEvent {
545    pub fn is_ctrl_pressed(&self) -> bool {
546        self.modifiers.ctrl
547    }
548    pub fn is_alt_pressed(&self) -> bool {
549        self.modifiers.alt
550    }
551    pub fn is_shift_pressed(&self) -> bool {
552        self.modifiers.shift
553    }
554    pub fn is_meta_pressed(&self) -> bool {
555        self.modifiers.meta
556    }
557}
558
559#[derive(Clone, Debug)]
560pub struct TextInputEvent {
561    pub text: String,
562}
563
564#[derive(Clone, Debug)]
565pub enum ImeEvent {
566    /// IME composition started
567    Start,
568    /// Composition text updated
569    Update {
570        text: String,
571        cursor: Option<(usize, usize)>, // (start, end) of composition range
572    },
573    /// Composition committed (finalized)
574    Commit(String),
575    /// Composition cancelled
576    Cancel,
577}
578
579#[derive(Clone, Debug)]
580pub enum InputEvent {
581    Pointer(PointerEvent),
582    Key(KeyEvent),
583    Text(TextInputEvent),
584    Ime(ImeEvent),
585    Gamepad(GamepadEvent),
586}
587
588/// Opaque gamepad handle. Backend-local index, stable for the connection
589/// lifetime. Survives across frames; invalid after [`GamepadEvent::Disconnected`].
590#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
591pub struct GamepadId(pub u32);
592
593/// Standard-layout buttons (SDL gamecontroller mapping positions).
594/// Backends translate hardware codes to these; unknown buttons are dropped.
595#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
596pub enum GamepadButton {
597    /// Bottom face button (A / Cross). UI default: activate.
598    South,
599    /// Right face button (B / Circle). UI default: back.
600    East,
601    /// Left face button (X / Square).
602    West,
603    /// Top face button (Y / Triangle).
604    North,
605    Start,
606    Select,
607    LeftShoulder,
608    RightShoulder,
609    LeftStick,
610    RightStick,
611    DPadUp,
612    DPadDown,
613    DPadLeft,
614    DPadRight,
615}
616
617/// Analog axes, normalized to -1.0..=1.0. Triggers report 0.0..=1.0.
618#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
619pub enum GamepadAxis {
620    LeftStickX,
621    LeftStickY,
622    RightStickX,
623    RightStickY,
624    LeftTrigger,
625    RightTrigger,
626}
627
628/// A connected gamepad's polled state, published beside the polled keys and the
629/// mouse levels so a game reads every hardware source from one snapshot.
630#[derive(Clone, Debug, Default)]
631pub struct GamepadPad {
632    /// Backend-local index, stable for the connection's lifetime.
633    pub id: u32,
634    /// Driver name, as the backend reported it.
635    pub name: String,
636    /// USB vendor and product ids, `0` where the platform reports none.
637    pub vendor_id: u16,
638    pub product_id: u16,
639    /// The standard buttons that are down right now.
640    pub pressed: HashSet<GamepadButton>,
641    /// Live axis values, -1.0..=1.0 for sticks and 0.0..=1.0 for triggers.
642    pub axes: HashMap<GamepadAxis, f32>,
643}
644
645impl GamepadPad {
646    pub fn button(&self, button: GamepadButton) -> bool {
647        self.pressed.contains(&button)
648    }
649
650    pub fn axis(&self, axis: GamepadAxis) -> f32 {
651        self.axes.get(&axis).copied().unwrap_or(0.0)
652    }
653}
654
655/// Motion sensor a gamepad can report.
656#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
657pub enum SensorKind {
658    /// Angular velocity in degrees per second.
659    Gyroscope,
660    /// Proper acceleration in g.
661    Accelerometer,
662}
663
664/// One reading from a motion sensor, in the device frame.
665#[derive(Clone, Copy, Debug, PartialEq)]
666pub struct SensorSample {
667    pub kind: SensorKind,
668    /// `[x, y, z]`, scaled per [`SensorKind`].
669    pub data: [f32; 3],
670}
671
672/// Lowercases and strips punctuation, so a driver name matches a pad name
673/// despite interface suffixes ("Wireless Controller (Vendor: 054c)").
674pub fn normalize_device_name(name: &str) -> String {
675    name.chars()
676        .filter(|c| c.is_alphanumeric())
677        .flat_map(char::to_lowercase)
678        .collect()
679}
680
681impl SensorSample {
682    pub fn gyroscope(x: f32, y: f32, z: f32) -> Self {
683        Self {
684            kind: SensorKind::Gyroscope,
685            data: [x, y, z],
686        }
687    }
688
689    pub fn accelerometer(x: f32, y: f32, z: f32) -> Self {
690        Self {
691            kind: SensorKind::Accelerometer,
692            data: [x, y, z],
693        }
694    }
695}
696
697#[derive(Clone, Debug)]
698pub enum GamepadEvent {
699    Connected {
700        id: GamepadId,
701        name: String,
702        /// USB vendor and product ids, `0` where the platform reports none.
703        vendor_id: u16,
704        product_id: u16,
705    },
706    Disconnected {
707        id: GamepadId,
708    },
709    Button {
710        id: GamepadId,
711        button: GamepadButton,
712        pressed: bool,
713    },
714    Axis {
715        id: GamepadId,
716        axis: GamepadAxis,
717        /// -1.0..=1.0 (sticks) or 0.0..=1.0 (triggers). Backends deadzone.
718        value: f32,
719    },
720}
721
722impl GamepadEvent {
723    pub fn id(&self) -> GamepadId {
724        match *self {
725            GamepadEvent::Connected { id, .. } => id,
726            GamepadEvent::Disconnected { id } => id,
727            GamepadEvent::Button { id, .. } => id,
728            GamepadEvent::Axis { id, .. } => id,
729        }
730    }
731}
732
733#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
734pub enum InputMode {
735    #[default]
736    Touch,
737    /// Keyboard, Tab, arrow/D-pad, or other non-pointer navigation.
738    Keyboard,
739}
740
741thread_local! {
742    static INPUT_MODE: Cell<InputMode> = const { Cell::new(InputMode::Touch) };
743}
744
745/// Current input mode (Compose `InputModeManager.inputMode`).
746///
747/// Composition-local override ([`crate::locals::with_input_mode`]) wins over
748/// the thread default.
749#[inline]
750pub fn input_mode() -> InputMode {
751    crate::locals::local_input_mode().unwrap_or_else(default_input_mode)
752}
753
754pub(crate) fn default_input_mode() -> InputMode {
755    INPUT_MODE.get()
756}
757
758/// Force the global default input mode and request a frame.
759#[inline]
760pub fn set_input_mode_default(mode: InputMode) {
761    INPUT_MODE.set(mode);
762    crate::request_frame();
763}
764
765/// Request a new input mode. Returns `true` if the mode changed.
766///
767/// On change, requests a frame so focus chrome can appear/disappear.
768pub fn request_input_mode(mode: InputMode) -> bool {
769    let prev = INPUT_MODE.get();
770    if prev == mode {
771        return false;
772    }
773    INPUT_MODE.set(mode);
774    crate::frame_clock::request_frame();
775    true
776}
777
778/// `true` when focus indication should paint (focused **and** keyboard mode).
779#[inline]
780pub fn is_focus_visible(focused: bool) -> bool {
781    focused && input_mode() == InputMode::Keyboard
782}
783
784#[cfg(test)]
785mod input_mode_tests {
786    use super::*;
787    use crate::frame_clock::take_frame_request;
788    use crate::modifier::{Interaction, MutableInteractionSource};
789
790    #[test]
791    fn request_input_mode_changes_and_requests_frame() {
792        set_input_mode_default(InputMode::Touch);
793        let _ = take_frame_request();
794
795        assert!(!request_input_mode(InputMode::Touch));
796        assert!(!take_frame_request());
797
798        assert!(request_input_mode(InputMode::Keyboard));
799        assert_eq!(input_mode(), InputMode::Keyboard);
800        assert!(take_frame_request());
801
802        assert!(request_input_mode(InputMode::Touch));
803        assert_eq!(input_mode(), InputMode::Touch);
804        set_input_mode_default(InputMode::Touch);
805    }
806
807    #[test]
808    fn focus_visible_requires_keyboard_mode() {
809        set_input_mode_default(InputMode::Touch);
810        let src = MutableInteractionSource::new();
811        src.emit(Interaction::Focus);
812        assert!(src.source().collect_is_focused());
813        assert!(!src.source().collect_is_focus_visible());
814
815        set_input_mode_default(InputMode::Keyboard);
816        assert!(src.source().collect_is_focus_visible());
817
818        set_input_mode_default(InputMode::Touch);
819        src.emit(Interaction::Unfocus);
820    }
821
822    #[test]
823    fn with_input_mode_overrides_global() {
824        set_input_mode_default(InputMode::Touch);
825        crate::locals::with_input_mode(InputMode::Keyboard, || {
826            assert_eq!(input_mode(), InputMode::Keyboard);
827        });
828        assert_eq!(input_mode(), InputMode::Touch);
829    }
830}