use std::collections::BTreeMap;
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Binding {
pub id: &'static str,
pub key: &'static str,
pub describe: &'static str,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Keymap {
pub modifier: String,
pub keys: Vec<(String, String, String)>,
}
pub fn modes_path() -> PathBuf {
crate::storage::resolve_home().join("modes.toml")
}
#[derive(Debug, Default, serde::Deserialize)]
struct Section {
modifier: Option<String>,
#[serde(default)]
keys: BTreeMap<String, String>,
}
impl Keymap {
pub fn new(defaults: &[Binding]) -> Self {
Self { modifier: "alt".into(), keys: defaults.iter().map(|b| (b.id.into(), b.key.into(), b.describe.into())).collect() }
}
pub fn apply(&mut self, mode: &str, text: &str) -> Result<(), String> {
let all: BTreeMap<String, toml::Value> = toml::from_str(text).map_err(|e| e.to_string())?;
let Some(v) = all.get(mode) else { return Ok(()) };
let s: Section = v.clone().try_into().map_err(|e: toml::de::Error| e.to_string())?;
if let Some(m) = s.modifier {
if m != "alt" {
return Err(format!("modifier {m:?} is not supported yet (only \"alt\")"));
}
self.modifier = m;
}
for (id, key) in s.keys {
if key_bytes(&key).is_none() {
return Err(format!("unknown key {key:?} for {id}"));
}
match self.keys.iter_mut().find(|k| k.0 == id) {
Some(k) => k.1 = key.to_lowercase(),
None => return Err(format!("{mode} has no action {id:?}")),
}
}
Ok(())
}
pub fn load(mode: &str, defaults: &[Binding]) -> (Self, Option<String>) {
let mut k = Self::new(defaults);
let Ok(t) = std::fs::read_to_string(modes_path()) else { return (k, None) };
match k.apply(mode, &t) {
Ok(()) => (k, None),
Err(e) => (Self::new(defaults), Some(format!("modes.toml [{mode}]: {e}; using the default keys"))),
}
}
pub fn lookup(&self, bytes: &[u8]) -> Option<&str> {
self.keys.iter().find(|(_, k, _)| key_bytes(k).is_some_and(|kb| kb.iter().any(|b| b.as_slice() == bytes))).map(|(id, _, _)| id.as_str())
}
pub fn label(&self, id: &str) -> String {
format!("{}+{}", self.modifier, self.keys.iter().find(|k| k.0 == id).map_or("?", |k| k.1.as_str()))
}
}
pub fn keep_line(cmd: &str) -> Vec<u8> {
let mut v = b"\x05 \x15".to_vec();
v.extend(cmd.replace(['\r', '\n'], " ").as_bytes());
v.push(b'\r');
v
}
pub const RESTORE_LINE: &[u8] = b"\x19\x7f";
pub fn key_bytes(key: &str) -> Option<Vec<Vec<u8>>> {
let k = key.to_lowercase();
Some(match k.as_str() {
"up" => vec![b"\x1b[1;3A".to_vec(), b"\x1b\x1b[A".to_vec()],
"down" => vec![b"\x1b[1;3B".to_vec(), b"\x1b\x1b[B".to_vec()],
"right" => vec![b"\x1b[1;3C".to_vec(), b"\x1b\x1b[C".to_vec()],
"left" => vec![b"\x1b[1;3D".to_vec(), b"\x1b\x1b[D".to_vec()],
"enter" => vec![b"\x1b\r".to_vec()],
"pageup" => vec![b"\x1b[5;3~".to_vec(), b"\x1b\x1b[5~".to_vec()],
"pagedown" => vec![b"\x1b[6;3~".to_vec(), b"\x1b\x1b[6~".to_vec()],
"home" => vec![b"\x1b[1;3H".to_vec(), b"\x1b\x1b[H".to_vec(), b"\x1b\x1b[1~".to_vec()],
"end" => vec![b"\x1b[1;3F".to_vec(), b"\x1b\x1b[F".to_vec(), b"\x1b\x1b[4~".to_vec()],
"space" => vec![b"\x1b ".to_vec()],
"backspace" => vec![b"\x1b\x7f".to_vec(), b"\x1b\x08".to_vec()],
_ => {
let mut c = k.chars();
let ch = c.next()?;
if c.next().is_some() || ch.is_control() || ch == ':' {
return None;
}
let mut b = vec![0x1b];
b.extend(ch.to_string().as_bytes());
vec![b]
}
})
}