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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use anyhow::{format_err, Result};
use fidl_fuchsia_input::{Key, KeymapId};
use fidl_fuchsia_ui_input3::{KeyEventType, KeyMeaning, LockState, Modifiers, NonPrintableKey};
use lazy_static::lazy_static;
use std::collections::{self, HashMap};
use tracing::{debug, error};

mod defs;

pub mod config;
pub mod inverse_keymap;
pub mod usages;

lazy_static! {
    /// A US QWERTY keymap.
    pub static ref US_QWERTY: Keymap<'static> = Keymap::new(&defs::QWERTY_MAP);

    /// A US DVORAK keymap.
    pub static ref US_DVORAK: Keymap<'static> = Keymap::new(&defs::DVORAK_MAP);

    /// A FR AZERTY keymap.
    pub static ref FR_AZERTY: Keymap<'static> = Keymap::new(&defs::FR_AZERTY_MAP);

    /// A US COLEMAK keymap.
    pub static ref US_COLEMAK: Keymap<'static> = Keymap::new(&defs::COLEMAK_MAP);
}

/// Gets a keymap based on the supplied `keymap` selector.  If no keymap is
/// found the fallback is always US QWERTY.
pub fn select_keymap<'a>(keymap: &Option<String>) -> &'a Keymap<'a> {
    match keymap {
        Some(ref k) if k == "FR_AZERTY" => &FR_AZERTY,
        Some(ref k) if k == "US_DVORAK" => &US_DVORAK,
        Some(ref k) if k == "US_COLEMAK" => &US_COLEMAK,
        _ => &US_QWERTY,
    }
}

/// Converts the keymap string into a supported `KeymapId`.
///
/// An unknown keymap string always becomes [KeymapId::UsQwerty].
pub fn into_keymap_id(keymap: &str) -> KeymapId {
    match keymap {
        "FR_AZERTY" => KeymapId::FrAzerty,
        "US_DVORAK" => KeymapId::UsDvorak,
        "US_COLEMAK" => KeymapId::UsColemak,
        _ => KeymapId::UsQwerty,
    }
}

/// Extracts key meaning in accordance with the Fuchsia key event API specification.
///
/// Key meaning is returned verbatim if defined; otherwise, the US QWERTY keymap is
/// applied to the supplied `key` and the currently active modifiers and lock state.
///
/// These usually come from a `fidl.fuchsia.ui.input3/KeyEvent`, so you can simply
/// pass its components in if you have one. But, a valid `KeyEvent` is not required,
/// and the caller can fill each of the parameters at will.
///
/// If neither the key nor the key meaning are defined, an "unidentified"
/// nonprintable key meaning is returned.
pub fn get_key_meaning(
    key: &Option<Key>,
    key_meaning: &Option<KeyMeaning>,
    lock_state: &Option<LockState>,
    modifiers: &Option<Modifiers>,
) -> KeyMeaning {
    key_meaning.unwrap_or_else(|| {
        // Specification note: If key meaning is unset, then the key meaning
        // must be recovered from the hardware key by applying the US_QWERTY
        // keymap to the hardware key value, using the currently applicable
        // modifier and lock state.
        let lock_state =
            LockStateKeys::new().with(lock_state.unwrap_or(LockState::from_bits_allow_unknown(0)));
        let modifiers =
            ModifierState::new().with(modifiers.unwrap_or(Modifiers::from_bits_allow_unknown(0)));
        let key = key.unwrap_or(Key::Unknown);
        US_QWERTY
            .apply(key, &modifiers, &lock_state)
            .unwrap_or(KeyMeaning::NonPrintableKey(NonPrintableKey::Unidentified))
    })
}

/// A codepoint returned by [hid_usage_to_code_point] for HID usages that do
/// not have an associated code point, e.g. Alt.
pub(crate) const EMPTY_CODEPOINT: u32 = 0;

/// A Us Qwerty keymap
pub struct Keymap<'a> {
    map: &'a [Option<defs::KeyLevels>],
}

impl AsRef<[Option<defs::KeyLevels>]> for Keymap<'_> {
    fn as_ref(&self) -> &[Option<defs::KeyLevels>] {
        self.map
    }
}

impl<'a> Keymap<'a> {
    /// Creates a new keymap.
    fn new(map: &'a [Option<defs::KeyLevels>]) -> Self {
        Keymap { map }
    }

