Skip to main content

eternal_ui/
event.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Input events, as the windowing layer hands them to the toolkit.
6
7use bitflags::bitflags;
8
9use crate::geometry::Point;
10
11bitflags! {
12    /// Modifier keys held during a key or pointer event.
13    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
14    pub struct Modifiers: u8 {
15        const CTRL = 1 << 0;
16        const SHIFT = 1 << 1;
17        const ALT = 1 << 2;
18        /// Command on macOS, the Windows key elsewhere.
19        const META = 1 << 3;
20    }
21}
22
23/// A key, independent of keyboard layout for the named ones and by produced
24/// character for the rest.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26pub enum Key {
27    /// A key that types a character. Letters are lower case, so `Ctrl+S`
28    /// and `Ctrl+Shift+S` both carry `Char('s')`.
29    Char(char),
30    Enter,
31    Escape,
32    Tab,
33    Backspace,
34    Delete,
35    Space,
36    ArrowLeft,
37    ArrowRight,
38    ArrowUp,
39    ArrowDown,
40    Home,
41    End,
42    PageUp,
43    PageDown,
44    /// A function key, `F(1)` through `F(24)`.
45    F(u8),
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
49pub enum PointerButton {
50    Primary,
51    Secondary,
52    Middle,
53}
54
55/// Something the user did.
56#[derive(Clone, Debug, PartialEq)]
57pub enum Event {
58    PointerMove {
59        position: Point,
60    },
61    PointerDown {
62        position: Point,
63        button: PointerButton,
64    },
65    PointerUp {
66        position: Point,
67        button: PointerButton,
68    },
69    /// The pointer left the window.
70    PointerLeave,
71    Wheel {
72        position: Point,
73        /// Scroll distance in pixels, positive down and right.
74        delta: Point,
75    },
76    KeyDown {
77        key: Key,
78        modifiers: Modifiers,
79    },
80    KeyUp {
81        key: Key,
82        modifiers: Modifiers,
83    },
84    /// Text produced by a key press, after the platform's input method has
85    /// had its say. This is what text fields insert; `KeyDown` is for
86    /// shortcuts and navigation.
87    Text(String),
88}
89
90impl Event {
91    /// The pointer position for pointer events.
92    pub fn position(&self) -> Option<Point> {
93        match self {
94            Self::PointerMove { position }
95            | Self::PointerDown { position, .. }
96            | Self::PointerUp { position, .. }
97            | Self::Wheel { position, .. } => Some(*position),
98            _ => None,
99        }
100    }
101}