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
use input_handler::InputHandler;
use std::hash::Hash;
use winit::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};

/// If this event was for manipulating a keyboard key then this will return the `VirtualKeyCode`
/// and the new state.
pub fn get_key(event: &Event) -> Option<(VirtualKeyCode, ElementState)> {
    match *event {
        Event::WindowEvent { ref event, .. } => match *event {
            WindowEvent::KeyboardInput {
                input:
                    KeyboardInput {
                        virtual_keycode: Some(ref virtual_keycode),
                        state,
                        ..
                    },
                ..
            } => Some((*virtual_keycode, state)),
            _ => None,
        },
        _ => None,
    }
}

/// Returns true if the event passed in is a key down event for the
/// provided `VirtualKeyCode`.
pub fn is_key_down(event: &Event, key_code: VirtualKeyCode) -> bool {
    let op = get_key(event);
    if let Some((key, state)) = op {
        return key == key_code && state == ElementState::Pressed;
    }
    return false;
}

/// Returns true if the event passed in is a request to close the game window.
pub fn is_close_requested(event: &Event) -> bool {
    match *event {
        Event::WindowEvent { ref event, .. } => match *event {
            WindowEvent::CloseRequested => true,
            _ => false,
        },
        _ => false,
    }
}

/// Gets the input axis value from the `InputHandler`.
/// If the name is None, it will return the default value of the axis (0.0).
pub fn get_input_axis_simple<A, B>(name: &Option<A>, input: &InputHandler<A, B>) -> f32
where
    A: Send + Sync + Hash + Eq + Clone + 'static,
    B: Send + Sync + Hash + Eq + Clone + 'static,
{
    name.as_ref()
        .and_then(|ref n| input.axis_value(n))
        .unwrap_or(0.0) as f32
}