    /// Attaches a fixed [KeyMeaning] to the given [Key] if one exists.
    ///
    /// These are mostly the default key meanings of keys on a US QWERTY keyboard.
    /// As such, we must try the key to key meaning mapping coming from the keymap first,
    /// to allow the keymap the option to move these keys around when this is desired.
    ///
    /// We do not really expect these to happen frequently in standardized keymaps,
    /// but custom keymaps might do this (e.g. mapping Esc to CapsLock), and in
    /// general we should avoid putting arbitrary constraints on key maps if such
    /// are not necessary.
    fn try_into_nonprintable(&self, key: Key) -> Option<KeyMeaning> {
        match key {
            Key::Enter => Some(NonPrintableKey::Enter),
            Key::Tab => Some(NonPrintableKey::Tab),
            Key::Backspace => Some(NonPrintableKey::Backspace),
            Key::Escape => Some(NonPrintableKey::Escape),
            Key::Up => Some(NonPrintableKey::Up),
            Key::Down => Some(NonPrintableKey::Down),
            Key::Left => Some(NonPrintableKey::Left),
            Key::Right => Some(NonPrintableKey::Right),
            Key::End => Some(NonPrintableKey::End),
            Key::Home => Some(NonPrintableKey::Home),
            Key::PageUp => Some(NonPrintableKey::PageUp),
            Key::PageDown => Some(NonPrintableKey::PageDown),
            Key::RightAlt => Some(if std::ptr::eq(self, &*FR_AZERTY) {
                // Used for Chromium testing - not yet handled consistently and
                // seriously.
                NonPrintableKey::AltGraph
            } else {
                NonPrintableKey::Alt
            }),
            Key::LeftAlt => Some(NonPrintableKey::Alt),
            Key::RightCtrl => Some(NonPrintableKey::Control),
            Key::LeftCtrl => Some(NonPrintableKey::Control),
            Key::CapsLock => Some(NonPrintableKey::CapsLock),
            Key::LeftShift => Some(NonPrintableKey::Shift),
            Key::RightShift => Some(NonPrintableKey::Shift),
            Key::LeftMeta => Some(NonPrintableKey::Meta),
            Key::RightMeta => Some(NonPrintableKey::Meta),
            Key::NumLock => Some(NonPrintableKey::NumLock),
            Key::ScrollLock => Some(NonPrintableKey::ScrollLock),
            Key::F1 => Some(NonPrintableKey::F1),
            Key::F2 => Some(NonPrintableKey::F2),
            Key::F3 => Some(NonPrintableKey::F3),
            Key::F4 => Some(NonPrintableKey::F4),
            Key::F5 => Some(NonPrintableKey::F5),
            Key::F6 => Some(NonPrintableKey::F6),
            Key::F7 => Some(NonPrintableKey::F7),
            Key::F8 => Some(NonPrintableKey::F8),
            Key::F9 => Some(NonPrintableKey::F9),
            Key::F10 => Some(NonPrintableKey::F10),
            Key::F11 => Some(NonPrintableKey::F11),
            Key::F12 => Some(NonPrintableKey::F12),

            // Multimedia keys, UI keys, browser keys etc.
            Key::AcBack => Some(NonPrintableKey::BrowserBack),
            Key::AcRefresh => Some(NonPrintableKey::BrowserRefresh),
            Key::AcFullScreenView => Some(NonPrintableKey::ZoomToggle),
            Key::AcSelectTaskApplication => Some(NonPrintableKey::Select),
            Key::BrightnessDown => Some(NonPrintableKey::BrightnessDown),
            Key::BrightnessUp => Some(NonPrintableKey::BrightnessUp),
            Key::PlayPause => Some(NonPrintableKey::MediaPlayPause),
            Key::Mute => Some(NonPrintableKey::AudioVolumeMute),
            Key::VolumeDown => Some(NonPrintableKey::AudioVolumeDown),
            Key::VolumeUp => Some(NonPrintableKey::AudioVolumeUp),
            _ => None,
        }
        .map(|k| KeyMeaning::NonPrintableKey(k))
    }

    /// Applies the keymap to the given key.
    pub fn apply(
        &self,
        key: Key,
        modifier_state: &impl ModifierChecker,
        lock_state: &impl LockStateChecker,
    ) -> Option<KeyMeaning> {
        let hid_usage = usages::input3_key_to_hid_usage(key);

        // Try to apply the keymap first. Failing that, try fixed nonprintable
        // keys.
        self.hid_usage_to_code_point(hid_usage, modifier_state, lock_state)
            .ok()
            .and_then(|v| if v == EMPTY_CODEPOINT { None } else { Some(v) })
            .map(KeyMeaning::Codepoint)
            .or_else(|| self.try_into_nonprintable(key))
            .or_else(|| {
                debug!(
                    ?key,
                    ?hid_usage,
                    modifiers = ?modifier_state,
                    ?lock_state,
                    "keymaps::Keymap::apply: no KeyMeaning"
                );
                None
            })
    }

    /// Converts a HID usage for a key to a Unicode code point where such a code point exists, based on
    /// a US QWERTY keyboard layout.  Returns EMPTY_CODEPOINT if a code point does not exist (e.g. Alt),
    /// and an error in case the mapping somehow fails.
    pub fn hid_usage_to_code_point(
        &self,
        hid_usage: u32,
        modifier_state: &impl ModifierChecker,
        lock_state: &impl LockStateChecker,
    ) -> Result<u32> {
        if (hid_usage as usize) < self.map.len() {
            if let Some(ref map_entry) = self.map[hid_usage as usize] {
                map_entry
                    .get_key(modifier_state, lock_state)
                    .map(|c| c as u32)
                    .ok_or(format_err!("Invalid USB HID code: {:?}", hid_usage))
            } else {
                Ok(EMPTY_CODEPOINT) // No code point provided by a keymap, e.g. Enter.
            }
        } else {
            Ok(EMPTY_CODEPOINT) // No code point available, e.g. Shift, Alt, etc.
        }
    }

    pub fn hid_usage_to_code_point_for_mods(
        &self,
        hid_usage: u32,
        shift: bool,
        caps_lock: bool,
    ) -> Option<u32> {
        let modifier_state = ModifierState::new()
            .with_if(Modifiers::LEFT_SHIFT, shift)
            .with_if(Modifiers::RIGHT_SHIFT, shift);
        let lock_state = LockStateKeys::new().with_if(LockState::CAPS_LOCK, caps_lock);
        let code_point = self.hid_usage_to_code_point(hid_usage, &modifier_state, &lock_state);
        match code_point {
            Ok(EMPTY_CODEPOINT) => None,
            Ok(c) => Some(c),
            Err(_) => None,
        }
    }
}

/// A trait for something that can be tested for modifier presence.
pub trait ModifierChecker: std::fmt::Debug {
    fn test(&self, value: Modifiers) -> bool;
}

/// Tracks the current state of "significant" modifier keys.
///
/// Currently, a modifier key is "significant" if it affects the mapping of a
/// Fuchsia key to a key meaning.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ModifierState {
    /// The internal modifier state.
    state: Modifiers,
}

impl Default for ModifierState {
    fn default() -> Self {
        Self { state: Modifiers::empty() }
    }
}

impl ModifierChecker for ModifierState {
    /// Test if the modifier state contains the modifiers from `value`.
    fn test(&self, value: Modifiers) -> bool {
        self.state.contains(value)
    }
}

impl ModifierState {
    /// Creates a new [ModifierState] initializes with the default state (no
    /// modifiers are actuated).
    pub fn new() -> Self {
        Default::default()
    }

    /// Unconditionally adds the given modifier into the modifier state as
    /// actuated.
    ///
    /// Returns `Self` for chaining.
    pub fn with(self, value: Modifiers) -> Self {
        let mut state = self.state;
        state.insert(value);

        // For "sided" modifiers, maintain the "side-less" bit invariant too.
        match value {
            Modifiers::LEFT_SHIFT | Modifiers::RIGHT_SHIFT => {
                state.insert(Modifiers::SHIFT);
            }
            Modifiers::LEFT_ALT | Modifiers::RIGHT_ALT => {
                state.insert(Modifiers::ALT);
            }
            Modifiers::LEFT_META | Modifiers::RIGHT_META => {
                state.insert(Modifiers::META);
            }
            Modifiers::LEFT_CTRL | Modifiers::RIGHT_CTRL => {
                state.insert(Modifiers::CTRL);
            }
            _ => {}
        }
        Self { state }
    }

