simple/event.rs
1extern crate sdl2;
2use sdl2::event::Event as SDL_Event;
3pub use sdl2::keyboard::Scancode as Key;
4pub use sdl2::mouse::MouseButton;
5
6/**
7 * Event is an enumeration of the effects that a user can have on a running Window.
8 *
9 * TODO: Add support for more events like touch events and window resizes.
10 */
11#[derive(Copy, Clone, PartialEq)]
12pub enum Event {
13 /// Keyboard is either a keypress or a keyrelease. The `is_down` bool tells you which :)
14 Keyboard { is_down: bool, key: Key },
15
16 /// Mouse can be either a click or a click release. Refer to `is_down`. Note that the position
17 /// of the mouse at the time of the click is listed. The mouse may have moved in the meantime,
18 /// so for precision, you can use the position fields on this variant.
19 Mouse {
20 is_down: bool,
21 button: MouseButton,
22 mouse_x: i32,
23 mouse_y: i32,
24 },
25
26 /// The user has signaled to the OS that the application should be killed. This could happen
27 /// through clicking the X in the corner of the window or using CMD-Q or Alt-F4 (depending on
28 /// the platform).
29 ///
30 /// You normally do not have to catch this event yourself. Window has built-in code to process
31 /// this case.
32 Quit,
33}
34
35impl Event {
36 pub fn from_sdl2_event(e: SDL_Event) -> Option<Event> {
37 match e {
38 // Quit
39 SDL_Event::Quit { .. } => Some(Event::Quit),
40
41 // Keyboard
42 SDL_Event::KeyDown {
43 scancode: Some(key),
44 ..
45 } => Some(Event::Keyboard {
46 is_down: true,
47 key: key,
48 }),
49 SDL_Event::KeyUp {
50 scancode: Some(key),
51 ..
52 } => Some(Event::Keyboard {
53 is_down: false,
54 key: key,
55 }),
56
57 // Mouse
58 SDL_Event::MouseButtonDown {
59 mouse_btn: button,
60 x,
61 y,
62 ..
63 } => Some(Event::Mouse {
64 is_down: true,
65 button: button,
66 mouse_x: x,
67 mouse_y: y,
68 }),
69 SDL_Event::MouseButtonUp {
70 mouse_btn: button,
71 x,
72 y,
73 ..
74 } => Some(Event::Mouse {
75 is_down: false,
76 button: button,
77 mouse_x: x,
78 mouse_y: y,
79 }),
80
81 _ => None,
82 }
83 }
84}
85
86#[test]
87fn test_from_sdl2_event() {
88 fn test(input: SDL_Event, expected: Event) {
89 assert!(Event::from_sdl2_event(input).unwrap() == expected);
90 }
91
92 test(SDL_Event::Quit { timestamp: 0 }, Event::Quit);
93
94 // TODO: Test more comprehensively.
95}