use rho_browser::cdp::input::{DispatchKeyEvent, KeyEventKind, Modifiers};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Chord {
pub(super) modifiers: Modifiers,
pub(super) key: Key,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Key {
pub(super) key: String,
pub(super) code: Option<&'static str>,
pub(super) key_code: Option<u32>,
pub(super) text: Option<String>,
}
impl Key {
pub(super) fn down(&self, modifiers: Modifiers) -> DispatchKeyEvent {
let text = self
.text
.clone()
.filter(|_| modifiers.without(Modifiers::SHIFT) == Modifiers::NONE);
let kind = match text {
Some(_) => KeyEventKind::KeyDown,
None => KeyEventKind::RawKeyDown,
};
self.event(kind, text, modifiers)
}
pub(super) fn up(&self, modifiers: Modifiers) -> DispatchKeyEvent {
self.event(KeyEventKind::KeyUp, None, modifiers)
}
fn event(
&self,
kind: KeyEventKind,
text: Option<String>,
modifiers: Modifiers,
) -> DispatchKeyEvent {
DispatchKeyEvent {
kind,
key: self.key.clone(),
code: self.code.map(str::to_owned),
text,
windows_virtual_key_code: self.key_code,
modifiers,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Typed {
Key(Key),
Text(String),
}
const MODIFIERS: [(Modifiers, &str, &str, u32); 4] = [
(Modifiers::CTRL, "Control", "ControlLeft", 17),
(Modifiers::ALT, "Alt", "AltLeft", 18),
(Modifiers::META, "Meta", "MetaLeft", 91),
(Modifiers::SHIFT, "Shift", "ShiftLeft", 16),
];
struct Named {
names: &'static [&'static str],
key: &'static str,
code: &'static str,
key_code: u32,
text: Option<&'static str>,
}
const NAMED: [Named; 17] = [
Named {
names: &["enter", "return", "kp_enter"],
key: "Enter",
code: "Enter",
key_code: 13,
text: Some("\r"),
},
Named {
names: &["tab"],
key: "Tab",
code: "Tab",
key_code: 9,
text: None,
},
Named {
names: &["escape", "esc"],
key: "Escape",
code: "Escape",
key_code: 27,
text: None,
},
Named {
names: &["backspace"],
key: "Backspace",
code: "Backspace",
key_code: 8,
text: None,
},
Named {
names: &["delete", "del"],
key: "Delete",
code: "Delete",
key_code: 46,
text: None,
},
Named {
names: &["insert"],
key: "Insert",
code: "Insert",
key_code: 45,
text: None,
},
Named {
names: &["home"],
key: "Home",
code: "Home",
key_code: 36,
text: None,
},
Named {
names: &["end"],
key: "End",
code: "End",
key_code: 35,
text: None,
},
Named {
names: &["pageup", "page_up", "prior"],
key: "PageUp",
code: "PageUp",
key_code: 33,
text: None,
},
Named {
names: &["pagedown", "page_down", "next"],
key: "PageDown",
code: "PageDown",
key_code: 34,
text: None,
},
Named {
names: &["arrowup", "up"],
key: "ArrowUp",
code: "ArrowUp",
key_code: 38,
text: None,
},
Named {
names: &["arrowdown", "down"],
key: "ArrowDown",
code: "ArrowDown",
key_code: 40,
text: None,
},
Named {
names: &["arrowleft", "left"],
key: "ArrowLeft",
code: "ArrowLeft",
key_code: 37,
text: None,
},
Named {
names: &["arrowright", "right"],
key: "ArrowRight",
code: "ArrowRight",
key_code: 39,
text: None,
},
Named {
names: &["space"],
key: " ",
code: "Space",
key_code: 32,
text: Some(" "),
},
Named {
names: &["capslock", "caps_lock"],
key: "CapsLock",
code: "CapsLock",
key_code: 20,
text: None,
},
Named {
names: &["contextmenu", "menu"],
key: "ContextMenu",
code: "ContextMenu",
key_code: 93,
text: None,
},
];
const FUNCTION_CODES: [&str; 12] = [
"F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
];
pub(super) fn held(held: Modifiers) -> impl DoubleEndedIterator<Item = (Modifiers, Key)> {
MODIFIERS
.into_iter()
.filter(move |(modifier, ..)| held.contains(*modifier))
.map(|(modifier, key, code, key_code)| {
let key = Key {
key: key.to_owned(),
code: Some(code),
key_code: Some(key_code),
text: None,
};
(modifier, key)
})
}
pub(super) fn sequence(text: &str) -> Result<Vec<Chord>, String> {
let chords = text
.split_whitespace()
.map(chord)
.collect::<Result<Vec<_>, _>>()?;
if chords.is_empty() {
return Err("text names no key; write one such as \"Enter\" or \"ctrl+a\"".to_owned());
}
Ok(chords)
}
pub(super) fn modifiers(text: &str) -> Result<Modifiers, String> {
text.split('+').try_fold(Modifiers::NONE, |held, name| {
modifier(name)
.map(|(modifier, ..)| held.with(modifier))
.ok_or_else(|| {
format!(
"modifiers must name ctrl, alt, shift or meta, joined with +; got \"{text}\""
)
})
})
}
pub(super) fn typing(text: &str) -> Vec<Typed> {
let mut steps = Vec::new();
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
let key = match c {
'\r' => {
if chars.peek() == Some(&'\n') {
chars.next();
}
named("enter")
}
'\n' => named("enter"),
'\t' => named("tab"),
' '..='~' => Some(character(c)),
_ => None,
};
match (key, steps.last_mut()) {
(Some(key), _) => steps.push(Typed::Key(key)),
(None, Some(Typed::Text(text))) => text.push(c),
(None, _) => steps.push(Typed::Text(c.to_string())),
}
}
steps
}
fn chord(text: &str) -> Result<Chord, String> {
let (held, name) = match text.strip_suffix("++") {
Some(held) => (Some(held), "+"),
None if text == "+" => (None, "+"),
None => match text.rsplit_once('+') {
Some((held, name)) => (Some(held), name),
None => (None, text),
},
};
let modifiers = match held {
Some(held) => modifiers(held).map_err(|_| unknown(text))?,
None => Modifiers::NONE,
};
let key = key(name, modifiers).ok_or_else(|| unknown(text))?;
Ok(Chord { modifiers, key })
}
fn unknown(text: &str) -> String {
format!(
"\"{text}\" is not a key: name one such as Enter, Tab, Escape, Backspace, ArrowUp, PageDown, F5 or a single character, with any of ctrl, alt, shift and meta joined by +"
)
}
pub(super) fn key_code(key: &str) -> Option<u32> {
self::key(key, Modifiers::NONE).and_then(|key| key.key_code)
}
fn key(name: &str, modifiers: Modifiers) -> Option<Key> {
let mut chars = name.chars();
if let (Some(c), None) = (chars.next(), chars.next()) {
let c = if modifiers.contains(Modifiers::SHIFT) {
c.to_ascii_uppercase()
} else {
c
};
return Some(character(c));
}
let lower = name.to_ascii_lowercase();
if let Some((_, key, code, key_code)) = modifier(&lower) {
return Some(Key {
key: key.to_owned(),
code: Some(code),
key_code: Some(key_code),
text: None,
});
}
if let Some(number) = lower
.strip_prefix('f')
.and_then(|number| number.parse::<usize>().ok())
{
let code = *FUNCTION_CODES.get(number.checked_sub(1)?)?;
return Some(Key {
key: code.to_owned(),
code: Some(code),
key_code: Some(111 + u32::try_from(number).ok()?),
text: None,
});
}
named(&lower)
}
fn named(lower: &str) -> Option<Key> {
NAMED
.iter()
.find(|named| named.names.contains(&lower))
.map(|named| Key {
key: named.key.to_owned(),
code: Some(named.code),
key_code: Some(named.key_code),
text: named.text.map(str::to_owned),
})
}
fn modifier(name: &str) -> Option<(Modifiers, &'static str, &'static str, u32)> {
let modifier = match name.to_ascii_lowercase().as_str() {
"ctrl" | "control" => Modifiers::CTRL,
"alt" | "option" => Modifiers::ALT,
"meta" | "cmd" | "command" | "super" | "win" => Modifiers::META,
"shift" => Modifiers::SHIFT,
_ => return None,
};
MODIFIERS
.into_iter()
.find(|(candidate, ..)| *candidate == modifier)
}
fn character(c: char) -> Key {
let coded = match c {
'a'..='z' | 'A'..='Z' => Some((
LETTER_CODES[letter_index(c)],
u32::from(c.to_ascii_uppercase()),
)),
'0'..='9' => Some((DIGIT_CODES[usize::from(c as u8 - b'0')], u32::from(c))),
' ' => Some(("Space", 32)),
_ => None,
};
Key {
key: c.to_string(),
code: coded.map(|(code, _)| code),
key_code: coded.map(|(_, key_code)| key_code),
text: Some(c.to_string()),
}
}
fn letter_index(c: char) -> usize {
usize::from(c.to_ascii_uppercase() as u8 - b'A')
}
const LETTER_CODES: [&str; 26] = [
"KeyA", "KeyB", "KeyC", "KeyD", "KeyE", "KeyF", "KeyG", "KeyH", "KeyI", "KeyJ", "KeyK", "KeyL",
"KeyM", "KeyN", "KeyO", "KeyP", "KeyQ", "KeyR", "KeyS", "KeyT", "KeyU", "KeyV", "KeyW", "KeyX",
"KeyY", "KeyZ",
];
const DIGIT_CODES: [&str; 10] = [
"Digit0", "Digit1", "Digit2", "Digit3", "Digit4", "Digit5", "Digit6", "Digit7", "Digit8",
"Digit9",
];
#[cfg(test)]
#[path = "keys_tests.rs"]
mod tests;