use rustc_hash::FxHashMap;
use crate::Command;
use crate::EditorError;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Platform {
Apple,
#[default]
Other,
}
#[allow(
clippy::struct_excessive_bools,
reason = "one flag per physical modifier key"
)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Modifiers {
pub shift: bool,
pub ctrl: bool,
pub alt: bool,
pub meta: bool,
}
impl Modifiers {
pub const NONE: Self = Self {
shift: false,
ctrl: false,
alt: false,
meta: false,
};
pub const SHIFT: Self = Self {
shift: true,
..Self::NONE
};
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct KeyPress<'a> {
pub key: &'a str,
pub modifiers: Modifiers,
}
impl<'a> KeyPress<'a> {
#[must_use]
pub const fn new(key: &'a str, modifiers: Modifiers) -> Self {
Self { key, modifiers }
}
#[must_use]
pub const fn plain(key: &'a str) -> Self {
Self::new(key, Modifiers::NONE)
}
}
pub fn parse_binding(
binding: &str,
platform: Platform,
) -> Result<(String, Modifiers), EditorError> {
let invalid = || EditorError::InvalidKey(binding.to_owned());
let (prefix, key) = match (binding, binding.strip_suffix("--")) {
("-", _) => (None, "-"),
(_, Some(prefix)) => (Some(prefix), "-"),
_ => {
binding
.rsplit_once('-')
.map_or((None, binding), |(prefix, key)| (Some(prefix), key))
}
};
if key.is_empty() {
return Err(invalid());
}
let mut modifiers = Modifiers::NONE;
for name in prefix.into_iter().flat_map(|prefix| prefix.split('-')) {
let name = match (name, platform) {
("Mod", Platform::Apple) => "Meta",
("Mod", Platform::Other) => "Ctrl",
(name, _) => name,
};
match name {
"Shift" => modifiers.shift = true,
"Ctrl" | "Control" => modifiers.ctrl = true,
"Alt" | "Option" => modifiers.alt = true,
"Meta" | "Cmd" => modifiers.meta = true,
_ => return Err(invalid()),
}
}
Ok((normalize(key).into_owned(), modifiers))
}
fn normalize(key: &str) -> std::borrow::Cow<'_, str> {
let mut chars = key.chars();
match (chars.next(), chars.next()) {
(Some(only), None) if only.is_uppercase() => only.to_lowercase().collect::<String>().into(),
_ => key.into(),
}
}
#[derive(Clone, Default)]
pub struct Keymap {
bindings: FxHashMap<Modifiers, FxHashMap<Box<str>, Vec<Command>>>,
}
impl Keymap {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn bind(
&mut self,
binding: &str,
platform: Platform,
command: Command,
) -> Result<(), EditorError> {
let (key, modifiers) = parse_binding(binding, platform)?;
self.bindings
.entry(modifiers)
.or_default()
.entry(key.into_boxed_str())
.or_default()
.push(command);
Ok(())
}
#[must_use]
pub fn lookup(&self, press: KeyPress<'_>) -> &[Command] {
let key = normalize(press.key);
let found = self.find(press.modifiers, &key);
if !found.is_empty() || !press.modifiers.shift || key.chars().nth(1).is_some() {
return found;
}
let unshifted = Modifiers {
shift: false,
..press.modifiers
};
self.find(unshifted, &key)
}
fn find(&self, modifiers: Modifiers, key: &str) -> &[Command] {
self.bindings
.get(&modifiers)
.and_then(|keys| keys.get(key))
.map_or(&[], Vec::as_slice)
}
}
impl std::fmt::Debug for Keymap {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let count: usize = self.bindings.values().map(FxHashMap::len).sum();
formatter
.debug_struct("Keymap")
.field("keys", &count)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mod_follows_the_platform() {
let apple = parse_binding("Mod-Shift-Z", Platform::Apple).expect("valid");
let other = parse_binding("Mod-b", Platform::Other).expect("valid");
assert_eq!(
apple,
(
"z".to_owned(),
Modifiers {
shift: true,
meta: true,
..Modifiers::NONE
}
)
);
assert_eq!(
other,
(
"b".to_owned(),
Modifiers {
ctrl: true,
..Modifiers::NONE
}
)
);
}
#[test]
fn parses_named_keys_and_the_minus_key() {
let (key, modifiers) = parse_binding("Alt-ArrowLeft", Platform::Other).expect("valid");
let (minus, ctrl) = parse_binding("Ctrl--", Platform::Other).expect("valid");
assert_eq!(key, "ArrowLeft");
assert!(modifiers.alt);
assert_eq!(minus, "-");
assert!(ctrl.ctrl);
}
#[test]
fn rejects_unknown_modifiers_and_empty_keys() {
assert!(parse_binding("Hyper-a", Platform::Other).is_err());
assert!(parse_binding("Ctrl-", Platform::Other).is_err());
}
}