    /// Retrieves the modifier state.
    pub fn get_state(&self) -> Modifiers {
        self.state.clone()
    }

    /// Adds `modifier` into the modifier state as actuated, if `set` is true.
    /// Otherwise makes no changes to [ModifierState].
    ///
    /// Returns `Self` for chaining.
    pub fn with_if(self, value: Modifiers, set: bool) -> Self {
        match set {
            false => self,
            true => self.with(value),
        }
    }

    /// Update the modifier tracker state with this event.
    pub fn update(&mut self, event: KeyEventType, key: Key) {
        match event {
            // PRESSED event is a regular key press.
            // SYNC event is an update to key presses after a focus regain.
            KeyEventType::Pressed | KeyEventType::Sync => match key {
                Key::CapsLock => self.state.insert(Modifiers::CAPS_LOCK),
                Key::NumLock => self.state.insert(Modifiers::NUM_LOCK),
                Key::ScrollLock => self.state.insert(Modifiers::SCROLL_LOCK),
                // These modifiers are not defined in Key.
                // Key::Function
                // Key::Symbol

                // For "sided" modifiers, we must also maintain the "side-less"
                // bit. Here, and everywhere below.
                Key::LeftShift => {
                    self.state.insert(Modifiers::LEFT_SHIFT | Modifiers::SHIFT);
                }
                Key::RightShift => {
                    self.state.insert(Modifiers::RIGHT_SHIFT | Modifiers::SHIFT);
                }
                Key::LeftAlt => {
                    self.state.insert(Modifiers::LEFT_ALT | Modifiers::ALT);
                }
                Key::RightAlt => {
                    self.state.insert(Modifiers::RIGHT_ALT | Modifiers::ALT);
                }
                Key::LeftMeta => {
                    self.state.insert(Modifiers::LEFT_META | Modifiers::META);
                }
                Key::RightMeta => {
                    self.state.insert(Modifiers::RIGHT_META | Modifiers::META);
                }
                Key::LeftCtrl => {
                    self.state.insert(Modifiers::LEFT_CTRL | Modifiers::CTRL);
                }
                Key::RightCtrl => {
                    self.state.insert(Modifiers::RIGHT_CTRL | Modifiers::CTRL);
                }
                _ => {}
            },
            // PRESSED event is a regular key release.
            // CANCEL event is an update to key presses after a focus loss.
            KeyEventType::Released | KeyEventType::Cancel => match key {
                Key::CapsLock => {
                    self.state.remove(Modifiers::CAPS_LOCK);
                }
                Key::NumLock => self.state.remove(Modifiers::NUM_LOCK),
                Key::ScrollLock => self.state.remove(Modifiers::SCROLL_LOCK),

                Key::LeftShift => {
                    self.state.remove(Modifiers::LEFT_SHIFT);
                    if !self.state.contains(Modifiers::RIGHT_SHIFT) {
                        self.state.remove(Modifiers::SHIFT);
                    }
                }
                Key::RightShift => {
                    self.state.remove(Modifiers::RIGHT_SHIFT);
                    if !self.test(Modifiers::LEFT_SHIFT) {
                        self.state.remove(Modifiers::SHIFT);
                    }
                }
                Key::LeftAlt => {
                    self.state.remove(Modifiers::LEFT_ALT);
                    if !self.state.contains(Modifiers::RIGHT_ALT) {
                        self.state.remove(Modifiers::ALT);
                    }
                }
                Key::RightAlt => {
                    self.state.remove(Modifiers::RIGHT_ALT);
                    if !self.test(Modifiers::LEFT_ALT) {
                        self.state.remove(Modifiers::ALT);
                    }
                }
                Key::LeftMeta => {
                    self.state.remove(Modifiers::LEFT_META);
                    if !self.state.contains(Modifiers::RIGHT_META) {
                        self.state.remove(Modifiers::META);
                    }
                }
                Key::RightMeta => {
                    self.state.remove(Modifiers::RIGHT_META);
                    if !self.test(Modifiers::LEFT_META) {
                        self.state.remove(Modifiers::META);
                    }
                }
                Key::LeftCtrl => {
                    self.state.remove(Modifiers::LEFT_CTRL);
                    if !self.state.contains(Modifiers::RIGHT_CTRL) {
                        self.state.remove(Modifiers::CTRL);
                    }
                }
                Key::RightCtrl => {
                    self.state.remove(Modifiers::RIGHT_CTRL);
                    if !self.test(Modifiers::LEFT_CTRL) {
                        self.state.remove(Modifiers::CTRL);
                    }
                }
                _ => {}
            },
        }
    }

    /// Update the modifier tracker with this event.
    pub fn update_with_key_meaning(&mut self, event: KeyEventType, key_meaning: KeyMeaning) {
        match event {
            KeyEventType::Pressed | KeyEventType::Sync => match key_meaning {
                KeyMeaning::NonPrintableKey(NonPrintableKey::AltGraph) => {
                    self.state.insert(Modifiers::ALT_GRAPH)
                }
                _ => {}
            },
            KeyEventType::Released | KeyEventType::Cancel => match key_meaning {
                KeyMeaning::NonPrintableKey(NonPrintableKey::AltGraph) => {
                    self.state.remove(Modifiers::ALT_GRAPH)
                }
                _ => {}
            },
        }
    }
}

// The state of each lock key.
#[derive(Debug, Hash)]
enum State {
    // Lock was pressed.  (aka S1, see below)
    LockPressed,
    // Lock was pressed and released. (aka S2)
    LockPressedAndReleased,
    // Lock was pressed for the second time in a row.  (aka S3)
    LockPressedSecondTime,
}

/// A lock state checker.
pub trait LockStateChecker: std::fmt::Debug {
    fn test(&self, value: LockState) -> bool;
}

/// The lock state of the lock keys.
///
/// Consult the state diagram below for the intended state transition.  The
/// state encoding is given in [State].
///
/// ```ignore
/// Key    """""""\_________/"""""""""""\_________/""""
/// State  -------<    S1  ><     S2   ><    S3   >----
/// ```
///
/// Any other state is not explicitly accounted for: the state of "the lock is
/// not active" is encoded by not having a record of the key state.  This
/// allows us to implement the state machine for an arbitrary number of lock
/// keys.
#[derive(Debug)]
pub struct LockStateKeys {
    state: HashMap<LockState, State>,
}

