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
use {super::Key, winit::event::KeyboardInput};

const DEFAULT_EVENT_CAPACITY: usize = 16;

/// A container for Window-based keyboard input events.
#[derive(Debug)]
pub struct KeyBuf {
    char_buf: String,
    pressed_keys: Vec<Key>,
    released_keys: Vec<Key>,
}

impl KeyBuf {
    pub(crate) fn clear(&mut self) {
        self.char_buf.clear();
        self.pressed_keys.clear();
        self.released_keys.clear();
    }

    pub(crate) fn char_buf(&self) -> &str {
        &self.char_buf
    }

    pub(crate) fn handle(&mut self, _event: &KeyboardInput) {
        /*match event {
            Event::KeyboardInput(state, _, Some(key_code)) => self.handle_key(*state, *key_code),
            Event::ReceivedCharacter(chr) => self.handle_char(*chr),
            _ => unimplemented!(),
        }*/
    }

    fn handle_char(&mut self, chr: char) {
        if !chr.is_control() {
            self.char_buf.push(chr)
        }
    }

    /*fn handle_key(&mut self, state: ElementState, key_code: KeyCode) {
        match state {
            ElementState::Pressed => self.pressed_keys.push(key_code),
            ElementState::Released => {
                self.pressed_keys.retain(|&k| k != key_code);
                self.released_keys.push(key_code);
            }
        }
    }*/

    /// Returns `true` if the given key is physically pressed down right now.
    pub fn is_key_down(&self, key_code: Key) -> bool {
        self.pressed_keys.contains(&key_code)
    }

    /// Returns `true` if the given key was physically released just now.
    pub fn was_key_down(&self, key_code: Key) -> bool {
        self.released_keys.contains(&key_code)
    }
}

impl Default for KeyBuf {
    fn default() -> Self {
        Self {
            char_buf: String::with_capacity(DEFAULT_EVENT_CAPACITY),
            pressed_keys: Vec::with_capacity(DEFAULT_EVENT_CAPACITY),
            released_keys: Vec::with_capacity(DEFAULT_EVENT_CAPACITY),
        }
    }
}