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
use crate::handlers::{Action, ProcessKeys, HandlerResult};
use crate::key_codes::{KeyCode, KeyCodeInfo};
use crate::{iter_unhandled_mut, Event, EventStatus, USBKeyOut};
use no_std_compat::prelude::v1::*;

/// A sequence is a series of keystrokes (press and release)
/// that upon finish (ie. the release of the last key)
/// sends first a (configurable) number of backspaces (to undo the input)
/// and then an action.
///
/// sequence keys - even if matching are not handled by Sequence,
/// except if they're from the private range, in which
/// case the Sequence will consume the Events.
///
/// It is suggested to prefix your sequences with a unicode symbol,
/// so you can observe the feedback.
///
/// Note that for a final KeyCode::*, you will need to send a backspace,
/// but for a final unicode (or private) one you don't.
///
/// Sequences that are prefixes of others require you to double
/// up on the last key stroke of the prefix. Hitting it the first time
/// triggers the prefix sequence, eating the keypress event,
/// and the second time the longer sequence sees it and advances.
pub struct Sequence<'a, M> {
    sequence: &'a [u32],
    callback: M,
    backspaces: u8,
    pos: u8,
}

impl<'a, M: Action> Sequence<'a, M> {
    pub fn new(sequence: &'a [u32], callback: M, backspaces: u8) -> Sequence<'a, M> {
        if sequence.len() > 254 {
            panic!("Sequence too long, max 254 key codes");
        }
        Sequence {
            sequence,
            callback,
            backspaces,
            pos: 0,
        }
    }
}

impl<T: USBKeyOut, M: Action> ProcessKeys<T> for Sequence<'_, M> {
    fn process_keys(&mut self, events: &mut Vec<(Event, EventStatus)>, output: &mut T) ->HandlerResult {
        let mut codes_to_delete: Vec<u32> = Vec::new();
        // we need to scan for handled key releases if we don't see any unhandled ones -
        // they might have triggered a different sequence, which set them to Handled
        // but we still need to abort this one
        let mut matched = false;
        for (event, status) in iter_unhandled_mut(events).rev() {
            match event {
                Event::KeyRelease(kc) => {
                    matched = true;
                    if kc.keycode == self.sequence[self.pos as usize] {
                        if kc.keycode.is_private_keycode() {
                            *status = EventStatus::Handled;
                        }
                        self.pos += 1;
                        if self.pos == self.sequence.len() as u8 {
                            self.pos = 0;
                            for _ in 0..self.backspaces {
                                output.send_keys(&[KeyCode::BSpace]);
                                output.send_empty();
                            }
                            self.callback.on_trigger(output);
                            *status = EventStatus::Handled;
                            if !codes_to_delete.contains(&kc.original_keycode) {
                                codes_to_delete.push(kc.original_keycode);
                            }
                        }
                    } else {
                        self.pos = 0;
                    }
                }
                Event::KeyPress(kc) => {
                    if codes_to_delete.contains(&kc.original_keycode) {
                        *status = EventStatus::Handled;
                    }
                    if kc.keycode == self.sequence[self.pos as usize]
                        && kc.keycode.is_private_keycode()
                    {
                        *status = EventStatus::Handled;
                    }
                }
                _ => {}
            }
        }
        if !matched {
            for (event, _status) in events.iter() {
                match event {
                    Event::KeyRelease(kc) => {
                        if kc.keycode != self.sequence[self.pos as usize] {
                            self.pos = 0;
                        }
                    }
                    _ => {}
                }
            }
        }
    HandlerResult::NoOp
    }
}
#[cfg(test)]
//#[macro_use]
//extern crate std;
mod tests {
    use crate::handlers::{Sequence, USBKeyboard, UnicodeKeyboard};
    #[allow(unused_imports)]
    use crate::key_codes::{KeyCode, UserKey};
    #[allow(unused_imports)]
    use crate::test_helpers::{check_output, Checks, KeyOutCatcher};
    use crate::{Keyboard, USBKeyOut, UnicodeSendMode};
    #[allow(unused_imports)]
    use no_std_compat::prelude::v1::*;
    #[test]
    fn test_sequence() {
        use crate::key_codes::KeyCode::*;

        let map = &[A.to_u32(), B.to_u32(), C.to_u32()];
        let l = Sequence::new(map, X, 3);
        let mut k = Keyboard::new(KeyOutCatcher::new());
        k.output.state().unicode_mode = UnicodeSendMode::Debug;
        k.add_handler(Box::new(l));
        k.add_handler(Box::new(USBKeyboard::new()));

        k.pc(A, &[&[A]]);
        k.rc(A, &[&[]]);

        k.pc(B, &[&[B]]);
        k.rc(B, &[&[]]);

        k.pc(C, &[&[C]]);
        k.rc(C, &[&[BSpace], &[], &[BSpace], &[], &[BSpace], &[], &[X]]);

        k.pc(A, &[&[A]]);
        k.rc(A, &[&[]]);

        k.pc(B, &[&[B]]);
        k.rc(B, &[&[]]);

        k.pc(D, &[&[D]]);
        k.rc(D, &[&[]]);

        k.pc(B, &[&[B]]);
        k.rc(B, &[&[]]);

        k.pc(C, &[&[C]]);
        k.rc(C, &[&[]]);

        k.pc(A, &[&[A]]);
        k.rc(A, &[&[]]);

        k.pc(B, &[&[B]]);
        k.rc(B, &[&[]]);

        k.pc(C, &[&[C]]);
        k.rc(C, &[&[BSpace], &[], &[BSpace], &[], &[BSpace], &[], &[X]]);
    }

