M14.3: keyboard shortcut editor

Keyboard shortcut presets in the engine (`engine::shortcuts`): every menu entry (including
ones with bound parameters), registry command and frontend command is bindable, scoped
application-wide or to a panel. "EffectCraft Default" is After Effects' layout and
read-only; editing it creates a custom preset that stores only its differences. Presets
are saved in the config store; the shortcut dispatcher and the menus read the active one.

- Commands: shortcuts.list, shortcuts.set {command, params?, keys}, shortcuts.reset,
  shortcuts.preset {select|new|duplicate|delete|rename}, shortcuts.export/import (JSON),
  shortcuts.conflicts.
- Edit > Keyboard Shortcuts: preset bar, modifier toggles (or held keys), an on-screen
  keyboard coloured by scope (application-wide / panel-specific / both), key details,
  a searchable list of every command, record-or-type assignment with conflict warnings,
  reset to default; all widgets have automation ids.
- Tests: normalization, defaults conflict-free, conflict detection, custom preset creation
  and persistence, preset lifecycle + export/import, dispatch uses the custom preset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 09:14:54 -04:00
co-authored by Claude Opus 5.5
parent 47f7712364
commit 35f429363e
14 changed files with 1439 additions and 99 deletions
+150 -2
View File
@@ -1,9 +1,10 @@
//! Settings (`prefs.*`).
//! Settings (`prefs.*`) and keyboard shortcut presets (`shortcuts.*`).
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, str_p};
use crate::{Result, Session, cmd, query};
use crate::shortcuts::{DEFAULT_PRESET, binding_key, normalize};
use crate::{EngineError, Result, Session, cmd, query};
// ---------------------------------------------------------------- prefs
@@ -57,6 +58,146 @@ fn prefs_pages(_: &mut Session, _: &Value) -> Result<Value> {
Ok(crate::prefs::pages_json())
}
// ---------------------------------------------------------------- shortcuts
/// The bindable named by `command` (+ `params`), or by a binding key (`app.settings {...}`).
fn bindable(s: &Session, p: &Value, cmd: &str) -> Result<crate::shortcuts::Bindable> {
let c = str_p(p, "command").ok_or_else(|| bad(cmd, "missing `command`"))?;
let params = p.get("params").cloned().unwrap_or(Value::Null);
let t = s.shortcuts();
let key = binding_key(c, &params);
t.find(&key).or_else(|| t.find(c)).cloned().ok_or_else(|| bad(cmd, format!("`{key}` can't have a shortcut (see shortcuts.list)")))
}
fn keys_param(p: &Value, cmd: &str) -> Result<Vec<String>> {
Ok(match p.get("keys") {
None | Some(Value::Null) => vec![],
Some(Value::String(k)) if k.trim().is_empty() => vec![],
Some(Value::String(k)) => vec![k.clone()],
Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(),
Some(v) => return Err(bad(cmd, format!("`keys` must be a string or a list, not {v}"))),
})
}
fn sc_list(s: &mut Session, p: &Value) -> Result<Value> {
let q = str_p(p, "query").unwrap_or("").to_lowercase();
let assigned = p.get("assigned").and_then(Value::as_bool).unwrap_or(false);
let keys_q = str_p(p, "keys").and_then(normalize);
let t = s.shortcuts();
let rows: Vec<Value> = t
.bindables
.iter()
.filter_map(|b| {
let keys = t.keys.get(&b.key).cloned().unwrap_or_default();
if assigned && keys.is_empty() {
return None;
}
if let Some(k) = &keys_q
&& !keys.contains(k)
{
return None;
}
let hay = format!("{} {} {} {}", b.label, b.command, b.path.join(" "), keys.join(" ")).to_lowercase();
if !q.split_whitespace().all(|w| hay.contains(w)) {
return None;
}
let mut o = serde_json::to_value(b).unwrap_or_default();
o["keys"] = json!(keys);
Some(o)
})
.collect();
Ok(json!({"preset": s.keymaps.active, "presets": s.keymaps.names(), "count": rows.len(), "commands": rows}))
}
fn sc_set(s: &mut Session, p: &Value) -> Result<Value> {
let b = bindable(s, p, "shortcuts.set")?;
let keys = keys_param(p, "shortcuts.set")?;
let conflicts: Vec<_> = keys.iter().flat_map(|k| s.shortcuts().conflicts(&b, k)).collect();
let created = s.keymaps.set(&b, &keys).map_err(|e| bad("shortcuts.set", e))?;
s.shortcuts_changed();
let now = s.shortcuts().keys.get(&b.key).cloned().unwrap_or_default();
if let Some(n) = &created {
s.toast(format!("The default shortcuts can't be changed: created the preset \"{n}\""));
}
if !conflicts.is_empty() {
let names: Vec<String> = conflicts.iter().map(|c| format!("{} ({})", c.label, c.keys)).collect();
s.toast(format!("Shortcut conflict: also used by {}", names.join(", ")));
}
Ok(json!({"command": b.key, "keys": now, "preset": s.keymaps.active, "created": created, "conflicts": conflicts}))
}
fn sc_reset(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(c) = str_p(p, "command") {
let b = bindable(s, p, "shortcuts.reset")?;
let defaults = b.defaults.clone();
s.keymaps.set(&b, &defaults).map_err(|e| bad("shortcuts.reset", e))?;
s.shortcuts_changed();
return Ok(json!({"command": c, "keys": defaults}));
}
s.keymaps.reset_active();
s.shortcuts_changed();
Ok(json!({"preset": s.keymaps.active}))
}
fn sc_preset(s: &mut Session, p: &Value) -> Result<Value> {
let op = str_p(p, "op").unwrap_or("select");
let name = str_p(p, "name");
let e = |m: String| bad("shortcuts.preset", m);
let k = &mut s.keymaps;
match op {
"select" => k.select(name.unwrap_or(DEFAULT_PRESET)).map_err(e)?,
"new" => {
k.duplicate(DEFAULT_PRESET, Some(name.unwrap_or("Custom"))).map_err(e)?;
}
"duplicate" => {
let from = str_p(p, "from").map(str::to_string).unwrap_or_else(|| k.active.clone());
k.duplicate(&from, name).map_err(e)?;
}
"delete" => {
let n = name.map(str::to_string).unwrap_or_else(|| k.active.clone());
k.delete(&n).map_err(e)?;
}
"rename" => {
let to = str_p(p, "newName").ok_or_else(|| bad("shortcuts.preset", "missing `newName`"))?;
let from = name.map(str::to_string).unwrap_or_else(|| k.active.clone());
k.rename(&from, to).map_err(e)?;
}
_ => return Err(bad("shortcuts.preset", "op must be select, new, duplicate, delete or rename")),
}
s.shortcuts_changed();
Ok(json!({"preset": s.keymaps.active, "presets": s.keymaps.names()}))
}
fn sc_export(s: &mut Session, p: &Value) -> Result<Value> {
let doc = s.keymaps.export(str_p(p, "preset")).map_err(|e| bad("shortcuts.export", e))?;
if let Some(path) = str_p(p, "path") {
let text = serde_json::to_string_pretty(&doc).unwrap_or_default();
s.services.write_file(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
return Ok(json!({"path": path, "preset": doc["name"]}));
}
Ok(doc)
}
fn sc_import(s: &mut Session, p: &Value) -> Result<Value> {
let doc = match (str_p(p, "path"), p.get("preset")) {
(Some(path), _) => {
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
serde_json::from_slice(&bytes).map_err(|e| bad("shortcuts.import", format!("{path}: {e}")))?
}
(None, Some(v)) if v.is_object() => v.clone(),
_ => return Err(bad("shortcuts.import", "give `path` or `preset` (an exported document)")),
};
let name = s.keymaps.import(&doc, str_p(p, "name")).map_err(|e| bad("shortcuts.import", e))?;
s.shortcuts_changed();
Ok(json!({"preset": name}))
}
fn sc_conflicts(s: &mut Session, _: &Value) -> Result<Value> {
let c: Vec<Value> =
s.shortcuts().all_conflicts().into_iter().map(|(a, c)| json!({"command": a, "keys": c.keys, "with": c.key, "scope": c.scope})).collect();
Ok(json!(c))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
query!("prefs.get", "Get Setting", "{key?: e.g. general.undoLevels (omit for all settings)}", prefs_get),
@@ -72,5 +213,12 @@ pub fn specs() -> Vec<CommandSpec> {
prefs_open
),
query!("prefs.pages", "Settings Pages", "{}", prefs_pages),
query!("shortcuts.list", "List Keyboard Shortcuts", "{query?, keys?, assigned?: bool}", sc_list),
cmd!("shortcuts.set", "Set Keyboard Shortcut", [], None, "{command, params?, keys: \"Cmd+Shift+K\" | [keys] | null}", always, sc_set),
cmd!("shortcuts.reset", "Reset Keyboard Shortcuts", [], None, "{command?, params?}", always, sc_reset),
cmd!("shortcuts.preset", "Keyboard Shortcut Preset", [], None, "{op: select|new|duplicate|delete|rename, name?, from?, newName?}", always, sc_preset),
cmd!("shortcuts.export", "Export Keyboard Shortcuts", [], None, "{preset?, path?}", always, sc_export),
cmd!("shortcuts.import", "Import Keyboard Shortcuts", [], None, "{path? | preset?: exported document, name?}", always, sc_import),
query!("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "{}", sc_conflicts),
]
}
+5 -5
View File
@@ -1,13 +1,13 @@
//! Persistent configuration storage (Settings). The engine only sees the [`ConfigStore`] trait;
//! frontends choose where it lives: the desktop app uses a [`DirConfig`] in the platform config
//! directory, the web app can back it with `localStorage`, tests and headless runs use
//! [`MemoryConfig`] (or none at all).
//! Persistent configuration storage (Settings, keyboard shortcut presets, the crash-recovery
//! sentinel). The engine only sees the [`ConfigStore`] trait; frontends choose where it lives:
//! the desktop app uses a [`DirConfig`] in the platform config directory, the web app can back it
//! with `localStorage`, tests and headless runs use [`MemoryConfig`] (or none at all).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
/// Named text blobs (`prefs.json`).
/// Named text blobs (`prefs.json`, `shortcuts.json`, `session.lock`).
pub trait ConfigStore: Send + Sync {
fn read(&self, name: &str) -> Option<String>;
fn write(&self, name: &str, data: &str) -> std::io::Result<()>;
+12 -1
View File
@@ -16,6 +16,7 @@ pub mod menus;
pub mod prefs;
pub mod render_queue;
mod session_settings;
pub mod shortcuts;
use std::sync::Arc;
@@ -215,8 +216,15 @@ pub struct Session {
pub prefs: prefs::Prefs,
/// Bumped whenever settings change (frontends re-apply theme, labels…).
pub prefs_revision: u64,
/// Where settings are stored (`None` = nothing persists).
/// Where settings, shortcut presets and the crash-recovery sentinel are stored (`None` =
/// nothing persists).
pub config: Option<Arc<dyn config::ConfigStore>>,
/// Keyboard shortcut presets.
pub keymaps: shortcuts::Keymaps,
/// Frontend-only commands offered for binding.
pub ui_commands: Vec<shortcuts::UiCommand>,
/// Cache of the resolved active preset (read it with [`Session::shortcuts`]).
pub shortcut_table: std::sync::OnceLock<shortcuts::ShortcutTable>,
}
impl Default for Session {
@@ -241,6 +249,9 @@ impl Default for Session {
prefs: prefs::Prefs::default(),
prefs_revision: 0,
config: None,
keymaps: shortcuts::Keymaps::default(),
ui_commands: vec![],
shortcut_table: std::sync::OnceLock::new(),
}
}
}
+32 -6
View File
@@ -1,17 +1,22 @@
//! Session side of Settings.
//! Session side of Settings and keyboard shortcut presets.
use crate::Session;
use crate::prefs::{PREFS_FILE, Prefs};
use crate::shortcuts::{Keymaps, SHORTCUTS_FILE, ShortcutTable, UiCommand};
impl Session {
/// Load settings from the config store and apply them.
/// Load settings and shortcut presets from the config store and apply them.
pub fn load_settings(&mut self) {
if let Some(c) = &self.config
&& let Some(t) = c.read(PREFS_FILE)
{
self.prefs = Prefs::from_json(&t);
if let Some(c) = &self.config {
if let Some(t) = c.read(PREFS_FILE) {
self.prefs = Prefs::from_json(&t);
}
if let Some(t) = c.read(SHORTCUTS_FILE) {
self.keymaps = Keymaps::from_json(&t);
}
}
self.prefs_changed();
self.shortcuts_changed();
}
/// Settings changed: apply what the engine owns (cache budgets) and tell frontends.
@@ -36,4 +41,25 @@ impl Session {
log::warn!("saving settings: {e}");
}
}
/// Shortcut presets changed: rebuild the table and save them.
pub fn shortcuts_changed(&mut self) {
self.shortcut_table = std::sync::OnceLock::new();
if let Some(c) = &self.config
&& let Err(e) = c.write(SHORTCUTS_FILE, &self.keymaps.to_json())
{
log::warn!("saving keyboard shortcuts: {e}");
}
}
/// The frontend's own bindable commands (tools, timeline navigation…).
pub fn set_ui_commands(&mut self, cmds: Vec<UiCommand>) {
self.ui_commands = cmds;
self.shortcut_table = std::sync::OnceLock::new();
}
/// The active shortcut preset resolved against every bindable command.
pub fn shortcuts(&self) -> &ShortcutTable {
self.shortcut_table.get_or_init(|| ShortcutTable::build(&self.keymaps, &self.ui_commands))
}
}
+468
View File
@@ -0,0 +1,468 @@
//! Keyboard shortcut presets (Edit ▸ Keyboard Shortcuts).
//!
//! Every menu entry, registry command and frontend command is *bindable*: it has a binding key
//! (the command id, plus its bound parameters for entries such as `app.settings
//! {"page":"general"}`), a scope (application-wide or a panel) and default keys. The built-in
//! preset "EffectCraft Default" is After Effects' default keyboard layout and is read-only; custom
//! presets store only their differences from it. Editing the default preset first duplicates it
//! (as After Effects asks you to "Save As" a custom set). The shortcut dispatcher and the menus
//! read the active preset through [`ShortcutTable`].
//!
//! Shortcut text is `Ctrl+Cmd+Alt+Shift+Key` (`Cmd` is ⌘ on macOS and Ctrl elsewhere).
use std::collections::{BTreeMap, HashMap};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
/// Preset file in the config store.
pub const SHORTCUTS_FILE: &str = "shortcuts.json";
/// The built-in (read-only) preset.
pub const DEFAULT_PRESET: &str = "EffectCraft Default";
/// Scope of application-wide shortcuts.
pub const APP_SCOPE: &str = "Application";
/// A frontend-only command offered for binding (tools, timeline navigation…).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UiCommand {
pub id: String,
pub label: String,
pub shortcut: Option<String>,
}
/// One thing a shortcut can run.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Bindable {
/// Binding key: `command` or `command {params}`.
pub key: String,
pub command: String,
#[serde(skip_serializing_if = "Value::is_null")]
pub params: Value,
pub label: String,
/// Menu path (`["Layer", "New"]`) or a category for commands outside the menus.
pub path: Vec<String>,
/// `Application` or the panel the shortcut works in (`Timeline`, `Composition`…).
pub scope: String,
/// After Effects default keys.
pub defaults: Vec<String>,
}
/// The binding key of a command with bound parameters.
pub fn binding_key(command: &str, params: &Value) -> String {
match params {
Value::Null => command.to_string(),
Value::Object(m) if m.is_empty() => command.to_string(),
p => format!("{command} {p}"),
}
}
/// Scope of a frontend command from its id.
fn ui_scope(id: &str) -> &'static str {
if id.starts_with("timeline.") {
"Timeline"
} else if id.starts_with("view.") {
"Composition"
} else {
APP_SCOPE
}
}
/// Every bindable command: menu entries, registry commands outside the menus, then the
/// frontend's own commands.
pub fn bindables(ui: &[UiCommand]) -> Vec<Bindable> {
let mut out: Vec<Bindable> = vec![];
let mut seen: HashMap<String, usize> = HashMap::new();
let mut push = |b: Bindable, out: &mut Vec<Bindable>| {
if let Some(&i) = seen.get(&b.key) {
// Same command in two menus: merge defaults.
for d in b.defaults {
if !out[i].defaults.contains(&d) {
out[i].defaults.push(d);
}
}
return;
}
seen.insert(b.key.clone(), out.len());
out.push(b);
};
let entries = crate::menus::entries();
for (path, e) in &entries {
let key = binding_key(&e.command, &e.params);
let defaults = e.shortcut.iter().filter_map(|s| normalize(s)).collect();
push(
Bindable {
key,
command: e.command.clone(),
params: e.params.clone(),
label: e.label.clone(),
path: path.clone(),
scope: APP_SCOPE.into(),
defaults,
},
&mut out,
);
}
for c in crate::command_specs() {
if !c.journal || entries.iter().any(|(_, e)| e.command == c.id) {
continue;
}
let defaults = c.shortcut.and_then(normalize).into_iter().collect();
push(
Bindable {
key: c.id.to_string(),
command: c.id.to_string(),
params: Value::Null,
label: c.label.to_string(),
path: vec!["Commands".into()],
scope: APP_SCOPE.into(),
defaults,
},
&mut out,
);
}
for c in ui {
let scope = ui_scope(&c.id);
let cat = if scope == APP_SCOPE { "Tools & Panels" } else { scope };
push(
Bindable {
key: c.id.clone(),
command: c.id.clone(),
params: Value::Null,
label: c.label.clone(),
path: vec![cat.into()],
scope: scope.into(),
defaults: c.shortcut.as_deref().and_then(normalize).into_iter().collect(),
},
&mut out,
);
}
out
}
/// Canonical shortcut text (`cmd+shift+k`, `Shift+Cmd+K`, `⌘⇧K` → `Cmd+Shift+K`); `None` if it
/// has no key.
pub fn normalize(s: &str) -> Option<String> {
let s = s.trim();
if s.is_empty() {
return None;
}
let (mut ctrl, mut cmd, mut alt, mut shift) = (false, false, false, false);
let mut key: Option<String> = None;
// `Cmd++` / `+` name the plus key.
let (head, plus) = match s.strip_suffix("++") {
Some(h) => (h, true),
None if s == "+" => ("", true),
None => (s, false),
};
let mut parts: Vec<String> = head.split('+').filter(|p| !p.is_empty()).map(str::to_string).collect();
// macOS glyph notation.
if parts.len() == 1 && parts[0].chars().any(|c| "⌃⌥⇧⌘".contains(c)) {
let p = parts.remove(0);
let mut rest = String::new();
for c in p.chars() {
match c {
'⌃' => ctrl = true,
'⌥' => alt = true,
'⇧' => shift = true,
'⌘' => cmd = true,
c => rest.push(c),
}
}
if !rest.is_empty() {
parts.push(rest);
}
}
for p in parts {
match p.to_ascii_lowercase().as_str() {
"cmd" | "command" | "meta" | "super" | "win" => cmd = true,
"ctrl" | "control" => ctrl = true,
"alt" | "opt" | "option" => alt = true,
"shift" => shift = true,
_ => key = Some(key_name(&p)),
}
}
if plus {
key = Some("+".into());
}
let key = key?;
let mut out = String::new();
for (on, m) in [(ctrl, "Ctrl+"), (cmd, "Cmd+"), (alt, "Alt+"), (shift, "Shift+")] {
if on {
out.push_str(m);
}
}
out.push_str(&key);
Some(out)
}
fn key_name(k: &str) -> String {
let l = k.to_ascii_lowercase();
match l.as_str() {
"space" | "spacebar" => "Space".into(),
"esc" | "escape" => "Escape".into(),
"enter" | "return" => "Enter".into(),
"tab" => "Tab".into(),
"backspace" => "Backspace".into(),
"delete" | "del" => "Delete".into(),
"home" => "Home".into(),
"end" => "End".into(),
"pageup" | "pgup" => "PageUp".into(),
"pagedown" | "pgdn" => "PageDown".into(),
"up" | "arrowup" => "ArrowUp".into(),
"down" | "arrowdown" => "ArrowDown".into(),
"left" | "arrowleft" => "ArrowLeft".into(),
"right" | "arrowright" => "ArrowRight".into(),
_ if l.starts_with("num") => format!("Num{}", &k[3..]),
_ if l.len() > 1 && l.starts_with('f') && l[1..].chars().all(|c| c.is_ascii_digit()) => l.to_ascii_uppercase(),
_ if k.chars().count() == 1 => k.to_uppercase(),
_ => k.to_string(),
}
}
/// A custom preset: differences from the default (`[]` removes a default shortcut).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Preset {
pub name: String,
#[serde(default)]
pub overrides: BTreeMap<String, Vec<String>>,
}
/// The saved presets and which one is active.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Keymaps {
pub active: String,
pub presets: Vec<Preset>,
}
impl Default for Keymaps {
fn default() -> Self {
Keymaps { active: DEFAULT_PRESET.into(), presets: vec![] }
}
}
/// A conflict: another command already using the keys in an overlapping scope.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Conflict {
pub keys: String,
pub key: String,
pub label: String,
pub scope: String,
}
fn scopes_overlap(a: &str, b: &str) -> bool {
a == b || a == APP_SCOPE || b == APP_SCOPE
}
impl Keymaps {
pub fn from_json(text: &str) -> Keymaps {
let mut k: Keymaps = serde_json::from_str(text).unwrap_or_default();
if !k.presets.iter().any(|p| p.name == k.active) {
k.active = DEFAULT_PRESET.into();
}
k
}
pub fn to_json(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_default()
}
/// Preset names, the default first.
pub fn names(&self) -> Vec<String> {
std::iter::once(DEFAULT_PRESET.to_string()).chain(self.presets.iter().map(|p| p.name.clone())).collect()
}
pub fn active_preset(&self) -> Option<&Preset> {
self.presets.iter().find(|p| p.name == self.active)
}
/// Effective keys of a bindable in the active preset.
pub fn keys_of(&self, b: &Bindable) -> Vec<String> {
match self.active_preset().and_then(|p| p.overrides.get(&b.key)) {
Some(k) => k.clone(),
None => b.defaults.clone(),
}
}
fn unique_name(&self, base: &str) -> String {
if !self.names().iter().any(|n| n == base) {
return base.to_string();
}
(2..).map(|i| format!("{base} {i}")).find(|n| !self.names().contains(n)).unwrap_or_else(|| base.to_string())
}
/// Make sure a custom preset is active (editing the default duplicates it as "Custom").
/// Returns the name of a preset created for the edit.
fn ensure_custom(&mut self) -> Option<String> {
if self.active_preset().is_some() {
return None;
}
let name = self.unique_name("Custom");
self.presets.push(Preset { name: name.clone(), overrides: BTreeMap::new() });
self.active = name.clone();
Some(name)
}
/// Set the keys of a bindable (normalized; empty = no shortcut). Returns a newly created
/// preset name when the default was active.
pub fn set(&mut self, b: &Bindable, keys: &[String]) -> Result<Option<String>, String> {
let mut norm = vec![];
for k in keys {
let n = normalize(k).ok_or_else(|| format!("`{k}` is not a shortcut"))?;
if !norm.contains(&n) {
norm.push(n);
}
}
let created = self.ensure_custom();
let p = self.presets.iter_mut().find(|p| p.name == self.active).ok_or("no active preset")?;
if norm == b.defaults {
p.overrides.remove(&b.key);
} else {
p.overrides.insert(b.key.clone(), norm);
}
Ok(created)
}
/// Clear the active preset's changes (its shortcuts become the defaults).
pub fn reset_active(&mut self) {
let active = self.active.clone();
if let Some(p) = self.presets.iter_mut().find(|p| p.name == active) {
p.overrides.clear();
}
}
pub fn select(&mut self, name: &str) -> Result<(), String> {
if !self.names().iter().any(|n| n == name) {
return Err(format!("no shortcut preset `{name}`"));
}
self.active = name.to_string();
Ok(())
}
/// Duplicate a preset (the default or a custom one) under a new name and activate it.
pub fn duplicate(&mut self, from: &str, name: Option<&str>) -> Result<String, String> {
let overrides = if from == DEFAULT_PRESET {
BTreeMap::new()
} else {
self.presets.iter().find(|p| p.name == from).ok_or_else(|| format!("no shortcut preset `{from}`"))?.overrides.clone()
};
let name = self.unique_name(name.unwrap_or(&format!("{from} copy")));
self.presets.push(Preset { name: name.clone(), overrides });
self.active = name.clone();
Ok(name)
}
pub fn delete(&mut self, name: &str) -> Result<(), String> {
if name == DEFAULT_PRESET {
return Err("the default preset can't be deleted".into());
}
let n = self.presets.len();
self.presets.retain(|p| p.name != name);
if self.presets.len() == n {
return Err(format!("no shortcut preset `{name}`"));
}
if self.active == name {
self.active = DEFAULT_PRESET.into();
}
Ok(())
}
pub fn rename(&mut self, from: &str, to: &str) -> Result<(), String> {
if from == DEFAULT_PRESET || to == DEFAULT_PRESET {
return Err("the default preset can't be renamed".into());
}
if self.names().iter().any(|n| n == to) {
return Err(format!("a preset named `{to}` exists"));
}
let p = self.presets.iter_mut().find(|p| p.name == from).ok_or_else(|| format!("no shortcut preset `{from}`"))?;
p.name = to.to_string();
if self.active == from {
self.active = to.to_string();
}
Ok(())
}
/// A preset as a portable JSON document.
pub fn export(&self, name: Option<&str>) -> Result<Value, String> {
let name = name.unwrap_or(&self.active);
let overrides = if name == DEFAULT_PRESET {
BTreeMap::new()
} else {
self.presets.iter().find(|p| p.name == name).ok_or_else(|| format!("no shortcut preset `{name}`"))?.overrides.clone()
};
Ok(json!({"format": "effectcraft-shortcuts", "version": 1, "name": name, "base": DEFAULT_PRESET, "overrides": overrides}))
}
/// Import an exported preset (renamed if the name is taken) and activate it.
pub fn import(&mut self, doc: &Value, name: Option<&str>) -> Result<String, String> {
let overrides: BTreeMap<String, Vec<String>> =
serde_json::from_value(doc.get("overrides").cloned().unwrap_or_else(|| json!({}))).map_err(|e| format!("bad shortcut preset: {e}"))?;
let overrides = overrides.into_iter().map(|(k, v)| (k, v.iter().filter_map(|s| normalize(s)).collect())).collect();
let base = name.or_else(|| doc.get("name").and_then(Value::as_str)).unwrap_or("Imported");
let base = if base == DEFAULT_PRESET { "Imported" } else { base };
let name = self.unique_name(base);
self.presets.push(Preset { name: name.clone(), overrides });
self.active = name.clone();
Ok(name)
}
}
/// The active preset resolved against every bindable command.
#[derive(Clone, Debug, Default)]
pub struct ShortcutTable {
pub bindables: Vec<Bindable>,
/// Effective keys per binding key.
pub keys: HashMap<String, Vec<String>>,
}
impl ShortcutTable {
pub fn build(maps: &Keymaps, ui: &[UiCommand]) -> ShortcutTable {
let bindables = bindables(ui);
let keys = bindables.iter().map(|b| (b.key.clone(), maps.keys_of(b))).collect();
ShortcutTable { bindables, keys }
}
pub fn find(&self, key: &str) -> Option<&Bindable> {
self.bindables.iter().find(|b| b.key == key)
}
/// First shortcut of a command / menu entry (for menus).
pub fn shortcut_of(&self, command: &str, params: &Value) -> Option<&str> {
self.keys.get(&binding_key(command, params)).and_then(|k| k.first()).map(String::as_str)
}
/// Every active binding: (keys, bindable).
pub fn bindings(&self) -> Vec<(&str, &Bindable)> {
self.bindables.iter().flat_map(|b| self.keys.get(&b.key).into_iter().flatten().map(move |k| (k.as_str(), b))).collect()
}
/// Other bindables using `keys` in an overlapping scope.
pub fn conflicts(&self, b: &Bindable, keys: &str) -> Vec<Conflict> {
let Some(keys) = normalize(keys) else { return vec![] };
self.bindings()
.into_iter()
.filter(|(k, o)| *k == keys && o.key != b.key && scopes_overlap(&o.scope, &b.scope))
.map(|(k, o)| Conflict { keys: k.to_string(), key: o.key.clone(), label: o.label.clone(), scope: o.scope.clone() })
.collect()
}
/// Every pair of commands sharing keys in an overlapping scope.
pub fn all_conflicts(&self) -> Vec<(String, Conflict)> {
let mut by_keys: BTreeMap<&str, Vec<&Bindable>> = BTreeMap::new();
for (k, b) in self.bindings() {
if k != "Num*" {
by_keys.entry(k).or_default().push(b);
}
}
let mut out = vec![];
for (k, bs) in by_keys {
for (i, a) in bs.iter().enumerate() {
for b in &bs[i + 1..] {
if scopes_overlap(&a.scope, &b.scope) {
out.push((a.key.clone(), Conflict { keys: k.to_string(), key: b.key.clone(), label: b.label.clone(), scope: b.scope.clone() }));
}
}
}
}
out
}
}
+94 -1
View File
@@ -1,4 +1,4 @@
//! Settings.
//! Settings and keyboard shortcut presets.
use std::path::PathBuf;
use std::sync::Arc;
@@ -8,6 +8,7 @@ use serde_json::json;
use crate::Session;
use crate::config::{ConfigStore, MemoryConfig};
use crate::prefs::{PREFS_FILE, Prefs};
use crate::shortcuts::{DEFAULT_PRESET, Keymaps, normalize};
fn tmp(name: &str) -> PathBuf {
use std::sync::atomic::{AtomicU32, Ordering};
@@ -233,3 +234,95 @@ fn new_project_template_and_default_renderer() {
assert_eq!(s.active_comp().unwrap().renderer, effectcraft_project::Renderer::Advanced3D);
let _ = std::fs::remove_dir_all(d);
}
// ---------------------------------------------------------------- shortcuts
#[test]
fn shortcut_text_normalizes() {
assert_eq!(normalize("shift+cmd+k").as_deref(), Some("Cmd+Shift+K"));
assert_eq!(normalize("Opt+Ctrl+f5").as_deref(), Some("Ctrl+Alt+F5"));
assert_eq!(normalize("⌘⇧S").as_deref(), Some("Cmd+Shift+S"));
assert_eq!(normalize("Cmd++").as_deref(), Some("Cmd++"));
assert_eq!(normalize("space").as_deref(), Some("Space"));
assert_eq!(normalize("Cmd+").as_deref(), None);
}
#[test]
fn defaults_have_no_conflicts_and_match_the_menus() {
let s = Session::default();
let t = s.shortcuts();
assert!(t.all_conflicts().is_empty(), "{:?}", t.all_conflicts());
assert_eq!(t.shortcut_of("file.save", &json!(null)), Some("Cmd+S"));
assert_eq!(t.shortcut_of("app.settings", &json!({"page": "general"})), Some("Cmd+Alt+;"));
assert!(t.bindables.len() > 500);
}
#[test]
fn shortcut_edits_detect_conflicts_and_create_a_custom_preset() {
let store = Arc::new(MemoryConfig::default());
let mut s = Session { config: Some(store.clone()), ..Default::default() };
let r = s.execute_checked("shortcuts.set", json!({"command": "layer.newNull", "keys": "cmd+s"})).unwrap();
assert_eq!(r["keys"], json!(["Cmd+S"]));
assert_eq!(r["created"], json!("Custom"));
assert!(r["conflicts"].as_array().unwrap().iter().any(|c| c["key"] == "file.save"), "{r}");
assert_eq!(s.keymaps.active, "Custom");
assert_eq!(s.shortcuts().shortcut_of("layer.newNull", &json!(null)), Some("Cmd+S"));
assert!(!s.execute("shortcuts.conflicts", json!({})).unwrap().as_array().unwrap().is_empty());
// The default preset is untouched.
s.execute("shortcuts.preset", json!({"op": "select", "name": DEFAULT_PRESET})).unwrap();
assert_eq!(s.shortcuts().shortcut_of("layer.newNull", &json!(null)), Some("Cmd+Alt+Shift+Y"));
// Remove a shortcut; reset one.
s.execute("shortcuts.preset", json!({"op": "select", "name": "Custom"})).unwrap();
s.execute("shortcuts.set", json!({"command": "file.save", "keys": null})).unwrap();
assert_eq!(s.shortcuts().shortcut_of("file.save", &json!(null)), None);
s.execute("shortcuts.reset", json!({"command": "file.save"})).unwrap();
assert_eq!(s.shortcuts().shortcut_of("file.save", &json!(null)), Some("Cmd+S"));
// Bound-parameter entries are bindable too.
s.execute("shortcuts.set", json!({"command": "app.settings", "params": {"page": "labels"}, "keys": ["F9"]})).unwrap();
assert_eq!(s.shortcuts().shortcut_of("app.settings", &json!({"page": "labels"})), Some("F9"));
// Persisted.
let k = Keymaps::from_json(&store.read(crate::shortcuts::SHORTCUTS_FILE).unwrap());
assert_eq!(k.active, "Custom");
assert!(s.execute("shortcuts.set", json!({"command": "no.such", "keys": "F1"})).is_err());
assert!(s.execute("shortcuts.set", json!({"command": "file.save", "keys": "Cmd+"})).is_err());
let list = s.execute("shortcuts.list", json!({"keys": "F9"})).unwrap();
assert!(list["commands"].as_array().unwrap().iter().any(|c| c["command"] == "app.settings" && c["params"]["page"] == "labels"), "{list}");
}
#[test]
fn shortcut_presets_duplicate_rename_delete_export_import() {
let d = tmp("presets");
let mut s = Session::default();
s.execute("shortcuts.preset", json!({"op": "new", "name": "Mine"})).unwrap();
s.execute("shortcuts.set", json!({"command": "edit.undo", "keys": ["Cmd+Z", "F2"]})).unwrap();
s.execute("shortcuts.preset", json!({"op": "duplicate", "name": "Mine 2"})).unwrap();
assert_eq!(s.keymaps.names(), vec![DEFAULT_PRESET, "Mine", "Mine 2"]);
s.execute("shortcuts.preset", json!({"op": "rename", "name": "Mine 2", "newName": "Other"})).unwrap();
assert!(s.execute("shortcuts.preset", json!({"op": "delete", "name": DEFAULT_PRESET})).is_err());
let path = d.join("mine.json");
s.execute("shortcuts.export", json!({"preset": "Mine", "path": path.to_string_lossy()})).unwrap();
s.execute("shortcuts.preset", json!({"op": "delete", "name": "Mine"})).unwrap();
s.execute("shortcuts.preset", json!({"op": "delete", "name": "Other"})).unwrap();
assert_eq!(s.keymaps.active, DEFAULT_PRESET);
let r = s.execute("shortcuts.import", json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(r["preset"], json!("Mine"));
assert_eq!(s.shortcuts().keys["edit.undo"], vec!["Cmd+Z".to_string(), "F2".into()]);
s.execute("shortcuts.reset", json!({})).unwrap();
assert_eq!(s.shortcuts().keys["edit.undo"], vec!["Cmd+Z".to_string()]);
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn frontend_commands_are_bindable_with_panel_scope() {
let mut s = Session::default();
s.set_ui_commands(vec![
crate::shortcuts::UiCommand { id: "timeline.zoomIn".into(), label: "Zoom In Time".into(), shortcut: Some("=".into()) },
crate::shortcuts::UiCommand { id: "tool.hand".into(), label: "Hand Tool".into(), shortcut: Some("H".into()) },
]);
let b = s.shortcuts().find("timeline.zoomIn").unwrap().clone();
assert_eq!(b.scope, "Timeline");
assert_eq!(s.shortcuts().shortcut_of("tool.hand", &json!(null)), Some("H"));
// A panel shortcut conflicts with an application shortcut on the same keys.
let c = s.shortcuts().conflicts(&b, "H");
assert!(c.iter().any(|c| c.key == "tool.hand"));
}