keyboard_types/keyboard_event.rs
1#[cfg(feature = "serde")]
2use serde::{Deserialize, Serialize};
3
4use crate::{Code, Key, KeyState, Location, Modifiers};
5
6/// Keyboard events are issued for all pressed and released keys.
7#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
8#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9pub struct KeyboardEvent {
10 /// Whether the key is pressed or released.
11 pub state: KeyState,
12 /// Logical key value.
13 pub key: Key,
14 /// Physical key position.
15 pub code: Code,
16 /// Location for keys with multiple instances on common keyboards.
17 pub location: Location,
18 /// Flags for pressed modifier keys.
19 pub modifiers: Modifiers,
20 /// True if the key is currently auto-repeated.
21 pub repeat: bool,
22 /// Events with this flag should be ignored in a text editor
23 /// and instead [composition events](crate::CompositionEvent) should be used.
24 pub is_composing: bool,
25}
26
27impl KeyboardEvent {
28 /// Convenience constructor which takes `key` and `code`, sets `state` to
29 /// [`KeyState::Down`], and sets everything else to default values.
30 pub fn key_down(key: impl Into<Key>, code: Code) -> Self {
31 KeyboardEvent {
32 state: KeyState::Down,
33 key: key.into(),
34 code,
35 ..Default::default()
36 }
37 }
38
39 /// Convenience constructor which takes `key` and `code`, sets `state` to
40 /// [`KeyState::Up`], and sets everything else to default values.
41 pub fn key_up(key: impl Into<Key>, code: Code) -> Self {
42 KeyboardEvent {
43 state: KeyState::Up,
44 key: key.into(),
45 code,
46 ..Default::default()
47 }
48 }
49}