    #[test]
    fn test_sequence_unicode_trigger() {
        use crate::key_codes::KeyCode::*;

        let map = &[0xDF, B.to_u32(), C.to_u32()];
        let l = Sequence::new(map, X, 3);
        let mut k = Keyboard::new(KeyOutCatcher::new());
        k.output.state().unicode_mode = UnicodeSendMode::Debug;
        k.add_handler(Box::new(l));
        k.add_handler(Box::new(UnicodeKeyboard::new()));
        k.add_handler(Box::new(USBKeyboard::new()));

        k.pc(0xDF, &[&[]]);
        k.rc(0xDF, &[&[D], &[F], &[]]);

        k.pc(B, &[&[B]]);
        k.rc(B, &[&[]]);

        k.pc(C, &[&[C]]);
        k.rc(C, &[&[BSpace], &[], &[BSpace], &[], &[BSpace], &[], &[X]]);
    }
    #[test]
    fn test_sequence_private_trigger() {
        use crate::key_codes::KeyCode::*;

        let map = &[UserKey::UK1.to_u32(), B.to_u32(), C.to_u32()];
        let l = Sequence::new(map, X, 3);
        let mut k = Keyboard::new(KeyOutCatcher::new());
        k.output.state().unicode_mode = UnicodeSendMode::Debug;
        k.add_handler(Box::new(l));
        k.add_handler(Box::new(UnicodeKeyboard::new()));
        k.add_handler(Box::new(USBKeyboard::new()));

        k.pc(UserKey::UK1, &[&[]]);
        k.rc(UserKey::UK1, &[&[]]);

        k.pc(B, &[&[B]]);
        k.rc(B, &[&[]]);

        k.pc(C, &[&[C]]);
        k.rc(C, &[&[BSpace], &[], &[BSpace], &[], &[BSpace], &[], &[X]]);
    }
    #[test]
    fn test_sequence_mixed_trigger() {
        use crate::key_codes::KeyCode::*;
        let map = &[A.to_u32(), UserKey::UK1.to_u32(), 0x1234];
        let l = Sequence::new(map, X, 1);
        let mut k = Keyboard::new(KeyOutCatcher::new());
        k.output.state().unicode_mode = UnicodeSendMode::Debug;
        k.add_handler(Box::new(l));
        k.add_handler(Box::new(UnicodeKeyboard::new()));
        k.add_handler(Box::new(USBKeyboard::new()));

        k.pc(A, &[&[A]]);
        k.rc(A, &[&[]]);

        k.pc(UserKey::UK1, &[&[]]);
        k.rc(UserKey::UK1, &[&[]]);

        k.pc(0x1234, &[&[]]);
        k.rc(0x1234, &[&[BSpace], &[], &[X]]);
    }
    #[test]
    fn test_dual_sequence() {
        use crate::key_codes::KeyCode::*;
        let map = &[A.to_u32(), B.to_u32()];
        let map2 = &[A.to_u32(), C.to_u32()];
        let l1 = Sequence::new(map, X, 2);
        let l2 = Sequence::new(map2, Y, 1);
        let mut k = Keyboard::new(KeyOutCatcher::new());
        k.add_handler(Box::new(l1));
        k.add_handler(Box::new(l2));

        k.add_handler(Box::new(USBKeyboard::new()));

        k.pc(A, &[&[A]]);
        k.rc(A, &[&[]]);

        k.pc(B, &[&[B]]);
        k.rc(B, &[&[BSpace], &[], &[BSpace], &[], &[X]]);

        k.pc(C, &[&[C]]);
        k.rc(C, &[&[]]);
    }

    #[test]
    fn test_prefix_sequence() {
        use crate::key_codes::KeyCode::*;
        let map = &[A.to_u32(), B.to_u32()];
        let map2 = &[A.to_u32(), B.to_u32(), C.to_u32()];
        let l1 = Sequence::new(map, X, 2);
        let l2 = Sequence::new(map2, Y, 3);
        let mut k = Keyboard::new(KeyOutCatcher::new());
        k.add_handler(Box::new(l1));
        k.add_handler(Box::new(l2));

        k.add_handler(Box::new(USBKeyboard::new()));

        k.pc(A, &[&[A]]);
        k.rc(A, &[&[]]);

        k.pc(B, &[&[B]]);
        k.rc(B, &[&[BSpace], &[], &[BSpace], &[], &[X]]);

        k.pc(B, &[&[B]]);
        k.rc(B, &[&[]]);

        k.pc(C, &[&[C]]);
        k.rc(C, &[&[BSpace], &[], &[BSpace], &[], &[BSpace], &[], &[Y]]);
    }
}