use std::collections::{BTreeMap, HashMap};
use serde::{Deserialize, Serialize};
use winit::event::KeyEvent;
use winit::keyboard::{Key, ModifiersState, NamedKey};
use winit::platform::modifier_supplement::KeyEventExtModifierSupplement;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Action {
SplitLeft,
SplitRight,
SplitUp,
SplitDown,
FocusLeft,
FocusRight,
FocusUp,
FocusDown,
ResizeLeft,
ResizeRight,
ResizeUp,
ResizeDown,
ClosePane,
Zoom,
Copy,
SmartCopy,
Paste,
SelectAll,
Find,
CopyOutput,
OpenFolder,
FontBigger,
FontSmaller,
FontReset,
ScrollPageUp,
ScrollPageDown,
ScrollTop,
ScrollBottom,
Palette,
Settings,
Review,
Git,
Embed,
Chat,
Code,
}
struct Info {
action: Action,
id: &'static str,
label: &'static str,
keys: &'static [&'static str],
}
macro_rules! info {
($action:ident, $id:literal, $label:literal, [$($key:literal),*]) => {
Info { action: Action::$action, id: $id, label: $label, keys: &[$($key),*] }
};
}
const ACTIONS: &[Info] = &[
info!(SplitRight, "split_right", "Split right", ["ctrl+shift+right"]),
info!(SplitLeft, "split_left", "Split left", ["ctrl+shift+left"]),
info!(SplitDown, "split_down", "Split down", ["ctrl+shift+down"]),
info!(SplitUp, "split_up", "Split up", ["ctrl+shift+up"]),
info!(FocusLeft, "focus_left", "Focus the pane to the left", ["alt+left"]),
info!(FocusRight, "focus_right", "Focus the pane to the right", ["alt+right"]),
info!(FocusUp, "focus_up", "Focus the pane above", ["alt+up"]),
info!(FocusDown, "focus_down", "Focus the pane below", ["alt+down"]),
info!(ResizeLeft, "resize_left", "Move the divider left", ["alt+shift+left"]),
info!(ResizeRight, "resize_right", "Move the divider right", ["alt+shift+right"]),
info!(ResizeUp, "resize_up", "Move the divider up", ["alt+shift+up"]),
info!(ResizeDown, "resize_down", "Move the divider down", ["alt+shift+down"]),
info!(ClosePane, "close_pane", "Close the pane", ["ctrl+shift+w"]),
info!(Zoom, "zoom", "Zoom the pane", ["ctrl+shift+z"]),
info!(Copy, "copy", "Copy the selection", ["ctrl+shift+c"]),
info!(SmartCopy, "copy_or_interrupt", "Copy, or interrupt when nothing is selected", ["ctrl+c"]),
info!(Paste, "paste", "Paste", ["ctrl+v", "ctrl+shift+v", "shift+insert"]),
info!(SelectAll, "select_all", "Select the command line", ["ctrl+a"]),
info!(Find, "find", "Find in the scrollback", ["ctrl+shift+f"]),
info!(CopyOutput, "copy_output", "Copy the last command's output", ["ctrl+shift+o"]),
info!(OpenFolder, "open_folder", "Open the folder in Explorer", ["ctrl+shift+e"]),
info!(FontBigger, "font_bigger", "Bigger text", ["ctrl+=", "ctrl++"]),
info!(FontSmaller, "font_smaller", "Smaller text", ["ctrl+-"]),
info!(FontReset, "font_reset", "Reset the text size", ["ctrl+0"]),
info!(ScrollPageUp, "scroll_page_up", "Scroll a page up", ["shift+pageup"]),
info!(ScrollPageDown, "scroll_page_down", "Scroll a page down", ["shift+pagedown"]),
info!(ScrollTop, "scroll_top", "Scroll to the top", ["shift+home"]),
info!(ScrollBottom, "scroll_bottom", "Scroll to the bottom", ["shift+end"]),
info!(Palette, "palette", "Command palette", ["ctrl+shift+p"]),
info!(Settings, "settings", "Settings", ["ctrl+,"]),
info!(Review, "review", "Review changes", ["ctrl+shift+r"]),
info!(Git, "git", "Git workspace", ["ctrl+shift+b"]),
info!(Embed, "embed", "Switch between the terminal and what is open over it", ["ctrl+shift+t", "alt+t"]),
info!(Chat, "chat", "Switch between the do conversation and the terminal", ["ctrl+shift+a"]),
info!(Code, "code", "Switch between VS Code and the terminal", ["ctrl+shift+i"]),
];
impl Action {
pub fn all() -> impl Iterator<Item = Action> {
ACTIONS.iter().map(|i| i.action)
}
fn info(self) -> &'static Info {
ACTIONS.iter().find(|i| i.action == self).expect("every action is listed")
}
pub fn id(self) -> &'static str {
self.info().id
}
pub fn label(self) -> &'static str {
self.info().label
}
pub fn defaults(self) -> &'static [&'static str] {
self.info().keys
}
pub fn from_id(id: &str) -> Option<Action> {
ACTIONS.iter().find(|i| i.id == id).map(|i| i.action)
}
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum KeyList {
One(String),
Many(Vec<String>),
}
impl KeyList {
pub fn chords(&self) -> Vec<&str> {
match self {
KeyList::One(s) => vec![s.as_str()],
KeyList::Many(v) => v.iter().map(String::as_str).collect(),
}
}
}
const NAMED: &[&str] = &[
"left",
"right",
"up",
"down",
"pageup",
"pagedown",
"home",
"end",
"insert",
"delete",
"tab",
"enter",
"escape",
"space",
"backspace",
"f1",
"f2",
"f3",
"f4",
"f5",
"f6",
"f7",
"f8",
"f9",
"f10",
"f11",
"f12",
];
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Chord {
pub ctrl: bool,
pub shift: bool,
pub alt: bool,
pub key: String,
}
impl Chord {
pub fn parse(text: &str) -> Option<Chord> {
let text = text.trim().to_lowercase();
let (mods, key) = if text == "+" {
("", "+".to_string())
} else if let Some(head) = text.strip_suffix("++") {
(head, "+".to_string())
} else if text.ends_with('+') {
return None;
} else {
match text.rsplit_once('+') {
Some((mods, key)) => (mods, key.trim().to_string()),
None => ("", text.clone()),
}
};
let key = match key.as_str() {
"esc" => "escape".to_string(),
"return" => "enter".to_string(),
"pgup" => "pageup".to_string(),
"pgdn" => "pagedown".to_string(),
"del" => "delete".to_string(),
"ins" => "insert".to_string(),
"plus" => "+".to_string(),
"comma" => ",".to_string(),
"minus" => "-".to_string(),
k if k.starts_with("arrow") => k["arrow".len()..].to_string(),
k => k.to_string(),
};
if key.chars().count() != 1 && !NAMED.contains(&key.as_str()) {
return None;
}
let mut chord = Chord { ctrl: false, shift: false, alt: false, key };
for m in mods.split('+').map(str::trim).filter(|m| !m.is_empty()) {
match m {
"ctrl" | "control" => chord.ctrl = true,
"shift" => chord.shift = true,
"alt" | "option" => chord.alt = true,
_ => return None,
}
}
Some(chord)
}
pub fn from_event(event: &KeyEvent, mods: ModifiersState) -> Option<Chord> {
let key = match &event.logical_key {
Key::Named(n) => match n {
NamedKey::ArrowLeft => "left",
NamedKey::ArrowRight => "right",
NamedKey::ArrowUp => "up",
NamedKey::ArrowDown => "down",
NamedKey::PageUp => "pageup",
NamedKey::PageDown => "pagedown",
NamedKey::Home => "home",
NamedKey::End => "end",
NamedKey::Insert => "insert",
NamedKey::Delete => "delete",
NamedKey::Tab => "tab",
NamedKey::Enter => "enter",
NamedKey::Escape => "escape",
NamedKey::Space => "space",
NamedKey::Backspace => "backspace",
NamedKey::F1 => "f1",
NamedKey::F2 => "f2",
NamedKey::F3 => "f3",
NamedKey::F4 => "f4",
NamedKey::F5 => "f5",
NamedKey::F6 => "f6",
NamedKey::F7 => "f7",
NamedKey::F8 => "f8",
NamedKey::F9 => "f9",
NamedKey::F10 => "f10",
NamedKey::F11 => "f11",
NamedKey::F12 => "f12",
_ => return None,
}
.to_string(),
Key::Character(_) => match event.key_without_modifiers() {
Key::Character(c) if c.chars().count() == 1 => c.to_lowercase(),
_ => return None,
},
_ => return None,
};
Some(Chord { ctrl: mods.control_key(), shift: mods.shift_key(), alt: mods.alt_key(), key })
}
pub fn to_config(&self) -> String {
let mut parts = Vec::new();
if self.ctrl {
parts.push("ctrl");
}
if self.alt {
parts.push("alt");
}
if self.shift {
parts.push("shift");
}
parts.push(&self.key);
parts.join("+")
}
pub fn pretty(&self) -> String {
let key = match self.key.as_str() {
"pageup" => "PageUp".to_string(),
"pagedown" => "PageDown".to_string(),
k if k.chars().count() == 1 => k.to_uppercase(),
k => {
let mut c = k.chars();
c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default()
}
};
let mut parts = Vec::new();
if self.ctrl {
parts.push("Ctrl".to_string());
}
if self.alt {
parts.push("Alt".to_string());
}
if self.shift {
parts.push("Shift".to_string());
}
parts.push(key);
parts.join("+")
}
}
#[derive(Clone, Debug, Default)]
pub struct Keymap {
map: HashMap<Chord, Action>,
}
impl Keymap {
pub fn build(overrides: &BTreeMap<String, KeyList>) -> (Keymap, Vec<String>) {
let mut problems = Vec::new();
let mut bindings: Vec<(Action, Vec<Chord>)> = Vec::new();
let mut custom: Vec<(Action, Vec<Chord>)> = Vec::new();
for (id, keys) in overrides {
let Some(action) = Action::from_id(id) else {
problems.push(format!("unknown action '{id}' in [keys]"));
continue;
};
let mut chords = Vec::new();
for text in keys.chords() {
match Chord::parse(text) {
Some(c) => chords.push(c),
None => problems.push(format!("can't read the key '{text}' for {id}")),
}
}
custom.push((action, chords));
}
for action in Action::all() {
if custom.iter().any(|(a, _)| *a == action) {
continue;
}
bindings.push((action, action.defaults().iter().filter_map(|k| Chord::parse(k)).collect()));
}
let mut map = HashMap::new();
for (action, chords) in bindings {
for chord in chords {
map.insert(chord, action);
}
}
for (action, chords) in custom {
for chord in chords {
map.insert(chord, action);
}
}
(Keymap { map }, problems)
}
pub fn get(&self, chord: &Chord) -> Option<Action> {
self.map.get(chord).copied()
}
pub fn chords(&self, action: Action) -> Vec<Chord> {
let mut chords: Vec<Chord> = self.map.iter().filter(|(_, a)| **a == action).map(|(c, _)| c.clone()).collect();
chords.sort_by_key(Chord::to_config);
chords
}
pub fn describe(&self, action: Action) -> String {
self.chords(action).iter().map(Chord::pretty).collect::<Vec<_>>().join(" / ")
}
}
#[cfg(test)]
mod tests {
use super::*;
fn chord(s: &str) -> Chord {
Chord::parse(s).unwrap_or_else(|| panic!("{s} should parse"))
}
#[test]
fn chords_parse_and_print() {
let c = chord("Ctrl+Shift+F");
assert_eq!((c.ctrl, c.shift, c.alt, c.key.as_str()), (true, true, false, "f"));
assert_eq!(c.to_config(), "ctrl+shift+f");
assert_eq!(c.pretty(), "Ctrl+Shift+F");
assert_eq!(chord("alt+pgup").to_config(), "alt+pageup");
assert_eq!(chord("alt+PageUp").pretty(), "Alt+PageUp");
assert_eq!(chord("ctrl+arrowleft"), chord("ctrl+left"));
assert_eq!(chord("ctrl++").key, "+");
assert_eq!(chord("ctrl+,").key, ",");
assert_eq!(chord("ctrl+comma"), chord("ctrl+,"));
assert_eq!(chord("f5").pretty(), "F5");
assert_eq!(chord("esc").key, "escape");
for bad in ["", "ctrl+", "ctrl+shift+nope", "hyper+x", "ctrl+ab"] {
assert!(Chord::parse(bad).is_none(), "{bad:?} should not parse");
}
}
#[test]
fn defaults_are_valid_and_do_not_clash() {
let (map, problems) = Keymap::build(&BTreeMap::new());
assert!(problems.is_empty(), "{problems:?}");
let total: usize = Action::all().map(|a| a.defaults().len()).sum();
assert_eq!(map.map.len(), total, "two actions share a default chord");
for action in Action::all() {
assert!(!map.chords(action).is_empty(), "{action:?} has no key");
assert_eq!(Action::from_id(action.id()), Some(action));
}
assert_eq!(map.get(&chord("ctrl+shift+f")), Some(Action::Find));
assert_eq!(map.describe(Action::Paste), "Ctrl+Shift+V / Ctrl+V / Shift+Insert");
}
#[test]
fn user_keys_replace_defaults_and_win_clashes() {
let mut keys = BTreeMap::new();
keys.insert("find".to_string(), KeyList::One("ctrl+alt+f".into()));
keys.insert("settings".to_string(), KeyList::Many(vec!["ctrl+shift+z".into(), "f12".into()]));
keys.insert("nonsense".to_string(), KeyList::One("ctrl+x".into()));
keys.insert("copy".to_string(), KeyList::One("ctrl+shift+nope".into()));
let (map, problems) = Keymap::build(&keys);
assert_eq!(map.get(&chord("ctrl+alt+f")), Some(Action::Find));
assert_eq!(map.get(&chord("ctrl+shift+f")), None, "the old key is gone");
assert_eq!(map.get(&chord("ctrl+shift+z")), Some(Action::Settings));
assert_eq!(map.get(&chord("f12")), Some(Action::Settings));
assert!(map.chords(Action::Zoom).is_empty(), "zoom lost its key to settings");
assert_eq!(problems.len(), 2, "{problems:?}");
assert!(map.chords(Action::Copy).is_empty());
}
#[test]
fn config_accepts_one_chord_or_a_list() {
#[derive(Deserialize)]
struct T {
keys: BTreeMap<String, KeyList>,
}
let t: T = toml::from_str("[keys]\nfind = \"ctrl+f\"\npaste = [\"ctrl+v\", \"shift+insert\"]\n").unwrap();
assert_eq!(t.keys["find"].chords(), vec!["ctrl+f"]);
assert_eq!(t.keys["paste"].chords(), vec!["ctrl+v", "shift+insert"]);
}
}