diff --git a/Cargo.lock b/Cargo.lock index 434e4b6aa8a..ee80379f045 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2690,9 +2690,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]] @@ -5516,6 +5518,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 b5b814b1a22..7f41fec2235 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -37,6 +37,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 770540b6616..91faecc1086 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -15,7 +15,7 @@ //! step, because the outer `actions.play` id would otherwise hide a recorded `file.*` command from //! the top-level check. -use std::collections::{BTreeSet, VecDeque}; +use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -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, playback_row, prepare_action_id, shortcut_row}; +pub(crate) use identity::{has_legacy_shortcut, invalidate_duplicate_ids, remove_shortcuts, resolve_action_id, valid_action_id}; fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } @@ -37,6 +40,12 @@ 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, + /// Resolves a legacy shortcut to its original row even after a same-name row comes first. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub legacy_shortcut_owner: bool, #[serde(default)] pub steps: Vec<(String, Value)>, /// Indices of steps excluded from playback (unchecked in the Actions panel). @@ -64,7 +73,17 @@ 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, + legacy_shortcut_owner: false, + 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. @@ -83,6 +102,28 @@ impl Action { } } +/// The name is used for display and as the identity of a legacy action. +#[derive(Clone, Debug, PartialEq)] +pub struct PlaybackTarget { + pub name: String, + pub id: Option, +} + +impl From<&Action> for PlaybackTarget { + fn from(action: &Action) -> Self { + Self { name: action.name.clone(), id: action.action_id.clone().filter(|id| identity::valid_action_id(id)) } + } +} + +impl PlaybackTarget { + fn matches(&self, action: &Action) -> bool { + match (self.id.as_deref(), action.action_id.as_deref().filter(|id| identity::valid_action_id(id))) { + (None, None) => self.name == action.name, + (left, right) => left == right, + } + } +} + /// On-disk Actions library (`actions.json` in the preset store). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct ActionsFile { @@ -110,9 +151,9 @@ pub struct ActionState { /// Nesting depth of `actions.play`, bounded by the playback stack limit. #[serde(skip)] pub playing: u8, - /// Active action names, for cycle detection in engine and desktop playback. + /// Active action occurrences, for cycle detection in engine and desktop playback. #[serde(skip)] - pub playback_stack: Vec, + pub playback_stack: Vec, /// Number of steps executed by the current top-level playback tree. #[serde(skip)] pub playback_steps: u64, @@ -281,9 +322,9 @@ 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 = resolve_play_target(&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) { + if s.actions.playback_stack.iter().any(|target| target.matches(&action)) || s.actions.recording.is_some_and(|(_, i)| i == idx) { return Err(bad("actions.play", format!("recursive action call to `{}`", action.name))); } if s.actions.playback_stack.len() >= 16 { @@ -294,7 +335,7 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> { } /// Visit calls in the current namespace, leaving embedded inline Batch scopes untouched. -fn visit_calls(steps: &mut [(String, Value)], f: &mut impl FnMut(&str, &mut Value, bool)) { +pub(crate) fn visit_calls(steps: &mut [(String, Value)], f: &mut impl FnMut(&str, &mut Value, bool)) { let mut pending: Vec<_> = steps.iter_mut().rev().map(|(id, params)| (id.clone(), params)).collect(); while let Some((id, params)) = pending.pop() { let scoped = id == "file.automate.batch" && params.get("calledActions").is_some_and(|v| !v.is_null()); @@ -358,7 +399,7 @@ pub(crate) fn shift_action_calls(list: &mut [Action], at: usize, count: usize) { pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec { /// Resolve in the current namespace before capture rewrites the reference. fn target(list: &[Action], params: &Value, id: &str) -> Result { - if id == "file.automate.batch" { crate::file_cmds::batch_action(list, params) } else { resolve(list, params, id) } + if id == "file.automate.batch" { crate::file_cmds::batch_action(list, params) } else { resolve_play_target(list, params, id) } } /// Capture ordinary calls transitively, but retain an untouched source for scoped named Batch. fn targets(list: &[Action], steps: &mut [(String, Value)], depth: usize, queue: &mut VecDeque<(usize, usize)>, scoped: &mut BTreeSet) { @@ -377,8 +418,9 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec { for key in ["then", "else"] { - let Some(name) = params.get(key).and_then(Value::as_str) else { continue }; - if let Some(i) = list.iter().position(|a| a.name == name) { + if let Ok(Some(branch)) = conditional_branch(params, key) + && let Ok(i) = resolve_play_target(list, &branch, id) + { queue.push_back((i, depth)); } } @@ -413,7 +455,12 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec Vec Vec params["action"] = json!(name), } + if let Some(object) = params.as_object_mut() + && object.remove("actionId").is_some() + && id == "file.automate.batch" + { + // The source ID superseded this legacy qualifier. + object.remove("set"); + } return; } // Appended source copies must not make an originally missing numeric target valid. @@ -474,6 +529,32 @@ fn num(v: &Value) -> Option { v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64)) } +pub(crate) fn resolve_play_target(list: &[Action], p: &Value, cmd: &str) -> Result { + match p.get("actionId") { + Some(id) => id.as_str().and_then(|id| resolve_action_id(list, id)).ok_or_else(|| bad(cmd, "invalid, missing, or duplicate action ID")), + None => resolve(list, p, cmd), + } +} + +pub(crate) fn branch_id_field(branch: &str) -> &'static str { + if branch == "then" { "thenActionId" } else { "elseActionId" } +} + +/// A Conditional's selected branch takes the same target as Play Action. +pub fn conditional_branch(p: &Value, branch: &str) -> Result> { + let id = p.get(branch_id_field(branch)); + let name = match p.get(branch) { + None | Some(Value::Null) => None, + Some(Value::String(name)) if name.trim().is_empty() => None, + Some(Value::String(name)) => Some(name), + Some(_) => return Err(bad("actions.conditional", format!("'{branch}' must be an action name or null"))), + }; + Ok(match id { + Some(id) => Some(json!({"action": name, "actionId": id})), + None => name.map(|name| json!({"action": name})), + }) +} + pub(crate) fn resolve(list: &[Action], p: &Value, cmd: &str) -> Result { let Some(v) = p.get("action") else { return Err(bad(cmd, "needs \"action\" (a name or an index)")); @@ -779,7 +860,7 @@ pub fn begin_playback(s: &mut Session, action: &Action) -> Result, actio history::finish_playback(s); } if let Some((_, idx)) = recording { - restore_recording(s, idx, &action.name, from); + let params = recorded_target(s, action, from); + restore_recording(s, idx, params); } } /// Resume recording into action `idx` and journal the named call that suspended it. -pub fn restore_recording(s: &mut Session, idx: usize, action: &str, from: usize) { +pub fn restore_recording(s: &mut Session, idx: usize, params: Value) { s.actions.recording = Some((s.journal.len(), idx)); - let mut params = json!({"action": action}); + s.journal.push(("actions.play".into(), params)); +} + +pub fn recorded_target(s: &Session, action: &Action, from: usize) -> Value { + let mut params = json!({"action": action.name}); + if let Some(id) = &action.action_id + && s.actions.list.iter().filter(|other| other.name == action.name).take(2).count() > 1 + { + params["actionId"] = json!(id); + } if from > 0 { params["from"] = json!(from); } - s.journal.push(("actions.play".into(), params)); + params } /// What stops the caller of a Batch even where per-file errors don't (a direct Batch in a script @@ -898,6 +989,15 @@ 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 && has_legacy_shortcut(s, name) { + let key = format!("{PLAY_SHORTCUT_PREFIX}{name}"); + if let Some(owner) = shortcut_row(&s.actions.list, &key) { + s.actions.list[owner].legacy_shortcut_owner = true; + } + } let moved = s.actions.list.remove(idx); let result = json!({"action": moved.name, "index": to}); s.actions.list.insert(to, moved); @@ -954,15 +1054,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.edit_prefs(|prefs| { - prefs.shortcuts.remove(&key); - }); - } Ok(json!({"deleted": name})) } @@ -1031,18 +1125,23 @@ fn rename(s: &mut Session, p: &Value) -> Result { // A loaded library can hold two actions of one name (in different sets): a call follows the // 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 owned_shortcut = shortcut_row(&before, &format!("{PLAY_SHORTCUT_PREFIX}{old}")) == Some(idx); 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() { - "actions.play" if by_name => &["action"], - "actions.conditional" if by_name => &["then", "else"], + "actions.play" if resolve_play_target(&before, params, id).ok() == Some(idx) => &["action"], + "actions.conditional" => &["then", "else"], // A named Batch selects from the caller's list, by name alone or within its set; // explicit `steps` run instead of any named action, so those are left alone. "file.automate.batch" if params.get("steps").is_none() && crate::file_cmds::batch_action(&before, params).ok() == Some(idx) => &["action"], _ => &[], }; for key in keys { + if id == "actions.conditional" + && conditional_branch(params, key).ok().flatten().and_then(|target| resolve_play_target(&before, &target, id).ok()) != Some(idx) + { + continue; + } if params.get(*key).and_then(Value::as_str) == Some(old.as_str()) { params[*key] = json!(name); } @@ -1053,10 +1152,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) { + if owned_shortcut && (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) { - prefs.shortcuts.insert(to, key); + prefs.shortcuts.insert(to.clone(), key); + } + 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 00000000000..a39ba0a779a --- /dev/null +++ b/crates/engine/src/cmd/actions_cmds/identity.rs @@ -0,0 +1,144 @@ +//! Persisted action occurrences are independent of name, list order, and folder position. +use std::collections::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 valid_action_id(id: &str) -> bool { + id.len() == 32 && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +pub(crate) fn resolve_action_id(list: &[Action], id: &str) -> Option { + if !valid_action_id(id) { + 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()); + } + } +} + +/// Reacquire a paused row by the same identity its playback used. +pub fn playback_row(list: &[Action], action: &Action) -> Option { + if let Some(id) = action.action_id.as_deref().filter(|id| valid_action_id(id)) { + return resolve_action_id(list, id); + } + list.iter().position(|other| other.name == action.name) +} + +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)?; + let mut pinned = list.iter().enumerate().filter(|(_, action)| action.name == name && action.legacy_shortcut_owner); + if let Some((index, _)) = pinned.next() { + return pinned.next().is_none().then_some(index); + } + 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) +} + +/// Save a new identity before the shortcut edit can reach the separate preferences file. +pub fn commit_action_id(s: &mut Session, index: usize, id: String) -> Result<()> { + let action = s.actions.list.get(index).ok_or_else(|| bad(COMMAND, "action no longer exists"))?; + let owner = resolve_action_id(&s.actions.list, &id); + if let Some(current) = &action.action_id { + return if current == &id && owner == Some(index) { Ok(()) } else { Err(bad(COMMAND, "invalid or duplicate action ID")) }; + } + if !valid_action_id(&id) || s.actions.list.iter().any(|action| action.action_id.as_deref() == Some(id.as_str())) { + return Err(bad(COMMAND, "invalid or duplicate action ID")); + } + s.actions.list[index].action_id = Some(id); + let rev = s.actions.rev.saturating_add(1); + if let Some(store) = s.preset_store.as_mut() + && let Err(error) = store.commit_action_definitions(&s.actions, rev) + { + s.actions.list[index].action_id = None; + return Err(bad(COMMAND, error)); + } + s.actions.touch(); + Ok(()) +} + +/// 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) +} + +pub(crate) fn has_legacy_shortcut(s: &Session, name: &str) -> bool { + let key = format!("{PLAY_SHORTCUT_PREFIX}{name}"); + s.prefs().shortcuts.contains_key(&key) || s.prefs().alternate_shortcuts.contains_key(&key) +} + +/// 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.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index e71b23bca60..16f940ae134 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -165,6 +165,8 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "stop recording before duplicating an action")); } let mut copied = s.actions.list[idx].clone(); + copied.action_id = None; + copied.legacy_shortcut_owner = false; let mut names = crate::atn_cmds::UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone())); copied.name = names.claim(&format!("{} copy", copied.name)); let at = idx + 1; @@ -202,6 +204,8 @@ fn duplicate_set(s: &mut Session, source: &str, source_slot: Option) -> R action.name = names.claim(&format!("{} copy", action.name)); action.set = Some(name.clone()); action.set_slot = copy_slot; + action.action_id = None; + action.legacy_shortcut_owner = false; action }) .collect(); @@ -442,25 +446,18 @@ fn conditional(s: &mut Session, p: &Value) -> Result { Some(Value::String(c)) => c.clone(), _ => return Err(bad(cmd, format!("needs `if`, one of {}", CONDITIONS.join("|")))), }; - let branch = |key: &str| -> Result> { - match p.get(key) { - None | Some(Value::Null) => Ok(None), - Some(Value::String(n)) if !n.trim().is_empty() => Ok(Some(n.clone())), - Some(Value::String(_)) => Ok(None), - Some(_) => Err(bad(cmd, format!("`{key}` must be an action name or null"))), - } - }; - let (then, otherwise) = (branch("then")?, branch("else")?); + let (then, otherwise) = (crate::actions_cmds::conditional_branch(p, "then")?, crate::actions_cmds::conditional_branch(p, "else")?); let holds = evaluate(s, &condition)?; let played = if holds { then } else { otherwise }; - let mut out = json!({"if": condition, "holds": holds, "played": played}); - if let Some(name) = played { - let r = s.execute("actions.play", json!({"action": name}))?; + let mut out = json!({"if": condition, "holds": holds, "played": played.as_ref().and_then(|p| p.get("action"))}); + if let Some(params) = played { + let r = s.execute("actions.play", params)?; if let Some(f) = r.get("failed") { out["failed"] = f.clone(); } out["ran"] = r.get("ran").cloned().unwrap_or(json!(0)); - out["action"] = json!(name); + out["action"] = r["action"].clone(); + out["played"] = r["action"].clone(); } Ok(out) } 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 c2dca22d074..56f8c29cdc8 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, not_playing}; +use crate::actions_cmds::{Action, PLAY_SHORTCUT_PREFIX, has_legacy_shortcut, is_action_key, not_playing, shortcut_row}; 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); }); @@ -88,17 +88,38 @@ pub(crate) fn check_library_size(list: &[Action], sets: &[String], rows: &[Strin .map_err(|error| bad(cmd, error.to_string())) } -/// Replace only library data. Append uses None to leave both binding maps in place. -pub(crate) fn publish_library(s: &mut Session, list: Vec, sets: Vec, rows: Vec, new_shortcuts: Option, label: &'static str) { +/// Replace library definitions and remember both shortcut maps for the one-step undo. +/// 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 count = s.actions.list.len(); + let owners: Vec<_> = list[count..] + .iter() + .filter(|action| has_legacy_shortcut(s, &action.name)) + .filter_map(|action| shortcut_row(&list[..count], &format!("{PLAY_SHORTCUT_PREFIX}{}", action.name))) + .collect(); + for owner in owners { + list[owner].legacy_shortcut_owner = true; + } + (shortcuts.clone(), alternates.clone()) } - None => (shortcuts.clone(), alternates.clone()), }; + 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 { @@ -118,13 +139,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})) } @@ -146,8 +168,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})) } 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 e95e92fbf24..f40a9996ff5 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 @@ -102,7 +102,8 @@ fn whole_replace_validates_the_tail_and_keeps_every_set_in_order() { assert_eq!(s.actions.list, prior); } -/// Caption-only edits infer an explicit folder only when the caption is unambiguous. +/// Caption-only edits infer just one physical row, while explicit null, duplicate captions, +/// and captions shared with legacy sets retain the existing name-only behavior. #[test] fn recording_and_assignment_infer_only_unambiguous_folder_occurrences() { let mut s = Session::new(); @@ -121,7 +122,132 @@ fn recording_and_assignment_infer_only_unambiguous_folder_occurrences() { assert_eq!(s.actions.list[0].set_slot, Some(0)); } -/// Imported callers prefer the same physical folder when a target name is repeated. +/// 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_pins_existing_shortcuts_and_undo_restores_legacy_keys() { + let mut s = Session::new(); + 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(); + assert!(s.actions.list[0].legacy_shortcut_owner); + assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &shortcut), Some(0)); + assert_eq!(s.prefs().shortcuts[&shortcut], "F2"); + assert_eq!(s.prefs().alternate_shortcuts[&shortcut], ["F3"]); + 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"]); +} + +#[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).unwrap(); + } + 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")); +} + +#[test] +fn attachment_keeps_disk_batch_targets_and_does_not_resolve_foreign_ids() { + use crate::preset_store::{ACTIONS_FILE, PresetBackend}; + + let store = MemBackend::default(); + let foreign_id = "a".repeat(32); + let file = json!({"version":1,"actions":[ + {"name":"Target","set":"Saved"}, + {"name":"Caller","steps":[ + ["file.automate.batch",{"action":"Target","set":"Saved"}], + ["actions.play",{"action":0}], + ["actions.play",{"action":"Target","actionId":foreign_id}] + ]} + ]}); + store.write(ACTIONS_FILE, file.to_string().as_bytes()).unwrap(); + let mut s = Session::new(); + s.actions.list.push(Action { set: Some("Saved".into()), action_id: Some(foreign_id), ..Action::new("Target", Vec::new()) }); + assert!(s.attach_preset_store(open(Box::new(store))).is_empty()); + let list = &s.actions.list; + let calls = &list[2].steps; + assert_eq!(crate::file_cmds::batch_action(list, &calls[0].1).unwrap(), 1); + assert_eq!(crate::actions_cmds::resolve_play_target(list, &calls[1].1, "actions.play").unwrap(), 1); + assert!(crate::actions_cmds::resolve_play_target(list, &calls[2].1, "actions.play").is_err()); + assert_eq!(crate::actions_cmds::resolve(list, &json!({"action":"Target"}), "actions.play").unwrap(), 0); +} + +#[test] +fn attachment_keeps_unresolved_disk_calls_from_binding_to_early_actions() { + use crate::actions_cmds::{conditional_branch, resolve_play_target}; + use crate::preset_store::{ACTIONS_FILE, PresetBackend}; + + let store = MemBackend::default(); + let file = json!({"version":1,"actions":[{"name":"Disk caller","steps":[ + ["actions.play",{"action":"Early"}], + ["actions.conditional",{"if":"always","then":"Early"}], + ["file.automate.batch",{"action":"Early","set":"Session"}], + ["actions.play",{"action":1}] + ]}]}); + store.write(ACTIONS_FILE, file.to_string().as_bytes()).unwrap(); + let mut s = Session::new(); + s.actions.list.push(Action { set: Some("Session".into()), ..Action::new("Early", Vec::new()) }); + assert!(s.attach_preset_store(open(Box::new(store.clone()))).is_empty()); + s.sync_preset_store(); + + let mut s = Session::new(); + assert!(s.attach_preset_store(open(Box::new(store))).is_empty()); + let list = &s.actions.list; + let steps = &list[1].steps; + assert!(resolve_play_target(list, &steps[0].1, "actions.play").is_err()); + let branch = conditional_branch(&steps[1].1, "then").unwrap().unwrap(); + assert!(resolve_play_target(list, &branch, "actions.conditional").is_err()); + assert!(crate::file_cmds::batch_action(list, &steps[2].1).is_err()); + assert!(resolve_play_target(list, &steps[3].1, "actions.play").is_err()); + assert_eq!(s.execute("actions.play", json!({"action":"Early"})).unwrap()["action"], "Early"); +} + +/// Imported calls follow a local physical folder before falling back to the first archive name. #[test] fn whole_replace_resolves_unqualified_calls_in_their_own_occurrence() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index 3245ac4bf02..094fcccf040 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -122,21 +122,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 { @@ -250,6 +254,33 @@ pub fn parse_function_key(key: &str) -> Option<(u16, bool, bool)> { Some((n, shift, command)) } +/// ATN uses names for these calls. Only translate an ID when that name identifies +/// the same exported row; an absent or ambiguous target is an unsupported step. +fn export_targeted_items(id: &str, params: &Value, set: &str, actions: &[&Action]) -> Option> { + let targets: &[(&str, &str)] = match id { + "actions.play" => &[("actionId", "action")], + "actions.conditional" => &[("thenActionId", "then"), ("elseActionId", "else")], + _ => &[], + }; + if !targets.iter().any(|(key, _)| params.get(*key).is_some()) { + return export_items(id, params, set); + } + let mut params = params.clone(); + for (key, name) in targets { + if let Some(id) = params.get(*key) { + let id = id.as_str().filter(|id| crate::actions_cmds::valid_action_id(id))?; + let mut matches = actions.iter().filter(|action| action.action_id.as_deref() == Some(id)); + let action = matches.next()?; + if matches.next().is_some() || actions.iter().filter(|other| other.name == action.name).take(2).count() != 1 { + return None; + } + params[*name] = json!(action.name); + } + } + params["set"] = json!(set); + export_items(id, ¶ms, set) +} + /// The `.atn` bytes of `actions` as the set `set`. `function_keys` gives each action's key /// (`F1`…`F15`, with `Shift+` and `Cmd+` as [`function_key_name`] writes them). Steps with no Photoshop equivalent are an error unless `skip_unsupported`. pub fn export( @@ -257,16 +288,25 @@ 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() { - let Some(items) = export_items(id, params, set) else { + let Some(items) = export_targeted_items(id, params, set, actions) else { if skip_unsupported { skipped.push(Skipped { action: a.name.clone(), step: i, id: id.clone() }); continue; diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index 45e60ddfadc..863dbb0e82a 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,6 +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::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 +101,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 +143,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,12 +166,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 keys: Vec<(String, String)> = - s.prefs().shortcuts.iter().filter_map(|(k, v)| k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX).map(|n| (n.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 69c577ea358..4c2d87e3f8d 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/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 6af9a34e215..bad5cb2e215 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -610,6 +610,9 @@ pub(crate) fn batch_keeps_step(id: &str) -> bool { pub(crate) fn batch_action(list: &[crate::actions_cmds::Action], p: &Value) -> Result { const CMD: &str = "file.automate.batch"; + if p.get("actionId").is_some() { + return crate::actions_cmds::resolve_play_target(list, p, CMD); + } if let Some(set) = p.get("set").filter(|v| !v.is_null()) { let set = set.as_str().ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: "set must be a string".into() })?; let name = @@ -694,7 +697,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { list } }; - let mut called_name = None; + let mut called_target = None; let mut steps = if let Some(st) = p.get("steps") { parse_steps(st)? } else if let Some(act) = p.get("action").filter(|v| v.is_array()) { @@ -703,15 +706,15 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // The caller selects the source; calledActions supplies only its internal namespace. let index = batch_action(&s.actions.list, p)?; let (action, _) = crate::actions_cmds::playback_plan(s, &json!({"action": index}))?; - called_name = Some(action.name.clone()); + called_target = Some(crate::actions_cmds::PlaybackTarget::from(&action)); action.enabled_steps().map(|(_, (id, params))| (id.clone(), params.clone())).collect() }; let action_name = s .action_history .as_ref() .map(|group| group.name.clone()) - .or_else(|| s.actions.playback_stack.first().cloned()) - .or_else(|| called_name.clone()) + .or_else(|| s.actions.playback_stack.first().map(|target| target.name.clone())) + .or_else(|| called_target.as_ref().map(|target| target.name.clone())) .or_else(|| p.get("action").and_then(Value::as_str).map(str::to_string)) .or_else(|| p.get("action").and_then(|action| action.get("name")).and_then(Value::as_str).map(str::to_string)) .unwrap_or_else(|| "Batch".into()); @@ -758,7 +761,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // decoded and saved even with no steps) to the playback tree it is in and // hands the count on, so nested batches cannot multiply past the limit. A top-level named // action starts fresh; standalone explicit steps retain their existing behavior. - let named = called_name.is_some(); + let named = called_target.is_some(); let mut playback_steps = 0; if s.actions.playing > 0 || named { let spent = if s.actions.playing > 0 { s.actions.playback_steps } else { 0 }; @@ -772,7 +775,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } } let mut playback_stack = s.actions.playback_stack.clone(); - playback_stack.extend(called_name); + playback_stack.extend(called_target); let actions = crate::actions_cmds::ActionState { list, playing: if named { s.actions.playing.saturating_add(1) } else { s.actions.playing }, diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index d42d333128d..110dbe09d97 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -20,7 +20,7 @@ fn batch_resolves_action_by_name_and_detects_recursion() { p["output"] = json!(out); assert!(s.execute("file.automate.batch", p).is_err()); } - s.actions.playback_stack.push("Scale".into()); + s.actions.playback_stack.push(crate::actions_cmds::PlaybackTarget { name: "Scale".into(), id: None }); let err = s.execute("file.automate.batch", json!({"action":"Scale","input":[input],"output":out})).unwrap_err(); assert!(err.to_string().contains("recursive action call"), "{err}"); } @@ -532,7 +532,7 @@ fn named_open_document_batch_keeps_cycle_context_and_live_recorder() { crate::actions_cmds::Action::new("Leaf", vec![("actions.play".into(), json!({"action":0}))]), ]; let definitions = s.actions.list[1..].to_vec(); - s.actions.playback_stack = vec!["Enclosing".into()]; + s.actions.playback_stack = vec![crate::actions_cmds::PlaybackTarget { name: "Enclosing".into(), id: None }]; s.actions.recording = Some((s.journal.len(), 0)); let take = s.actions.take; s.authorize = Some(gate); @@ -540,7 +540,7 @@ fn named_open_document_batch_keeps_cycle_context_and_live_recorder() { let result = batch(&mut s, &json!({"source":"open","action":"Loop A"})).unwrap(); assert!(result["errors"][0]["error"].as_str().unwrap().contains("recursive action"), "{result}"); assert!(CALLS.load(Ordering::SeqCst) <= 2, "the cycle check must beat the finite sentinel"); - assert_eq!(s.actions.playback_stack, ["Enclosing"]); + assert_eq!(s.actions.playback_stack, [crate::actions_cmds::PlaybackTarget { name: "Enclosing".into(), id: None }]); assert_eq!(s.actions.recording.map(|(_, owner)| owner), Some(0)); assert_eq!(s.actions.take, take); assert_eq!(&s.actions.list[1..], definitions.as_slice()); @@ -549,7 +549,7 @@ fn named_open_document_batch_keeps_cycle_context_and_live_recorder() { let result = batch(&mut s, &json!({"source":"open","action":"Leaf","calledActions":embedded})).unwrap(); assert_eq!(result["errors"], json!([]), "{result}"); assert_eq!(doc(&s).walk().len(), before + 1); - assert_eq!(s.actions.playback_stack, ["Enclosing"]); + assert_eq!(s.actions.playback_stack, [crate::actions_cmds::PlaybackTarget { name: "Enclosing".into(), id: None }]); assert_eq!(s.actions.recording.map(|(_, owner)| owner), Some(0)); assert_eq!(s.actions.take, take); assert_eq!(&s.actions.list[1..], definitions.as_slice()); @@ -2778,7 +2778,7 @@ fn named_batch_limits_nesting_and_keeps_the_callers_state() { } s.actions.list.push(Action::new("Invert", vec![("image.adjustments.invert".into(), json!({}))])); s.actions.playing = 16; - s.actions.playback_stack = (0..16).map(|i| format!("Parent{i}")).collect(); + s.actions.playback_stack = (0..16).map(|i| crate::actions_cmds::PlaybackTarget { name: format!("Parent{i}"), id: None }).collect(); let before = s.actions.clone(); let error = s.execute("file.automate.batch", params.clone()).unwrap_err(); assert!(error.to_string().contains("nesting exceeds 16"), "{error}"); @@ -2834,14 +2834,14 @@ fn named_batch_charges_the_existing_budget_across_inputs_and_children() { Action::new("Leaf", vec![("select.deselect".into(), json!({})); 2]), ]; s.actions.playing = 1; - s.actions.playback_stack = vec!["Parent".into()]; + s.actions.playback_stack = vec![crate::actions_cmds::PlaybackTarget { name: "Parent".into(), id: None }]; s.actions.playback_steps = MAX_PLAYBACK_STEPS - 4; let result = s.execute("file.automate.batch", json!({"action": "Outer", "input": [input, input], "output": output, "naming": "{serial}"})).unwrap(); assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); assert!(result["errors"][0]["error"].as_str().unwrap().contains("step limit"), "{result}"); assert_eq!(s.actions.playback_steps, MAX_PLAYBACK_STEPS); assert_eq!(s.actions.playing, 1); - assert_eq!(s.actions.playback_stack, ["Parent"]); + assert_eq!(s.actions.playback_stack, [crate::actions_cmds::PlaybackTarget { name: "Parent".into(), id: None }]); } /// Nested named batches honor the caller's authorization and preserve its action state. diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index 194aca75df4..3a8958c02d9 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -57,6 +57,7 @@ use serde::{Deserialize, Serialize}; use crate::Session; +mod actions; mod patterns; pub use patterns::{Loaded as LoadedPattern, MAX_PATTERN_BYTES, PATTERNS_FILE, PREVIEW_SIDE as PATTERN_PREVIEW_SIDE}; @@ -754,6 +755,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()); } @@ -1106,30 +1108,38 @@ impl PresetStore { if self.actions_rev == rev { return; } - if self.actions_skipped { - self.warnings.push(format!("Couldn't save actions: {ACTIONS_FILE} could not be read, so it was left unchanged")); - self.actions_rev = rev; - return; - } - let file = crate::actions_cmds::ActionsFile { version: 1, actions: state.list.clone(), sets: state.sets.clone(), set_rows: state.set_rows.clone() }; - let bytes = match serde_json::to_vec_pretty(&file) { - Ok(b) => b, - Err(e) => { - self.warnings.push(format!("Couldn't save actions: {e}")); + let bytes = match self.action_bytes(state) { + Ok(bytes) => bytes, + Err(error) => { + self.warnings.push(error); self.actions_rev = rev; return; } }; - if bytes.len() as u64 > MAX_ACTIONS_BYTES { - self.warnings.push(format!("actions: the action list is too large to save ({} MB limit)", MAX_ACTIONS_BYTES >> 20)); - self.actions_rev = rev; - return; - } match self.backend.write(ACTIONS_FILE, &bytes) { Ok(()) => self.actions_rev = rev, Err(e) => self.warnings.push(format!("Couldn't save actions: {e}")), } } + + pub(crate) fn commit_action_definitions(&mut self, state: &crate::actions_cmds::ActionState, rev: u64) -> Result<(), String> { + let bytes = self.action_bytes(state)?; + self.backend.write(ACTIONS_FILE, &bytes).map_err(|error| format!("Couldn't save actions: {error}"))?; + self.actions_rev = rev; + Ok(()) + } + + fn action_bytes(&self, state: &crate::actions_cmds::ActionState) -> Result, String> { + if self.actions_skipped { + return Err(format!("Couldn't save actions: {ACTIONS_FILE} could not be read, so it was left unchanged")); + } + let file = crate::actions_cmds::ActionsFile { version: 1, actions: state.list.clone(), sets: state.sets.clone(), set_rows: state.set_rows.clone() }; + let bytes = serde_json::to_vec_pretty(&file).map_err(|error| format!("Couldn't save actions: {error}"))?; + if bytes.len() as u64 > MAX_ACTIONS_BYTES { + return Err(format!("actions: the action list is too large to save ({} MB limit)", MAX_ACTIONS_BYTES >> 20)); + } + Ok(bytes) + } } fn builtin_names() -> &'static [String] { @@ -1148,7 +1158,7 @@ impl Session { /// built-in of the same name; presets created before the store finished loading win), hide /// deleted built-ins, then sync. Returns the load warnings. pub fn attach_preset_store(&mut self, opened: Opened) -> Vec { - let Opened { store, presets, hidden_builtins, order, mut warnings, actions: disk, action_sets, action_set_rows, patterns } = opened; + let Opened { store, presets, hidden_builtins, order, mut warnings, actions: mut disk, action_sets, action_set_rows, patterns } = opened; let builtins = crate::pattern_cmds::builtin(); for l in patterns { let id = l.pattern.id.clone(); @@ -1188,8 +1198,8 @@ impl Session { } self.preset_store = Some(store); self.actions.set_rows_revision = self.actions.set_rows_revision.wrapping_add(1); - // In-memory actions (created before the store finished loading) win on name. Disk-only - // names are appended. An empty session takes the disk list and does not rewrite it. + // An empty session takes the disk list without rewriting it. Otherwise, keep the + // in-memory first match while retaining disk rows that own shortcuts or recorded calls. if self.actions.list.is_empty() && self.actions.sets.is_empty() && self.actions.set_rows.is_empty() && self.actions.library_undo.is_none() { self.actions.list = disk; self.actions.sets = action_sets; @@ -1199,6 +1209,7 @@ impl Session { st.actions_rev = 1; } } else { + actions::pin_disk_targets(self, &mut disk, &mut warnings); let offset = self.actions.set_rows.len(); self.actions.set_rows.extend(action_set_rows); for name in action_sets { @@ -1207,11 +1218,16 @@ impl Session { } } for mut action in disk { - if action.set_slot.is_some() || !self.actions.list.iter().any(|have| have.name == action.name) { + if action.set_slot.is_some() + || action.action_id.is_some() + || action.legacy_shortcut_owner + || !self.actions.list.iter().any(|have| have.name == action.name) + { action.set_slot = action.set_slot.and_then(|slot| slot.checked_add(offset)); self.actions.list.push(action); } } + crate::actions_cmds::invalidate_duplicate_ids(&mut self.actions.list); self.actions.library_undo = None; self.actions.rev = self.actions.rev.saturating_add(1).max(1); } diff --git a/crates/engine/src/preset_store/actions.rs b/crates/engine/src/preset_store/actions.rs new file mode 100644 index 00000000000..8128238235c --- /dev/null +++ b/crates/engine/src/preset_store/actions.rs @@ -0,0 +1,97 @@ +//! Keep a saved reference in its original namespace when startup attaches the disk library. +use std::collections::HashSet; + +use serde_json::{Value, json}; + +use crate::Session; +use crate::actions_cmds::{ + Action, PLAY_SHORTCUT_PREFIX, branch_id_field, conditional_branch, prepare_action_id, resolve_play_target, shortcut_row, valid_action_id, visit_calls, +}; + +/// Explicit IDs that failed in their source list must also fail after the lists are joined. +fn block_unknown_ids(list: &mut [Action]) { + let ids: HashSet<_> = list.iter().filter_map(|action| action.action_id.as_ref().filter(|id| valid_action_id(id)).cloned()).collect(); + for action in list { + visit_calls(&mut action.steps, &mut |command, params, _| { + let fields: &[&str] = match command { + "actions.play" | "file.automate.batch" => &["actionId"], + "actions.conditional" => &["thenActionId", "elseActionId"], + _ => &[], + }; + for field in fields { + if let Some(value) = params.get(*field) + && !value.as_str().is_some_and(|id| ids.contains(id)) + { + params[*field] = Value::Null; + } + } + }); + } +} + +pub(super) fn pin_disk_targets(s: &mut Session, disk: &mut [Action], warnings: &mut Vec) { + if s.actions.list.is_empty() || disk.is_empty() { + return; + } + block_unknown_ids(&mut s.actions.list); + block_unknown_ids(disk); + let memory = &s.actions.list; + + // Saved preferences predate the asynchronous attachment. Keep their legacy key, and + // persist the disk owner with the library so a failed store write cannot orphan the key. + let keys = s.prefs().shortcuts.keys().chain(s.prefs().alternate_shortcuts.keys()); + for key in keys { + let Some(name) = key.strip_prefix(PLAY_SHORTCUT_PREFIX) else { continue }; + if memory.iter().any(|action| action.name == name) + && !memory.iter().any(|action| action.name == name && action.legacy_shortcut_owner) + && let Some(row) = shortcut_row(disk, key) + { + disk[row].legacy_shortcut_owner = true; + } + } + + for row in 0..disk.len() { + let mut steps = std::mem::take(&mut disk[row].steps); + visit_calls(&mut steps, &mut |command, params, _| match command { + "actions.play" | "file.automate.batch" if params.get("actionId").is_none() => { + let resolve = |list: &[Action]| { + if command == "actions.play" { resolve_play_target(list, params, command) } else { crate::file_cmds::batch_action(list, params) } + }; + if params.get("action").is_some_and(Value::is_number) || resolve(memory).is_ok() { + let original = resolve(disk); + // A name or index that failed on disk must not acquire a target from the merge. + params["actionId"] = original.map_or(Value::Null, |row| pin_target(disk, row, warnings)); + } + } + "actions.conditional" => { + for branch in ["then", "else"] { + let field = branch_id_field(branch); + if params.get(field).is_some() { + continue; + } + if let Ok(Some(target)) = conditional_branch(params, branch) + && resolve_play_target(memory, &target, command).is_ok() + { + let original = resolve_play_target(disk, &target, command); + params[field] = original.map_or(Value::Null, |row| pin_target(disk, row, warnings)); + } + } + } + _ => {} + }); + disk[row].steps = steps; + } +} + +fn pin_target(list: &mut [Action], index: usize, warnings: &mut Vec) -> Value { + match prepare_action_id(list, index) { + Ok(id) => { + list[index].action_id = Some(id.clone()); + json!(id) + } + Err(error) => { + warnings.push(format!("actions: {error}")); + Value::Null + } + } +} diff --git a/crates/engine/src/shortcut_sets.rs b/crates/engine/src/shortcut_sets.rs index 4b36de1b823..ecfd36d19ba 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 dcff8d4d2c0..937c0ce54d5 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,8 +49,19 @@ 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 action_ids: Vec = app.session.actions.list.iter().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_key = |key: &str, alternate| { + let Some(row) = action_shortcut_row(app, key) else { return false }; + if !key.starts_with(actions_cmds::PLAY_SHORTCUT_PREFIX) { + return true; + } + let list = &app.session.actions.list; + let explicit = list[row].action_id.as_deref().map(actions_cmds::occurrence_key); + !explicit.is_some_and(|id| { + actions_cmds::shortcut_row(list, &id) == Some(row) + && if alternate { prefs.alternate_shortcuts.contains_key(&id) } else { prefs.shortcuts.contains_key(&id) } + }) + }; + let actions = prefs.shortcuts.keys().filter(|id| action_key(id.as_str(), false)).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). @@ -75,7 +87,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) @@ -98,6 +110,9 @@ 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 actions_cmds::is_action_key(id) && !action_key(id, true) { + continue; + } let main = prefs.shortcut(id, crate::shortcuts::default_shortcut(id).as_deref()).map(str::to_string); let user = prefs.alternate_shortcuts.contains_key(id); candidates.extend(prefs.alternates(id, main.as_deref()).into_iter().map(|k| (id, Some(k), user))); @@ -371,12 +386,21 @@ pub fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) { dispatch_as(app, ctx, id, false); } +fn action_shortcut_row(app: &PhotocraftApp, key: &str) -> Option { + if key.starts_with(actions_cmds::PLAY_SHORTCUT_PREFIX) && app.services.preset_store.is_some() && app.session.preset_store.is_none() { + return None; + } + actions_cmds::shortcut_row(&app.session.actions.list, key) +} + /// [`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 outcome = if !crate::menus::is_enabled(app, command_id) { - let why = disabled_reason(app, command_id); + let is_action = actions_cmds::is_action_key(id); + let action = action_shortcut_row(app, id); + 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; @@ -384,10 +408,15 @@ 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(row) = action { + let list = &app.session.actions.list; + let target = match id.strip_prefix(actions_cmds::PLAY_SHORTCUT_PREFIX) { + Some(name) if list.iter().position(|action| action.name == name) == Some(row) => json!({"action": name}), + Some(_) => json!({"action": row}), + None => json!({"actionId": list[row].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 ce7e3fcc392..eb38d03054d 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,181 @@ 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()))); + h.state_mut().session.actions.set_rows.push("Before".into()); + 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(); + let (empty, _) = photocraft_engine::atn_cmds::export("Before", &[], &[], false).unwrap(); + let data = photocraft_paint::tile::b64_encode(&empty); + h.state_mut().run("actions.load", json!({"data":data})).unwrap(); + assert_eq!(h.state().session.actions.list[0].set_slot, Some(1)); + 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 attachment_preserves_disk_keys_and_calls_without_changing_name_lookup() { + use photocraft_engine::preset_store::{ACTIONS_FILE, MemBackend, PresetBackend, open}; + + let store = MemBackend::default(); + let file = json!({"version":1,"set_rows":["Saved"],"actions":[ + {"name":"Target","set":"Saved","set_slot":0,"steps":[["layer.new.layer",{"name":"disk target"}]]}, + {"name":"Disk caller","steps":[["actions.play",{"action":"Target"}]]}, + {"name":"Disk conditional","steps":[["actions.conditional",{"if":"always","then":"Target"}]]} + ]}); + store.write(ACTIONS_FILE, file.to_string().as_bytes()).unwrap(); + + let mut h = harness(); + h.state_mut().session.load_prefs_json(r#"{"shortcuts":{"actions.play:Target":"F2"},"alternateShortcuts":{"actions.play:Target":["F3"]}}"#).unwrap(); + h.state_mut().session.actions.list.push(actions_cmds::Action::new("Target", vec![("layer.new.layer".into(), json!({"name":"memory target"}))])); + assert!(h.state_mut().session.attach_preset_store(open(Box::new(store.clone()))).is_empty()); + let disk_key = "actions.play:Target"; + assert!(h.state().session.actions.list[1].legacy_shortcut_owner); + assert_eq!(h.state().session.prefs().shortcuts[disk_key], "F2"); + assert_eq!(h.state().session.prefs().alternate_shortcuts[disk_key], ["F3"]); + + h.state_mut().run("actions.play", json!({"action":"Target"})).unwrap(); + assert_eq!(active_name(&h), "memory target"); + press(&mut h, "F2"); + assert_eq!(active_name(&h), "disk target"); + let saved = h.state().session.prefs_to_json(); + + let mut h = harness(); + h.state_mut().session.load_prefs_json(&saved).unwrap(); + assert!(h.state_mut().session.attach_preset_store(open(Box::new(store))).is_empty()); + press(&mut h, "F3"); + assert_eq!(active_name(&h), "disk target"); + for caller in ["Disk caller", "Disk conditional"] { + h.state_mut().run("actions.play", json!({"action":"Target"})).unwrap(); + assert_eq!(active_name(&h), "memory target"); + let result = h.state_mut().run("actions.play", json!({"action":caller})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(active_name(&h), "disk target"); + } +} + +#[test] +fn new_occurrence_key_shadows_legacy_primary_until_the_identity_is_missing() { + let mut h = harness(); + h.state_mut().session.actions.list.push(actions_cmds::Action::new("Target", Vec::new())); + h.state_mut().session.edit_prefs(|p| { + p.shortcuts.insert("actions.play:Target".into(), "F2".into()); + }); + crate::actions::assign_shortcut(h.state_mut(), 0, "F4").unwrap(); + let key = action_key(&h, 0); + assert!(bindings(h.state()).iter().any(|(id, _)| id == &key)); + assert!(!bindings(h.state()).iter().any(|(id, _)| id == "actions.play:Target")); + // An async backend may have saved the preferences but still have the old Actions file. + h.state_mut().session.actions.list[0].action_id = None; + assert!(!bindings(h.state()).iter().any(|(id, _)| id == &key)); + assert!(bindings(h.state()).iter().any(|(id, _)| id == "actions.play:Target")); +} + +#[test] +fn failed_action_id_write_keeps_the_legacy_shortcut_after_reopen() { + use photocraft_engine::preset_store::{ACTIONS_FILE, MemBackend, PresetBackend, open}; + + struct RejectActionsWrite(MemBackend); + impl PresetBackend for RejectActionsWrite { + fn list(&self) -> Result, String> { + self.0.list() + } + fn read(&self, name: &str, max: u64) -> Result, String> { + self.0.read(name, max) + } + fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String> { + if name == ACTIONS_FILE { + return Err("injected Actions write failure".into()); + } + self.0.write(name, bytes) + } + fn remove(&self, name: &str) -> Result<(), String> { + self.0.remove(name) + } + } + + let store = MemBackend::default(); + let file = json!({"version":1,"actions":[{"name":"Target","steps":[["layer.new.layer",{"name":"legacy target"}]]}]}); + let original = file.to_string().into_bytes(); + store.write(ACTIONS_FILE, &original).unwrap(); + + let mut h = harness(); + h.state_mut().session.load_prefs_json(r#"{"shortcuts":{"actions.play:Target":"F2"},"alternateShortcuts":{"actions.play:Target":["F3"]}}"#).unwrap(); + h.state_mut().session.attach_preset_store(open(Box::new(RejectActionsWrite(store.clone())))); + let failure = crate::actions::assign_shortcut(h.state_mut(), 0, "F4").unwrap_err(); + assert!(failure.contains("injected Actions write failure")); + assert!(h.state().session.actions.list[0].action_id.is_none()); + assert_eq!(store.read(ACTIONS_FILE, 4096).unwrap(), original); + let saved_prefs = h.state().session.prefs_to_json(); + + let mut h = harness(); + h.state_mut().session.load_prefs_json(&saved_prefs).unwrap(); + h.state_mut().session.attach_preset_store(open(Box::new(store))); + assert_eq!(h.state().session.prefs().shortcuts["actions.play:Target"], "F2"); + assert_eq!(h.state().session.prefs().alternate_shortcuts["actions.play:Target"], ["F3"]); + assert!(!h.state().session.prefs().shortcuts.values().any(|key| key == "F4")); + press(&mut h, "F2"); + assert_eq!(active_name(&h), "legacy target"); +} + +#[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 +968,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 +977,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 +994,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 +1013,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 +1032,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 +1052,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 c778737997f..bda9fe79fa0 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -241,26 +241,43 @@ 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 { - 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 previous = list[index].action_id.is_none().then(|| (prefs.shortcuts.clone(), prefs.alternate_shortcuts.clone())); + let pending = app.services.preset_store.is_some() && app.session.preset_store.is_none(); + let legacy_owner = !pending && actions_cmds::shortcut_row(list, &legacy) == Some(index); 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() { + // Retain the old key as a fallback if an asynchronous store never commits the ID. + // A live ID-based override shadows it, including an explicit "None" assignment. + for (other, assigned) in &prefs.shortcuts { + if actions_cmds::is_action_key(other) + && other != &id + && assigned == shortcut + && !shortcut.is_empty() + && !(other.starts_with(actions_cmds::PLAY_SHORTCUT_PREFIX) && (pending || (legacy_owner && other == &legacy))) + { set.insert(other.clone(), json!("")); } } 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, "allowUnknown": true, "removeConflicts": false}))?; + if let Err(error) = actions_cmds::commit_action_id(&mut app.session, index, action_id) { + if let Some((shortcuts, alternate_shortcuts)) = previous { + app.session.edit_prefs(|prefs| { + prefs.shortcuts = shortcuts; + prefs.alternate_shortcuts = alternate_shortcuts; + }); + } + let error = error.to_string(); + app.ui.status = error.clone(); + app.ui.status_error = true; + return Err(error); + } + Ok(result) } /// Replay edits synchronously, with view steps handled by the shell in the same order. @@ -333,11 +350,19 @@ fn end_at(c: Called, ran: &mut u64, failed: &mut Option, paused: &mut Opt /// A resumed playback goes on in the action this one called (`inner`, see [`play_owned`]) inside /// this one's playback frame, so its recursion checks still see this caller; the call was step /// `from - 1`. `None` when there is nothing to replay. -fn replay_inner(app: &mut PhotocraftApp, caller: &str, from: usize, inner: &[(String, usize)]) -> Option { - let ((name, child_from), rest) = inner.split_first()?; +fn resume_target(action: &Action, from: usize) -> Value { + let mut params = json!({"action": action.name, "from": from}); + if let Some(id) = actions_cmds::PlaybackTarget::from(action).id { + params["actionId"] = json!(id); + } + params +} + +fn replay_inner(app: &mut PhotocraftApp, caller: &str, from: usize, inner: &[(&Action, usize)]) -> Option { + let ((action, child_from), rest) = inner.split_first()?; let step = from.saturating_sub(1); let target = app.session.active().map(|d| d.doc.id); - Some(match play_owned(app, &json!({"action": name, "from": child_from}), None, rest) { + Some(match play_owned(app, &resume_target(action, *child_from), None, rest) { Ok(value) => called(app, caller, step, "actions.play", &value, target), Err(error) => Called::Failed(json!({"step": step, "id": "actions.play", "error": error})), }) @@ -359,28 +384,26 @@ fn nested_call(id: &str) -> Option { /// and Stop messages. The result is the engine command's, with the branch's `paused` or `stopped`. /// Malformed params go to the engine command, which refuses them with its own error. fn conditional(app: &mut PhotocraftApp, p: &Value) -> Result { - let branch = |key: &str| match p.get(key) { - None | Some(Value::Null) => Some(None), - Some(Value::String(n)) => Some(Some(n.clone()).filter(|n| !n.trim().is_empty())), - Some(_) => None, - }; - let (Some(condition), Some(then), Some(otherwise)) = (p.get("if").and_then(Value::as_str), branch("then"), branch("else")) else { + let (Some(condition), Ok(then), Ok(otherwise)) = + (p.get("if").and_then(Value::as_str), actions_cmds::conditional_branch(p, "then"), actions_cmds::conditional_branch(p, "else")) + else { return app.session.execute("actions.conditional", p.clone()).map_err(|e| e.to_string()); }; let Ok(holds) = photocraft_engine::actions_edit_cmds::evaluate(&app.session, condition) else { return app.session.execute("actions.conditional", p.clone()).map_err(|e| e.to_string()); }; let played = if holds { then } else { otherwise }; - let mut out = json!({"if": condition, "holds": holds, "played": played}); - if let Some(name) = played { - let r = play(app, &json!({"action": name}))?; + let mut out = json!({"if": condition, "holds": holds, "played": played.as_ref().and_then(|p| p.get("action"))}); + if let Some(params) = played { + let r = play(app, ¶ms)?; for key in ["failed", "paused", "stopped"] { if let Some(v) = r.get(key) { out[key] = v.clone(); } } out["ran"] = r.get("ran").cloned().unwrap_or(json!(0)); - out["action"] = json!(name); + out["action"] = r["action"].clone(); + out["played"] = r["action"].clone(); } Ok(out) } @@ -475,7 +498,7 @@ fn pause_recorded_step(app: &mut PhotocraftApp, action: &Action, i: usize, id: & /// back, with that named call journaled, only when the whole call ends. `inner` are the called /// actions a resumed playback replays first, outermost first, each `(action, from)`: the first is /// the one this action's step before `from` called ([`resume`]). -fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option, inner: &[(String, usize)]) -> Result { +fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option, inner: &[(&Action, usize)]) -> Result { let (action, from) = match actions_cmds::playback_plan(&app.session, params) { Ok(plan) => plan, Err(e) => { @@ -495,7 +518,7 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option, let owner = recording .map(|(_, idx)| { let into = app.session.actions.list.get(idx).map(|a| a.name.clone()); - json!({"index": idx, "into": into, "action": action.name, "from": from}) + json!({"index": idx, "into": into, "target": actions_cmds::recorded_target(&app.session, &action, from)}) }) .or(suspended); let mut ran = 0u64; @@ -1136,14 +1159,11 @@ pub const RESUME: &str = "__resumeAction"; /// Resume the recording a paused call suspended and journal that call, once. fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) { let Some(owner) = owner else { return }; - let (Some(idx), Some(into), Some(name)) = ( - owner.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()), - owner.get("into").and_then(Value::as_str), - owner.get("action").and_then(Value::as_str), - ) else { + let (Some(idx), Some(into), Some(params)) = + (owner.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()), owner.get("into").and_then(Value::as_str), owner.get("target")) + else { return; }; - let from = owner.get("from").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).unwrap_or(0); // `suspended_guard` refuses what would move the recorded action, but another command may // still replace the list: the call goes to the action of that name, never to whatever now // sits at the old index, and is dropped if that action is gone. @@ -1152,7 +1172,7 @@ fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) { if let Some(idx) = target && app.session.actions.recording.is_none() { - actions_cmds::restore_recording(&mut app.session, idx, name, from); + actions_cmds::restore_recording(&mut app.session, idx, params.clone()); } } @@ -1240,8 +1260,7 @@ pub(crate) struct PausedPlayback { record: Option, history: Option, /// The actions still to play after this one, as they were when Play started a whole set. - /// Actions have no id, so the whole action stands in for one: an action deleted and made again - /// under the same name, or edited, while the dialog is open no longer matches. + /// The whole action also guards against edits while the dialog is open. then: Vec, /// The steps that Play ran before this pause (earlier actions of the set, and this one's /// steps before the dialog), so the final count covers the whole Play. @@ -1265,8 +1284,7 @@ pub(crate) struct PausedPlayback { /// whose own step runs on confirm. timed: bool, /// The paused action and each of its callers as they were when it paused, innermost first. - /// The continuation goes on by name, so an action edited, deleted or replaced by a new one of - /// the same name meanwhile ends it there instead of playing the new action's tail ([`resume`]). + /// The continuation checks these snapshots before resuming any remaining steps. played: Vec, } @@ -1491,15 +1509,13 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) } let saved = app.session.authorize; let service = if app.automation_input { app.services.automation_authorize } else { None }; + let list = &app.session.actions.list; let remaining = !paused.then.is_empty() || !paused.callers.is_empty() - || app - .session - .actions - .list - .iter() - .find(|action| action.name == paused.action) - .is_some_and(|action| action.enabled_steps().any(|(i, _)| i >= paused.from)); + || paused.played.first().is_some_and(|action| { + let live = actions_cmds::playback_row(list, action).and_then(|row| list.get(row)); + action.enabled_steps().any(|(i, _)| i >= paused.from) || live.is_some_and(|action| action.enabled_steps().any(|(i, _)| i >= paused.from)) + }); let gate = if remaining { continuation_gate(saved, service).and_then(|live| continuation_gate(paused.gate, live)) } else { Ok(saved.or(service).or(paused.gate)) }; let gate = match gate { @@ -1513,11 +1529,8 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) return Err(error); } }; - // The rest plays by name: refuse it when an action of the paused call changed meanwhile, so a - // new action of the same name never plays from the old one's step. With nothing left to play, - // the call simply ends. (Another document coming to the front fails `history.resume` above.) - let list = &app.session.actions.list; - if remaining && paused.played.iter().any(|a| list.iter().find(|b| b.name == a.name) != Some(a)) { + // Verify each live occurrence against the exact definition that paused. + if remaining && paused.played.iter().any(|a| actions_cmds::playback_row(list, a).and_then(|row| list.get(row)) != Some(a)) { let error = "the action changed while it was paused"; actions_cmds::finish_pending_history(&mut app.session); restore_recording(app, owner.as_ref()); @@ -1528,11 +1541,12 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) } // The paused action goes on, then each action that called it, inside its callers' frames: // replay starts at the outermost, which replays the inner ones first. - let frames: Vec<(String, usize)> = paused.callers.iter().rev().cloned().chain(std::iter::once((paused.action.clone(), paused.from))).collect(); + let positions = paused.callers.iter().rev().map(|(_, from)| *from).chain(std::iter::once(paused.from)); + let frames: Vec<_> = paused.played.iter().rev().zip(positions).collect(); let Some(((outer, outer_from), inner)) = frames.split_first() else { return Err("this dialog doesn't belong to a paused action".into()); }; - let params = json!({"action": outer, "from": outer_from}); + let params = resume_target(outer, *outer_from); // A dialog's own step runs on its confirm; a paced wait's step already ran and was counted. let own = u64::from(!paused.timed); app.session.authorize = gate; @@ -1973,27 +1987,29 @@ 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) { +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")); - let current = app.session.prefs().shortcuts.get(&shortcut_id(name)).cloned().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)); - 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); - ui.close(); + { + 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(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, index, &chosen); + ui.close(); + } } + ui.add_enabled_ui(key > 0, |ui| { + 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, index, &photocraft_engine::atn_cmds::function_key_name(key, shift, command)); + } + }); } - ui.add_enabled_ui(key > 0, |ui| { - 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)); - } - }); ui.separator(); ui.menu_button(tl!("Color"), |ui| { for (id, label) in [ @@ -2146,11 +2162,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()) + 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, @@ -2174,7 +2187,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); + 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 ee1acdbeaf1..b872d6fd2b4 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -70,8 +70,13 @@ fn duplicate_selected_physical_folder_keeps_occurrences_and_shortcuts() { .into_iter() .map(|(name, set, slot)| Action { set: Some(set.into()), set_slot: Some(slot), ..Action::new(name, Vec::new()) }) .collect(); + let id = "0123456789abcdef0123456789abcdef"; + app.session.actions.list[1].action_id = Some(id.into()); + app.session.actions.list[1].legacy_shortcut_owner = true; + let occurrence = actions_cmds::occurrence_key(id); app.session.edit_prefs(|prefs| { prefs.shortcuts.insert("actions.play:Chosen".into(), "F2".into()); + prefs.shortcuts.insert(occurrence.clone(), "F3".into()); }); app.ui.actions.selected_set = Some("Same".into()); app.ui.actions.selected_set_slot = Some(1); @@ -92,6 +97,9 @@ fn duplicate_selected_physical_folder_keeps_occurrences_and_shortcuts() { ); assert_eq!(app.session.prefs().shortcuts["actions.play:Chosen"], "F2"); assert!(!app.session.prefs().shortcuts.contains_key("actions.play:Chosen copy")); + assert_eq!(actions_cmds::shortcut_row(&app.session.actions.list, &occurrence), Some(1)); + assert!(app.session.actions.list[2].action_id.is_none()); + assert!(!app.session.actions.list[2].legacy_shortcut_owner); app.ui.actions.selected_set = Some("Same".into()); app.ui.actions.selected_set_slot = Some(3); @@ -108,6 +116,12 @@ fn duplicate_selected_physical_folder_keeps_occurrences_and_shortcuts() { assert_eq!(legacy, json!({"set": "Later copy", "index": 4, "actions": 1})); assert_eq!(app.session.actions.list[4].set_slot, None); assert_eq!(app.session.actions.set_rows.len(), 6); + + let action_copy = app.run("actions.duplicate", json!({"action": 1})).unwrap(); + assert_eq!(action_copy["index"], 2); + assert!(app.session.actions.list[2].action_id.is_none()); + assert!(!app.session.actions.list[2].legacy_shortcut_owner); + assert_eq!(actions_cmds::shortcut_row(&app.session.actions.list, &occurrence), Some(1)); } /// A nested Load can compact same-caption rows before the panel repaints. @@ -609,7 +623,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 { @@ -2285,6 +2299,25 @@ fn pause_child(app: &mut PhotocraftApp) -> u64 { v["paused"]["dialog"].as_u64().unwrap() } +#[test] +fn a_bound_same_name_call_resumes_the_selected_occurrence() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 6, "background": "#203040"})).unwrap(); + let id = "a".repeat(32); + let mut second = + Action::new("Same", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1.5})), ("layer.new.layer".into(), json!({"name":"Suffix"}))]); + second.action_id = Some(id.clone()); + second.dialogs.insert(0); + let first = + Action::new("Same", vec![("actions.play".into(), json!({"action":"Same","actionId":id})), ("layer.new.layer".into(), json!({"name":"caller tail"}))]); + app.session.actions.list.extend([first, second]); + + let playback = play(&mut app, &json!({"action":"Same"})).unwrap(); + let dialog = playback["paused"]["dialog"].as_u64().expect("the selected occurrence's blur dialog"); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert_eq!(layer_names(&app), ["Suffix", "caller tail"]); +} + #[test] fn a_recorded_call_paused_by_a_dialog_records_one_call_and_replays_once() { let mut app = recording_with_dialog_child(); 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 113f8b71934..e7d9ed27075 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);