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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use {Button, Event, Input};

/// Stores button state.
#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum ButtonState {
    /// Button was pressed.
    Press,
    /// Button was released.
    Release,
}

/// Button arguments.
#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ButtonArgs {
    /// New state of the button.
    pub state: ButtonState,
    /// The button that changed state.
    pub button: Button,
    /// An optional scancode that tells the physical layout of a keyboard key.
    /// For other devices than keyboard, this is set to `None`.
    ///
    /// Scancode follows SDL (https://wiki.libsdl.org/SDL_Scancode).
    ///
    /// This is stored here to make `Button` equality check work with keyboard layouts.
    ///
    /// Some window backends might not support scancodes.
    /// To test a window backend, use https://github.com/PistonDevelopers/piston-examples/tree/master/user_input
    pub scancode: Option<i32>,
}

/// Changed button state.
pub trait ButtonEvent: Sized {
    /// Creates a button event.
    ///
    /// Preserves time stamp from original input event, if any.
    fn from_button_args(args: ButtonArgs, old_event: &Self) -> Option<Self>;
    /// Calls closure if this is a button event.
    fn button<U, F>(&self, f: F) -> Option<U> where F: FnMut(ButtonArgs) -> U;
    /// Returns button arguments.
    fn button_args(&self) -> Option<ButtonArgs> {
        self.button(|args| args)
    }
}

impl ButtonEvent for Event {
    fn from_button_args(args: ButtonArgs, old_event: &Self) -> Option<Self> {
        let timestamp = if let Event::Input(_, x) = old_event {*x} else {None};
        Some(Event::Input(Input::Button(args), timestamp))
    }
    fn button<U, F>(&self, mut f: F) -> Option<U>
        where F: FnMut(ButtonArgs) -> U
    {
        match *self {
            Event::Input(Input::Button(args), _) => Some(f(args)),
            _ => None,
        }
    }
}

/// The press of a button.
pub trait PressEvent: Sized {
    /// Creates a press event.
    ///
    /// Preserves scancode from original button event, if any.
    /// Preserves time stamp from original input event, if any.
    fn from_button(button: Button, old_event: &Self) -> Option<Self>;
    /// Calls closure if this is a press event.
    fn press<U, F>(&self, f: F) -> Option<U> where F: FnMut(Button) -> U;
    /// Returns press arguments.
    fn press_args(&self) -> Option<Button> {
        self.press(|button| button)
    }
}

impl<T> PressEvent for T where T: ButtonEvent {
    fn from_button(button: Button, old_event: &Self) -> Option<Self> {
        if let Some(mut args) = old_event.button_args() {
            args.state = ButtonState::Press;
            args.button = button;
            ButtonEvent::from_button_args(args, old_event)
        } else {
            ButtonEvent::from_button_args(ButtonArgs {
                state: ButtonState::Press,
                button: button,
                scancode: None
            }, old_event)
        }
    }

    fn press<U, F>(&self, mut f: F) -> Option<U>
        where F: FnMut(Button) -> U
    {
        if let Some(ButtonArgs {
            state: ButtonState::Press, button, ..
        }) = self.button_args() {
            Some(f(button))
        } else {
            None
        }
    }
}

/// The release of a button.
pub trait ReleaseEvent: Sized {
    /// Creates a release event.
    ///
    /// Preserves scancode from original button event, if any.
    /// Preserves time stamp from original input event, if any.
    fn from_button(button: Button, old_event: &Self) -> Option<Self>;
    /// Calls closure if this is a release event.
    fn release<U, F>(&self, f: F) -> Option<U> where F: FnMut(Button) -> U;
    /// Returns release arguments.
    fn release_args(&self) -> Option<Button> {
        self.release(|button| button)
    }
}

impl<T> ReleaseEvent for T where T: ButtonEvent {
    fn from_button(button: Button, old_event: &Self) -> Option<Self> {
        if let Some(mut args) = old_event.button_args() {
            args.state = ButtonState::Release;
            args.button = button;
            ButtonEvent::from_button_args(args, old_event)
        } else {
            ButtonEvent::from_button_args(ButtonArgs {
                state: ButtonState::Release,
                button: button,
                scancode: None
            }, old_event)
        }
    }

    fn release<U, F>(&self, mut f: F) -> Option<U>
        where F: FnMut(Button) -> U
    {
        if let Some(ButtonArgs {
            state: ButtonState::Release, button, ..
        }) = self.button_args() {
            Some(f(button))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_input_press() {
        use super::super::{Button, Key};

        let e: Event = ButtonArgs {
            state: ButtonState::Press,
            button: Key::S.into(),
            scancode: None,
        }.into();
        let button = Button::Keyboard(Key::A);
        let x: Option<Event> = PressEvent::from_button(button, &e);
        let y: Option<Event> = x.clone()
            .unwrap()
            .press(|button| PressEvent::from_button(button, x.as_ref().unwrap()))
            .unwrap();
        assert_eq!(x, y);
    }

    #[test]
    fn test_input_release() {
        use super::super::{Button, Key};

        let e: Event = ButtonArgs {
            state: ButtonState::Release,
            button: Key::S.into(),
            scancode: None,
        }.into();
        let button = Button::Keyboard(Key::A);
        let x: Option<Event> = ReleaseEvent::from_button(button, &e);
        let y: Option<Event> = x.clone()
            .unwrap()
            .release(|button| ReleaseEvent::from_button(button, x.as_ref().unwrap()))
            .unwrap();
        assert_eq!(x, y);
    }
}