input/
close.rs

1use crate::{Event, Input};
2
3/// Close arguments.
4#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize, Hash)]
5pub struct CloseArgs;
6
7/// Window is closing.
8pub trait CloseEvent: Sized {
9    /// Creates a close event from arguments.
10    ///
11    /// Preserves time stamp from original input event, if any.
12    fn from_close_args(args: &CloseArgs, old_event: &Self) -> Option<Self>;
13    /// Calls closure if this is a close event.
14    fn close<U, F>(&self, f: F) -> Option<U>
15    where
16        F: FnMut(&CloseArgs) -> U;
17    /// Returns close arguments.
18    fn close_args(&self) -> Option<CloseArgs> {
19        self.close(|args| *args)
20    }
21}
22
23impl CloseEvent for Event {
24    fn from_close_args(args: &CloseArgs, old_event: &Self) -> Option<Self> {
25        let timestamp = if let Event::Input(_, x) = old_event {
26            *x
27        } else {
28            None
29        };
30        Some(Event::Input(Input::Close(*args), timestamp))
31    }
32
33    fn close<U, F>(&self, mut f: F) -> Option<U>
34    where
35        F: FnMut(&CloseArgs) -> U,
36    {
37        match *self {
38            Event::Input(Input::Close(ref args), _) => Some(f(args)),
39            _ => None,
40        }
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn test_input_close() {
50        use CloseArgs;
51        use Event;
52
53        let e: Event = CloseArgs.into();
54        let x: Option<Event> = CloseEvent::from_close_args(&CloseArgs, &e);
55        let y: Option<Event> = x
56            .clone()
57            .unwrap()
58            .close(|args| CloseEvent::from_close_args(args, x.as_ref().unwrap()))
59            .unwrap();
60        assert_eq!(x, y);
61    }
62}