Skip to main content

rust_glass/
input.rs

1//! Keyboard, pointer and text input.
2//!
3//! The window host turns platform events into [`Event`]s. The state of the
4//! current frame is in [`Context::input`](crate::Context::input).
5
6use crate::accessibility::Action;
7use crate::context::Id;
8use crate::geometry::{Vec2, vec2};
9
10/// A key that widgets react to. Letters arrive lowercase in [`Key::Char`].
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12#[allow(missing_docs)]
13pub enum Key {
14    Enter,
15    Escape,
16    Tab,
17    Space,
18    Backspace,
19    Delete,
20    Left,
21    Right,
22    Up,
23    Down,
24    Home,
25    End,
26    PageUp,
27    PageDown,
28    /// A character key, lowercase.
29    Char(char),
30}
31
32/// Modifier keys held during a key press.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub struct Modifiers {
35    /// Shift.
36    pub shift: bool,
37    /// Control.
38    pub ctrl: bool,
39    /// Alt, or Option on macOS.
40    pub alt: bool,
41    /// The key for shortcuts: Command on macOS, Control elsewhere.
42    pub command: bool,
43}
44
45/// Something that happened since the last frame. Positions are in points.
46#[derive(Clone, Debug)]
47pub enum Event {
48    /// The pointer moved to this position.
49    PointerMoved(Vec2),
50    /// The pointer left the window.
51    PointerLeft,
52    /// The primary button or a touch went down.
53    PointerDown,
54    /// The primary button or a touch went up.
55    PointerUp,
56    /// The secondary button went down.
57    SecondaryDown,
58    /// The wheel or touchpad scrolled by this many points.
59    Scroll(Vec2),
60    /// A key was pressed.
61    Key(Key),
62    /// Text was typed.
63    Text(String),
64    /// The modifier keys changed.
65    Modifiers(Modifiers),
66    /// The window gained (`true`) or lost focus.
67    Focus(bool),
68    /// Text was pasted from the clipboard.
69    Paste(String),
70    /// Text an input method is composing and has not committed yet. The
71    /// range is the cursor or selection inside it, in bytes. An empty string
72    /// ends the composition.
73    Preedit(String, Option<(usize, usize)>),
74    /// A request from assistive technology, such as a screen reader.
75    Access(Id, Action),
76}
77
78/// Text an input method is composing, shown at the caret of the focused
79/// field.
80#[derive(Clone, Debug, Default, PartialEq)]
81pub struct Preedit {
82    /// The text so far.
83    pub text: String,
84    /// The cursor or selection inside the text, in bytes.
85    pub cursor: Option<(usize, usize)>,
86}
87
88/// Input state of the current frame.
89#[derive(Clone, Debug, Default)]
90pub struct Input {
91    /// Pointer position, or `None` outside the window.
92    pub pointer: Option<Vec2>,
93    /// How far the pointer moved since the last frame.
94    pub delta: Vec2,
95    /// The primary button is down.
96    pub down: bool,
97    /// The primary button went down this frame.
98    pub pressed: bool,
99    /// The primary button went up this frame.
100    pub released: bool,
101    /// The secondary button went down this frame.
102    pub secondary_clicked: bool,
103    /// This frame's press is the second of a double click.
104    pub double_clicked: bool,
105    /// Where the last press started.
106    pub press_origin: Vec2,
107    /// Wheel movement this frame. Shift turns vertical movement sideways.
108    pub scroll: Vec2,
109    /// Keys pressed this frame. Widgets remove the ones they handle with
110    /// [`Input::take_key`].
111    pub keys: Vec<(Key, Modifiers)>,
112    /// Text typed or pasted this frame.
113    pub text: String,
114    /// Modifier keys held now.
115    pub modifiers: Modifiers,
116    /// The window has keyboard focus.
117    pub focused: bool,
118    /// Text an input method is composing. Persists across frames.
119    pub preedit: Option<Preedit>,
120    last_press: f64,
121    /// A press and its release in the same frame: the release waits one frame.
122    deferred_up: bool,
123}
124
125impl Input {
126    /// Creates the state of a focused window without input.
127    pub fn new() -> Self {
128        Self { focused: true, last_press: -10.0, ..Default::default() }
129    }
130
131    /// Starts a frame: clears what lasted one frame and applies `events`.
132    pub(crate) fn begin(&mut self, events: &[Event], time: f64) {
133        self.delta = Vec2::ZERO;
134        self.pressed = false;
135        self.released = false;
136        self.secondary_clicked = false;
137        self.double_clicked = false;
138        self.scroll = Vec2::ZERO;
139        self.keys.clear();
140        self.text.clear();
141        if std::mem::take(&mut self.deferred_up) {
142            self.released = true;
143            self.down = false;
144        }
145        for e in events {
146            match e {
147                Event::PointerMoved(p) => {
148                    if let Some(old) = self.pointer {
149                        self.delta += *p - old;
150                    }
151                    self.pointer = Some(*p);
152                }
153                Event::PointerLeft => {
154                    if !self.down {
155                        self.pointer = None;
156                    }
157                }
158                Event::PointerDown => {
159                    self.pressed = true;
160                    self.down = true;
161                    let p = self.pointer.unwrap_or(vec2(-1.0, -1.0));
162                    self.double_clicked =
163                        time - self.last_press < 0.35 && (p - self.press_origin).length() < 5.0;
164                    self.last_press = if self.double_clicked { -10.0 } else { time };
165                    self.press_origin = p;
166                }
167                Event::PointerUp => {
168                    if self.pressed {
169                        self.deferred_up = true;
170                    } else {
171                        self.released = true;
172                        self.down = false;
173                    }
174                }
175                Event::SecondaryDown => self.secondary_clicked = true,
176                Event::Scroll(d) => self.scroll += *d,
177                Event::Key(k) => self.keys.push((*k, self.modifiers)),
178                Event::Text(t) => self.text.push_str(t),
179                Event::Paste(t) => self.text.push_str(t),
180                Event::Preedit(t, c) => {
181                    self.preedit = (!t.is_empty()).then(|| Preedit { text: t.clone(), cursor: *c });
182                }
183                Event::Access(..) => {}
184                Event::Modifiers(m) => self.modifiers = *m,
185                Event::Focus(f) => {
186                    self.focused = *f;
187                    if !*f && self.down {
188                        self.down = false;
189                        self.released = true;
190                    }
191                }
192            }
193        }
194        // Shift turns a mouse wheel sideways.
195        if self.modifiers.shift && self.scroll.x == 0.0 {
196            self.scroll = vec2(self.scroll.y, 0.0);
197        }
198    }
199
200    /// Another frame is needed to deliver everything.
201    pub(crate) fn pending(&self) -> bool {
202        self.deferred_up
203    }
204
205    /// Returns `true` if `key` was pressed this frame and no widget took it.
206    pub fn key(&self, key: Key) -> bool {
207        self.keys.iter().any(|x| x.0 == key)
208    }
209
210    /// Returns `true` if `key` was pressed this frame, and removes it so
211    /// widgets drawn later do not see it.
212    pub fn take_key(&mut self, key: Key) -> bool {
213        let n = self.keys.len();
214        self.keys.retain(|x| x.0 != key);
215        n != self.keys.len()
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn click_within_one_frame_is_not_lost() {
225        let mut i = Input::new();
226        i.begin(&[Event::PointerMoved(vec2(1.0, 1.0)), Event::PointerDown, Event::PointerUp], 0.0);
227        assert!(i.pressed && i.down && !i.released && i.pending());
228        i.begin(&[], 0.016);
229        assert!(!i.pressed && !i.down && i.released);
230    }
231
232    #[test]
233    fn double_click() {
234        let mut i = Input::new();
235        for (t, want) in [(0.0, false), (0.2, true), (0.3, false)] {
236            i.begin(&[Event::PointerMoved(vec2(1.0, 1.0)), Event::PointerDown], t);
237            assert_eq!(i.double_clicked, want);
238            i.begin(&[Event::PointerUp], t + 0.05);
239        }
240    }
241}