summaryrefslogtreecommitdiff
path: root/racer-tracer/src/key_inputs.rs
blob: 06e0f992fbc616c05feb6d10f43ebfe0fca4cff0 (plain)
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
use std::collections::HashMap;

use minifb::{Key, Window};

use crate::error::TracerError;

pub type KeyClosure<'a> = &'a (dyn Fn(f64) -> Result<(), TracerError> + Send + Sync);

pub struct KeyInputs<'a> {
    is_down_callbacks: HashMap<Key, Vec<KeyClosure<'a>>>,
    is_released_callbacks: HashMap<Key, Vec<KeyClosure<'a>>>,
}

impl<'a> KeyInputs<'a> {
    pub fn new() -> Self {
        KeyInputs {
            is_down_callbacks: HashMap::new(),
            is_released_callbacks: HashMap::new(),
        }
    }

    pub fn release(&mut self, key: Key, closure: KeyClosure<'a>) {
        let callbacks = self
            .is_released_callbacks
            .entry(key)
            .or_insert_with(Vec::new);
        callbacks.push(closure);
    }

    pub fn down(&mut self, key: Key, closure: KeyClosure<'a>) {
        let callbacks = self.is_down_callbacks.entry(key).or_insert_with(Vec::new);
        callbacks.push(closure);
    }

    pub fn update(&mut self, window: &Window, dt: f64) {
        self.is_down_callbacks
            .iter_mut()
            .filter(|(key, _callbacks)| window.is_key_down(**key))
            .for_each(|(_key, callbacks)| {
                callbacks.iter_mut().for_each(|callback| {
                    if let Err(e) = callback(dt) {
                        println!("Key callback error: {}", e)
                    }
                })
            });
        self.is_released_callbacks
            .iter_mut()
            .filter(|(key, _callbacks)| window.is_key_released(**key))
            .for_each(|(_key, callbacks)| {
                callbacks.iter_mut().for_each(|callback| {
                    if let Err(e) = callback(dt) {
                        println!("Key callback error: {}", e)
                    }
                })
            });
    }
}