Skip to main content

crisol_core/commands/
keybindings.rs

1//! The keybindings file and the VS Code importer.
2//!
3//! ```
4//! use crisol_core::commands::keybindings;
5//! ```
6
7use super::{BindingError, CommandId, CommandRegistry, KeySequence};
8
9/// One command binding in a keybindings file.
10#[derive(Clone, Debug, PartialEq, Eq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12#[non_exhaustive]
13/// # Example
14///
15/// ```
16/// use crisol_core::commands::KeybindingEntry;
17/// ```
18pub struct KeybindingEntry {
19    /// The command to bind.
20    pub command: CommandId,
21    /// A chord or a space-separated chord sequence.
22    pub keys: String,
23    /// An optional context expression. The registry applies command-level contexts;
24    /// this field is preserved for round-tripping an imported file.
25    pub when: Option<String>,
26}
27
28impl KeybindingEntry {
29    /// A binding with no context.
30    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    /// Attach a context expression.
39    pub fn when(mut self, when: impl Into<String>) -> Self {
40        self.when = Some(when.into());
41        self
42    }
43}
44
45/// A versioned keybindings file.
46///
47/// ```json
48/// { "version": 1, "bindings": [{ "command": "file.save", "keys": "Ctrl+S" }] }
49/// ```
50#[derive(Clone, Debug, PartialEq, Eq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
52#[non_exhaustive]
53pub struct Keybindings {
54    /// File format version. Currently 1.
55    pub version: u32,
56    /// The bindings.
57    pub bindings: Vec<KeybindingEntry>,
58}
59
60impl Default for Keybindings {
61    fn default() -> Self {
62        Self::new()
63    }
64}
65
66impl Keybindings {
67    /// The current file version.
68    pub const VERSION: u32 = 1;
69
70    /// An empty file.
71    pub fn new() -> Self {
72        Self {
73            version: Self::VERSION,
74            bindings: Vec::new(),
75        }
76    }
77
78    /// Add a binding.
79    pub fn with(mut self, entry: KeybindingEntry) -> Self {
80        self.bindings.push(entry);
81        self
82    }
83
84    /// Apply every entry to a registry and return the entries that failed.
85    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    /// The active bindings of a registry, ready to save.
106    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/// Why a keybindings file entry could not be applied.
117#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
118#[non_exhaustive]
119/// # Example
120///
121/// ```
122/// use crisol_core::commands::keybindings::KeybindingError;
123/// ```
124pub enum KeybindingError {
125    /// The shortcut text is invalid.
126    #[error("`{command}` has an invalid shortcut `{keys}`")]
127    InvalidSequence {
128        /// The command.
129        command: CommandId,
130        /// The invalid text.
131        keys: String,
132    },
133    /// The registry rejected the binding.
134    #[error("`{command}` was not bound: {error}")]
135    Binding {
136        /// The command.
137        command: CommandId,
138        /// The registry error.
139        error: BindingError,
140    },
141}
142
143/// Why a keybindings file could not be read.
144#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
145#[non_exhaustive]
146/// # Example
147///
148/// ```
149/// use crisol_core::commands::KeybindingsError;
150/// ```
151pub enum KeybindingsError {
152    /// The JSON is malformed.
153    #[error("invalid keybindings JSON: {0}")]
154    Json(String),
155    /// The version is newer than this crate understands.
156    #[error("unsupported keybindings version {0}")]
157    UnsupportedVersion(u32),
158    /// The VS Code file is not an array of bindings.
159    #[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        /// Parse a versioned keybindings file.
177        ///
178        /// # Errors
179        /// When the JSON is malformed or the version is newer than [`Self::VERSION`].
180        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        /// Serialize the file as pretty JSON.
189        ///
190        /// # Errors
191        /// When serialization fails (it does not for these types).
192        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        /// Read a `keybindings.json` from VS Code.
197        ///
198        /// VS Code's file is an array of `{ "key", "command", "when" }` objects. Keys are
199        /// normalized to this crate's chord syntax; command ids are kept as written.
200        ///
201        /// # Errors
202        /// When the JSON is not an array of VS Code bindings.
203        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                // VS Code writes `-command` to remove a default binding; it is not a command.
209                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}