impl Default for LockStateKeys {
    fn default() -> Self {
        LockStateKeys { state: HashMap::new() }
    }
}

impl LockStateChecker for LockStateKeys {
    /// Returns true if the lock state value is set.
    fn test(&self, value: LockState) -> bool {
        self.state.contains_key(&value)
    }
}

impl LockStateKeys {
    /// Creates a new [LockStateKeys] initializes with the default state (no
    /// modifiers are actuated).
    pub fn new() -> Self {
        Default::default()
    }

    /// Unconditionally adds the given lock state as actuated.
    ///
    /// Returns `Self` for chaining.
    pub fn with(self, value: LockState) -> Self {
        let mut state = self.state;
        state.insert(value, State::LockPressedAndReleased);
        Self { state }
    }

    /// Adds `value` into the modifier state as actuated, if `set` is true.
    /// Otherwise makes no changes to [LockStateKeys].
    ///
    /// Returns `Self` for chaining.
    pub fn with_if(self, value: LockState, set: bool) -> Self {
        match set {
            false => self,
            true => self.with(value),
        }
    }

    /// Update the modifier tracker state with this event.
    pub fn update(&mut self, event: KeyEventType, key: Key) {
        let lock_key = match key {
            Key::CapsLock => LockState::CAPS_LOCK,
            Key::NumLock => LockState::NUM_LOCK,
            Key::ScrollLock => LockState::SCROLL_LOCK,
            // FUNCTION_LOCK
            // SYMBOL_LOCK
            // etc.
            _ => LockState::from_bits_allow_unknown(0),
        };
        if lock_key == LockState::from_bits_allow_unknown(0) {
            return;
        }
        let lock_state = self.state.get(&lock_key);
        match (event, lock_state) {
            (KeyEventType::Pressed, None) => {
                self.state.insert(lock_key, State::LockPressed);
            }
            (KeyEventType::Pressed, Some(State::LockPressedAndReleased)) => {
                self.state.insert(lock_key, State::LockPressedSecondTime);
            }
            (KeyEventType::Released, Some(State::LockPressed)) => {
                self.state.insert(lock_key, State::LockPressedAndReleased);
            }
            (KeyEventType::Released, Some(State::LockPressedSecondTime)) => {
                self.state.remove(&lock_key);
            }

            // These should not happen.
            (KeyEventType::Pressed, Some(State::LockPressed))
            | (KeyEventType::Pressed, Some(State::LockPressedSecondTime))
            | (KeyEventType::Released, None)
            | (KeyEventType::Released, Some(State::LockPressedAndReleased)) => {
                error!(?event, ?key, state = ?self.state, "unexpected state transition");
            }

            // SYNC and CANCEL don't change the lock state.
            (_, __) => {}
        }
    }

    /// Gets the recorded lock state.
    pub fn get_state(&self) -> LockState {
        self.state
            .keys()
            .map(|k| k.clone())
            .fold(LockState::from_bits_allow_unknown(0), |acc, k| acc | k)
    }
}

/// Tracks the current state of all the keyboard keys.
///
/// This is repetitive code, so perhaps better handle it here.  You can feed
/// the keyboard events into its [KeyState::update] method.
///
/// [KeyState] keeps track of the ordering the keys were pressed, and you can
/// call [KeyState::get_ordered_keys] to get a sequence of currently pressed
/// keys, in the order they were pressed.  This is useful for emitting keyboard
/// events that must happen in a very particular ordering.
#[derive(Debug, Clone, Default)]
pub struct KeyState {
    // Using BTreeSet for deterministic key iteration ordering.
    /// A collection that predictably iterates over all the keys in the order
    /// they were pressed.
    // Must iterate through key-value pairs in the order of increasing keys.
    ordinal_to_key: collections::BTreeMap<u64, Key>,
    /// Backwards map for quickly finding the ordinal of a specific key.
    // A bidirectional map could work here, but we don't use one yet on Fuchsia,
    // avoiding a new dependency with two maps.
    key_to_ordinal: collections::HashMap<Key, u64>,
    /// The next new pressed key will get this ordinal.
    // The ordinal increments with each unique key, but is reset back to zero
    // when no keys are pressed.  This should be enough to not overflow in any
    // realistic scenarios.
    next_ordinal: u64,
}

impl KeyState {
    /// Creates a new [KeyState]
    pub fn new() -> Self {
        KeyState {
            next_ordinal: 0,
            key_to_ordinal: collections::HashMap::new(),
            ordinal_to_key: collections::BTreeMap::new(),
        }
    }

    /// Updates the key tracking state with the given key event pair.
    pub fn update(&mut self, event: KeyEventType, key: Key) {
        match event {
            KeyEventType::Pressed | KeyEventType::Sync => {
                if let None = self.key_to_ordinal.insert(key, self.next_ordinal) {
                    // Only if the inserted key was not in the set of pressed
                    // keys.
                    self.ordinal_to_key.insert(self.next_ordinal, key);
                    self.next_ordinal = self.next_ordinal + 1;
                }
            }
            KeyEventType::Released | KeyEventType::Cancel => {
                if let Some(ordinal) = self.key_to_ordinal.remove(&key) {
                    self.ordinal_to_key.remove_entry(&ordinal);
                }
                //  If no keys remain in the pressed set, reset the ordinal.
                if self.key_to_ordinal.is_empty() {
                    assert!(self.ordinal_to_key.is_empty());
                    self.next_ordinal = 0;
                }
            }
        }
    }

    /// Returns true if `key` is noted as pressed.
    pub fn is_pressed(&self, key: &Key) -> bool {
        self.key_to_ordinal.contains_key(key)
    }

    /// Returns `true` if at least one key from `keys` is pressed.
    pub fn pressed_any(&self, keys: &[Key]) -> bool {
        keys.iter().any(|k| self.is_pressed(k))
    }

    /// Returns `true` if all keys from `keys` are pressed.
    pub fn pressed_all(&self, keys: &[Key]) -> bool {
        keys.iter().all(|k| self.is_pressed(k))
    }

