use std::{collections::HashMap, fmt::Display, ops::Deref, str::FromStr}; use anyhow::Context; use keymaps::{key_repr::Key, map_tree::MapTrie}; use serde::{Deserialize, Serialize}; pub mod commands; #[derive(Deserialize, Serialize, Debug)] #[allow(clippy::module_name_repetitions)] pub struct RawKeyMap(HashMap); #[derive(Clone, Deserialize, Serialize, Debug, PartialEq, PartialOrd)] /// What values to use for: `riverctl ` pub struct KeyConfig { command: Vec, #[serde(default = "default_mode")] modes: Vec, #[serde(default = "MapMode::default")] map_mode: MapMode, } impl FromStr for KeyMap { type Err = anyhow::Error; fn from_str(s: &str) -> Result { let raw: RawKeyMap = serde_json::from_str(s).context("Failed to parse the keymap config file as json.")?; let mut out = MapTrie::::new(); for (key, value) in raw.0 { out.insert(&[key], value.clone()) .with_context(|| format!("Failed to insert mapping {key} -> {value}"))?; } Ok(Self(out)) } } impl Display for KeyConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.command.join(" ").as_str()) } } fn default_mode() -> Vec { vec!["normal".to_owned()] } #[derive(Copy, Deserialize, Serialize, Debug, Clone, Default, PartialEq, PartialOrd)] enum MapMode { #[default] Map, MapMouse, Unmap, } impl Display for MapMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { ::fmt(self, f) } } #[derive(Debug)] pub struct KeyMap(MapTrie); impl Display for KeyMap { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl Deref for KeyMap { type Target = MapTrie; fn deref(&self) -> &Self::Target { &self.0 } }