1use crate::{Event, Input, Motion};
4
5#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
8pub struct ControllerButton {
9 pub id: u32,
11 pub button: u8,
13}
14
15impl ControllerButton {
16 pub fn new(id: u32, button: u8) -> Self {
19 ControllerButton { id, button }
20 }
21}
22
23#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
25pub struct ControllerHat {
26 pub id: u32,
28 pub state: crate::HatState,
30 pub which: u8,
32}
33
34impl ControllerHat {
35 pub fn new(id: u32, which: u8, state: crate::HatState) -> Self {
38 ControllerHat { id, state, which }
39 }
40}
41
42#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, PartialOrd, Debug)]
45pub struct ControllerAxisArgs {
46 pub id: u32,
48 pub axis: u8,
50 pub position: f64,
53}
54
55impl ControllerAxisArgs {
56 pub fn new(id: u32, axis: u8, position: f64) -> Self {
59 ControllerAxisArgs { id, axis, position }
60 }
61}
62
63pub trait ControllerAxisEvent: Sized {
65 fn from_controller_axis_args(args: ControllerAxisArgs, old_event: &Self) -> Option<Self>;
69 fn controller_axis<U, F>(&self, f: F) -> Option<U>
71 where
72 F: FnMut(ControllerAxisArgs) -> U;
73 fn controller_axis_args(&self) -> Option<ControllerAxisArgs> {
75 self.controller_axis(|args| args)
76 }
77}
78
79impl ControllerAxisEvent for Event {
80 fn from_controller_axis_args(args: ControllerAxisArgs, old_event: &Self) -> Option<Self> {
81 let timestamp = if let Event::Input(_, x) = old_event {
82 *x
83 } else {
84 None
85 };
86 Some(Event::Input(
87 Input::Move(Motion::ControllerAxis(args)),
88 timestamp,
89 ))
90 }
91
92 fn controller_axis<U, F>(&self, mut f: F) -> Option<U>
93 where
94 F: FnMut(ControllerAxisArgs) -> U,
95 {
96 match *self {
97 Event::Input(Input::Move(Motion::ControllerAxis(args)), _) => Some(f(args)),
98 _ => None,
99 }
100 }
101}
102
103#[cfg(test)]
104mod controller_axis_tests {
105 use super::*;
106
107 #[test]
108 fn test_input_controller_axis() {
109 let e: Event = ControllerAxisArgs::new(0, 1, 0.9).into();
110 let a: Option<Event> =
111 ControllerAxisEvent::from_controller_axis_args(ControllerAxisArgs::new(0, 1, 0.9), &e);
112 let b: Option<Event> = a
113 .clone()
114 .unwrap()
115 .controller_axis(|cnt| {
116 ControllerAxisEvent::from_controller_axis_args(
117 ControllerAxisArgs::new(cnt.id, cnt.axis, cnt.position),
118 a.as_ref().unwrap(),
119 )
120 })
121 .unwrap();
122 assert_eq!(a, b);
123 }
124}