use super::{BindingError, CommandId, CommandRegistry, KeySequence};
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct KeybindingEntry {
pub command: CommandId,
pub keys: String,
pub when: Option<String>,
}
impl KeybindingEntry {
pub fn new(command: impl Into<CommandId>, keys: impl Into<String>) -> Self {
Self {
command: command.into(),
keys: keys.into(),
when: None,
}
}
pub fn when(mut self, when: impl Into<String>) -> Self {
self.when = Some(when.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Keybindings {
pub version: u32,
pub bindings: Vec<KeybindingEntry>,
}
impl Default for Keybindings {
fn default() -> Self {
Self::new()
}
}
impl Keybindings {
pub const VERSION: u32 = 1;
pub fn new() -> Self {
Self {
version: Self::VERSION,
bindings: Vec::new(),
}
}
pub fn with(mut self, entry: KeybindingEntry) -> Self {
self.bindings.push(entry);
self
}
pub fn apply(&self, registry: &mut CommandRegistry) -> Vec<KeybindingError> {
let mut errors = Vec::new();
for entry in &self.bindings {
let Some(sequence) = KeySequence::parse(&entry.keys) else {
errors.push(KeybindingError::InvalidSequence {
command: entry.command.clone(),
keys: entry.keys.clone(),
});
continue;
};
if let Err(error) = registry.bind(&entry.command, sequence) {
errors.push(KeybindingError::Binding {
command: entry.command.clone(),
error,
});
}
}
errors
}
pub fn from_registry(registry: &CommandRegistry) -> Self {
let mut file = Self::new();
for (sequence, command) in registry.bindings() {
file.bindings
.push(KeybindingEntry::new(command, sequence.to_key_string()));
}
file
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum KeybindingError {
#[error("`{command}` has an invalid shortcut `{keys}`")]
InvalidSequence {
command: CommandId,
keys: String,
},
#[error("`{command}` was not bound: {error}")]
Binding {
command: CommandId,
error: BindingError,
},
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum KeybindingsError {
#[error("invalid keybindings JSON: {0}")]
Json(String),
#[error("unsupported keybindings version {0}")]
UnsupportedVersion(u32),
#[error("invalid VS Code keybindings: {0}")]
InvalidVscode(String),
}
#[cfg(feature = "serde")]
mod file {
use super::*;
#[derive(serde::Deserialize)]
struct VscodeEntry {
key: String,
command: String,
#[serde(default)]
when: Option<String>,
}
impl Keybindings {
pub fn from_json(json: &str) -> Result<Self, KeybindingsError> {
let file: Self = serde_json::from_str(json).map_err(|error| KeybindingsError::Json(error.to_string()))?;
if file.version > Self::VERSION {
return Err(KeybindingsError::UnsupportedVersion(file.version));
}
Ok(file)
}
pub fn to_json(&self) -> Result<String, KeybindingsError> {
serde_json::to_string_pretty(self).map_err(|error| KeybindingsError::Json(error.to_string()))
}
pub fn import_vscode(json: &str) -> Result<Self, KeybindingsError> {
let entries: Vec<VscodeEntry> =
serde_json::from_str(json).map_err(|error| KeybindingsError::InvalidVscode(error.to_string()))?;
let mut file = Self::new();
for entry in entries {
if entry.command.starts_with('-') {
continue;
}
let keys = normalize_vscode_keys(&entry.key);
if KeySequence::parse(&keys).is_none() {
continue;
}
let mut binding = KeybindingEntry::new(entry.command, keys);
binding.when = entry.when;
file.bindings.push(binding);
}
Ok(file)
}
}
}
#[cfg(feature = "serde")]
fn normalize_vscode_keys(keys: &str) -> String {
keys.split_whitespace()
.map(|chord| {
chord
.split('+')
.map(|part| match part.to_ascii_lowercase().as_str() {
"ctrl" | "control" => "Ctrl".to_owned(),
"cmd" | "command" | "cmdorctrl" => "Cmd".to_owned(),
"alt" | "option" => "Alt".to_owned(),
"shift" => "Shift".to_owned(),
other => other.to_owned(),
})
.collect::<Vec<_>>()
.join("+")
})
.collect::<Vec<_>>()
.join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::commands::Command;
#[test]
fn files_apply_and_report_errors() {
let mut registry = CommandRegistry::new();
registry.register(Command::new("file.save", "Save"));
registry.register(Command::new("file.close", "Close"));
let file = Keybindings::new()
.with(KeybindingEntry::new("file.save", "Ctrl+S"))
.with(KeybindingEntry::new("file.close", "Ctrl+W"))
.with(KeybindingEntry::new("missing.command", "Ctrl+M"))
.with(KeybindingEntry::new("file.save", "not a chord"));
let errors = file.apply(&mut registry);
assert_eq!(errors.len(), 2);
assert_eq!(
registry.binding(&CommandId::new("file.save")).map(ToString::to_string),
Some("Ctrl+S".to_owned())
);
}
#[cfg(feature = "serde")]
#[test]
fn json_round_trips_and_imports_vscode() {
let file = Keybindings::new().with(KeybindingEntry::new("file.save", "Ctrl+S"));
let json = file.to_json().expect("serialize");
let back = Keybindings::from_json(&json).expect("parse");
assert_eq!(back, file);
let vscode = r#"[{"key":"ctrl+shift+p","command":"workbench.palette","when":"editorFocus"}]"#;
let imported = Keybindings::import_vscode(vscode).expect("vscode");
assert_eq!(imported.bindings.len(), 1);
assert_eq!(imported.bindings[0].keys, "Ctrl+Shift+p");
assert_eq!(imported.bindings[0].when.as_deref(), Some("editorFocus"));
}
}