crisol_core/commands/
keybindings.rs1use super::{BindingError, CommandId, CommandRegistry, KeySequence};
8
9#[derive(Clone, Debug, PartialEq, Eq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12#[non_exhaustive]
13pub struct KeybindingEntry {
19 pub command: CommandId,
21 pub keys: String,
23 pub when: Option<String>,
26}
27
28impl KeybindingEntry {
29 pub fn new(command: impl Into<CommandId>, keys: impl Into<String>) -> Self {
31 Self {
32 command: command.into(),
33 keys: keys.into(),
34 when: None,
35 }
36 }
37
38 pub fn when(mut self, when: impl Into<String>) -> Self {
40 self.when = Some(when.into());
41 self
42 }
43}
44
45#[derive(Clone, Debug, PartialEq, Eq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
52#[non_exhaustive]
53pub struct Keybindings {
54 pub version: u32,
56 pub bindings: Vec<KeybindingEntry>,
58}
59
60impl Default for Keybindings {
61 fn default() -> Self {
62 Self::new()
63 }
64}
65
66impl Keybindings {
67 pub const VERSION: u32 = 1;
69
70 pub fn new() -> Self {
72 Self {
73 version: Self::VERSION,
74 bindings: Vec::new(),
75 }
76 }
77
78 pub fn with(mut self, entry: KeybindingEntry) -> Self {
80 self.bindings.push(entry);
81 self
82 }
83
84 pub fn apply(&self, registry: &mut CommandRegistry) -> Vec<KeybindingError> {
86 let mut errors = Vec::new();
87 for entry in &self.bindings {
88 let Some(sequence) = KeySequence::parse(&entry.keys) else {
89 errors.push(KeybindingError::InvalidSequence {
90 command: entry.command.clone(),
91 keys: entry.keys.clone(),
92 });
93 continue;
94 };
95 if let Err(error) = registry.bind(&entry.command, sequence) {
96 errors.push(KeybindingError::Binding {
97 command: entry.command.clone(),
98 error,
99 });
100 }
101 }
102 errors
103 }
104
105 pub fn from_registry(registry: &CommandRegistry) -> Self {
107 let mut file = Self::new();
108 for (sequence, command) in registry.bindings() {
109 file.bindings
110 .push(KeybindingEntry::new(command, sequence.to_key_string()));
111 }
112 file
113 }
114}
115
116#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
118#[non_exhaustive]
119pub enum KeybindingError {
125 #[error("`{command}` has an invalid shortcut `{keys}`")]
127 InvalidSequence {
128 command: CommandId,
130 keys: String,
132 },
133 #[error("`{command}` was not bound: {error}")]
135 Binding {
136 command: CommandId,
138 error: BindingError,
140 },
141}
142
143#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
145#[non_exhaustive]
146pub enum KeybindingsError {
152 #[error("invalid keybindings JSON: {0}")]
154 Json(String),
155 #[error("unsupported keybindings version {0}")]
157 UnsupportedVersion(u32),
158 #[error("invalid VS Code keybindings: {0}")]
160 InvalidVscode(String),
161}
162
163#[cfg(feature = "serde")]
164mod file {
165 use super::*;
166
167 #[derive(serde::Deserialize)]
168 struct VscodeEntry {
169 key: String,
170 command: String,
171 #[serde(default)]
172 when: Option<String>,
173 }
174
175 impl Keybindings {
176 pub fn from_json(json: &str) -> Result<Self, KeybindingsError> {
181 let file: Self = serde_json::from_str(json).map_err(|error| KeybindingsError::Json(error.to_string()))?;
182 if file.version > Self::VERSION {
183 return Err(KeybindingsError::UnsupportedVersion(file.version));
184 }
185 Ok(file)
186 }
187
188 pub fn to_json(&self) -> Result<String, KeybindingsError> {
193 serde_json::to_string_pretty(self).map_err(|error| KeybindingsError::Json(error.to_string()))
194 }
195
196 pub fn import_vscode(json: &str) -> Result<Self, KeybindingsError> {
204 let entries: Vec<VscodeEntry> =
205 serde_json::from_str(json).map_err(|error| KeybindingsError::InvalidVscode(error.to_string()))?;
206 let mut file = Self::new();
207 for entry in entries {
208 if entry.command.starts_with('-') {
210 continue;
211 }
212 let keys = normalize_vscode_keys(&entry.key);
213 if KeySequence::parse(&keys).is_none() {
214 continue;
215 }
216 let mut binding = KeybindingEntry::new(entry.command, keys);
217 binding.when = entry.when;
218 file.bindings.push(binding);
219 }
220 Ok(file)
221 }
222 }
223}
224
225#[cfg(feature = "serde")]
226fn normalize_vscode_keys(keys: &str) -> String {
227 keys.split_whitespace()
228 .map(|chord| {
229 chord
230 .split('+')
231 .map(|part| match part.to_ascii_lowercase().as_str() {
232 "ctrl" | "control" => "Ctrl".to_owned(),
233 "cmd" | "command" | "cmdorctrl" => "Cmd".to_owned(),
234 "alt" | "option" => "Alt".to_owned(),
235 "shift" => "Shift".to_owned(),
236 other => other.to_owned(),
237 })
238 .collect::<Vec<_>>()
239 .join("+")
240 })
241 .collect::<Vec<_>>()
242 .join(" ")
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248 use crate::commands::Command;
249
250 #[test]
251 fn files_apply_and_report_errors() {
252 let mut registry = CommandRegistry::new();
253 registry.register(Command::new("file.save", "Save"));
254 registry.register(Command::new("file.close", "Close"));
255 let file = Keybindings::new()
256 .with(KeybindingEntry::new("file.save", "Ctrl+S"))
257 .with(KeybindingEntry::new("file.close", "Ctrl+W"))
258 .with(KeybindingEntry::new("missing.command", "Ctrl+M"))
259 .with(KeybindingEntry::new("file.save", "not a chord"));
260 let errors = file.apply(&mut registry);
261 assert_eq!(errors.len(), 2);
262 assert_eq!(
263 registry.binding(&CommandId::new("file.save")).map(ToString::to_string),
264 Some("Ctrl+S".to_owned())
265 );
266 }
267
268 #[cfg(feature = "serde")]
269 #[test]
270 fn json_round_trips_and_imports_vscode() {
271 let file = Keybindings::new().with(KeybindingEntry::new("file.save", "Ctrl+S"));
272 let json = file.to_json().expect("serialize");
273 let back = Keybindings::from_json(&json).expect("parse");
274 assert_eq!(back, file);
275 let vscode = r#"[{"key":"ctrl+shift+p","command":"workbench.palette","when":"editorFocus"}]"#;
276 let imported = Keybindings::import_vscode(vscode).expect("vscode");
277 assert_eq!(imported.bindings.len(), 1);
278 assert_eq!(imported.bindings[0].keys, "Ctrl+Shift+p");
279 assert_eq!(imported.bindings[0].when.as_deref(), Some("editorFocus"));
280 }
281}