diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs
index 23b64ae30e..f73a702385 100644
--- a/crates/automation/src/workspace.rs
+++ b/crates/automation/src/workspace.rs
@@ -369,6 +369,10 @@ fn command_uses_ambient_path(id: &str, params: &Value) -> bool {
}
// With a `path` the file is written there; without one the bytes come back as `data`.
"actions.save" | "swatches.export" => params.get("path").is_some(),
+ // Shortcut sets: a .kys read or written by path, or a Summarize page written by path.
+ "edit.keyboardShortcuts" => {
+ params.get("path").is_some() || ["importKys", "exportKys", "summarize"].iter().any(|k| params.get(*k).and_then(|v| v.get("path")).is_some())
+ }
"plugin.reload" => true,
_ => false,
}
@@ -712,6 +716,12 @@ mod tests {
assert!(authorize_desktop_engine_command("image.mode.cmyk", &serde_json::json!({})).is_err());
assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "/outside/profile.icc"})).is_err());
assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "srgb"})).is_ok());
+ // Shortcut sets: text in and out is fine; a path reads or writes the filesystem.
+ let ks = |p: serde_json::Value| authorize_engine_command("edit.keyboardShortcuts", &p);
+ assert!(ks(serde_json::json!({"exportKys": true, "summarize": true, "importKys": ""})).is_ok());
+ for key in ["importKys", "exportKys", "summarize"] {
+ assert!(ks(serde_json::json!({ key: {"path": "/outside/set.kys"} })).is_err(), "{key}");
+ }
assert!(authorize_engine_command("filter.distort.displace", &serde_json::json!({"mapPath": "outside.png"})).is_err());
assert!(authorize_engine_command("layer.setAdjustment", &serde_json::json!({"file": "outside.cube"})).is_err());
assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "colorSettings.workingRgb", "value": "outside.icc"})).is_err());
diff --git a/crates/engine/src/kys.rs b/crates/engine/src/kys.rs
index f996e23475..6a0ff99c84 100644
--- a/crates/engine/src/kys.rs
+++ b/crates/engine/src/kys.rs
@@ -160,12 +160,14 @@ fn key(label: &str) -> String {
l.trim_end_matches('…').trim().to_lowercase()
}
-/// The engine's own candidates: every command in a menu, in command order.
+/// The engine's own candidates: every command in a menu (the engine's, then the shell's), in
+/// command order.
pub fn command_candidates() -> Vec {
- crate::command_specs()
- .iter()
- .filter(|c| !c.menu.is_empty())
- .map(|c| Candidate { id: c.id.to_string(), label: c.label.to_string(), default: c.shortcut.map(str::to_string) })
+ let engine = crate::command_specs().iter().map(|c| (c.id, c.label, c.menu, c.shortcut));
+ engine
+ .chain(crate::shell_commands::SHELL_COMMANDS.iter().copied())
+ .filter(|c| !c.2.is_empty())
+ .map(|(id, label, _, default)| Candidate { id: id.to_string(), label: label.to_string(), default: default.map(str::to_string) })
.collect()
}
@@ -219,8 +221,8 @@ pub fn plan(candidates: impl IntoIterator, set: &KysSet) -> Pl
}
/// The tool keys of `set` matched to `tools` (our tool id and Photoshop's name for it, which is
-/// ours too: "Move Tool"): tool id → key (a single letter, upper case), and the names with no
-/// tool here. A row PhotoCraft wrote names the tool by id. A key that isn't one letter is skipped.
+/// ours too: "Move Tool"): tool id → key (normalised: a letter, or an F-key), and the names with no
+/// tool here. A row PhotoCraft wrote names the tool by id. A key with modifiers is skipped.
pub fn plan_tools<'a>(tools: impl IntoIterator, set: &KysSet) -> (BTreeMap, Vec) {
let tools: Vec<(&str, &str)> = tools.into_iter().collect();
let mut keys = BTreeMap::new();
@@ -232,11 +234,10 @@ pub fn plan_tools<'a>(tools: impl IntoIterator, set:
unknown.push(row.name.clone());
continue;
};
- let mut letters = row.shortcuts.first().map(|k| k.trim()).unwrap_or_default().chars();
- if let (Some(c), None) = (letters.next(), letters.next())
- && c.is_ascii_alphanumeric()
- {
- keys.insert((*id).to_string(), c.to_ascii_uppercase().to_string());
+ // One key without modifiers (Photoshop's letters; our tools may also take an F-key).
+ let key = row.shortcuts.first().and_then(|k| normalize_shortcut(k.trim()));
+ if let Some(k) = key.filter(|k| !k.contains('+') || k == "+") {
+ keys.insert((*id).to_string(), k);
}
}
(keys, unknown)
@@ -448,7 +449,7 @@ mod tests {
assert_eq!(keys.get("tools.select.move").map(String::as_str), Some("V"));
assert_eq!(keys.get("tools.select.pencil").map(String::as_str), Some("N"), "case-insensitive, upper-cased");
assert_eq!(keys.get("tools.select.brush").map(String::as_str), Some("B"), "by pc-id");
- assert!(!keys.contains_key("tools.select.lasso"), "a tool key is one letter");
+ assert!(!keys.contains_key("tools.select.lasso"), "a tool key has no modifiers");
assert_eq!(unknown, vec!["Imaginary Tool".to_string()]);
// Our own export reads back by id.
let out = write("T", &[Entry { id: "tools.select.pencil".into(), label: "Pencil Tool".into(), tool: true, keys: vec!["F".into()] }]);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index ba618f6ac8..41915c544d 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -103,6 +103,7 @@ pub mod sample_cmds;
pub mod sampler_cmds;
pub mod select_extra_cmds;
pub mod selection_cmds;
+pub mod shell_commands;
pub mod shortcut_sets;
pub mod slice_cmds;
pub mod smart_cmds;
diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs
index c732daeefd..10a1fdedcd 100644
--- a/crates/engine/src/prefs.rs
+++ b/crates/engine/src/prefs.rs
@@ -1495,9 +1495,65 @@ pub fn default_alternates(id: &str) -> impl Iterator + '_ {
ALTERNATE_SHORTCUTS.iter().filter(move |(c, _)| *c == id).map(|(_, sc)| *sc)
}
-/// Every bindable id with its default: commands, then the temporary tools.
+/// Keys the system takes before the app sees them (switching apps, closing the window, force
+/// quit): `edit.keyboardShortcuts` won't bind them, as Photoshop won't. `sc` is in our notation,
+/// where `Cmd` is Ctrl off the Mac.
+pub fn reserved_shortcut(sc: &str) -> bool {
+ let Some(n) = normalize_shortcut(sc) else { return false };
+ let reserved: &[&str] = if cfg!(target_os = "macos") {
+ &["Cmd+Tab", "Cmd+Shift+Tab", "Cmd+Alt+Escape", "Cmd+`"]
+ } else if cfg!(target_os = "windows") {
+ &["Alt+Tab", "Alt+Shift+Tab", "Alt+F4", "Cmd+Alt+Delete", "Cmd+Escape", "Cmd+Shift+Escape"]
+ } else {
+ // Linux and the BSDs: window switching and closing, and the virtual consoles.
+ &[
+ "Alt+Tab",
+ "Alt+Shift+Tab",
+ "Alt+F4",
+ "Cmd+Alt+Delete",
+ "Cmd+Alt+F1",
+ "Cmd+Alt+F2",
+ "Cmd+Alt+F3",
+ "Cmd+Alt+F4",
+ "Cmd+Alt+F5",
+ "Cmd+Alt+F6",
+ "Cmd+Alt+F7",
+ "Cmd+Alt+F8",
+ "Cmd+Alt+F9",
+ "Cmd+Alt+F10",
+ "Cmd+Alt+F11",
+ "Cmd+Alt+F12",
+ ]
+ };
+ reserved.iter().filter_map(|r| normalize_shortcut(r)).any(|r| r == n)
+}
+
+/// What a bindable id is: a command (the engine's or the shell's), a tool, or a held tool.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BindKind {
+ Command,
+ Tool,
+ Hold,
+}
+
+/// Every bindable id: (id, label, menu path, default key, kind). The engine's commands, the
+/// shell's ([`crate::shell_commands::SHELL_COMMANDS`]), the tools and the held temporary tools,
+/// so Edit › Keyboard Shortcuts works the same with or without the app's UI.
+pub fn bindable_items() -> impl Iterator, BindKind)> {
+ let engine = crate::command_specs().iter().map(|c| (c.id, c.label, c.menu, c.shortcut, BindKind::Command));
+ let shell = crate::shell_commands::SHELL_COMMANDS.iter().map(|c| (c.0, c.1, c.2, c.3, BindKind::Command));
+ let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1, &["Tools"][..], t.2, BindKind::Tool));
+ let hold = TEMPORARY_TOOLS.iter().map(|t| (t.0, t.1, &["Tools", "Temporary"][..], Some(t.2), BindKind::Hold));
+ engine.chain(shell).chain(tools).chain(hold)
+}
+
+/// Every bindable id with its default.
fn bindable() -> impl Iterator)> {
- crate::command_specs().iter().map(|c| (c.id, c.shortcut)).chain(TEMPORARY_TOOLS.iter().map(|t| (t.0, Some(t.2))))
+ bindable_items().map(|i| (i.0, i.3))
+}
+
+fn is_tool(id: &str) -> bool {
+ crate::shell_commands::tool_default(id).is_some()
}
/// Shortcuts bound to more than one command: (shortcut, ids). `bindings` are (id, shortcut).
@@ -1866,18 +1922,45 @@ fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result {
let imported;
let mut import = None;
let p = match p.get("importKys") {
- Some(xml) => {
- let xml = xml.as_str().ok_or_else(|| bad(cmd, "`importKys` is the text of a .kys file"))?;
+ Some(v) => {
+ // The file's text, or {"path": …} to read it.
+ let read;
+ let xml = match v {
+ Value::String(s) => s.as_str(),
+ Value::Object(o) => {
+ let path =
+ o.get("path").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, "`importKys.path` is a .kys file"))?;
+ read = read_text_file(path, crate::kys::MAX_BYTES).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
+ read.as_str()
+ }
+ _ => return Err(bad(cmd, "`importKys` is the text of a .kys file, or {\"path\": …}")),
+ };
let set = crate::kys::parse(xml).map_err(|e| bad(cmd, e))?;
let plan = crate::kys::plan(crate::kys::command_candidates(), &set);
let mut merged = serde_json::Map::new();
- for (id, sc) in &plan.set {
+ // A key the system reserves is left out (reported as `reserved`), not a failed import.
+ let mut skipped: Vec = Vec::new();
+ for (id, sc) in plan.set.iter().filter(|(id, sc)| {
+ let bad = reserved_shortcut(sc);
+ if bad {
+ skipped.push(format!("{id}: {sc}"));
+ }
+ !bad
+ }) {
let default = crate::command_specs().iter().find(|c| c.id == id).and_then(|c| c.shortcut).and_then(normalize_shortcut);
merged.insert(id.clone(), if default.as_deref() == Some(sc.as_str()) { Value::Null } else { json!(sc) });
}
+ // Tool keys: a tool's own letter restores it (and its Shift cycling).
+ let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1));
+ let (tool_keys, unknown_tools) = crate::kys::plan_tools(tools, &set);
+ for (id, key) in &tool_keys {
+ let own = crate::shell_commands::tool_default(id).flatten().is_some_and(|d| d.eq_ignore_ascii_case(key));
+ merged.insert(id.clone(), if own { Value::Null } else { json!(key) });
+ }
merged.extend(p.get("set").and_then(Value::as_object).cloned().unwrap_or_default());
let mut alternates = serde_json::Map::new();
for (id, keys) in &plan.alternate_keys {
+ let keys: &Vec = &keys.iter().filter(|k| !reserved_shortcut(k)).cloned().collect();
let main = plan.set.get(id).map(String::as_str);
let default = Preferences::default().alternates(id, main);
alternates.insert(id.clone(), if *keys == default { Value::Null } else { json!(keys) });
@@ -1892,6 +1975,9 @@ fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result {
"alternates": plan.alternates,
"alternateKeys": plan.alternate_keys,
"toolKeys": set.tool_keys,
+ "tools": tool_keys,
+ "unknownTools": unknown_tools,
+ "reserved": skipped,
"windows": set.windows,
}));
let mut with_import = p.clone();
@@ -1914,6 +2000,17 @@ fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result {
if !set.is_empty() || !alts.is_empty() {
let allow_unknown = p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false);
changed = true;
+ // Reserved system keys can't be bound, by hand or from a file.
+ let reserved = |v: &Value| -> Option {
+ let keys = match v {
+ Value::String(s) => vec![s.clone()],
+ other => alternate_keys(other).unwrap_or_default(),
+ };
+ keys.into_iter().find(|k| reserved_shortcut(k))
+ };
+ if let Some((id, k)) = set.iter().chain(alts.iter()).find_map(|(id, v)| reserved(v).map(|k| (id, k))) {
+ return Err(bad(cmd, format!("`{k}` (for `{id}`) is reserved by the system and can't be assigned")));
+ }
for (id, v) in set {
if !bindable().any(|(b, _)| b == id) && !allow_unknown {
return Err(bad(cmd, format!("unknown command `{id}`")));
@@ -1935,9 +2032,11 @@ fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result {
.chain(alts.iter().flat_map(|(id, v)| alternate_keys(v).unwrap_or_default().into_iter().map(move |k| (id.as_str(), k))))
.collect();
for (id, sc) in assigned {
- // Shell commands (View › Zoom In) have alternates but no engine default.
- let shell = ALTERNATE_SHORTCUTS.iter().filter(|(c, _)| crate::commands::find(c).is_none()).map(|(c, _)| (*c, None));
- for (c, def) in bindable().chain(shell) {
+ for (c, def) in bindable() {
+ // Tools may share a key: they cycle with Shift, as Photoshop's groups do.
+ if is_tool(id) && is_tool(c) {
+ continue;
+ }
// Never strip a command that this same call is assigning:
// two entries for one key are a clash inside the call, which
// the returned conflicts list reports (#719). Stripping
@@ -1964,11 +2063,7 @@ fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result {
}
let prefs = s.prefs();
let filter = p.get("filter").and_then(Value::as_str).map(str::to_ascii_lowercase);
- let temporary = TEMPORARY_TOOLS.iter().map(|t| (t.0, t.1, &["Tools", "Temporary"][..], Some(t.2), true));
- let list: Vec = crate::command_specs()
- .iter()
- .map(|c| (c.id, c.label, c.menu, c.shortcut, false))
- .chain(temporary)
+ let list: Vec = bindable_items()
.filter(|c| filter.as_ref().is_none_or(|f| c.0.to_ascii_lowercase().contains(f) || c.1.to_ascii_lowercase().contains(f)))
.filter(|c| {
p.get("list").and_then(Value::as_bool).unwrap_or(false)
@@ -1976,15 +2071,17 @@ fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result {
|| prefs.shortcuts.contains_key(c.0)
|| prefs.alternate_shortcuts.contains_key(c.0)
})
- .map(|(id, label, menu, def, hold)| {
+ .map(|(id, label, menu, def, kind)| {
let main = prefs.shortcut(id, def);
let defaults: Vec<&str> = default_alternates(id).collect();
let mut v = json!({"id": id, "label": label, "menu": menu, "default": def, "shortcut": main, "alternates": prefs.alternates(id, main)});
if !defaults.is_empty() {
v["defaultAlternates"] = json!(defaults);
}
- if hold {
- v["hold"] = json!(true);
+ match kind {
+ BindKind::Hold => v["hold"] = json!(true),
+ BindKind::Tool => v["tool"] = json!(true),
+ BindKind::Command => {}
}
v
})
@@ -1995,8 +2092,12 @@ fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result {
bindings.extend(main.map(|m| (id, m.to_string())));
bindings.extend(prefs.alternates(id, main).into_iter().map(|k| (id, k)));
}
- let conflicts: Vec =
- conflicts(bindings.iter().map(|(id, k)| (*id, k.as_str()))).into_iter().map(|(sc, ids)| json!({"shortcut": sc, "commands": ids})).collect();
+ // Tools sharing a key are a cycling group, not a conflict.
+ let conflicts: Vec = conflicts(bindings.iter().map(|(id, k)| (*id, k.as_str())))
+ .into_iter()
+ .filter(|(_, ids)| !ids.iter().all(|id| is_tool(id)))
+ .map(|(sc, ids)| json!({"shortcut": sc, "commands": ids}))
+ .collect();
let mut out = json!({"overrides": prefs.shortcuts, "alternateOverrides": prefs.alternate_shortcuts, "commands": list, "conflicts": conflicts});
if let (Some(o), Value::Object(sets)) = (out.as_object_mut(), crate::shortcut_sets::describe(prefs)) {
o.extend(sets);
@@ -2004,21 +2105,36 @@ fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result {
// The bindings as a `.kys` file, or Photoshop's Summarize page (the engine's commands; the
// app's dialog writes both with the shell's commands and tools added).
let set_name = if prefs.shortcut_set.is_empty() { crate::shortcut_sets::DEFAULTS_NAME } else { prefs.shortcut_set.as_str() };
- if p.get("exportKys").and_then(Value::as_bool) == Some(true) {
+ if let Some(target) = file_target(cmd, p.get("exportKys"))? {
let entries: Vec =
- crate::shortcut_sets::bound(prefs).into_iter().map(|(id, label, _, keys)| crate::kys::Entry { id, label, tool: false, keys }).collect();
- out["kys"] = json!(crate::kys::write(set_name, &entries));
+ crate::shortcut_sets::bound(prefs).into_iter().map(|b| crate::kys::Entry { id: b.id, label: b.label, tool: b.tool, keys: b.keys }).collect();
+ let text = crate::kys::write(set_name, &entries);
+ match target {
+ Some(path) => {
+ write_text_file(&path, &text).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
+ out["kysPath"] = json!(path);
+ }
+ None => out["kys"] = json!(text),
+ }
}
- if let Some(v) = p.get("summarize").filter(|v| !v.is_null() && *v != &json!(false)) {
+ if let Some(target) = file_target(cmd, p.get("summarize"))? {
+ let v = p.get("summarize").cloned().unwrap_or(Value::Null);
let mac = v.get("mac").and_then(Value::as_bool).unwrap_or(cfg!(target_os = "macos"));
let mut sections: Vec = Vec::new();
- for (_, label, menu, keys) in crate::shortcut_sets::bound(prefs) {
+ for crate::shortcut_sets::Bound { label, menu, keys, .. } in crate::shortcut_sets::bound(prefs) {
match sections.iter_mut().find(|(m, _)| *m == menu) {
Some((_, rows)) => rows.push((label, keys)),
None => sections.push((menu, vec![(label, keys)])),
}
}
- out["html"] = json!(crate::shortcut_sets::summarize(set_name, §ions, mac));
+ let html = crate::shortcut_sets::summarize(set_name, §ions, mac);
+ match target {
+ Some(path) => {
+ write_text_file(&path, &html).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
+ out["htmlPath"] = json!(path);
+ }
+ None => out["html"] = json!(html),
+ }
}
if let Some(import) = import {
out["import"] = import;
@@ -2026,6 +2142,46 @@ fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result {
Ok(out)
}
+/// An output parameter (`exportKys`, `summarize`): absent or false → `None`; true (or an object
+/// without `path`) → `Some(None)`, the text comes back in the reply; `{"path": …}` →
+/// `Some(Some(path))`, written there.
+fn file_target(cmd: &str, v: Option<&Value>) -> Result