use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::Deserialize;
use crate::widgets::command_palette::Command;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Chord {
code: KeyCode,
mods: KeyModifiers,
}
impl Chord {
fn normalize(code: KeyCode, mods: KeyModifiers) -> Self {
let mut m = mods
& (KeyModifiers::CONTROL
| KeyModifiers::ALT
| KeyModifiers::SHIFT
| KeyModifiers::SUPER);
let code = match code {
KeyCode::Char(c) if c.is_ascii_uppercase() => {
m |= KeyModifiers::SHIFT;
KeyCode::Char(c.to_ascii_lowercase())
}
KeyCode::Char(c) => KeyCode::Char(c.to_ascii_lowercase()),
other => other,
};
Self { code, mods: m }
}
pub fn from_event(key: KeyEvent) -> Self {
Self::normalize(key.code, key.modifiers)
}
pub fn iterm2_forwarder(self) -> Option<(String, String)> {
if !self.mods.contains(KeyModifiers::SUPER) {
return None;
}
let KeyCode::Char(c) = self.code else {
return None;
};
let shift = self.mods.contains(KeyModifiers::SHIFT);
if shift && !c.is_ascii_alphabetic() {
return None;
}
let vk = mac_ansi_keycode(c)?;
let codepoint = if shift {
c.to_ascii_uppercase() as u32
} else {
c as u32
};
let mut mask = 0x10_0000u32; let mut modbyte = 1u32 + 8; if shift {
mask |= 0x2_0000;
modbyte += 1;
}
if self.mods.contains(KeyModifiers::ALT) {
mask |= 0x8_0000;
modbyte += 2;
}
if self.mods.contains(KeyModifiers::CONTROL) {
mask |= 0x4_0000;
modbyte += 4;
}
Some((
format!("0x{codepoint:x}-0x{mask:x}-0x{vk:x}"),
csi_u_hex(codepoint, modbyte),
))
}
pub fn ghostty_trigger(self) -> Option<String> {
if !self.mods.contains(KeyModifiers::SUPER) {
return None;
}
let KeyCode::Char(c) = self.code else {
return None;
};
if self.mods.contains(KeyModifiers::SHIFT) && !c.is_ascii_alphabetic() {
return None;
}
let mut t = String::from("cmd");
if self.mods.contains(KeyModifiers::CONTROL) {
t.push_str("+ctrl");
}
if self.mods.contains(KeyModifiers::ALT) {
t.push_str("+alt");
}
if self.mods.contains(KeyModifiers::SHIFT) {
t.push_str("+shift");
}
t.push('+');
t.push(c.to_ascii_lowercase());
Some(t)
}
pub fn parse(s: &str) -> Option<Chord> {
if s.trim().is_empty() {
return None;
}
let mut mods = KeyModifiers::empty();
let mut code: Option<KeyCode> = None;
for raw in s.split('+') {
let tok = raw.trim().to_ascii_lowercase();
if tok.is_empty() {
code = Some(KeyCode::Char('+'));
continue;
}
match tok.as_str() {
"ctrl" | "control" => mods |= KeyModifiers::CONTROL,
"alt" | "opt" | "option" => mods |= KeyModifiers::ALT,
"shift" => mods |= KeyModifiers::SHIFT,
"cmd" | "command" | "super" | "meta" | "win" => mods |= KeyModifiers::SUPER,
"mod" => {
if cfg!(target_os = "macos") {
mods |= KeyModifiers::SUPER;
} else {
mods |= KeyModifiers::CONTROL;
}
}
other => code = Some(parse_key(other)?),
}
}
code.map(|c| Chord::normalize(c, mods))
}
}
fn csi_u_hex(codepoint: u32, modbyte: u32) -> String {
let mut parts = vec![String::from("0x1b"), String::from("0x5b")];
parts.extend(codepoint.to_string().bytes().map(|b| format!("0x{b:x}")));
parts.push(String::from("0x3b"));
parts.extend(modbyte.to_string().bytes().map(|b| format!("0x{b:x}")));
parts.push(String::from("0x75"));
parts.join(" ")
}
fn mac_ansi_keycode(c: char) -> Option<u32> {
Some(match c.to_ascii_lowercase() {
'a' => 0x00,
'b' => 0x0b,
'c' => 0x08,
'd' => 0x02,
'e' => 0x0e,
'f' => 0x03,
'g' => 0x05,
'h' => 0x04,
'i' => 0x22,
'j' => 0x26,
'k' => 0x28,
'l' => 0x25,
'm' => 0x2e,
'n' => 0x2d,
'o' => 0x1f,
'p' => 0x23,
'q' => 0x0c,
'r' => 0x0f,
's' => 0x01,
't' => 0x11,
'u' => 0x20,
'v' => 0x09,
'w' => 0x0d,
'x' => 0x07,
'y' => 0x10,
'z' => 0x06,
'0' => 0x1d,
'1' => 0x12,
'2' => 0x13,
'3' => 0x14,
'4' => 0x15,
'5' => 0x17,
'6' => 0x16,
'7' => 0x1a,
'8' => 0x1c,
'9' => 0x19,
'-' => 0x1b,
'=' => 0x18,
'[' => 0x21,
']' => 0x1e,
'\\' => 0x2a,
';' => 0x29,
'\'' => 0x27,
',' => 0x2b,
'.' => 0x2f,
'/' => 0x2c,
'`' => 0x32,
' ' => 0x31,
_ => return None,
})
}
fn parse_key(tok: &str) -> Option<KeyCode> {
if let Some(n) = tok.strip_prefix('f')
&& let Ok(num) = n.parse::<u8>()
&& (1..=24).contains(&num)
{
return Some(KeyCode::F(num));
}
Some(match tok {
"enter" | "return" | "cr" => KeyCode::Enter,
"tab" => KeyCode::Tab,
"esc" | "escape" => KeyCode::Esc,
"space" => KeyCode::Char(' '),
"up" => KeyCode::Up,
"down" => KeyCode::Down,
"left" => KeyCode::Left,
"right" => KeyCode::Right,
"backspace" | "bs" => KeyCode::Backspace,
"delete" | "del" => KeyCode::Delete,
"home" => KeyCode::Home,
"end" => KeyCode::End,
"pageup" | "pgup" => KeyCode::PageUp,
"pagedown" | "pgdn" => KeyCode::PageDown,
"insert" | "ins" => KeyCode::Insert,
s => {
let mut chars = s.chars();
let c = chars.next()?;
if chars.next().is_some() {
return None; }
KeyCode::Char(c)
}
})
}
pub(crate) fn strip_line_comments(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let mut in_string = false;
let mut escaped = false;
let mut chars = src.chars().peekable();
while let Some(c) = chars.next() {
if in_string {
out.push(c);
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == '"' {
in_string = false;
}
continue;
}
match c {
'"' => {
in_string = true;
out.push(c);
}
'/' if chars.peek() == Some(&'/') => {
for skipped in chars.by_ref() {
if skipped == '\n' {
out.push('\n');
break;
}
}
}
_ => out.push(c),
}
}
out
}
#[derive(Debug, Deserialize)]
struct Binding {
key: String,
command: String,
}
#[derive(Debug, Clone, Default)]
pub struct Keymap {
bindings: HashMap<Chord, Command>,
}
impl Keymap {
pub fn load(path: &Path) -> Self {
let Ok(json) = std::fs::read_to_string(path) else {
return Self::default();
};
Self::from_json(&json)
}
pub fn from_json(json: &str) -> Self {
let rows: Vec<Binding> =
serde_json::from_str(&strip_line_comments(json)).unwrap_or_default();
let mut bindings = HashMap::new();
for row in rows {
if let (Some(chord), Some(cmd)) =
(Chord::parse(&row.key), Command::from_id(&row.command))
{
bindings.insert(chord, cmd);
}
}
Self { bindings }
}
pub fn is_empty(&self) -> bool {
self.bindings.is_empty()
}
pub fn chords(&self) -> Vec<Chord> {
self.bindings.keys().copied().collect()
}
pub fn command_for(&self, key: KeyEvent) -> Option<Command> {
self.bindings.get(&Chord::from_event(key)).copied()
}
}
pub fn keybindings_path() -> PathBuf {
crate::prefs::config_dir().join("keybindings.json")
}
pub const TEMPLATE: &str = r#"// croft keyboard shortcuts. Rebind any palette command by its id.
// "mod" is Cmd on macOS, Ctrl on Linux. Modifiers: ctrl, alt/opt, shift, cmd/super, mod.
// Run "Preferences: Open Settings" to see command ids, or the command palette.
//
// In iTerm2, reserved Cmd chords must be forwarded first: run `croft setup-iterm2`.
// Ctrl / Alt / function-key bindings always reach croft.
[
{ "key": "mod+,", "command": "open_settings" }
]
"#;
#[cfg(test)]
mod tests {
use super::*;
fn ev(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
KeyEvent::new(code, mods)
}
#[test]
fn parses_modifier_stack_and_letter() {
let c = Chord::parse("ctrl+shift+p").unwrap();
assert_eq!(
c,
Chord::from_event(ev(
KeyCode::Char('p'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
))
);
}
#[test]
fn uppercase_letter_event_folds_to_shift_so_it_matches_a_shift_binding() {
let bound = Chord::parse("cmd+shift+p").unwrap();
let live = Chord::from_event(ev(KeyCode::Char('P'), KeyModifiers::SUPER));
assert_eq!(bound, live);
}
#[test]
fn function_key_and_named_keys_parse() {
assert_eq!(
Chord::parse("f2"),
Some(Chord::normalize(KeyCode::F(2), KeyModifiers::empty()))
);
assert_eq!(
Chord::parse("cmd+enter").unwrap(),
Chord::from_event(ev(KeyCode::Enter, KeyModifiers::SUPER))
);
}
#[test]
fn literal_plus_key_parses() {
assert_eq!(
Chord::parse("ctrl++").unwrap(),
Chord::from_event(ev(KeyCode::Char('+'), KeyModifiers::CONTROL))
);
}
#[test]
fn mod_resolves_per_platform() {
let c = Chord::parse("mod+s").unwrap();
let expected = if cfg!(target_os = "macos") {
KeyModifiers::SUPER
} else {
KeyModifiers::CONTROL
};
assert_eq!(c, Chord::from_event(ev(KeyCode::Char('s'), expected)));
}
#[test]
fn iterm2_forwarder_reproduces_the_hand_written_consts() {
let (k, h) = Chord::parse("cmd+f").unwrap().iterm2_forwarder().unwrap();
assert_eq!(k, "0x66-0x100000-0x3");
assert_eq!(h, "0x1b 0x5b 0x31 0x30 0x32 0x3b 0x39 0x75");
let (k, h) = Chord::parse("cmd+shift+p")
.unwrap()
.iterm2_forwarder()
.unwrap();
assert_eq!(k, "0x50-0x120000-0x23");
assert_eq!(h, "0x1b 0x5b 0x38 0x30 0x3b 0x31 0x30 0x75");
let (k, h) = Chord::parse("cmd+.").unwrap().iterm2_forwarder().unwrap();
assert_eq!(k, "0x2e-0x100000-0x2f");
assert_eq!(h, "0x1b 0x5b 0x34 0x36 0x3b 0x39 0x75");
let (k, h) = Chord::parse("cmd+shift+z")
.unwrap()
.iterm2_forwarder()
.unwrap();
assert_eq!(k, "0x5a-0x120000-0x6");
assert_eq!(h, "0x1b 0x5b 0x39 0x30 0x3b 0x31 0x30 0x75");
let (k, _) = Chord::parse("cmd+0").unwrap().iterm2_forwarder().unwrap();
assert_eq!(k, "0x30-0x100000-0x1d");
}
#[test]
fn iterm2_forwarder_skips_chords_that_need_no_forwarding_or_cant_encode() {
assert_eq!(Chord::parse("ctrl+alt+g").unwrap().iterm2_forwarder(), None);
assert_eq!(Chord::parse("f2").unwrap().iterm2_forwarder(), None);
assert_eq!(
Chord::parse("cmd+shift+/").unwrap().iterm2_forwarder(),
None
);
assert_eq!(Chord::parse("cmd+enter").unwrap().iterm2_forwarder(), None);
}
#[test]
fn junk_tokens_yield_none() {
assert_eq!(Chord::parse("ctrl+notakey"), None);
assert_eq!(Chord::parse(""), None);
}
#[test]
fn keymap_resolves_command_ids_and_skips_bad_rows() {
let json = r#"[
{ "key": "cmd+,", "command": "open_settings" },
{ "key": "ctrl+shift+p", "command": "quick_open" },
{ "key": "garbage++key", "command": "save_file" },
{ "key": "cmd+j", "command": "no_such_command" }
]"#;
let km = Keymap::from_json(json);
assert_eq!(
km.command_for(ev(KeyCode::Char(','), KeyModifiers::SUPER)),
Some(Command::OpenSettings)
);
assert_eq!(
km.command_for(ev(
KeyCode::Char('p'),
KeyModifiers::CONTROL | KeyModifiers::SHIFT
)),
Some(Command::QuickOpen)
);
assert_eq!(
km.command_for(ev(KeyCode::Char('j'), KeyModifiers::SUPER)),
None
);
}
#[test]
fn strips_line_comments_but_keeps_slashes_in_strings() {
let stripped =
strip_line_comments("// lead\n[{ \"key\": \"a//b\", \"command\": \"x\" }] // trailing");
assert!(!stripped.contains("lead"));
assert!(!stripped.contains("trailing"));
assert!(
stripped.contains("a//b"),
"// inside a quoted value must survive"
);
}
#[test]
fn empty_or_missing_json_is_empty_keymap() {
assert!(Keymap::from_json("").is_empty());
assert!(Keymap::from_json("not json").is_empty());
assert!(Keymap::load(Path::new("/no/such/keybindings.json")).is_empty());
}
#[test]
fn template_parses_as_a_valid_keymap() {
let km = Keymap::from_json(TEMPLATE);
assert_eq!(
km.command_for(ev(
KeyCode::Char(','),
if cfg!(target_os = "macos") {
KeyModifiers::SUPER
} else {
KeyModifiers::CONTROL
}
)),
Some(Command::OpenSettings)
);
}
}