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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
use crate::constants::*;
pub use crate::events::RelAxisEvent;
use serde::{Deserialize, Serialize};
use std::iter::FromIterator;

/// An OutputAction is an action that can be sent to the OutputDevice to simulate keyboard and mouse
/// inputs.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum OutputAction {
    StateChange(StateChange),
    Pulse(Pulse),
    Toggle(Toggle),
}

/// The different types of possible OutputActions
///
/// Used for when wanting to denote the type of an OutputAction without having the actual event
/// struct.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum OutputActionType {
    StateChange,
    Pulse,
    Toggle,
}

/// A Toggle output event.
///
/// Equivalent to pressing the key if it's not pressed, or letting go of a key if it is pressed.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct Toggle {
    pub keys: Option<KeyList>,
    pub axes: Option<AxisList>,
}

impl Toggle {
    /// Create a new Toggle event.
    ///
    /// Example:
    /// ```
    /// use chord2key::output::actions::*;
    /// use chord2key::constants::*;
    ///
    /// let t = Toggle::new(
    ///     Some(vec![KeyCode::KEY_W]),
    ///     Some(vec![(RelAxisCode::REL_X, 5)].into()),
    /// );
    /// ```
    pub fn new(keys: Option<KeyList>, axes: Option<AxisList>) -> Self {
        Self {
            keys,
            axes,
        }
    }
}

/// The data representing a pulsed output event
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct Pulse {
    pub keys: Option<KeyList>,
    pub axes: Option<AxisList>,
}

impl Pulse {
    /// Creates a new Pulse
    ///
    /// # Example
    /// ```
    /// use chord2key::constants::*;
    /// use chord2key::output::actions::*;
    ///
    /// let pulse = Pulse::new(Some(vec![KeyCode::KEY_W]), None);
    ///
    /// assert!(pulse.keys.is_some());
    /// assert!(pulse.axes.is_none());
    /// ```
    pub fn new(keys: Option<KeyList>, axes: Option<AxisList>) -> Self {
        Self {
            keys,
            axes,
        }
    }
}

/// The data used to represent a change of output state
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct StateChange {
    pub keys: Option<KeyStateChange>,
    pub axes: Option<AxisList>,
}

impl StateChange {
    /// Creates a new StateChange
    ///
    /// # Example
    /// ```
    /// use chord2key::constants::*;
    /// use chord2key::output::actions::*;
    ///
    /// let keys = Some(KeyStateChange {
    ///     keys: vec![KeyCode::KEY_W],
    ///     state: PressState::Down,
    /// });
    /// let change = StateChange::new(keys, None);
    ///
    /// assert!(change.axes.is_none());
    /// assert!(change.keys.unwrap().keys[0] == KeyCode::KEY_W);
    /// ```
    pub fn new(keys: Option<KeyStateChange>, axes: Option<AxisList>) -> Self {
        Self {
            keys,
            axes,
        }
    }

    /// Inverts a StateChange to its reciprocal.
    ///
    /// This flips the press state of its keys (up to down and vice versa), and sets all axis values
    /// to 0.
    ///
    /// # Example
    /// ```
    /// use chord2key::constants::*;
    /// use chord2key::output::actions::*;
    ///
    /// let keys = Some(KeyStateChange {
    ///     keys: vec![KeyCode::KEY_W],
    ///     state: PressState::Down,
    /// });
    /// let axes = Some(vec![(RelAxisCode::REL_X, 5)].into());
    /// let mut change = StateChange::new(keys, axes);
    ///
    /// if let Some(ref axes) = change.axes {
    ///     assert!(axes.iter().next().unwrap().state() == 5);
    /// }
    /// if let Some(ref keys) = change.keys {
    ///     assert!(keys.state == PressState::Down);
    /// }
    ///
    /// change.inverse();
    ///
    /// assert!(change.axes.unwrap().iter().next().unwrap().state() == 0);
    /// assert!(change.keys.unwrap().state == PressState::Up);
    /// ```
    pub fn inverse(&mut self) -> &mut Self {
        self.keys.iter_mut().for_each(|change| change.inverse());
        self.axes.iter_mut().for_each(|change| change.inverse());
        self
    }
}

/// The data used to represent a change of key state
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct KeyStateChange {
    pub keys: KeyList,
    pub state: PressState,
}

impl KeyStateChange {
    /// Inverses the state of a KeyStateChange
    ///
    /// # Example
    /// ```
    /// use chord2key::constants::*;
    /// use chord2key::output::actions::*;
    ///
    /// let mut change = KeyStateChange {
    ///     keys: vec![KeyCode::KEY_W, KeyCode::KEY_S],
    ///     state: PressState::Down,
    /// };
    ///
    /// assert_eq!(change.state, PressState::Down);
    ///
    /// change.inverse();
    /// assert_eq!(change.state, PressState::Up);
    /// ```
    pub fn inverse(&mut self) {
        match self.state {
            PressState::Down => {
                self.state = PressState::Up;
            }
            PressState::Up => {
                self.state = PressState::Down;
            }
        }
    }
}

