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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! Driver for a PS/2 keyboard.
//!
//! Supports PS/2 Scan Code Set 1 and 2, on both UK and UK English keyboards. See [the
//! OSDev Wiki](https://wiki.osdev.org/PS/2_Keyboard).
//!
//! Requires that you sample a pin in an interrupt routine and shift in the
//! bit. We don't sample the pin in this library, as that makes testing
//! difficult, and it means you have to make this object a global static mut
//! that the interrupt can access, which is unsafe.

#![cfg_attr(not(test), no_std)]

// ****************************************************************************
//
// Imports
//
// ****************************************************************************

#[cfg(not(test))]
use core::marker::PhantomData;

#[cfg(test)]
use std::marker::PhantomData;

// ****************************************************************************
//
// Modules
//
// ****************************************************************************

mod scancodes;
pub use scancodes::{ScancodeSet1, ScancodeSet2};

// ****************************************************************************
//
// Public Types
//
// ****************************************************************************

/// `Keyboard<T, S>` encapsulates decode/sampling logic, and handles state transitions and key events.
/// Size: 10 bytes
#[derive(Debug)]
pub struct Keyboard<T, S>
where
    T: KeyboardLayout,
    S: ScancodeSet,
{
    register: u16,
    num_bits: u8,
    decode_state: DecodeState,
    modifiers: Modifiers,
    _layout: PhantomData<T>,
    _set: PhantomData<S>,
}

/// Indicates different error conditions.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Error {
    BadStartBit,
    BadStopBit,
    ParityError,
    UnknownKeyCode,
    #[doc(hidden)]
    InvalidState,
}

