• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 mod data;
6 
7 use std::collections::HashMap;
8 
9 use data::MapEntry;
10 use data::KEYCODE_MAP;
11 
12 /// Specifies which type of scancode to convert *from* in the KeycodeTranslator.
13 #[allow(dead_code)]
14 pub enum KeycodeTypes {
15     XkbScancode,
16     WindowsScancode,
17     MacScancode,
18 }
19 
20 /// Translates scancodes of a particular type into Linux keycodes.
21 pub struct KeycodeTranslator {
22     keycode_map: HashMap<u32, MapEntry>,
23 }
24 
25 impl KeycodeTranslator {
26     /// Create a new KeycodeTranslator that translates from the `from_type` type to Linux keycodes.
new(from_type: KeycodeTypes) -> KeycodeTranslator27     pub fn new(from_type: KeycodeTypes) -> KeycodeTranslator {
28         let mut kcm: HashMap<u32, MapEntry> = HashMap::new();
29         for entry in KEYCODE_MAP.iter() {
30             kcm.insert(
31                 match from_type {
32                     KeycodeTypes::XkbScancode => entry.xkb,
33                     KeycodeTypes::WindowsScancode => entry.win,
34                     KeycodeTypes::MacScancode => entry.mac,
35                 },
36                 *entry,
37             );
38         }
39         KeycodeTranslator { keycode_map: kcm }
40     }
41 
42     /// Translates the scancode in `from_code` into a Linux keycode.
translate(&self, from_code: u32) -> Option<u16>43     pub fn translate(&self, from_code: u32) -> Option<u16> {
44         Some(self.keycode_map.get(&from_code)?.linux_keycode)
45     }
46 }
47 
48 #[cfg(test)]
49 mod tests {
50     use crate::keycode_converter::KeycodeTranslator;
51     use crate::keycode_converter::KeycodeTypes;
52 
53     #[test]
test_translate_win_lin()54     fn test_translate_win_lin() {
55         let translator = KeycodeTranslator::new(KeycodeTypes::WindowsScancode);
56         let translated_code = translator.translate(0x47);
57         assert!(translated_code.is_some());
58         assert_eq!(translated_code.unwrap(), 71);
59     }
60 
61     #[test]
test_translate_missing_entry()62     fn test_translate_missing_entry() {
63         let translator = KeycodeTranslator::new(KeycodeTypes::WindowsScancode);
64 
65         // No keycodes are this large.
66         let translated_code = translator.translate(0x9999999);
67         assert!(translated_code.is_none());
68     }
69 }
70