1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use winit::event::{ElementState, Event, VirtualKeyCode, WindowEvent};
#[derive(Clone, Debug, Default)]
pub struct KeyBuf {
chars: Vec<char>,
held: Vec<VirtualKeyCode>,
pressed: Vec<VirtualKeyCode>,
released: Vec<VirtualKeyCode>,
}
impl KeyBuf {
pub fn any_held(&self) -> bool {
!self.held.is_empty()
}
pub fn any_pressed(&self) -> bool {
!self.pressed.is_empty()
}
pub fn any_released(&self) -> bool {
!self.released.is_empty()
}
pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
self.chars.iter().copied()
}
pub fn update(&mut self) {
self.chars.clear();
self.pressed.clear();
self.released.clear();
}
pub fn handle_event(&mut self, event: &Event<'_, ()>) -> bool {
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput { input, .. } if input.virtual_keycode.is_some() => {
let key = input.virtual_keycode.unwrap();
match input.state {
ElementState::Pressed => {
if let Err(idx) = self.pressed.binary_search(&key) {
self.pressed.insert(idx, key);
}
if let Err(idx) = self.held.binary_search(&key) {
self.held.insert(idx, key);
}
}
ElementState::Released => {
if let Ok(idx) = self.held.binary_search(&key) {
self.held.remove(idx);
}
if let Err(idx) = self.released.binary_search(&key) {
self.released.insert(idx, key);
}
}
}
true
}
WindowEvent::ReceivedCharacter(char) => {
self.chars.push(*char);
true
}
_ => false,
},
_ => false,
}
}
pub fn is_held(&self, key: &VirtualKeyCode) -> bool {
self.held.binary_search(key).is_ok()
}
pub fn is_pressed(&self, key: &VirtualKeyCode) -> bool {
self.pressed.binary_search(key).is_ok()
}
pub fn is_released(&self, key: &VirtualKeyCode) -> bool {
self.released.binary_search(key).is_ok()
}
pub fn held(&self) -> impl Iterator<Item = VirtualKeyCode> + '_ {
self.held.iter().copied()
}
pub fn pressed(&self) -> impl Iterator<Item = VirtualKeyCode> + '_ {
self.pressed.iter().copied()
}
pub fn released(&self) -> impl Iterator<Item = VirtualKeyCode> + '_ {
self.released.iter().copied()
}
}