input/
cursor.rs

1use crate::{Event, Input};
2
3/// When window gets or loses cursor.
4pub trait CursorEvent: Sized {
5    /// Creates a cursor event.
6    ///
7    /// Preserves time stamp from original input event, if any.
8    fn from_cursor(cursor: bool, old_event: &Self) -> Option<Self>;
9    /// Calls closure if this is a cursor event.
10    fn cursor<U, F>(&self, f: F) -> Option<U>
11    where
12        F: FnMut(bool) -> U;
13    /// Returns cursor arguments.
14    fn cursor_args(&self) -> Option<bool> {
15        self.cursor(|val| val)
16    }
17}
18
19impl CursorEvent for Event {
20    fn from_cursor(cursor: bool, old_event: &Self) -> Option<Self> {
21        let timestamp = if let Event::Input(_, x) = old_event {
22            *x
23        } else {
24            None
25        };
26        Some(Event::Input(Input::Cursor(cursor), timestamp))
27    }
28
29    fn cursor<U, F>(&self, mut f: F) -> Option<U>
30    where
31        F: FnMut(bool) -> U,
32    {
33        match *self {
34            Event::Input(Input::Cursor(val), _) => Some(f(val)),
35            _ => None,
36        }
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn test_input_cursor() {
46        use super::super::Input;
47
48        let e: Event = Input::Cursor(false).into();
49        let x: Option<Event> = CursorEvent::from_cursor(true, &e);
50        let y: Option<Event> = x
51            .clone()
52            .unwrap()
53            .cursor(|cursor| CursorEvent::from_cursor(cursor, x.as_ref().unwrap()))
54            .unwrap();
55        assert_eq!(x, y);
56    }
57}