    /// Gets all the keys from the set.
    pub fn get_set(&self) -> collections::BTreeSet<Key> {
        let mut ret = collections::BTreeSet::new();
        let _k = self.key_to_ordinal.keys().for_each(|k| {
            ret.insert(*k);
        });
        ret
    }

    /// Gets the list of all currently pressed keys, in the order they were
    /// pressed.
    pub fn get_ordered_keys(&self) -> Vec<Key> {
        // Iteration MUST produce keys in a strictly increasing sequence.
        self.ordinal_to_key.iter().map(|(_, key)| *key).collect()
    }

    /// Clears the state of [Self], and expunges any stored key presses.
    pub fn clear(&mut self) {
        self.next_ordinal = 0;
        self.ordinal_to_key.clear();
        self.key_to_ordinal.clear();
    }
}

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

    const HID_USAGE_KEY_A: u32 = 0x04;
    const HID_USAGE_KEY_B: u32 = 0x05;
    const HID_USAGE_KEY_C: u32 = 0x06;
    const HID_USAGE_KEY_K: u32 = 0x0e;
    const HID_USAGE_KEY_L: u32 = 0x0f;
    const HID_USAGE_KEY_M: u32 = 0x10;
    const HID_USAGE_KEY_N: u32 = 0x11;
    const HID_USAGE_KEY_Q: u32 = 0x14;
    const HID_USAGE_KEY_U: u32 = 0x18;
    const HID_USAGE_KEY_1: u32 = 0x1e;
    const HID_USAGE_KEY_SEMICOLON: u32 = 0x33;

    // The effects of Shift and CapsLock on keys are different for non-letters.
    #[test]
    fn caps_lock_effect() -> Result<()> {
        assert_eq!(
            '1' as u32,
            US_QWERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_1,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        assert_eq!(
            '!' as u32,
            US_QWERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_1,
                &ModifierState::new().with(Modifiers::LEFT_SHIFT),
                &LockStateKeys::new(),
            )?
        );
        Ok(())
    }

    #[test]
    fn spotcheck_us_qwerty_keymap() -> Result<()> {
        assert_eq!(
            'a' as u32,
            US_QWERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_A,
                &ModifierState::new(),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'a' as u32,
            US_QWERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_A,
                &ModifierState::new().with(Modifiers::CAPS_LOCK),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'A' as u32,
            US_QWERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_A,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        assert_eq!(
            'A' as u32,
            US_QWERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_A,
                &ModifierState::new().with(Modifiers::RIGHT_SHIFT),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'A' as u32,
            US_QWERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_A,
                &ModifierState::new().with(Modifiers::LEFT_SHIFT),
                &LockStateKeys::new(),
            )?
        );
        Ok(())
    }

    #[test]
    fn spotcheck_fr_azerty_keymap() -> Result<()> {
        assert_eq!(
            'a' as u32,
            FR_AZERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_Q,
                &ModifierState::new(),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'M' as u32,
            FR_AZERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_SEMICOLON,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        assert_eq!(
            ',' as u32,
            FR_AZERTY.hid_usage_to_code_point(
                HID_USAGE_KEY_M,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        Ok(())
    }

    #[test]
    fn spotcheck_us_dvorak_keymap() -> Result<()> {
        assert_eq!(
            'a' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_A,
                &ModifierState::default(),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'a' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_A,
                &ModifierState::new().with(Modifiers::CAPS_LOCK),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'A' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_A,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        assert_eq!(
            'x' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_B,
                &ModifierState::new(),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'X' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_B,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        assert_eq!(
            'X' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_B,
                &ModifierState::new().with(Modifiers::LEFT_SHIFT),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'n' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_L,
                &ModifierState::new(),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'N' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_L,
                &ModifierState::new().with(Modifiers::LEFT_SHIFT),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'N' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_L,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        assert_eq!(
            '\'' as u32,
            US_DVORAK.hid_usage_to_code_point(
                HID_USAGE_KEY_Q,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        Ok(())
    }

    #[test]
    fn spotcheck_us_colemak_keymap() -> Result<()> {
        assert_eq!(
            'c' as u32,
            US_COLEMAK.hid_usage_to_code_point(
                HID_USAGE_KEY_C,
                &ModifierState::new().with(Modifiers::CAPS_LOCK),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'O' as u32,
            US_COLEMAK.hid_usage_to_code_point(
                HID_USAGE_KEY_SEMICOLON,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        assert_eq!(
            'L' as u32,
            US_COLEMAK.hid_usage_to_code_point(
                HID_USAGE_KEY_U,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        assert_eq!(
            'e' as u32,
            US_COLEMAK.hid_usage_to_code_point(
                HID_USAGE_KEY_K,
                &ModifierState::new(),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'M' as u32,
            US_COLEMAK.hid_usage_to_code_point(
                HID_USAGE_KEY_M,
                &ModifierState::new(),
                &LockStateKeys::new().with(LockState::CAPS_LOCK),
            )?
        );
        assert_eq!(
            'A' as u32,
            US_COLEMAK.hid_usage_to_code_point(
                HID_USAGE_KEY_A,
                &ModifierState::new().with(Modifiers::LEFT_SHIFT),
                &LockStateKeys::new(),
            )?
        );
        assert_eq!(
            'k' as u32,
            US_COLEMAK.hid_usage_to_code_point(
                HID_USAGE_KEY_N,
                &ModifierState::new(),
                &LockStateKeys::new(),
            )?
        );
        Ok(())
    }

    // CapsLock ______/""""""""\_______/"""""""""\_______
    // Modifier ______/""""""""\_______/"""""""""\______
    #[test_case(Key::CapsLock, Modifiers::CAPS_LOCK; "CapsLock")]
    #[test_case(Key::NumLock, Modifiers::NUM_LOCK; "NumLock")]
    #[test_case(Key::ScrollLock, Modifiers::SCROLL_LOCK; "ScrollLock")]
    // Key::Function
    // Key::Symbol
    // Key::AltGraph
    // Test "sided" modifiers.
    #[test_case(Key::RightShift, Modifiers::RIGHT_SHIFT|Modifiers::SHIFT; "RightShift")]
    #[test_case(Key::LeftShift, Modifiers::LEFT_SHIFT|Modifiers::SHIFT; "LeftShift")]
    #[test_case(Key::RightAlt, Modifiers::RIGHT_ALT|Modifiers::ALT; "RightAlt")]
    #[test_case(Key::LeftAlt, Modifiers::LEFT_ALT|Modifiers::ALT; "LeftAlt")]
    #[test_case(Key::RightMeta, Modifiers::RIGHT_META|Modifiers::META; "RightMeta")]
    #[test_case(Key::LeftMeta, Modifiers::LEFT_META|Modifiers::META; "LeftMeta")]
    #[test_case(Key::RightCtrl, Modifiers::RIGHT_CTRL|Modifiers::CTRL; "RightCtrl")]
    #[test_case(Key::LeftCtrl, Modifiers::LEFT_CTRL|Modifiers::CTRL; "LeftCtrl")]
    fn test_caps_lock_modifier(key: Key, modifier: Modifiers) {
        let mut modifier_state: ModifierState = Default::default();
        assert!(!modifier_state.test(modifier));

        modifier_state.update(KeyEventType::Pressed, key);
        assert!(modifier_state.test(modifier));

        modifier_state.update(KeyEventType::Released, key);
        assert!(!modifier_state.test(modifier));

        modifier_state.update(KeyEventType::Pressed, key);
        assert!(modifier_state.test(modifier));

        modifier_state.update(KeyEventType::Released, key);
        assert!(!modifier_state.test(modifier));
    }

    // Interleaved use of sided modifiers sets and resets the "non-sided"
    // modifier bit correctly.
    //
    // KeyA      """""\____________/""""""""""""""""
    //                :
    // KeyB      """""""""""\_____________/"""""""""
    //                :                   :
    // Modifier  """""\___________________/"""""""""
    //
    // KeyA is the first of the two sided keys, and KeyB is the second of the
    // two sided keys.
    #[test_case(Key::LeftShift, Key::RightShift, Modifiers::SHIFT; "Shift/LR")]
    #[test_case(Key::RightShift, Key::LeftShift, Modifiers::SHIFT; "Shift/RL")]
    #[test_case(Key::LeftAlt, Key::RightAlt, Modifiers::ALT; "Alt/LR")]
    #[test_case(Key::RightAlt, Key::LeftAlt, Modifiers::ALT; "Alt/RL")]
    #[test_case(Key::LeftMeta, Key::RightMeta, Modifiers::META; "Meta/LR")]
    #[test_case(Key::RightMeta, Key::LeftMeta, Modifiers::META; "Meta/RL")]
    #[test_case(Key::RightCtrl, Key::LeftCtrl, Modifiers::CTRL; "Ctrl/RL")]
    #[test_case(Key::LeftCtrl, Key::RightCtrl, Modifiers::CTRL; "Ctrl/LR")]
    fn test_sided_keys(key_a: Key, key_b: Key, modifier: Modifiers) {
        let mut modifier_state = ModifierState::new();
        assert!(
            !modifier_state.test(modifier),
            "state: {:?}, key_a: {:?}, key_b: {:?}",
            &modifier_state,
            &key_a,
            &key_b
        );

        modifier_state.update(KeyEventType::Pressed, key_a);
        assert!(
            modifier_state.test(modifier),
            "state: {:?}, key_a: {:?}, key_b: {:?}",
            &modifier_state,
            &key_a,
            &key_b
        );

        modifier_state.update(KeyEventType::Pressed, key_b);
        assert!(
            modifier_state.test(modifier),
            "state: {:?}, key_a: {:?}, key_b: {:?}",
            &modifier_state,
            &key_a,
            &key_b
        );

        modifier_state.update(KeyEventType::Released, key_a);
        assert!(
            modifier_state.test(modifier),
            "state: {:?}, key_a: {:?}, key_b: {:?}",
            &modifier_state,
            &key_a,
            &key_b
        );

        modifier_state.update(KeyEventType::Released, key_b);
        assert!(
            !modifier_state.test(modifier),
            "state: {:?}, key_a: {:?}, key_b: {:?}",
            &modifier_state,
            &key_a,
            &key_b
        );
    }

    // Check that the lock state is set and reset properly.
    //
    // Key       ______/""""""""\_______/"""""""""\_______
    // LockState ______/""""""""""""""""""""""""""\______
    #[test_case(Key::CapsLock, LockState::CAPS_LOCK; "CapsLock")]
    #[test_case(Key::NumLock, LockState::NUM_LOCK; "NumLock")]
    #[test_case(Key::ScrollLock, LockState::SCROLL_LOCK; "ScrollLock")]
    fn test_lock_state(key: Key, lock_state: LockState) {
        let mut state: LockStateKeys = Default::default();
        assert!(!state.test(lock_state));
        assert_eq!(state.get_state(), LockState::from_bits_allow_unknown(0));

        state.update(KeyEventType::Pressed, key);
        assert!(state.test(lock_state), "{:?}", state.get_state());
        assert_eq!(state.get_state(), lock_state);

        state.update(KeyEventType::Released, key);
        assert!(state.test(lock_state), "{:?}", state.get_state());
        assert_eq!(state.get_state(), lock_state);

        state.update(KeyEventType::Pressed, key);
        assert!(state.test(lock_state), "{:?}", state.get_state());
        assert_eq!(state.get_state(), lock_state);

        state.update(KeyEventType::Released, key);
        assert!(!state.test(lock_state), "{:?}", state.get_state());
        assert_eq!(state.get_state(), LockState::from_bits_allow_unknown(0));
    }

    #[test]
    fn test_modifier_tracker() {
        let mut modifier_state: ModifierState = Default::default();
        assert!(!modifier_state.test(Modifiers::SHIFT));

        modifier_state.update(KeyEventType::Pressed, Key::LeftShift);
        assert!(modifier_state.test(Modifiers::SHIFT));
        modifier_state.update(KeyEventType::Released, Key::LeftShift);
        assert!(!modifier_state.test(Modifiers::SHIFT));

        modifier_state.update(KeyEventType::Pressed, Key::RightShift);
        assert!(modifier_state.test(Modifiers::SHIFT));
        modifier_state.update(KeyEventType::Released, Key::RightShift);
        assert!(!modifier_state.test(Modifiers::SHIFT));

        modifier_state.update(KeyEventType::Pressed, Key::CapsLock);
        assert!(!modifier_state.test(Modifiers::SHIFT));
        assert!(modifier_state.test(Modifiers::CAPS_LOCK));
        modifier_state.update(KeyEventType::Released, Key::CapsLock);
        assert!(!modifier_state.test(Modifiers::SHIFT));
        assert!(!modifier_state.test(Modifiers::CAPS_LOCK));
        modifier_state.update(KeyEventType::Pressed, Key::CapsLock);
        assert!(!modifier_state.test(Modifiers::SHIFT));
        assert!(modifier_state.test(Modifiers::CAPS_LOCK));
        modifier_state.update(KeyEventType::Released, Key::CapsLock);
        assert!(!modifier_state.test(Modifiers::SHIFT));
        assert!(!modifier_state.test(Modifiers::CAPS_LOCK));
    }

    #[test]
    fn test_key_meaning_modifier_tracker() {
        let mut modifier_state: ModifierState = Default::default();
        assert!(!modifier_state.test(Modifiers::ALT_GRAPH));

        modifier_state.update_with_key_meaning(
            KeyEventType::Pressed,
            KeyMeaning::NonPrintableKey(NonPrintableKey::AltGraph),
        );
        assert!(modifier_state.test(Modifiers::ALT_GRAPH));
        modifier_state.update_with_key_meaning(
            KeyEventType::Released,
            KeyMeaning::NonPrintableKey(NonPrintableKey::AltGraph),
        );
        assert!(!modifier_state.test(Modifiers::ALT_GRAPH));
    }

    // CapsLock            ________/""""""""""\_______/"""""\_____
    // LeftShift           ____________/"""""""""""\______________
    // is_shift_active     ____________/"""""""""""\______________
    // is_caps_lock_active ________/""""""""""\_______/"""""\_____
    #[test]
    fn test_interleaved_caps_lock_and_shift() {
        let mut modifier_state: ModifierState = Default::default();
        assert!(!modifier_state.test(Modifiers::SHIFT));

        modifier_state.update(KeyEventType::Pressed, Key::CapsLock);
        assert!(!modifier_state.test(Modifiers::SHIFT));
        assert!(modifier_state.test(Modifiers::CAPS_LOCK));

        modifier_state.update(KeyEventType::Pressed, Key::LeftShift);
        assert!(modifier_state.test(Modifiers::SHIFT));
        assert!(modifier_state.test(Modifiers::CAPS_LOCK));

        modifier_state.update(KeyEventType::Released, Key::CapsLock);
        assert!(modifier_state.test(Modifiers::SHIFT));
        assert!(!modifier_state.test(Modifiers::CAPS_LOCK));

        modifier_state.update(KeyEventType::Released, Key::LeftShift);
        // Caps Lock is still active...
        assert!(!modifier_state.test(Modifiers::SHIFT));
        assert!(!modifier_state.test(Modifiers::CAPS_LOCK));

        // Press and release Caps Lock again.
        modifier_state.update(KeyEventType::Pressed, Key::CapsLock);
        assert!(!modifier_state.test(Modifiers::SHIFT));
        assert!(modifier_state.test(Modifiers::CAPS_LOCK));

        modifier_state.update(KeyEventType::Released, Key::CapsLock);
        assert!(!modifier_state.test(Modifiers::SHIFT));
        assert!(!modifier_state.test(Modifiers::CAPS_LOCK));
    }

    #[test]
    fn key_state_tracker() {
        let mut t = KeyState::new();
        assert_eq!(false, t.is_pressed(&Key::Space));
        t.update(KeyEventType::Pressed, Key::Space);
        assert_eq!(true, t.is_pressed(&Key::Space));

        t.update(KeyEventType::Released, Key::Space);

        assert_eq!(false, t.is_pressed(&Key::Space));

        t.update(KeyEventType::Sync, Key::Space);
        assert_eq!(true, t.is_pressed(&Key::Space));

        t.update(KeyEventType::Cancel, Key::Space);
        assert_eq!(false, t.is_pressed(&Key::Space));
    }

    #[test]
    fn key_state_tracker_any_and_all() {
        let mut t = KeyState::new();

        assert_eq!(false, t.pressed_any(&vec![]));
        assert_eq!(true, t.pressed_all(&vec![]));

        t.update(KeyEventType::Pressed, Key::Space);
        t.update(KeyEventType::Pressed, Key::Tab);

        assert_eq!(true, t.pressed_any(&vec![Key::LeftShift, Key::Space,]));
        assert_eq!(false, t.pressed_any(&vec![Key::RightShift, Key::LeftShift]));
        assert_eq!(true, t.pressed_all(&vec![Key::Space,]));
        assert_eq!(true, t.pressed_all(&vec![Key::Space, Key::Tab,]));

        let keys = t.get_set();
        assert_eq!(true, t.pressed_all(&vec![Key::Space, Key::Tab,]));

        let mut expected = collections::BTreeSet::new();
        expected.insert(Key::Space);
        expected.insert(Key::Tab);
        assert_eq!(keys, expected, "want: {:?} was: {:?}", &expected, &keys);
    }

    #[test_case(
        &US_QWERTY,
        Key::A,
        ModifierState::new(),
        LockStateKeys::new(),
        Some(KeyMeaning::Codepoint(97));
        "test basic mapping")
    ]
    #[test_case(
        &US_QWERTY,
        Key::A,
        ModifierState::new().with(Modifiers::LEFT_SHIFT),
        LockStateKeys::new(),
        Some(KeyMeaning::Codepoint(65));
        "test basic mapping - capital letter")
    ]
    #[test_case(
        // This test case is needed for Chromium integration.
        // See https://fxbug.dev/42061371.
        &FR_AZERTY,
        Key::RightAlt,
        ModifierState::new(),
        LockStateKeys::new(),
        Some(KeyMeaning::NonPrintableKey(NonPrintableKey::AltGraph));
        "test FR AZERTY right Alt mapping to AltGr")
    ]
    #[test_case(
        &US_QWERTY,
        Key::RightAlt,
        ModifierState::new(),
        LockStateKeys::new(),
        Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Alt));
        "test US QWERTY right Alt mapping")
    ]
    #[test_case(
        &US_QWERTY,
        Key::AcFullScreenView,
        ModifierState::new(),
        LockStateKeys::new(),
        Some(KeyMeaning::NonPrintableKey(NonPrintableKey::ZoomToggle));
        "Spot check multimedia keys")
    ]
    #[test_case(
        &US_QWERTY,
        Key::Tab,
        ModifierState::new(),
        LockStateKeys::new(),
        Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Tab));
        "Tab")
    ]
    #[test_case(
        &US_QWERTY,
        Key::Enter,
        ModifierState::new(),
        LockStateKeys::new(),
        Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Enter));
        "Enter")
    ]
    #[test_case(
        &US_QWERTY,
        Key::Backspace,
        ModifierState::new(),
        LockStateKeys::new(),
        Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Backspace));
        "Backspace")
    ]
    fn test_keymap_apply(
        keymap: &Keymap<'_>,
        key: Key,
        modifier_state: ModifierState,
        lock_state: LockStateKeys,
        expected: Option<KeyMeaning>,
    ) {
        let actual = keymap.apply(key, &modifier_state, &lock_state);
        assert_eq!(expected, actual, "expected: {:?}, actual: {:?}", expected, actual);
    }

    #[test_case(
        Key::AcBack,
        KeyMeaning::NonPrintableKey(NonPrintableKey::BrowserBack);
        "BrowserBack"
      )
    ]
    #[test_case(
        Key::AcRefresh,
        KeyMeaning::NonPrintableKey(NonPrintableKey::BrowserRefresh);
        "BrowserRefresh"
    )
    ]
    #[test_case(
        Key::AcFullScreenView,
        KeyMeaning::NonPrintableKey(NonPrintableKey::ZoomToggle);
        "ZoomToggle"
      )
    ]
    #[test_case(
        Key::AcSelectTaskApplication,
        KeyMeaning::NonPrintableKey(NonPrintableKey::Select);
        "Select"
      )
    ]
    #[test_case(
        Key::BrightnessDown,
        KeyMeaning::NonPrintableKey(NonPrintableKey::BrightnessDown);
        "BrightnessDown"
      )
    ]
    #[test_case(
        Key::BrightnessUp,
        KeyMeaning::NonPrintableKey(NonPrintableKey::BrightnessUp);
        "BrightnessUp"
      )
    ]
    #[test_case(
        Key::PlayPause,
        KeyMeaning::NonPrintableKey(NonPrintableKey::MediaPlayPause);
        "MediaPlayPause"
      )
    ]
    #[test_case(
        Key::Mute,
        KeyMeaning::NonPrintableKey(NonPrintableKey::AudioVolumeMute);
        "AudioVolumeMute"
      )
    ]
    #[test_case(
        Key::VolumeUp,
        KeyMeaning::NonPrintableKey(NonPrintableKey::AudioVolumeUp);
        "AudioVolumeUp"
      )
    ]
    #[test_case(
        Key::VolumeDown,
        KeyMeaning::NonPrintableKey(NonPrintableKey::AudioVolumeDown);
        "AudioVolumeDown"
      )
    ]
    #[test_case(
        Key::Escape,
        KeyMeaning::NonPrintableKey(NonPrintableKey::Escape);
        "Escape"
      )
    ]
    #[test_case(
        Key::Enter,
        KeyMeaning::NonPrintableKey(NonPrintableKey::Enter);
        "Enter"
      )
    ]
    #[test_case(
        Key::Tab,
        KeyMeaning::NonPrintableKey(NonPrintableKey::Tab);
        "Tab"
       )
    ]
    #[test_case(
        Key::Backspace,
        KeyMeaning::NonPrintableKey(NonPrintableKey::Backspace);
        "Backspace"
      )
    ]
    fn spot_check_key_meanings(key: Key, expected: KeyMeaning) {
        let actual = US_QWERTY.apply(key, &ModifierState::new(), &LockStateKeys::new());
        assert_eq!(Some(expected), actual);
    }

    // Test that the keys are ordered in the sequence they were pressed.
    //
    // A ____/"""""""""""""""
    // B _______/"""""""\____
    // C __/"""""""""""""""""
    // D __________/"""""""""
    //
    // KeyState::get_ordered_keys() => [C, A, D]
    //
    // since out of the keys that are still pressed, C, A and D were actuated
    // in that order.
    #[test]
    fn key_ordering() {
        let mut t = KeyState::new();

        t.update(KeyEventType::Pressed, Key::C);
        t.update(KeyEventType::Pressed, Key::A);
        t.update(KeyEventType::Pressed, Key::B);
        t.update(KeyEventType::Pressed, Key::D);
        // Repeated
        t.update(KeyEventType::Pressed, Key::A);

        t.update(KeyEventType::Released, Key::B);

        assert_eq!(vec![Key::C, Key::A, Key::D], t.get_ordered_keys());

        t.clear();
        let expected: Vec<Key> = vec![];
        assert_eq!(expected, t.get_ordered_keys());
    }

    #[test]
    fn key_ordering_with_reset() {
        let mut t = KeyState::new();

        t.update(KeyEventType::Pressed, Key::A);
        t.update(KeyEventType::Pressed, Key::B);
        t.update(KeyEventType::Released, Key::B);
        t.update(KeyEventType::Released, Key::A);

        let expected: Vec<Key> = vec![];
        assert_eq!(expected, t.get_ordered_keys());

        t.update(KeyEventType::Pressed, Key::C);

        assert_eq!(vec![Key::C], t.get_ordered_keys());

        t.update(KeyEventType::Pressed, Key::A);

        assert_eq!(vec![Key::C, Key::A], t.get_ordered_keys());
    }

    #[test]
    fn key_ordering_misuse() {
        let mut t = KeyState::new();

        t.update(KeyEventType::Released, Key::B);
        t.update(KeyEventType::Pressed, Key::A);
        t.update(KeyEventType::Released, Key::A);

        let expected: Vec<Key> = vec![];
        assert_eq!(expected, t.get_ordered_keys());

        t.update(KeyEventType::Pressed, Key::C);

        assert_eq!(vec![Key::C], t.get_ordered_keys());

        t.update(KeyEventType::Pressed, Key::A);

        assert_eq!(vec![Key::C, Key::A], t.get_ordered_keys());

        t.update(KeyEventType::Pressed, Key::A);
        t.update(KeyEventType::Pressed, Key::B);
        t.update(KeyEventType::Pressed, Key::C);

        assert_eq!(vec![Key::C, Key::A, Key::B], t.get_ordered_keys());
    }
}