Parse KeyPress

pull/39/head
Takashi Kokubun 2 years ago
parent fed0b5526f
commit 10845ed7c0
No known key found for this signature in database
GPG Key ID: 6FFC433B12EE23DD

@ -18,14 +18,23 @@ pub fn parse_key(input: &str) -> Result<Key, Box<dyn Error>> {
// xremap's custom aliases like k0kubun/karabiner-dsl
let key = match &name[..] {
"CTRL_R" => Key::KEY_RIGHTCTRL,
"CTRL_L" => Key::KEY_LEFTCTRL,
// Shift
"SHIFT_R" => Key::KEY_RIGHTSHIFT,
"SHIFT_L" => Key::KEY_LEFTSHIFT,
// Control
"CONTROL_R" => Key::KEY_RIGHTCTRL,
"CONTROL_L" => Key::KEY_LEFTCTRL,
"CTRL_R" => Key::KEY_RIGHTCTRL,
"CTRL_L" => Key::KEY_LEFTCTRL,
// Alt
"ALT_R" => Key::KEY_RIGHTALT,
"ALT_L" => Key::KEY_LEFTALT,
// Windows
"SUPER_R" => Key::KEY_RIGHTMETA,
"SUPER_L" => Key::KEY_LEFTMETA,
"WIN_R" => Key::KEY_RIGHTMETA,
"WIN_L" => Key::KEY_LEFTMETA,
// else
_ => Key::KEY_RESERVED,
};
if key != Key::KEY_RESERVED {

@ -5,9 +5,61 @@ use std::error::Error;
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct KeyPress {
pub key: Key,
pub shift: bool,
pub control: bool,
pub alt: bool,
pub windows: bool,
}
enum Modifier {
Shift,
Control,
Alt,
Windows,
}
pub fn parse_keypress(input: &str) -> Result<KeyPress, Box<dyn Error>> {
let key = parse_key(input)?;
return Ok(KeyPress { key });
let keys: Vec<&str> = input.split("-").collect();
if let Some((key, modifiers)) = keys.split_last() {
let mut shift = false;
let mut control = false;
let mut alt = false;
let mut windows = false;
for modifier in modifiers.iter() {
match parse_modifier(modifier) {
Some(Modifier::Shift) => shift = true,
Some(Modifier::Control) => control = true,
Some(Modifier::Alt) => alt = true,
Some(Modifier::Windows) => windows = true,
None => return Err(format!("unknown modifier: {}", modifier).into())
}
}
// TODO: invalidate modifier keys in `key`?
Ok(KeyPress { key: parse_key(key)?, shift, control, alt, windows })
} else {
Err(format!("empty keypress: {}", input).into())
}
}
fn parse_modifier(modifier: &str) -> Option<Modifier> {
// Everything is case-insensitive
match &modifier.to_uppercase()[..] {
// Shift
"SHIFT" => Some(Modifier::Shift),
// Control
"C" => Some(Modifier::Control),
"CTRL" => Some(Modifier::Control),
"CONTROL" => Some(Modifier::Control),
// Alt
"M" => Some(Modifier::Alt),
"ALT" => Some(Modifier::Alt),
// Windows
"SUPER" => Some(Modifier::Windows),
"WIN" => Some(Modifier::Windows),
"WINDOWS" => Some(Modifier::Windows),
// else
_ => None,
}
}

Loading…
Cancel
Save