diff --git a/Cargo.lock b/Cargo.lock index dc725c05f3..c724b24693 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2658,9 +2658,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] @@ -5312,6 +5314,7 @@ dependencies = [ "craft-print", "exr", "flate2", + "getrandom 0.3.4", "photocraft-affinity", "photocraft-algo", "photocraft-cms", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 6d6700dc91..f97d38fbfe 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -36,6 +36,7 @@ base64 = "0.22" blake3 = { version = "1.8", default-features = false, features = ["pure"] } photocraft-codecs = { workspace = true } flate2 = { workspace = true } +getrandom = { workspace = true, features = ["wasm_js"] } craft-print = { workspace = true } # Photoshop `.kys` shortcut sets (`edit.keyboardShortcuts` `importKys`); already in the tree diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index ae38d885dc..cf11a43f7a 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -24,9 +24,12 @@ use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; mod history; +mod identity; pub(crate) use history::ActionHistory; pub use history::{ActionHistoryContinuation, finish_pending_history, suspend_history}; pub(crate) use history::{before_edit as before_action_edit, begin_document_history, finish_document_history, history_rows, reconcile_history_removal}; +pub use identity::{action_shortcut, commit_action_id, is_action_key, occurrence_key, prepare_action_id, shortcut_row}; +pub(crate) use identity::{invalidate_duplicate_ids, pin_shortcut, remove_shortcuts}; fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } @@ -37,6 +40,9 @@ fn bad(cmd: &str, msg: impl Into) -> EngineError { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Action { pub name: String, + /// Stable identity for occurrence shortcuts and stored calls. Legacy rows have no ID. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub action_id: Option, #[serde(default)] pub steps: Vec<(String, Value)>, /// Indices of steps excluded from playback (unchecked in the Actions panel). @@ -64,7 +70,7 @@ pub const BUTTON_COLORS: [&str; 8] = ["", "red", "orange", "yellow", "green", "b impl Action { pub fn new(name: impl Into, steps: Vec<(String, Value)>) -> Self { - Self { name: name.into(), steps, disabled: BTreeSet::new(), dialogs: BTreeSet::new(), set: None, set_slot: None, color: String::new() } + Self { name: name.into(), action_id: None, steps, disabled: BTreeSet::new(), dialogs: BTreeSet::new(), set: None, set_slot: None, color: String::new() } } /// Apply `f` to every per-step index set (`disabled`, `dialogs`) after steps moved. @@ -278,7 +284,13 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> { if s.actions.playing > 0 && s.actions.playback_stack.is_empty() { return Err(bad("actions.play", "an action is already playing")); } - let idx = resolve(&s.actions.list, p, "actions.play")?; + let idx = match p.get("actionId") { + Some(id) => id + .as_str() + .and_then(|id| identity::resolve_action_id(&s.actions.list, id)) + .ok_or_else(|| bad("actions.play", "invalid, missing, or duplicate action ID"))?, + None => resolve(&s.actions.list, p, "actions.play")?, + }; let action = s.actions.list.get(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?; if s.actions.playback_stack.iter().any(|name| name == &action.name) || s.actions.recording.is_some_and(|(_, i)| i == idx) { return Err(bad("actions.play", format!("recursive action call to `{}`", action.name))); @@ -848,6 +860,20 @@ fn move_item(s: &mut Session, p: &Value) -> Result { if to >= s.actions.list.len() { return Err(bad("actions.move", "destination is out of range")); } + let name = &s.actions.list[idx].name; + let first = s.actions.list.iter().position(|action| &action.name == name).unwrap_or(idx); + let changes_owner = if first == idx { to > idx && s.actions.list[idx + 1..=to].iter().any(|action| &action.name == name) } else { to <= first }; + if changes_owner { + let mut shortcuts = s.prefs().shortcuts.clone(); + let mut alternates = s.prefs().alternate_shortcuts.clone(); + pin_shortcut(&mut s.actions.list, first, &mut shortcuts, &mut alternates)?; + if shortcuts != s.prefs().shortcuts || alternates != s.prefs().alternate_shortcuts { + s.edit_prefs(|prefs| { + prefs.shortcuts = shortcuts; + prefs.alternate_shortcuts = alternates; + }); + } + } let moved = s.actions.list.remove(idx); let result = json!({"action": moved.name, "index": to}); s.actions.list.insert(to, moved); @@ -904,16 +930,9 @@ fn delete(s: &mut Session, p: &Value) -> Result { if s.actions.recording.is_some() { return Err(bad("actions.delete", "stop recording before deleting an action")); } + remove_shortcuts(s, |row, _| row == idx); let name = s.actions.list.remove(idx).name; s.actions.touch(); - // Its function key goes with it, or the next action given the same name would inherit it. - let key = format!("{PLAY_SHORTCUT_PREFIX}{name}"); - if s.prefs().shortcuts.contains_key(&key) || s.prefs().alternate_shortcuts.contains_key(&key) { - s.edit_prefs(|prefs| { - prefs.shortcuts.remove(&key); - prefs.alternate_shortcuts.remove(&key); - }); - } Ok(json!({"deleted": name})) } @@ -1012,7 +1031,6 @@ fn rename(s: &mut Session, p: &Value) -> Result { // rename only if it resolved to this action before it, so one reaching the other stays put. let before = s.actions.list.clone(); let by_name = resolve(&before, &json!({"action": old}), "actions.rename").ok() == Some(idx); - let ambiguous_binding = ambiguous_shortcut_names(&before).contains(old.as_str()); let calls = s.actions.list.iter_mut().flat_map(|a| a.steps.iter_mut()).chain(s.journal.iter_mut().skip(pending)); for (id, params) in calls { let keys: &[&str] = match id.as_str() { @@ -1034,15 +1052,13 @@ fn rename(s: &mut Session, p: &Value) -> Result { } s.actions.touch(); let (from, to) = (format!("{PLAY_SHORTCUT_PREFIX}{old}"), format!("{PLAY_SHORTCUT_PREFIX}{name}")); - if s.prefs().shortcuts.contains_key(&from) || (ambiguous_binding && s.prefs().alternate_shortcuts.contains_key(&from)) { + if by_name && (s.prefs().shortcuts.contains_key(&from) || s.prefs().alternate_shortcuts.contains_key(&from)) { s.edit_prefs(|prefs| { - if let Some(key) = prefs.shortcuts.remove(&from) - && !ambiguous_binding - { - prefs.shortcuts.insert(to, key); + if let Some(key) = prefs.shortcuts.remove(&from) { + prefs.shortcuts.insert(to.clone(), key); } - if ambiguous_binding { - prefs.alternate_shortcuts.remove(&from); + if let Some(keys) = prefs.alternate_shortcuts.remove(&from) { + prefs.alternate_shortcuts.insert(to, keys); } }); } diff --git a/crates/engine/src/cmd/actions_cmds/identity.rs b/crates/engine/src/cmd/actions_cmds/identity.rs new file mode 100644 index 0000000000..02acc13693 --- /dev/null +++ b/crates/engine/src/cmd/actions_cmds/identity.rs @@ -0,0 +1,133 @@ +//! Persisted action occurrences are independent of name, list order, and folder position. +use std::collections::{BTreeMap, HashSet}; + +use super::{Action, PLAY_SHORTCUT_PREFIX, bad}; +use crate::{Result, Session}; + +const OCCURRENCE_PREFIX: &str = "actions.playById:"; +const COMMAND: &str = "action shortcut"; + +pub fn is_action_key(key: &str) -> bool { + key.starts_with(PLAY_SHORTCUT_PREFIX) || key.starts_with(OCCURRENCE_PREFIX) +} + +pub fn occurrence_key(id: &str) -> String { + format!("{OCCURRENCE_PREFIX}{id}") +} + +pub(crate) fn resolve_action_id(list: &[Action], id: &str) -> Option { + if id.len() != 32 || !id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { + return None; + } + let mut matches = list.iter().enumerate().filter(|(_, action)| action.action_id.as_deref() == Some(id)); + let (index, _) = matches.next()?; + matches.next().is_none().then_some(index) +} + +/// Never let a duplicated on-disk ID become valid just because one of its rows is removed. +pub(crate) fn invalidate_duplicate_ids(list: &mut [Action]) { + let mut seen = HashSet::new(); + let mut duplicates = HashSet::new(); + for id in list.iter().filter_map(|action| action.action_id.as_ref()) { + if !seen.insert(id) { + duplicates.insert(id.clone()); + } + } + for action in list { + if action.action_id.as_ref().is_some_and(|id| duplicates.contains(id)) { + action.action_id = Some(String::new()); + } + } +} + +pub fn shortcut_row(list: &[Action], key: &str) -> Option { + if let Some(id) = key.strip_prefix(OCCURRENCE_PREFIX) { + return resolve_action_id(list, id); + } + let name = key.strip_prefix(PLAY_SHORTCUT_PREFIX)?; + list.iter().position(|action| action.name == name) +} + +/// Prepare an ID without changing the library, so a denied shortcut edit leaves it untouched. +pub fn prepare_action_id(list: &[Action], index: usize) -> Result { + let action = list.get(index).ok_or_else(|| bad(COMMAND, "action no longer exists"))?; + if let Some(id) = &action.action_id { + return if resolve_action_id(list, id) == Some(index) { Ok(id.clone()) } else { Err(bad(COMMAND, "invalid or duplicate action ID")) }; + } + let mut bytes = [0; 16]; + getrandom::fill(&mut bytes).map_err(|error| bad(COMMAND, format!("could not create an action ID: {error}")))?; + let id = format!("{:032x}", u128::from_be_bytes(bytes)); + if list.iter().any(|a| a.action_id.as_deref() == Some(id.as_str())) { + return Err(bad(COMMAND, "duplicate generated action ID")); + } + Ok(id) +} + +/// Complete a successful shortcut edit. The shortcut command only edits preferences. +pub fn commit_action_id(s: &mut Session, index: usize, id: String) { + if s.actions.list[index].action_id.is_none() { + s.actions.list[index].action_id = Some(id); + s.actions.touch(); + s.sync_preset_store(); + } +} + +/// A valid explicit key takes precedence over a legacy key for the same row. +pub fn action_shortcut(s: &Session, index: usize) -> Option<&str> { + let list = &s.actions.list; + let action = list.get(index)?; + let keys = &s.prefs().shortcuts; + if let Some(id) = action.action_id.as_deref().filter(|id| resolve_action_id(list, id) == Some(index)) + && let Some(key) = keys.get(&occurrence_key(id)) + { + return Some(key.as_str()); + } + let legacy = format!("{PLAY_SHORTCUT_PREFIX}{}", action.name); + (shortcut_row(list, &legacy) == Some(index)).then(|| keys.get(&legacy)).flatten().map(String::as_str) +} + +/// Move a legacy binding to its already resolved row before an edit changes name lookup. +pub(crate) fn pin_shortcut( + list: &mut [Action], + index: usize, + shortcuts: &mut BTreeMap, + alternates: &mut BTreeMap>, +) -> Result<()> { + let legacy = format!("{PLAY_SHORTCUT_PREFIX}{}", list[index].name); + if shortcut_row(list, &legacy) != Some(index) || !(shortcuts.contains_key(&legacy) || alternates.contains_key(&legacy)) { + return Ok(()); + } + let id = prepare_action_id(list, index)?; + let key = occurrence_key(&id); + list[index].action_id = Some(id); + if let Some(binding) = shortcuts.remove(&legacy) { + shortcuts.entry(key.clone()).or_insert(binding); + } + if let Some(bindings) = alternates.remove(&legacy) { + alternates.entry(key).or_insert(bindings); + } + Ok(()) +} + +/// Remove only the bindings owned by the deleted rows, before the indices or first match change. +pub(crate) fn remove_shortcuts(s: &mut Session, remove: impl Fn(usize, &Action) -> bool) { + let list = &s.actions.list; + let mut keys = s + .prefs() + .shortcuts + .keys() + .chain(s.prefs().alternate_shortcuts.keys()) + .filter(|key| shortcut_row(list, key).is_some_and(|row| remove(row, &list[row]))) + .cloned() + .peekable(); + if keys.peek().is_none() { + return; + } + let keys: Vec<_> = keys.collect(); + s.edit_prefs(|prefs| { + for key in keys { + prefs.shortcuts.remove(&key); + prefs.alternate_shortcuts.remove(&key); + } + }); +} diff --git a/crates/engine/src/cmd/actions_edit_cmds/library_commands.rs b/crates/engine/src/cmd/actions_edit_cmds/library_commands.rs index 7be7a5277d..1291dc8016 100644 --- a/crates/engine/src/cmd/actions_edit_cmds/library_commands.rs +++ b/crates/engine/src/cmd/actions_edit_cmds/library_commands.rs @@ -5,7 +5,7 @@ use std::io::{self, Write}; use serde::Serialize; use serde_json::{Value, json}; -use crate::actions_cmds::{Action, PLAY_SHORTCUT_PREFIX, ambiguous_shortcut_names, not_playing}; +use crate::actions_cmds::{Action, is_action_key, not_playing, pin_shortcut}; use crate::{Result, Session}; use super::bad; @@ -51,13 +51,13 @@ pub(crate) fn confirmed_idle(s: &Session, p: &Value, cmd: &str) -> Result<()> { } fn action_bindings(bindings: &BTreeMap) -> BTreeMap { - bindings.iter().filter(|(id, _)| id.starts_with(PLAY_SHORTCUT_PREFIX)).map(|(id, value)| (id.clone(), value.clone())).collect() + bindings.iter().filter(|(id, _)| is_action_key(id)).map(|(id, value)| (id.clone(), value.clone())).collect() } fn replace_bindings(s: &mut Session, shortcuts: Shortcuts, alternates: Alternates) { s.edit_prefs(|prefs| { - prefs.shortcuts.retain(|id, _| !id.starts_with(PLAY_SHORTCUT_PREFIX)); - prefs.alternate_shortcuts.retain(|id, _| !id.starts_with(PLAY_SHORTCUT_PREFIX)); + prefs.shortcuts.retain(|id, _| !is_action_key(id)); + prefs.alternate_shortcuts.retain(|id, _| !is_action_key(id)); prefs.shortcuts.extend(shortcuts); prefs.alternate_shortcuts.extend(alternates); }); @@ -89,28 +89,34 @@ pub(crate) fn check_library_size(list: &[Action], sets: &[String], rows: &[Strin } /// Replace library definitions and remember both shortcut maps for the one-step undo. -/// Append retains unambiguous shortcuts and drops names that no longer identify one action. -pub(crate) fn publish_library(s: &mut Session, list: Vec, sets: Vec, rows: Vec, new_shortcuts: Option, label: &'static str) { +/// Append pins an existing legacy binding before adding a namesake. +pub(crate) fn publish_library( + s: &mut Session, + mut list: Vec, + sets: Vec, + rows: Vec, + new_shortcuts: Option, + label: &'static str, + cmd: &str, +) -> Result<()> { let shortcuts = action_bindings(&s.prefs().shortcuts); let alternates = action_bindings(&s.prefs().alternate_shortcuts); let (after_shortcuts, after_alternates) = match new_shortcuts { - Some(keys) => { - replace_bindings(s, keys.clone(), Alternates::new()); - (keys, Alternates::new()) - } + Some(keys) => (keys, Alternates::new()), None => { - let ambiguous = ambiguous_shortcut_names(&list); - let keep = |id: &str| id.strip_prefix(PLAY_SHORTCUT_PREFIX).is_none_or(|name| !ambiguous.contains(name)); - let mut keys = shortcuts.clone(); - let mut alternate_keys = alternates.clone(); - keys.retain(|id, _| keep(id)); - alternate_keys.retain(|id, _| keep(id)); - if keys != shortcuts || alternate_keys != alternates { - replace_bindings(s, keys.clone(), alternate_keys.clone()); + let (mut keys, mut alternate_keys) = (shortcuts.clone(), alternates.clone()); + let count = s.actions.list.len(); + let owners: Vec<_> = list[count..].iter().filter_map(|action| list[..count].iter().position(|prior| prior.name == action.name)).collect(); + for owner in owners { + pin_shortcut(&mut list, owner, &mut keys, &mut alternate_keys)?; } (keys, alternate_keys) } }; + check_library_size(&list, &sets, &rows, cmd)?; + if after_shortcuts != shortcuts || after_alternates != alternates { + replace_bindings(s, after_shortcuts.clone(), after_alternates.clone()); + } let document_history = s.documents().iter().map(|st| (st.doc.id, st.history.row_ids().max().unwrap_or(0), st.history.is_cleared())).collect(); // A document edit after a library command must start a new undo step. for st in &mut s.docs { @@ -130,13 +136,14 @@ pub(crate) fn publish_library(s: &mut Session, list: Vec, sets: Vec Result { confirmed_idle(s, p, "actions.clearAll")?; let count = s.actions.list.len(); if count != 0 || !s.actions.sets.is_empty() || !s.actions.set_rows.is_empty() { - publish_library(s, Vec::new(), Vec::new(), Vec::new(), Some(Shortcuts::new()), "Undo Clear All Actions"); + publish_library(s, Vec::new(), Vec::new(), Vec::new(), Some(Shortcuts::new()), "Undo Clear All Actions", "actions.clearAll")?; } Ok(json!({"cleared":count})) } @@ -158,8 +165,7 @@ pub(super) fn reset(s: &mut Session, p: &Value) -> Result { for (name, command) in [("Invert Colors", "image.adjustments.invert"), ("Desaturate", "image.adjustments.desaturate")] { list.push(Action { set: Some(NAME.into()), set_slot: Some(slot), ..Action::new(name, vec![(command.into(), json!({}))]) }); } - check_library_size(&list, &sets, &rows, CMD)?; - publish_library(s, list, sets, rows, (!append).then(Shortcuts::new), "Undo Reset Actions"); + publish_library(s, list, sets, rows, (!append).then(Shortcuts::new), "Undo Reset Actions", CMD)?; Ok(json!({"set":NAME,"slot":slot,"appended":append,"actions":2})) } @@ -177,8 +183,7 @@ fn undo_state(s: &Session) -> Result<&LibraryUndo> { pub fn undo_library_label(s: &Session) -> Option<&'static str> { let undo = undo_state(s).ok()?; if let Some(st) = s.active().filter(|st| st.history.can_undo()) { - let (_, last_id, was_cleared) = - undo.document_history.iter().find(|(id, _, _)| *id == st.doc.id).copied().unwrap_or((st.doc.id, 0, false)); + let (_, last_id, was_cleared) = undo.document_history.iter().find(|(id, _, _)| *id == st.doc.id).copied().unwrap_or((st.doc.id, 0, false)); let current_id = st.history.row_id(st.history.past_len()).unwrap_or(0); if current_id > last_id || (st.history.is_cleared() && !was_cleared) { return None; diff --git a/crates/engine/src/cmd/actions_edit_cmds/library_commands/tests.rs b/crates/engine/src/cmd/actions_edit_cmds/library_commands/tests.rs index 26c9750969..b93f673129 100644 --- a/crates/engine/src/cmd/actions_edit_cmds/library_commands/tests.rs +++ b/crates/engine/src/cmd/actions_edit_cmds/library_commands/tests.rs @@ -125,36 +125,73 @@ fn recording_and_assignment_infer_only_unambiguous_folder_occurrences() { /// Repeated factory actions keep their display names. A name-only shortcut is removed /// when that name ceases to identify a physical row, and Undo restores the binding. #[test] -fn repeated_reset_and_store_attachment_do_not_retarget_shortcuts() { +fn repeated_reset_pins_existing_shortcuts_and_undo_restores_legacy_keys() { let mut s = Session::new(); - let store = MemBackend::default(); - s.attach_preset_store(open(Box::new(store.clone()))); s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); let shortcut = format!("{PLAY_SHORTCUT_PREFIX}Invert Colors"); s.edit_prefs(|prefs| { prefs.shortcuts.insert(shortcut.clone(), "F2".into()); prefs.alternate_shortcuts.insert(shortcut.clone(), vec!["F3".into()]); }); + let before = s.actions.list.clone(); + let prefs = s.prefs().clone(); + assert!(s.execute("actions.reset", json!({"confirm":false,"mode":"append"})).is_err()); + assert_eq!(s.actions.list, before); + assert_eq!(s.prefs().shortcuts, prefs.shortcuts); + assert_eq!(s.prefs().alternate_shortcuts, prefs.alternate_shortcuts); + s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); + let key = crate::actions_cmds::occurrence_key(s.actions.list[0].action_id.as_deref().unwrap()); + assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &key), Some(0)); + assert_eq!(s.prefs().shortcuts[&key], "F2"); + assert_eq!(s.prefs().alternate_shortcuts[&key], ["F3"]); assert!(!s.prefs().shortcuts.contains_key(&shortcut)); assert!(!s.prefs().alternate_shortcuts.contains_key(&shortcut)); assert_eq!(s.actions.list.iter().filter(|action| action.name == "Invert Colors").count(), 2); + s.execute("actions.undoLibrary", json!({})).unwrap(); + assert_eq!(s.actions.list, before); assert_eq!(s.prefs().shortcuts[&shortcut], "F2"); assert_eq!(s.prefs().alternate_shortcuts[&shortcut], ["F3"]); - s.sync_preset_store(); + assert!(!s.prefs().shortcuts.contains_key(&key)); +} - let mut attached = Session::new(); - attached.actions.list.push(Action::new("Invert Colors", Vec::new())); - attached.edit_prefs(|prefs| { - prefs.shortcuts.insert(shortcut.clone(), "F2".into()); - prefs.alternate_shortcuts.insert(shortcut.clone(), vec!["F3".into()]); - }); - attached.attach_preset_store(open(Box::new(store))); - assert_eq!(attached.actions.list.iter().filter(|action| action.name == "Invert Colors").count(), 2); - assert!(!attached.prefs().shortcuts.contains_key(&shortcut)); - assert!(!attached.prefs().alternate_shortcuts.contains_key(&shortcut)); - assert_eq!(attached.execute("actions.get", json!({"action":"Invert Colors"})).unwrap()["set"], serde_json::Value::Null); +#[test] +fn duplicate_stored_ids_stay_unplayable_after_deleting_one_row() { + use crate::preset_store::{ACTIONS_FILE, PresetBackend}; + + let store = MemBackend::default(); + let id = "0".repeat(32); + let file = json!({"version":1,"actions":[{"name":"First","action_id":id},{"name":"Second","action_id":id}]}); + store.write(ACTIONS_FILE, file.to_string().as_bytes()).unwrap(); + let mut s = Session::new(); + s.attach_preset_store(open(Box::new(store))); + let key = crate::actions_cmds::occurrence_key(&id); + assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &key), None); + s.execute("actions.delete", json!({"action":"First"})).unwrap(); + assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &key), None); + assert!(s.execute("actions.play", json!({"actionId":id,"action":"Second"})).is_err()); + assert!(s.execute("actions.play", json!({"actionId":"invalid","action":"Second"})).is_err()); + assert_eq!(s.execute("actions.play", json!({"action":"Second"})).unwrap()["ran"], 0); +} + +#[test] +fn atn_export_and_load_keep_function_keys_of_duplicate_rows_separate() { + let mut s = Session::new(); + for _ in 0..2 { + s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); + } + for (row, key) in [(0, "F2"), (2, "F3")] { + let id = crate::actions_cmds::prepare_action_id(&s.actions.list, row).unwrap(); + s.edit_prefs(|prefs| prefs.shortcuts.insert(crate::actions_cmds::occurrence_key(&id), key.into())); + crate::actions_cmds::commit_action_id(&mut s, row, id); + } + let archive = s.execute("actions.save", json!({"set":"PhotoCraft Basics","skipUnsupported":true})).unwrap(); + let mut loaded = Session::new(); + let result = loaded.execute("actions.load", json!({"data":archive["data"]})).unwrap(); + assert_eq!(result["functionKeys"], json!([{"action":"Invert Colors","key":"F2"},{"action":"Invert Colors 2","key":"F3"}])); + assert_eq!(crate::actions_cmds::action_shortcut(&loaded, 0), Some("F2")); + assert_eq!(crate::actions_cmds::action_shortcut(&loaded, 2), Some("F3")); } /// Imported calls follow a local physical folder before falling back to the first archive name. diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index 8b2e82125e..2ca6c33f4f 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -120,21 +120,25 @@ pub(super) struct ReplacementSet { pub keys: Vec<(usize, String)>, } +pub(super) fn import_first_with_keys(bytes: &[u8], encoding: Option<&str>) -> std::result::Result { + let file = atn::parse_with_encoding(bytes, encoding).map_err(|error| error.to_string())?; + Ok(convert_with_keys(&file)) +} + pub(super) fn import_sets(bytes: &[u8], encoding: Option<&str>) -> std::result::Result, String> { let files = atn::parse_sets_with_encoding(bytes, encoding).map_err(|error| error.to_string())?; - Ok(files + Ok(files.iter().map(convert_with_keys).collect()) +} + +fn convert_with_keys(file: &AtnFile) -> ReplacementSet { + let keys = file + .actions .iter() - .map(|file| { - let keys = file - .actions - .iter() - .enumerate() - .filter(|(_, action)| action.function_key > 0) - .map(|(index, action)| (index, function_key_name(action.function_key, action.shift, action.command))) - .collect(); - ReplacementSet { imported: convert_set(file), keys } - }) - .collect()) + .enumerate() + .filter(|(_, action)| action.function_key > 0) + .map(|(index, action)| (index, function_key_name(action.function_key, action.shift, action.command))) + .collect(); + ReplacementSet { imported: convert_set(file), keys } } fn convert_set(file: &AtnFile) -> Imported { @@ -252,12 +256,21 @@ pub fn export( actions: &[&Action], function_keys: &[(String, String)], skip_unsupported: bool, +) -> std::result::Result<(Vec, Vec), String> { + export_with_keys(set, actions, |_, action| function_keys.iter().find(|(name, _)| name == &action.name).map(|(_, key)| key.as_str()), skip_unsupported) +} + +pub(super) fn export_with_keys<'a>( + set: &str, + actions: &[&Action], + key: impl Fn(usize, &Action) -> Option<&'a str>, + skip_unsupported: bool, ) -> std::result::Result<(Vec, Vec), String> { let mut skipped = Vec::new(); let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new(), ..Default::default() }; - for a in actions { + for (index, a) in actions.iter().enumerate() { let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() }; - if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) { + if let Some((n, shift, command)) = key(index, a).and_then(parse_function_key) { (out.function_key, out.shift, out.command) = (n, shift, command); } for (i, (id, params)) in a.steps.iter().enumerate() { diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index b97ca6e30e..e8c55ed9ac 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -1,4 +1,4 @@ -use super::convert::{UniqueNames, export, import_with_encoding}; +use super::convert::{ReplacementSet, UniqueNames, export_with_keys, import_first_with_keys}; use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json}; mod replacement; @@ -19,7 +19,7 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(cmd, "encoding must be \"auto\" or a label such as shift_jis, gbk, big5, euc-kr, windows-1252, macintosh")), }; let (bytes, _) = crate::preset_import_cmds::file_bytes(p, cmd, ".atn file")?; - let mut imp = import_with_encoding(&bytes, encoding).map_err(|e| bad(cmd, e))?; + let ReplacementSet { imported: mut imp, keys: function_keys } = import_first_with_keys(&bytes, encoding).map_err(|e| bad(cmd, e))?; let original_set = imp.set.clone(); match p.get("set") { None | Some(Value::Null) => {} @@ -37,7 +37,7 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(cmd, "`replace` must be true or false")), }; if replace { - crate::actions_cmds::discard_ambiguous_shortcuts(s); + crate::actions_cmds::remove_shortcuts(s, |_, action| action.set.as_deref() == Some(imp.set.as_str())); s.actions.list.retain(|a| a.set.as_deref() != Some(imp.set.as_str())); let mut slots = Vec::with_capacity(s.actions.set_rows.len()); let mut next = 0; @@ -100,12 +100,12 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { if !s.actions.list.iter().any(|a| a.set.as_deref() == Some(imp.set.as_str())) && !s.actions.sets.contains(&imp.set) { s.actions.sets.push(imp.set.clone()); } - let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect(); + let keys: Vec<_> = function_keys.into_iter().map(|(index, key)| (names[index].clone(), key)).collect(); if !keys.is_empty() { s.edit_prefs(|prefs| { for (name, key) in &keys { // A function key belongs to one action. - prefs.shortcuts.retain(|k, v| !(k.starts_with(crate::actions_cmds::PLAY_SHORTCUT_PREFIX) && v == key)); + prefs.shortcuts.retain(|k, v| !(crate::actions_cmds::is_action_key(k) && v == key)); prefs.shortcuts.insert(format!("{}{name}", crate::actions_cmds::PLAY_SHORTCUT_PREFIX), key.clone()); } }); @@ -142,13 +142,19 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { if set_slot.is_some() && p.get("action").is_some() { return Err(bad(cmd, "select a folder occurrence or an action")); } - let (set, actions): (String, Vec<&Action>) = if p.get("action").is_some() { + let (set, indices): (String, Vec) = if p.get("action").is_some() { let idx = crate::actions_cmds::resolve(&s.actions.list, p, cmd)?; let a = &s.actions.list[idx]; - (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a]) + (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![idx]) } else if let Some(set) = set_param { - let list: Vec<&Action> = - s.actions.list.iter().filter(|a| a.set.as_deref() == Some(set.as_str()) && (p.get("setSlot").is_none() || a.set_slot == set_slot)).collect(); + let list: Vec = s + .actions + .list + .iter() + .enumerate() + .filter(|(_, a)| a.set.as_deref() == Some(set.as_str()) && (p.get("setSlot").is_none() || a.set_slot == set_slot)) + .map(|(index, _)| index) + .collect(); // An empty set New Set made is written with no actions, as Photoshop saves one. let known_row = p.get("setSlot").is_none() && s.actions.set_rows.contains(&set); if list.is_empty() && set_slot.is_none() && !known_row && !s.actions.sets.contains(&set) { @@ -159,15 +165,12 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { if s.actions.list.is_empty() { return Err(bad(cmd, "there are no actions to save")); } - (DEFAULT_SET.to_string(), s.actions.list.iter().collect()) + (DEFAULT_SET.to_string(), (0..s.actions.list.len()).collect()) }; + let actions: Vec<&Action> = indices.iter().map(|&index| &s.actions.list[index]).collect(); let names: Vec = actions.iter().map(|a| a.name.clone()).collect(); - let ambiguous = crate::actions_cmds::ambiguous_shortcut_names(&s.actions.list); - let keys: Vec<(String, String)> = s.prefs().shortcuts.iter().filter_map(|(k, v)| { - let name = k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX)?; - (!ambiguous.contains(name)).then(|| (name.to_string(), v.clone())) - }).collect(); - let (bytes, skipped) = export(&set, &actions, &keys, skip).map_err(|e| bad(cmd, e))?; + let key = |index, _: &Action| crate::actions_cmds::action_shortcut(s, indices[index]); + let (bytes, skipped) = export_with_keys(&set, &actions, key, skip).map_err(|e| bad(cmd, e))?; let steps: usize = actions.iter().map(|a| a.steps.len()).sum::().saturating_sub(skipped.len()); let mut out = json!({"set": set, "actions": names, "steps": steps, "bytes": bytes.len(), "skipped": skipped}); match p.get("path") { diff --git a/crates/engine/src/cmd/atn_cmds/files/replacement.rs b/crates/engine/src/cmd/atn_cmds/files/replacement.rs index 69c577ea35..4c2d87e3f8 100644 --- a/crates/engine/src/cmd/atn_cmds/files/replacement.rs +++ b/crates/engine/src/cmd/atn_cmds/files/replacement.rs @@ -106,6 +106,6 @@ pub(in super::super) fn replace(s: &mut Session, p: &Value) -> Result { let (bytes, _) = crate::preset_import_cmds::file_bytes(p, COMMAND, ".atn file")?; let Replacement { list, rows, keys, warnings, unsupported } = Replacement::parse(&bytes, encoding)?; let result = json!({"sets":rows,"actions":list.iter().map(|a| &a.name).collect::>(),"warnings":warnings,"unsupported":unsupported}); - publish_library(s, list, Vec::new(), rows, Some(keys), "Undo Replace Actions"); + publish_library(s, list, Vec::new(), rows, Some(keys), "Undo Replace Actions", COMMAND)?; Ok(result) } diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index 8afc5a1087..38db8e4f29 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -754,6 +754,7 @@ fn load_actions(backend: &dyn PresetBackend, warnings: &mut Vec) -> Opti }; match serde_json::from_slice::(&bytes) { Ok(mut file) if file.version == 1 => { + crate::actions_cmds::invalidate_duplicate_ids(&mut file.actions); for action in &mut file.actions { action.set_slot = action.set_slot.filter(|&slot| action.set.is_some() && file.set_rows.get(slot) == action.set.as_ref()); } diff --git a/crates/engine/src/shortcut_sets.rs b/crates/engine/src/shortcut_sets.rs index 4b36de1b82..ecfd36d19b 100644 --- a/crates/engine/src/shortcut_sets.rs +++ b/crates/engine/src/shortcut_sets.rs @@ -78,7 +78,7 @@ impl ShortcutSet { /// An action's function key (`actions.play:`): kept by the action, not by a set. fn is_action_key(id: &str) -> bool { - id.starts_with(crate::actions_cmds::PLAY_SHORTCUT_PREFIX) + crate::actions_cmds::is_action_key(id) } /// A set name as given, trimmed; an error for an empty, overlong or reserved name. diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index 7e98b6b800..f8bffa8800 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -8,6 +8,7 @@ //! silently, as the greyed menu item shows. use egui::{Key, KeyboardShortcut}; +use photocraft_engine::actions_cmds; use serde_json::json; use crate::PhotocraftApp; @@ -48,10 +49,8 @@ pub fn take_log(ctx: &egui::Context) -> Vec<(String, Outcome)> { /// their overrides apply. Held temporary tools (Space…) are not here: see [`crate::hold_keys`]. pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> { let prefs = app.session.prefs(); - let ambiguous = photocraft_engine::actions_cmds::ambiguous_shortcut_names(&app.session.actions.list); - let action_ids: Vec = app.session.actions.list.iter().filter(|a| !ambiguous.contains(a.name.as_str())) - .map(|a| crate::actions::shortcut_id(&a.name)).collect(); - let actions = action_ids.iter().map(|id| (id.as_str(), prefs.shortcut(id, None).map(str::to_string))); + let action_row = |key: &str| actions_cmds::shortcut_row(&app.session.actions.list, key); + let actions = prefs.shortcuts.keys().filter(|id| action_row(id.as_str()).is_some()).map(|id| (id.as_str(), prefs.shortcut(id, None).map(str::to_string))); // The Keyboard Shortcuts dialog lists Photoshop's Window › item (`window.panel.*`) // in place of the shell command it runs (`window.toggle.*`, see `menus::panel_alias`), so an // edit to that row reassigns or removes the shell command's default too (#1272). @@ -77,7 +76,7 @@ pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> { .iter() .filter(|(id, sc)| { !sc.is_empty() - && !id.starts_with(crate::actions::SHORTCUT_PREFIX) + && !actions_cmds::is_action_key(id) && photocraft_engine::commands::find(id).is_none() && !crate::menus::UI_COMMANDS.iter().any(|c| c.0 == id.as_str()) && !crate::hold_keys::is_temporary(id) @@ -100,7 +99,7 @@ pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> { let alternate_ids: std::collections::BTreeSet<&str> = photocraft_engine::prefs::ALTERNATE_SHORTCUTS.iter().map(|(id, _)| *id).chain(prefs.alternate_shortcuts.keys().map(String::as_str)).collect(); for id in alternate_ids { - if id.strip_prefix(crate::actions::SHORTCUT_PREFIX).is_some_and(|name| ambiguous.contains(name)) { + if actions_cmds::is_action_key(id) && action_row(id).is_none() { continue; } let main = prefs.shortcut(id, crate::shortcuts::default_shortcut(id).as_deref()).map(str::to_string); @@ -378,11 +377,12 @@ pub fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) { /// [`dispatch`]; with `last`, an adjustment dialog opens at its last confirmed settings. fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: bool) { - let action = id.strip_prefix(crate::actions::SHORTCUT_PREFIX); - let command_id = if action.is_some() { "actions.play" } else { id }; - let ambiguous = action.is_some_and(|name| photocraft_engine::actions_cmds::ambiguous_shortcut_names(&app.session.actions.list).contains(name)); - let outcome = if ambiguous || !crate::menus::is_enabled(app, command_id) { - let why = if ambiguous { "Multiple Actions use this name".into() } else { disabled_reason(app, command_id) }; + let is_action = actions_cmds::is_action_key(id); + let action = actions_cmds::shortcut_row(&app.session.actions.list, id).map(|row| &app.session.actions.list[row]); + let command_id = if is_action { "actions.play" } else { id }; + let missing = is_action && action.is_none(); + let outcome = if missing || !crate::menus::is_enabled(app, command_id) { + let why = if missing { "The Action no longer exists".into() } else { disabled_reason(app, command_id) }; let template = "{label} is not available: {reason}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("label", crate::i18n::tr_id(crate::i18n::current(), id, &label(id))), ("reason", tl!(&why))]); app.ui.status_error = true; @@ -390,10 +390,13 @@ fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: boo } else if ctx.data(|d| d.get_temp::(dry_run_id())).unwrap_or(false) { Outcome::Ran } else { - let r = if let Some(name) = action { - // Use the normal command path: synthetic input and every nested action - // step must still pass the automation authorizer. - crate::menus::invoke(app, ctx, "actions.play", json!({"action": name})).and_then(|v| { + let r = if let Some(action) = action { + let target = match id.strip_prefix(actions_cmds::PLAY_SHORTCUT_PREFIX) { + Some(name) => json!({"action": name}), + None => json!({"actionId": action.action_id}), + }; + // Synthetic input and every nested action still pass the automation authorizer. + crate::menus::invoke(app, ctx, "actions.play", target).and_then(|v| { crate::actions::report_play(app, &v); if v.get("failed").is_some_and(|f| f.is_object()) { Err(app.ui.status.clone()) } else { Ok(v) } }) diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index ce7e3fcc39..34fa63b4a0 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -7,6 +7,7 @@ use egui::{Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use photocraft_doc::LayerContent; +use photocraft_engine::actions_cmds; use serde_json::json; use super::{Focus, Outcome, bindings, set_dry_run, take_log}; @@ -782,6 +783,71 @@ fn clip_key_toggles_several_selected_layers() { assert!(!is_clipped(&h, paint) && !is_clipped(&h, top) && !is_clipped(&h, base)); } +fn action_key(h: &Harness<'_, PhotocraftApp>, index: usize) -> String { + actions_cmds::occurrence_key(h.state().session.actions.list[index].action_id.as_deref().unwrap()) +} + +fn repeated_reset_shortcuts(h: &mut Harness<'_, PhotocraftApp>) { + for _ in 0..2 { + h.state_mut().run("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); + } + for (index, key, name) in [(0, "F2", "first occurrence"), (2, "F3", "second occurrence")] { + h.state_mut().session.actions.list[index].steps = vec![("layer.new.layer".into(), json!({"name":name}))]; + crate::actions::assign_shortcut(h.state_mut(), index, key).unwrap(); + } +} + +#[test] +fn f2_dispatches_only_the_first_same_named_action() { + let mut h = harness(); + repeated_reset_shortcuts(&mut h); + let count = h.state().session.active().unwrap().doc.layers.len(); + press(&mut h, "F2"); + assert_eq!(active_name(&h), "first occurrence"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), count + 1); +} + +#[test] +fn f3_dispatches_only_the_second_same_named_action_after_reorder_and_reopen() { + use photocraft_engine::preset_store::{MemBackend, open}; + + let mut h = harness(); + let store = MemBackend::default(); + h.state_mut().session.attach_preset_store(open(Box::new(store.clone()))); + repeated_reset_shortcuts(&mut h); + let first_key = action_key(&h, 0); + let second_key = action_key(&h, 2); + h.state_mut().run("actions.move", json!({"action":2,"to":0})).unwrap(); + h.state_mut().session.sync_preset_store(); + let prefs = h.state().session.prefs_to_json(); + + let mut h = harness(); + h.state_mut().session.load_prefs_json(&prefs).unwrap(); + h.state_mut().session.attach_preset_store(open(Box::new(store))); + assert_eq!(action_key(&h, 0), second_key); + let count = h.state().session.active().unwrap().doc.layers.len(); + press(&mut h, "F3"); + assert_eq!(active_name(&h), "second occurrence"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), count + 1); + h.state_mut().run("actions.delete", json!({"action":1})).unwrap(); + assert!(!h.state().session.prefs().shortcuts.contains_key(&first_key)); + assert_eq!(h.state().session.prefs().shortcuts[&second_key], "F3"); + press(&mut h, "F2"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), count + 1); +} + +#[test] +fn denied_shortcut_assignment_leaves_identity_and_bindings_unmodified() { + let mut h = harness(); + h.state_mut().session.actions.list.push(actions_cmds::Action::new("Action", Vec::new())); + h.state_mut().services.automation_command = Some(Box::new(|_, _| Err("denied shortcut edit".into()))); + h.state_mut().automation_input = true; + let prefs = h.state().session.prefs().shortcuts.clone(); + assert!(crate::actions::assign_shortcut(h.state_mut(), 0, "F2").is_err()); + assert!(h.state().session.actions.list[0].action_id.is_none()); + assert_eq!(h.state().session.prefs().shortcuts, prefs); +} + #[test] fn named_action_function_key_replays_and_survives_preferences_roundtrip() { let mut h = harness(); @@ -792,7 +858,7 @@ fn named_action_function_key_replays_and_survives_preferences_roundtrip() { ..Default::default() }; h.state_mut().session.actions.list.push(action); - crate::actions::assign_shortcut(h.state_mut(), "LivePrint 2R", "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); let saved = serde_json::to_value(h.state().session.prefs()).unwrap(); let restored = serde_json::from_value(saved).unwrap(); h.state_mut().session.edit_prefs(|p| *p = restored); @@ -801,9 +867,9 @@ fn named_action_function_key_replays_and_survives_preferences_roundtrip() { assert_eq!(active_name(&h), "F6 overlay"); assert_eq!(h.state().ui.status, "Played 1 step"); assert!(!h.state().ui.status_error); - assert_eq!(take_log(&h.ctx), vec![(crate::actions::shortcut_id("LivePrint 2R"), Outcome::Ran)]); + assert_eq!(take_log(&h.ctx), vec![(action_key(&h, 0), Outcome::Ran)]); h.state_mut().run("actions.delete", json!({"action": "LivePrint 2R"})).unwrap(); - assert!(bindings(h.state()).iter().all(|(id, _)| !id.starts_with(crate::actions::SHORTCUT_PREFIX))); + assert!(bindings(h.state()).iter().all(|(id, _)| !actions_cmds::is_action_key(id))); assert!(bindings(h.state()).iter().any(|(_, sc)| *sc == parse("F6").unwrap())); } @@ -818,14 +884,14 @@ fn assigning_action_function_key_moves_it_and_reports_failed_steps() { ..Default::default() }); } - crate::actions::assign_shortcut(h.state_mut(), "first", "F6").unwrap(); - crate::actions::assign_shortcut(h.state_mut(), "second", "F6").unwrap(); - assert_eq!(h.state().session.prefs().shortcuts[&crate::actions::shortcut_id("first")], ""); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 1, "F6").unwrap(); + assert_eq!(h.state().session.prefs().shortcuts[&action_key(&h, 0)], ""); h.state_mut().ui.actions.selected = Some(0); press(&mut h, "F6"); assert!(h.state().ui.status_error); assert!(h.state().ui.status.contains("Step 1 (no.such.command) failed")); - assert!(matches!(&take_log(&h.ctx)[..], [(id, Outcome::Failed(_))] if id == "actions.play:second")); + assert!(matches!(&take_log(&h.ctx)[..], [(id, Outcome::Failed(_))] if id == &action_key(&h, 1))); } #[test] @@ -837,10 +903,11 @@ fn action_function_key_checks_automation_authorization() { disabled: Default::default(), ..Default::default() }); - crate::actions::assign_shortcut(h.state_mut(), "restricted", "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); h.state_mut().services.automation_command = Some(Box::new(|id, _| if id == "actions.play" { Err("denied action playback".into()) } else { Ok(()) })); h.state_mut().automation_input = true; - super::dispatch(h.state_mut(), &egui::Context::default(), "actions.play:restricted"); + let id = action_key(&h, 0); + super::dispatch(h.state_mut(), &egui::Context::default(), &id); assert_eq!(h.state().ui.status, "denied action playback"); assert_eq!(active_name(&h), "paint"); } @@ -855,7 +922,7 @@ fn fit_shortcut_records_and_f6_fits_the_resized_canvas() { assert_eq!(h.state().session.actions.list[0].steps.iter().map(|s| s.0.as_str()).collect::>(), ["image.canvasSize", "view.fitOnScreen"]); let item = crate::menus::menu_items(h.state()).into_iter().find(|i| i.id == "view.fitOnScreen").unwrap(); assert_eq!(item.shortcut.as_deref(), Some("Cmd+0")); - crate::actions::assign_shortcut(h.state_mut(), "Resize and fit", "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); h.state_mut().ui.views[0].zoom = 0.1; h.state_mut().ui.views[0].center = [0.0, 0.0]; press(&mut h, "F6"); @@ -875,7 +942,7 @@ fn f6_while_recording_records_a_named_call_not_the_child_steps() { disabled: Default::default(), ..Default::default() }); - crate::actions::assign_shortcut(h.state_mut(), "LivePrint 2R", "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); h.state_mut().run("actions.record", json!({"name":"Action 2"})).unwrap(); press(&mut h, "F6"); assert_eq!(active_name(&h), "Nested overlay"); diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 7e6b4ab741..34b1f901d0 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -225,29 +225,35 @@ pub fn action_steps(action: &Action) -> Vec { action.enabled_steps().map(|(_, (id, p))| json!([id, p])).collect() } -/// Named action bindings use the existing persisted shortcut overrides. Keeping the -/// name in the key means selecting or deleting another row cannot retarget F6. -pub(crate) const SHORTCUT_PREFIX: &str = actions_cmds::PLAY_SHORTCUT_PREFIX; - -pub(crate) fn shortcut_id(name: &str) -> String { - format!("{SHORTCUT_PREFIX}{name}") -} - -pub(crate) fn assign_shortcut(app: &mut PhotocraftApp, name: &str, shortcut: &str) -> Result { - if actions_cmds::ambiguous_shortcut_names(&app.session.actions.list).contains(name) { - return Err(tl!("Rename the action before assigning it a shortcut.").into()); - } - let id = shortcut_id(name); +pub(crate) fn assign_shortcut(app: &mut PhotocraftApp, index: usize, shortcut: &str) -> Result { + let list = &app.session.actions.list; + let action_id = actions_cmds::prepare_action_id(list, index).map_err(|error| error.to_string())?; + let id = actions_cmds::occurrence_key(&action_id); + let legacy = format!("{}{}", actions_cmds::PLAY_SHORTCUT_PREFIX, list[index].name); + let prefs = app.session.prefs(); let mut set = serde_json::Map::new(); - // A function key belongs to only one action. Ordinary menu bindings remain - // intact and become available again when the action binding is removed. - for (other, assigned) in &app.session.prefs().shortcuts { - if other.starts_with(SHORTCUT_PREFIX) && other != &id && assigned == shortcut && !shortcut.is_empty() { + let mut alternates = serde_json::Map::new(); + // A function key belongs to only one action. Ordinary menu bindings remain intact. + for (other, assigned) in &prefs.shortcuts { + if actions_cmds::is_action_key(other) && other != &id && assigned == shortcut && !shortcut.is_empty() { set.insert(other.clone(), json!("")); } } + if actions_cmds::shortcut_row(list, &legacy) == Some(index) { + if prefs.shortcuts.contains_key(&legacy) { + set.insert(legacy.clone(), Value::Null); + } + if let Some(keys) = prefs.alternate_shortcuts.get(&legacy) { + if !prefs.alternate_shortcuts.contains_key(&id) { + alternates.insert(id.clone(), json!(keys)); + } + alternates.insert(legacy, Value::Null); + } + } set.insert(id, json!(shortcut)); - app.run("edit.keyboardShortcuts", json!({"set": set, "allowUnknown": true, "removeConflicts": false})) + let result = app.run("edit.keyboardShortcuts", json!({"set": set, "alternates": alternates, "allowUnknown": true, "removeConflicts": false}))?; + actions_cmds::commit_action_id(&mut app.session, index, action_id); + Ok(result) } /// Replay edits synchronously, with view steps handled by the shell in the same order. @@ -1763,21 +1769,18 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, se SetHeaderResult { toggled, picked, save } } -fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index: usize, name: &str, swatch: &str, ambiguous: bool) { +fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index: usize, swatch: &str) { egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { ui.label(tl!("Keyboard Shortcuts")); - if ambiguous { - ui.label(tl!("Rename the action before assigning it a shortcut.")); - } - ui.add_enabled_ui(!ambiguous, |ui| { - let current = app.session.prefs().shortcuts.get(&shortcut_id(name)).cloned().unwrap_or_default(); + { + let current = actions_cmds::action_shortcut(&app.session, index).unwrap_or_default(); // Photoshop's Action Options: a function key, with Shift and Command (#7646). - let (key, mut shift, mut command) = photocraft_engine::atn_cmds::parse_function_key(¤t).unwrap_or((0, false, false)); + let (key, mut shift, mut command) = photocraft_engine::atn_cmds::parse_function_key(current).unwrap_or((0, false, false)); for number in std::iter::once(0).chain(1..=12) { let label = if number == 0 { tl!("None").to_string() } else { format!("F{number}") }; if ui.selectable_label(key == number, label).clicked() { let chosen = if number == 0 { String::new() } else { photocraft_engine::atn_cmds::function_key_name(number, shift, command) }; - let _ = assign_shortcut(app, name, &chosen); + let _ = assign_shortcut(app, index, &chosen); ui.close(); } } @@ -1785,10 +1788,10 @@ fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index let command_label = if cfg!(target_os = "macos") { tl!("Command") } else { tl!("Ctrl") }; let toggled = ui.checkbox(&mut shift, tl!("Shift")).changed() | ui.checkbox(&mut command, command_label).changed(); if toggled { - let _ = assign_shortcut(app, name, &photocraft_engine::atn_cmds::function_key_name(key, shift, command)); + let _ = assign_shortcut(app, index, &photocraft_engine::atn_cmds::function_key_name(key, shift, command)); } }); - }); + } ui.separator(); ui.menu_button(tl!("Color"), |ui| { for (id, label) in [ @@ -1816,8 +1819,6 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } let t = Tokens::get(ui.ctx()); let recording = app.session.actions.recording; - let ambiguous: std::collections::HashSet = actions_cmds::ambiguous_shortcut_names(&app.session.actions.list) - .into_iter().map(str::to_string).collect(); let rows: Vec = app .session .actions @@ -1943,11 +1944,8 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.painter().text( pos2(rect.right() - 8.0, rect.center().y), Align2::RIGHT_CENTER, - app.session - .prefs() - .shortcuts - .get(&shortcut_id(name)) - .filter(|s| !s.is_empty() && !ambiguous.contains(name.as_str())) + actions_cmds::action_shortcut(&app.session, i) + .filter(|key| !key.is_empty()) .map_or_else(|| step_count(nsteps, disabled.len()), |key| format!("{key} · {}", step_count(nsteps, disabled.len()))), egui::FontId::proportional(11.0), t.text_faint, @@ -1971,7 +1969,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } // Clicks inside stay open, so Shift and Command can both be ticked; every item that // finishes closes the menu itself. - action_context_menu(app, &resp, i, name, swatch, ambiguous.contains(name.as_str())); + action_context_menu(app, &resp, i, swatch); if resp.double_clicked() && !button_mode { // Photoshop renames in place when the name itself is double-clicked. if resp.interact_pointer_pos().is_some_and(|p| name_rect.expand2(vec2(4.0, 13.0)).contains(p)) { diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index f435b20a49..39488b0a0f 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -60,15 +60,6 @@ fn repeated_factory_rows_select_and_play_independently() { app.ui.actions.slot_revision = app.session.actions.set_rows_revision; assert_eq!(playback_targets(&app), [2, 3]); assert_eq!(new_action_set(&app).unwrap().slot, Some(1)); - - // An older or manually edited preferences file can still contain a name-only key. - let id = shortcut_id("Invert Colors"); - app.session.edit_prefs(|prefs| { - prefs.shortcuts.insert(id.clone(), "F2".into()); - prefs.alternate_shortcuts.insert(id.clone(), vec!["F3".into()]); - }); - assert!(!crate::shortcut_dispatch::bindings(&app).iter().any(|(bound, _)| bound == &id)); - assert!(assign_shortcut(&mut app, "Invert Colors", "F4").is_err()); } #[test] @@ -510,7 +501,7 @@ fn a_function_key_with_shift_and_command_plays_its_action() { }); let key = photocraft_engine::atn_cmds::function_key_name(2, true, true); assert_eq!(key, "Cmd+Shift+F2"); - assign_shortcut(&mut app, "Action 1", &key).unwrap(); + assign_shortcut(&mut app, 0, &key).unwrap(); let ctx = egui::Context::default(); let press = |app: &mut PhotocraftApp, modifiers| { ctx.begin_pass(egui::RawInput { @@ -3026,15 +3017,12 @@ fn replace_picker_checks_selected_source_and_rechecks_payload_on_confirm() { if p.get("path").is_some() { return Err("path denied by policy".into()); } - if p.get("data").is_some() && policy.get() { - Ok(()) - } else { - Err("payload denied by policy".into()) - } - }); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { - file_dialog: Some(file_dialog), automation_command: Some(automation_command), ..Default::default() + if p.get("data").is_some() && policy.get() { Ok(()) } else { Err("payload denied by policy".into()) } }); + let mut app = PhotocraftApp::new( + photocraft_engine::Session::new(), + crate::Services { file_dialog: Some(file_dialog), automation_command: Some(automation_command), ..Default::default() }, + ); app.run("actions.newSet", json!({"name":"Keep"})).unwrap(); let ctx = egui::Context::default(); for attempt in 0..2 { @@ -3076,9 +3064,10 @@ fn stale_same_caption_selection_does_not_follow_a_compacted_slot() { fn dragging_uses_the_displayed_folder_occurrence() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.session.actions.set_rows = vec!["Same".into(), "Same".into()]; - app.session.actions.list = [("A", 0), ("B", 1), ("C", 0)].into_iter().map(|(name, slot)| { - Action { set: Some("Same".into()), set_slot: Some(slot), ..Action::new(name, Vec::new()) } - }).collect(); + app.session.actions.list = [("A", 0), ("B", 1), ("C", 0)] + .into_iter() + .map(|(name, slot)| Action { set: Some("Same".into()), set_slot: Some(slot), ..Action::new(name, Vec::new()) }) + .collect(); move_row(&mut app, DragRow { action: 0, step: None }, 1, 2); assert_eq!(app.session.actions.list[1].name, "A"); assert_eq!(app.session.actions.list[1].set_slot, Some(0)); diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs index 113f8b7193..e7d9ed2707 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs @@ -183,7 +183,7 @@ fn the_set_dropdown_keeps_action_function_keys_like_use_set() { p.shortcut_sets.insert("B".into(), b); }); h.state_mut().run("edit.keyboardShortcuts", json!({"useSet": ""})).unwrap(); - crate::actions::assign_shortcut(h.state_mut(), "Sepia", "F2").unwrap(); + h.state_mut().run("edit.keyboardShortcuts", json!({"set":{"actions.play:Sepia":"F2"},"allowUnknown":true})).unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); @@ -215,7 +215,7 @@ fn an_edit_still_marks_the_set_modified_and_sets_save_no_action_keys() { let (mut h, first, _) = dialog(vec![]); h.state_mut().ui.dialogs.retain(|d| d.id != first); h.state_mut().run("edit.keyboardShortcuts", json!({"set": {"edit.copy": "F9"}, "saveSet": "A"})).unwrap(); - crate::actions::assign_shortcut(h.state_mut(), "Sepia", "F2").unwrap(); + h.state_mut().run("edit.keyboardShortcuts", json!({"set":{"actions.play:Sepia":"F2"},"allowUnknown":true})).unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4);