impl From<StateChange> for Pulse {
    fn from(sc: StateChange) -> Self {
        Self {
            keys: sc.keys.map(|ksc| ksc.keys),
            axes: sc.axes,
        }
    }
}
impl From<Toggle> for Pulse {
    fn from(t: Toggle) -> Self {
        Self {
            keys: t.keys,
            axes: t.axes,
        }
    }
}

impl From<Pulse> for StateChange {
    fn from(pulse: Pulse) -> Self {
        Self {
            keys: pulse.keys.map(|keys| KeyStateChange {
                keys,
                state: PressState::Down,
            }),
            axes: pulse.axes,
        }
    }
}
impl From<Toggle> for StateChange {
    fn from(t: Toggle) -> Self {
        Self {
            keys: t.keys.map(|keys| KeyStateChange {
                keys,
                state: PressState::Down,
            }),
            axes: t.axes,
        }
    }
}

impl From<Pulse> for Toggle {
    fn from(pulse: Pulse) -> Self {
        Self {
            keys: pulse.keys,
            axes: pulse.axes,
        }
    }
}
impl From<StateChange> for Toggle {
    fn from(sc: StateChange) -> Self {
        Self {
            keys: sc.keys.map(|ksc| ksc.keys),
            axes: sc.axes,
        }
    }
}

impl From<OutputAction> for Pulse {
    fn from(ev: OutputAction) -> Self {
        match ev {
            OutputAction::Pulse(p) => p,
            OutputAction::StateChange(sc) => sc.into(),
            OutputAction::Toggle(t) => t.into(),
        }
    }
}
impl From<OutputAction> for StateChange {
    fn from(ev: OutputAction) -> Self {
        match ev {
            OutputAction::Pulse(p) => p.into(),
            OutputAction::StateChange(sc) => sc,
            OutputAction::Toggle(t) => t.into(),
        }
    }
}
impl From<OutputAction> for Toggle {
    fn from(ev: OutputAction) -> Self {
        match ev {
            OutputAction::Pulse(p) => p.into(),
            OutputAction::StateChange(sc) => sc.into(),
            OutputAction::Toggle(t) => t,
        }
    }
}

/// A list of KeyCodes.
pub type KeyList = Vec<KeyCode>;

/// A list of Relative Axes and their state
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct AxisList(Vec<RelAxisEvent>);

impl AxisList {
    /// Inverts all axis states inside the list
    ///
    /// The inverse of an axis state is defined to always be 0.
    ///
    /// Example:
    /// ```
    /// use chord2key::output::actions::*;
    /// use chord2key::constants::*;
    ///
    /// let mut list: AxisList = vec![
    ///     (RelAxisCode::REL_X, -5),
    ///     (RelAxisCode::REL_Y,-5),
    /// ].into();
    ///
    /// list.iter().for_each(|e| {
    ///     assert!(e.state() == -5);
    /// });
    ///
    /// list.inverse();
    ///
    /// list.iter().for_each(|e| {
    ///     assert!(e.state() == 0);
    /// });
    pub fn inverse(&mut self) {
        self.0.iter_mut().for_each(|e| e.set_state(0));
    }

    /// Returns an iterator over immutable references to the RelAxisEvents within the list
    ///
    /// Example:
    /// ```
    /// use chord2key::output::actions::*;
    /// use chord2key::constants::*;
    ///
    /// let list: AxisList = vec![
    ///     (RelAxisCode::REL_X, -5),
    ///     (RelAxisCode::REL_Y,-5),
    /// ].into();
    ///
    /// list.iter().for_each(|e| {
    ///     assert!(e.state() == -5);
    /// });
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = &RelAxisEvent> {
        self.0.iter()
    }

    /// Returns an iterator over mutable references to the RelAxisEvents within the list
    ///
    /// Example:
    /// ```
    /// use chord2key::output::actions::*;
    /// use chord2key::constants::*;
    ///
    /// let mut list: AxisList = vec![
    ///     (RelAxisCode::REL_X, -5),
    ///     (RelAxisCode::REL_Y,-5),
    /// ].into();
    ///
    /// list.iter().for_each(|e| {
    ///     assert!(e.state() == -5);
    /// });
    ///
    /// list.iter_mut().for_each(|e| {
    ///     e.set_state(2);
    /// });
    ///
    /// list.iter().for_each(|e| {
    ///     assert!(e.state() == 2);
    /// });
    /// ```
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut RelAxisEvent> {
        self.0.iter_mut()
    }
}

impl FromIterator<RelAxisEvent> for AxisList {
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = RelAxisEvent>,
    {
        Self(Vec::<RelAxisEvent>::from_iter(iter))
    }
}

impl From<Vec<(RelAxisCode, i32)>> for AxisList {
    fn from(al: Vec<(RelAxisCode, i32)>) -> Self {
        Self(
            al.iter()
                .map(|(code, state)| RelAxisEvent::new(*code, *state))
                .collect(),
        )
    }
}