diff options
Diffstat (limited to 'gpu_display/src/keycode_converter/mod.rs')
-rw-r--r-- | gpu_display/src/keycode_converter/mod.rs | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/gpu_display/src/keycode_converter/mod.rs b/gpu_display/src/keycode_converter/mod.rs new file mode 100644 index 0000000..40fdb95 --- /dev/null +++ b/gpu_display/src/keycode_converter/mod.rs @@ -0,0 +1,66 @@ +// Copyright 2019 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +mod data; + +use data::{MapEntry, KEYCODE_MAP}; +use std::collections::HashMap; + +/// Specifies which type of scancode to convert *from* in the KeycodeTranslator. +pub enum KeycodeTypes { + XkbScancode, + WindowsScancode, + MacScancode, +} + +/// Translates scancodes of a particular type into Linux keycodes. +pub struct KeycodeTranslator { + keycode_map: HashMap<u32, MapEntry>, +} + +impl KeycodeTranslator { + /// Create a new KeycodeTranslator that translates from the `from_type` type to Linux keycodes. + pub fn new(from_type: KeycodeTypes) -> KeycodeTranslator { + let mut kcm: HashMap<u32, MapEntry> = HashMap::new(); + for entry in KEYCODE_MAP.into_iter() { + kcm.insert( + match from_type { + KeycodeTypes::XkbScancode => entry.xkb, + KeycodeTypes::WindowsScancode => entry.win, + KeycodeTypes::MacScancode => entry.mac, + }, + *entry, + ); + } + KeycodeTranslator { keycode_map: kcm } + } + + /// Translates the scancode in `from_code` into a Linux keycode. + pub fn translate(&self, from_code: u32) -> Option<u16> { + Some(self.keycode_map.get(&from_code)?.linux_keycode) + } +} + +#[cfg(test)] +mod tests { + use crate::keycode_converter::KeycodeTranslator; + use crate::keycode_converter::KeycodeTypes; + + #[test] + fn test_translate_win_lin() { + let translator = KeycodeTranslator::new(KeycodeTypes::WindowsScancode); + let translated_code = translator.translate(0x47); + assert!(translated_code.is_some()); + assert_eq!(translated_code.unwrap(), 71); + } + + #[test] + fn test_translate_missing_entry() { + let translator = KeycodeTranslator::new(KeycodeTypes::WindowsScancode); + + // No keycodes are this large. + let translated_code = translator.translate(0x9999999); + assert!(translated_code.is_none()); + } +} |