/// Keycodes that can be generated by a keyboard.
#[derive(Debug, PartialEq, Eq, Copy, Clone, PartialOrd, Ord)]
pub enum KeyCode {
    AltLeft,
    AltRight,
    ArrowDown,
    ArrowLeft,
    ArrowRight,
    ArrowUp,
    BackSlash,
    Backspace,
    BackTick,
    BracketSquareLeft,
    BracketSquareRight,
    CapsLock,
    Comma,
    ControlLeft,
    ControlRight,
    Delete,
    End,
    Enter,
    Escape,
    Equals,
    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F12,
    Fullstop,
    Home,
    Insert,
    Key1,
    Key2,
    Key3,
    Key4,
    Key5,
    Key6,
    Key7,
    Key8,
    Key9,
    Key0,
    Menus,
    Minus,
    Numpad0,
    Numpad1,
    Numpad2,
    Numpad3,
    Numpad4,
    Numpad5,
    Numpad6,
    Numpad7,
    Numpad8,
    Numpad9,
    NumpadEnter,
    NumpadLock,
    NumpadSlash,
    NumpadStar,
    NumpadMinus,
    NumpadPeriod,
    NumpadPlus,
    PageDown,
    PageUp,
    PauseBreak,
    PrintScreen,
    ScrollLock,
    SemiColon,
    ShiftLeft,
    ShiftRight,
    Slash,
    Spacebar,
    Tab,
    Quote,
    WindowsLeft,
    WindowsRight,
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H,
    I,
    J,
    K,
    L,
    M,
    N,
    O,
    P,
    Q,
    R,
    S,
    T,
    U,
    V,
    W,
    X,
    Y,
    Z,
    /// Not on US keyboards
    HashTilde,
    // Scan code set 1 unique codes
    PrevTrack,
    NextTrack,
    Mute,
    Calculator,
    Play,
    Stop,
    VolumeDown,
    VolumeUp,
    WWWHome,
}

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum KeyState {
    Up,
    Down,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct KeyEvent {
    pub code: KeyCode,
    pub state: KeyState,
}

pub trait KeyboardLayout {
    /// Convert a `KeyCode` enum to a Unicode character, if possible.
    /// KeyCode::A maps to `Some('a')` (or `Some('A')` if shifted), while
    /// KeyCode::AltLeft returns `None`
    fn map_keycode(keycode: KeyCode, modifiers: &Modifiers) -> DecodedKey;
}

pub trait ScancodeSet {
    /// Handles state logic based on the byte.
    /// `ConsumeState::Consume(state)` indicates that the byte is now consumed and
    /// there may or may not be a new state.
    ///
    /// `ConsumeState::Proceed(state)` indicates that the byte should be passed to
    /// the map methods, and there may or may not be a new state.
    fn advance_state(state: DecodeState, code: u8) -> Result<ConsumeState, Error>;

    /// Convert a Scan Code set X byte to our 'KeyCode' enum
    fn map_scancode(code: u8) -> Result<KeyCode, Error>;

    /// Convert a Scan Code Set X extended byte (prefixed E0) to our `KeyCode`
    /// enum.
    fn map_extended_scancode(code: u8) -> Result<KeyCode, Error>;
}

pub enum ConsumeState {
    Consume(DecodeState),
    Proceed(DecodeState),
}

impl ConsumeState {
    /// Allocates a new decode state
    fn extract_state(&self) -> DecodeState {
        match self {
            &ConsumeState::Consume(ref st) => st.clone(),
            &ConsumeState::Proceed(ref st) => st.clone(),
        }
    }
}

#[derive(Debug)]
pub struct Modifiers {
    pub lshift: bool,
    pub rshift: bool,
    pub numlock: bool,
    pub capslock: bool,
    pub alt_gr: bool,
}

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum DecodedKey {
    RawKey(KeyCode),
    Unicode(char),
}

// ****************************************************************************
//
// Public Data
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Private Types
//
// ****************************************************************************

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum DecodeState {
    Start,
    Extended,
    Release,
    ExtendedRelease,
}

// ****************************************************************************
//
// Private Data
//
// ****************************************************************************

const KEYCODE_BITS: u8 = 11;
const EXTENDED_KEY_CODE: u8 = 0xE0;
const KEY_RELEASE_CODE: u8 = 0xF0;

// ****************************************************************************
//
// Public Functions and Implementation
//
// ****************************************************************************

impl<T, S> Keyboard<T, S>
where
    T: KeyboardLayout,
    S: ScancodeSet,
{
    /// Make a new Keyboard object with the given layout.
    pub fn new(_layout: T, _set: S) -> Keyboard<T, S> {
        Keyboard {
            register: 0,
            num_bits: 0,
            decode_state: DecodeState::Start,
            modifiers: Modifiers {
                lshift: false,
                rshift: false,
                numlock: true,
                capslock: false,
                alt_gr: false,
            },
            _layout: PhantomData,
            _set: PhantomData,
        }
    }

    /// Clears the bit register.
    ///
    /// Call this when there is a timeout reading data from the keyboard.
    pub fn clear(&mut self) {
        self.register = 0;
        self.num_bits = 0;
        self.decode_state = DecodeState::Start;
    }

    /// Processes a 16-bit word from the keyboard.
    ///
    /// * The start bit (0) must be in bit 0.
    /// * The data octet must be in bits 1..8, with the LSB in bit 1 and the
    ///   MSB in bit 8.
    /// * The parity bit must be in bit 9.
    /// * The stop bit (1) must be in bit 10.
    pub fn add_word(&mut self, word: u16) -> Result<Option<KeyEvent>, Error> {
        let byte = Self::check_word(word)?;
        self.add_byte(byte)
    }

    /// Processes an 8-bit byte from the keyboard.
    ///
    /// We assume the start, stop and parity bits have been processed and
    /// verified.
    pub fn add_byte(&mut self, byte: u8) -> Result<Option<KeyEvent>, Error> {
        let st = self.decode_state;
        self.clear();
        let consume_state = S::advance_state(st, byte)?;
        self.decode_state = consume_state.extract_state();
        match consume_state {
            ConsumeState::Consume(_) => Ok(None),
            ConsumeState::Proceed(st) => match st {
                DecodeState::Start => {
                    let code = S::map_scancode(byte)?;
                    Ok(Some(KeyEvent::new(code, KeyState::Down)))
                }
                DecodeState::Extended => {
                    let code = S::map_extended_scancode(byte)?;
                    Ok(Some(KeyEvent::new(code, KeyState::Down)))
                }
                DecodeState::Release => {
                    let code = S::map_scancode(byte)?;
                    Ok(Some(KeyEvent::new(code, KeyState::Up)))
                }
                DecodeState::ExtendedRelease => {
                    let code = S::map_extended_scancode(byte)?;
                    Ok(Some(KeyEvent::new(code, KeyState::Up)))
                }
            },
        }
    }

    /// Shift a bit into the register.
    ///
    /// Call this /or/ call `add_word` - don't call both.
    /// Until the last bit is added you get Ok(None) returned.
    pub fn add_bit(&mut self, bit: bool) -> Result<Option<KeyEvent>, Error> {
        self.register |= (bit as u16) << self.num_bits;
        self.num_bits += 1;
        if self.num_bits == KEYCODE_BITS {
            let word = self.register;
            self.add_word(word)
        } else {
            Ok(None)
        }
    }

    /// Processes a `KeyEvent` returned from `add_bit`, `add_byte` or `add_word`
    /// and produces a decoded key.
    ///
    /// For example, the KeyEvent for pressing the '5' key on your keyboard
    /// gives a DecodedKey of unicode character '5', unless the shift key is
    /// held in which case you get the unicode character '%'.
    pub fn process_keyevent(&mut self, ev: KeyEvent) -> Option<DecodedKey> {
        match ev {
            KeyEvent {
                code: KeyCode::ShiftLeft,
                state: KeyState::Down,
            } => {
                self.modifiers.lshift = true;
                None
            }
            KeyEvent {
                code: KeyCode::ShiftRight,
                state: KeyState::Down,
            } => {
                self.modifiers.rshift = true;
                None
            }
            KeyEvent {
                code: KeyCode::ShiftLeft,
                state: KeyState::Up,
            } => {
                self.modifiers.lshift = false;
                None
            }
            KeyEvent {
                code: KeyCode::ShiftRight,
                state: KeyState::Up,
            } => {
                self.modifiers.rshift = false;
                None
            }
            KeyEvent {
                code: KeyCode::CapsLock,
                state: KeyState::Down,
            } => {
                self.modifiers.capslock = !self.modifiers.capslock;
                None
            }
            KeyEvent {
                code: KeyCode::NumpadLock,
                state: KeyState::Down,
            } => {
                self.modifiers.numlock = !self.modifiers.numlock;
                None
            }
            KeyEvent {
                code: KeyCode::AltRight,
                state: KeyState::Down,
            } => {
                self.modifiers.alt_gr = true;
                None
            }
            KeyEvent {
                code: KeyCode::AltRight,
                state: KeyState::Up,
            } => {
                self.modifiers.alt_gr = false;
                None
            }
            KeyEvent {
                code: c,
                state: KeyState::Down,
            } => Some(T::map_keycode(c, &self.modifiers)),
            _ => None,
        }
    }

    fn get_bit(word: u16, offset: usize) -> bool {
        ((word >> offset) & 0x0001) != 0
    }

    fn has_even_number_bits(data: u8) -> bool {
        (data.count_ones() % 2) == 0
    }

    /// Check 11-bit word has 1 start bit, 1 stop bit and an odd parity bit.
    fn check_word(word: u16) -> Result<u8, Error> {
        let start_bit = Self::get_bit(word, 0);
        let parity_bit = Self::get_bit(word, 9);
        let stop_bit = Self::get_bit(word, 10);
        let data = ((word >> 1) & 0xFF) as u8;

        if start_bit {
            return Err(Error::BadStartBit);
        }

        if !stop_bit {
            return Err(Error::BadStopBit);
        }

        let need_parity = Self::has_even_number_bits(data);

        // Odd parity, so these must not match
        if need_parity != parity_bit {
            return Err(Error::ParityError);
        }

        Ok(data)
    }
}

impl KeyEvent {
    pub fn new(code: KeyCode, state: KeyState) -> KeyEvent {
        KeyEvent { code, state }
    }
}

// ****************************************************************************
//
// Keyboard Layouts
//
// ****************************************************************************

impl Modifiers {
    pub fn is_shifted(&self) -> bool {
        (self.lshift | self.rshift) ^ self.capslock
    }
}

pub mod layouts;

// ****************************************************************************
//
// Tests
//
// ****************************************************************************

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_f9() {
        let mut k = Keyboard::new(layouts::Us104Key, ScancodeSet2);
        // start
        assert_eq!(k.add_bit(false), Ok(None));
        // 8 data bits (LSB first)
        assert_eq!(k.add_bit(true), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        // parity
        assert_eq!(k.add_bit(false), Ok(None));
        // stop
        assert_eq!(
            k.add_bit(true),
            Ok(Some(KeyEvent::new(KeyCode::F9, KeyState::Down)))
        );
    }

    #[test]
    fn test_f9_word() {
        let mut k = Keyboard::new(layouts::Us104Key, ScancodeSet2);
        assert_eq!(
            k.add_word(0x0402),
            Ok(Some(KeyEvent::new(KeyCode::F9, KeyState::Down)))
        );
    }

    #[test]
    fn test_f9_byte() {
        let mut k = Keyboard::new(layouts::Us104Key, ScancodeSet2);
        assert_eq!(
            k.add_byte(0x01),
            Ok(Some(KeyEvent::new(KeyCode::F9, KeyState::Down)))
        );
    }

    #[test]
    fn test_keyup_keydown() {
        let mut k = Keyboard::new(layouts::Us104Key, ScancodeSet2);
        assert_eq!(
            k.add_byte(0x01),
            Ok(Some(KeyEvent::new(KeyCode::F9, KeyState::Down)))
        );
        assert_eq!(
            k.add_byte(0x01),
            Ok(Some(KeyEvent::new(KeyCode::F9, KeyState::Down)))
        );
        assert_eq!(k.add_byte(0xF0), Ok(None));
        assert_eq!(
            k.add_byte(0x01),
            Ok(Some(KeyEvent::new(KeyCode::F9, KeyState::Up)))
        );
    }

    #[test]
    fn test_f5() {
        let mut k = Keyboard::new(layouts::Us104Key, ScancodeSet2);
        // start
        assert_eq!(k.add_bit(false), Ok(None));
        // 8 data bits (LSB first)
        assert_eq!(k.add_bit(true), Ok(None));
        assert_eq!(k.add_bit(true), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        // parity
        assert_eq!(k.add_bit(true), Ok(None));
        // stop
        assert_eq!(
            k.add_bit(true),
            Ok(Some(KeyEvent::new(KeyCode::F5, KeyState::Down)))
        );
    }

    #[test]
    fn test_f5_up() {
        let mut k = Keyboard::new(layouts::Us104Key, ScancodeSet2);
        // Send F0

        // start
        assert_eq!(k.add_bit(false), Ok(None));
        // 8 data bits (LSB first)
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(true), Ok(None));
        assert_eq!(k.add_bit(true), Ok(None));
        assert_eq!(k.add_bit(true), Ok(None));
        assert_eq!(k.add_bit(true), Ok(None));
        // parity
        assert_eq!(k.add_bit(true), Ok(None));
        // stop
        assert_eq!(k.add_bit(true), Ok(None));

        // Send 03

        // start
        assert_eq!(k.add_bit(false), Ok(None));
        // 8 data bits (LSB first)
        assert_eq!(k.add_bit(true), Ok(None));
        assert_eq!(k.add_bit(true), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        assert_eq!(k.add_bit(false), Ok(None));
        // parity
        assert_eq!(k.add_bit(true), Ok(None));
        // stop
        assert_eq!(
            k.add_bit(true),
            Ok(Some(KeyEvent::new(KeyCode::F5, KeyState::Up)))
        );
    }

    #[test]
    fn test_shift() {
        let mut k = Keyboard::new(layouts::Uk105Key, ScancodeSet2);
        // A with left shift held
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::ShiftLeft, KeyState::Down)),
            None
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::A, KeyState::Down)),
            Some(DecodedKey::Unicode('A'))
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::A, KeyState::Up)),
            None
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::ShiftLeft, KeyState::Up)),
            None
        );

        // A with no shift
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::A, KeyState::Down)),
            Some(DecodedKey::Unicode('a'))
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::A, KeyState::Up)),
            None
        );

        // A with right shift held
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::ShiftRight, KeyState::Down)),
            None
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::A, KeyState::Down)),
            Some(DecodedKey::Unicode('A'))
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::A, KeyState::Up)),
            None
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::ShiftRight, KeyState::Up)),
            None
        );

        // Caps lock ON
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::CapsLock, KeyState::Down)),
            None
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::CapsLock, KeyState::Up)),
            None
        );

        // Letters are now caps
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::X, KeyState::Down)),
            Some(DecodedKey::Unicode('X'))
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::X, KeyState::Up)),
            None
        );

        // Unless you press shift
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::ShiftRight, KeyState::Down)),
            None
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::A, KeyState::Down)),
            Some(DecodedKey::Unicode('a'))
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::A, KeyState::Up)),
            None
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::ShiftRight, KeyState::Up)),
            None
        );
    }

    #[test]
    fn test_numlock() {
        let mut k = Keyboard::new(layouts::Uk105Key, ScancodeSet2);

        // Numlock ON by default
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::Numpad0, KeyState::Down)),
            Some(DecodedKey::Unicode('0'))
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::Numpad0, KeyState::Up)),
            None
        );

        // Numlock OFF
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::NumpadLock, KeyState::Down)),
            None
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::NumpadLock, KeyState::Up)),
            None
        );

        // Now KP_0 produces INSERT
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::Numpad0, KeyState::Down)),
            Some(DecodedKey::RawKey(KeyCode::Insert))
        );
        assert_eq!(
            k.process_keyevent(KeyEvent::new(KeyCode::Numpad0, KeyState::Up)),
            None
        );
    }

    #[test]
    fn validate_scancodes() {
        let mut codes = Vec::new();
        let mut errs = Vec::new();
        for code in 0x00..=0x7F {
            let r = ScancodeSet1::map_scancode(code);
            match r {
                Ok(c) => codes.push(c),
                Err(_) => errs.push(code),
            }
        }
        codes.sort();
        println!("{:?}", codes);
        assert_eq!(codes.len(), 85);
        assert_eq!(errs.len(), 43);

        let mut codes = Vec::new();
        let mut errs = Vec::new();
        for code in 0x00..=0xFF {
            let r = ScancodeSet2::map_scancode(code);
            match r {
                Ok(c) => codes.push(c),
                Err(_) => errs.push(code),
            }
        }
        codes.sort();
        println!("{:?}", codes);
        assert_eq!(codes.len(), 85);
        assert_eq!(errs.len(), 171);
    }

    #[test]
    fn test_set_1_down_up_down() {
        let mut k = Keyboard::new(layouts::Us104Key, ScancodeSet1);
        assert_eq!(
            k.add_byte(0x1e),
            Ok(Some(KeyEvent::new(KeyCode::A, KeyState::Down)))
        );
        assert_eq!(
            k.add_byte(0x9e),
            Ok(Some(KeyEvent::new(KeyCode::A, KeyState::Up)))
        );
        assert_eq!(
            k.add_byte(0x1f),
            Ok(Some(KeyEvent::new(KeyCode::S, KeyState::Down)))
        );
    }
}

// ****************************************************************************
//
// End Of File
//
// ****************************************************************************