From e3416ade754eb4ca9a62326b40acc51ad60dce18 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 6 Nov 2026 09:49:55 -0800 Subject: [PATCH 1/4] Preserve Classic Actions undo order and library identities --- crates/engine/src/cmd/actions_cmds.rs | 52 +++++++-- crates/engine/src/cmd/actions_edit_cmds.rs | 24 ++++- .../cmd/actions_edit_cmds/library_commands.rs | 41 ++++++- .../library_commands/tests.rs | 70 ++++++++++++ crates/engine/src/cmd/atn_cmds/files.rs | 11 +- .../src/cmd/atn_cmds/files/replacement.rs | 4 +- crates/engine/src/preset_store.rs | 2 + crates/ui-egui/src/input/shortcut_dispatch.rs | 12 ++- crates/ui-egui/src/input/shortcuts/tests.rs | 4 + crates/ui-egui/src/menus/invoke.rs | 2 +- crates/ui-egui/src/menus/items.rs | 2 +- crates/ui-egui/src/menus/native_menu.rs | 2 +- crates/ui-egui/src/menus/state.rs | 4 +- crates/ui-egui/src/panels/actions.rs | 83 ++++++++------ crates/ui-egui/src/panels/actions/library.rs | 74 ++++++++++--- crates/ui-egui/src/panels/actions/tests.rs | 102 +++++++++++++++++- crates/ui-egui/src/tools/vector_ui.rs | 7 ++ crates/ui-egui/src/transform_undo_tests.rs | 4 + 18 files changed, 422 insertions(+), 78 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index cbf5f017894..ae38d885dc7 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}; @@ -125,6 +125,9 @@ pub struct ActionState { /// Ordered folder occurrences from whole-library commands, including empty and same-name rows. #[serde(skip)] pub set_rows: Vec, + /// Changes when old physical folder positions may name different occurrences. + #[serde(skip)] + pub set_rows_revision: u64, /// The latest destructive panel edit, separate from document History. #[serde(skip)] pub library_undo: Option>, @@ -490,6 +493,7 @@ fn from_step(p: &Value, len: usize) -> Result { Ok(i) } +/// List distinct captions and, when present, the ordered physical occurrences separately. fn list(s: &mut Session, _p: &Value) -> Result { let actions: Vec = s .actions @@ -552,7 +556,7 @@ fn record(s: &mut Session, p: &Value) -> Result { Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), Some(_) => return Err(bad("actions.record", "\"set\" must be a set name or null")), }; - let set_slot = crate::actions_edit_cmds::set_slot(s, p, set.as_deref(), "actions.record")?; + let set_slot = crate::actions_edit_cmds::assignment_slot(s, p, set.as_deref(), "actions.record")?; s.actions.list.push(Action { set, set_slot, ..Action::new(name, Vec::new()) }); s.actions.touch(); s.actions.list.len() - 1 @@ -904,9 +908,10 @@ fn delete(s: &mut Session, p: &Value) -> Result { 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) { + if s.prefs().shortcuts.contains_key(&key) || s.prefs().alternate_shortcuts.contains_key(&key) { s.edit_prefs(|prefs| { prefs.shortcuts.remove(&key); + prefs.alternate_shortcuts.remove(&key); }); } Ok(json!({"deleted": name})) @@ -954,6 +959,35 @@ fn toggle(s: &mut Session, p: &Value) -> Result { /// Prefix of the persisted shortcut override that plays a named action (`actions.play:`). pub const PLAY_SHORTCUT_PREFIX: &str = "actions.play:"; +/// Names whose legacy shortcut key cannot select a particular physical occurrence. +/// Legacy libraries without explicit slots keep their original first-match lookup. +pub fn ambiguous_shortcut_names(list: &[Action]) -> HashSet<&str> { + if !list.iter().any(|action| action.set_slot.is_some()) { + return HashSet::new(); + } + let mut seen = HashMap::new(); + let mut ambiguous = HashSet::new(); + for action in list { + let name = action.name.as_str(); + let slotted = action.set_slot.is_some(); + if seen.insert(name, slotted).is_some_and(|prior| prior || slotted) { + ambiguous.insert(name); + } + } + ambiguous +} + +/// Clear bindings for ambiguous physical occurrences before they could be retargeted. +pub(crate) fn discard_ambiguous_shortcuts(s: &mut Session) { + let ids: HashSet<_> = ambiguous_shortcut_names(&s.actions.list).into_iter().map(|name| format!("{PLAY_SHORTCUT_PREFIX}{name}")).collect(); + if ids.iter().any(|id| s.prefs().shortcuts.contains_key(id) || s.prefs().alternate_shortcuts.contains_key(id)) { + s.edit_prefs(|prefs| { + prefs.shortcuts.retain(|id, _| !ids.contains(id)); + prefs.alternate_shortcuts.retain(|id, _| !ids.contains(id)); + }); + } +} + /// Rename an action in place. Nested `actions.play` steps, named Batch steps and `actions.conditional` branches /// that call it by name, and its function-key binding, follow the new name so nothing silently /// stops working. @@ -978,6 +1012,7 @@ fn rename(s: &mut Session, p: &Value) -> Result { // rename only if it resolved to this action before it, so one reaching the other stays put. let before = s.actions.list.clone(); let by_name = resolve(&before, &json!({"action": old}), "actions.rename").ok() == Some(idx); + let ambiguous_binding = ambiguous_shortcut_names(&before).contains(old.as_str()); let calls = s.actions.list.iter_mut().flat_map(|a| a.steps.iter_mut()).chain(s.journal.iter_mut().skip(pending)); for (id, params) in calls { let keys: &[&str] = match id.as_str() { @@ -999,11 +1034,16 @@ 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 s.prefs().shortcuts.contains_key(&from) || (ambiguous_binding && s.prefs().alternate_shortcuts.contains_key(&from)) { s.edit_prefs(|prefs| { - if let Some(key) = prefs.shortcuts.remove(&from) { + if let Some(key) = prefs.shortcuts.remove(&from) + && !ambiguous_binding + { prefs.shortcuts.insert(to, key); } + if ambiguous_binding { + prefs.alternate_shortcuts.remove(&from); + } }); } Ok(json!({"action": name, "index": idx})) @@ -1124,7 +1164,7 @@ pub fn specs() -> Vec { label: "List Actions", menu: &[], shortcut: None, - params: "{} → {actions:[{name, steps:count, set:name|null}], sets:[name…] (every set in panel order, empty ones too), recording:name|null}", + params: "{} → {actions:[{name, steps:count, set:name|null, setSlot:index?}], sets:[name…] (distinct captions), setRows:[name…]? (ordered physical folders), recording:name|null}", enabled: always, run: list, journal: false, diff --git a/crates/engine/src/cmd/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index 1a55a381a48..5840f045ea4 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -126,11 +126,12 @@ fn assign_set(s: &mut Session, p: &Value) -> Result { let set = match p.get("set") { None | Some(Value::Null) => None, Some(Value::String(n)) if p.get("setSlot").and_then(Value::as_u64).is_some() => Some(n.clone()), + Some(Value::String(n)) if n.trim() != n.as_str() && assignment_slot(s, p, Some(n.as_str()), cmd)?.is_some() => Some(n.clone()), Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), Some(Value::String(_)) => return Err(bad(cmd, "`set` is empty; pass null to take the action out of its set")), Some(_) => return Err(bad(cmd, "`set` must be a name or null")), }; - let slot = set_slot(s, p, set.as_deref(), cmd)?; + let slot = assignment_slot(s, p, set.as_deref(), cmd)?; let action = &mut s.actions.list[idx]; action.set = set; action.set_slot = slot; @@ -139,8 +140,8 @@ fn assign_set(s: &mut Session, p: &Value) -> Result { Ok(result) } -/// Every set name, in the Actions panel's order: the sets of the actions as they first appear, -/// then the empty ones New Set made. +/// Distinct set captions in panel order, including legacy empty sets. +/// Use `actions.list`'s ordered `setRows` for physical folder occurrences. pub fn set_names(s: &Session) -> Vec { let mut seen = std::collections::HashSet::new(); s.actions @@ -163,6 +164,23 @@ pub(crate) fn set_slot(s: &Session, p: &Value, name: Option<&str>, cmd: &str) -> Ok(Some(slot)) } +/// Record or assign by caption alone only when it denotes one explicit occurrence. +/// Explicit null and captions shared with a legacy set keep their name-only semantics. +pub(crate) fn assignment_slot(s: &Session, p: &Value, name: Option<&str>, cmd: &str) -> Result> { + if p.get("setSlot").is_some() { + return set_slot(s, p, name, cmd); + } + let Some(name) = name else { return Ok(None) }; + if s.actions.sets.iter().any(|set| set == name) + || s.actions.list.iter().any(|action| action.set_slot.is_none() && action.set.as_deref() == Some(name)) + { + return Ok(None); + } + let mut matches = s.actions.set_rows.iter().enumerate().filter(|(_, caption)| caption.as_str() == name); + let first = matches.next().map(|(slot, _)| slot); + Ok(if matches.next().is_none() { first } else { None }) +} + /// New Set…: an empty set folder, named `name` or "Set N" (the first number no set has), that New /// Action can record into. fn new_set(s: &mut Session, p: &Value) -> Result { 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 99a92cd0550..7be7a5277dc 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, ambiguous_shortcut_names, not_playing}; use crate::{Result, Session}; use super::bad; @@ -16,9 +16,11 @@ mod tests; type Shortcuts = BTreeMap; type Alternates = BTreeMap>; +/// Snapshot of the definitions and shortcut bindings changed by one library edit. #[derive(Clone, Debug, PartialEq)] pub struct LibraryUndo { label: &'static str, + document_history: Vec<(photocraft_doc::DocId, u64, bool)>, list: Vec, sets: Vec, rows: Vec, @@ -86,7 +88,8 @@ 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. +/// Replace library definitions and remember both shortcut maps for the one-step undo. +/// Append retains unambiguous shortcuts and drops names that no longer identify one action. pub(crate) fn publish_library(s: &mut Session, list: Vec, sets: Vec, rows: Vec, new_shortcuts: Option, label: &'static str) { let shortcuts = action_bindings(&s.prefs().shortcuts); let alternates = action_bindings(&s.prefs().alternate_shortcuts); @@ -95,10 +98,27 @@ pub(crate) fn publish_library(s: &mut Session, list: Vec, sets: Vec (shortcuts.clone(), alternates.clone()), + None => { + let ambiguous = ambiguous_shortcut_names(&list); + let keep = |id: &str| id.strip_prefix(PLAY_SHORTCUT_PREFIX).is_none_or(|name| !ambiguous.contains(name)); + let mut keys = shortcuts.clone(); + let mut alternate_keys = alternates.clone(); + keys.retain(|id, _| keep(id)); + alternate_keys.retain(|id, _| keep(id)); + if keys != shortcuts || alternate_keys != alternates { + replace_bindings(s, keys.clone(), alternate_keys.clone()); + } + (keys, alternate_keys) + } }; + 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 { + st.coalesce = None; + } let undo = LibraryUndo { label, + document_history, list: std::mem::replace(&mut s.actions.list, list), sets: std::mem::replace(&mut s.actions.sets, sets), rows: std::mem::replace(&mut s.actions.set_rows, rows), @@ -107,6 +127,7 @@ pub(crate) fn publish_library(s: &mut Session, list: Vec, sets: Vec Result<&LibraryUndo> { Ok(undo) } +/// Label for Edit Undo when the latest library change precedes no undoable document edit. pub fn undo_library_label(s: &Session) -> Option<&'static str> { - s.actions.library_undo.as_ref()?; - undo_state(s).ok().map(|undo| undo.label) + let undo = undo_state(s).ok()?; + if let Some(st) = s.active().filter(|st| st.history.can_undo()) { + let (_, last_id, was_cleared) = + undo.document_history.iter().find(|(id, _, _)| *id == st.doc.id).copied().unwrap_or((st.doc.id, 0, false)); + let current_id = st.history.row_id(st.history.past_len()).unwrap_or(0); + if current_id > last_id || (st.history.is_cleared() && !was_cleared) { + return None; + } + } + Some(undo.label) } pub(super) fn undo_enabled(s: &Session) -> std::result::Result<(), String> { @@ -167,6 +197,7 @@ pub(super) fn undo(s: &mut Session, _: &Value) -> Result { s.actions.list = undo.list; s.actions.sets = undo.sets; s.actions.set_rows = undo.rows; + s.actions.set_rows_revision = s.actions.set_rows_revision.wrapping_add(1); replace_bindings(s, undo.shortcuts, undo.alternates); s.actions.touch(); Ok(json!({"undone":true})) 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 421128ef517..26c9750969f 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 @@ -101,3 +101,73 @@ fn whole_replace_validates_the_tail_and_keeps_every_set_in_order() { s.execute("actions.undoLibrary", json!({})).unwrap(); assert_eq!(s.actions.list, prior); } + +/// 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(); + s.actions.set_rows = vec!["Exact ".into(), "Shared".into(), "Shared".into(), "Legacy".into()]; + s.actions.sets.push("Legacy".into()); + s.execute("actions.record", json!({"name":"Recorded","set":"Exact "})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].set_slot, Some(0)); + for set in ["Shared", "Legacy"] { + s.execute("actions.assignSet", json!({"action":0,"set":set})).unwrap(); + assert_eq!(s.actions.list[0].set_slot, None); + } + s.execute("actions.assignSet", json!({"action":0,"set":"Exact ","setSlot":null})).unwrap(); + assert_eq!(s.actions.list[0].set_slot, None); + s.execute("actions.assignSet", json!({"action":0,"set":"Exact "})).unwrap(); + assert_eq!(s.actions.list[0].set_slot, Some(0)); +} + +/// Repeated factory actions keep their display names. A name-only shortcut is removed +/// when that name ceases to identify a physical row, and Undo restores the binding. +#[test] +fn repeated_reset_and_store_attachment_do_not_retarget_shortcuts() { + let mut s = Session::new(); + let store = MemBackend::default(); + s.attach_preset_store(open(Box::new(store.clone()))); + s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); + let shortcut = format!("{PLAY_SHORTCUT_PREFIX}Invert Colors"); + s.edit_prefs(|prefs| { + prefs.shortcuts.insert(shortcut.clone(), "F2".into()); + prefs.alternate_shortcuts.insert(shortcut.clone(), vec!["F3".into()]); + }); + s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); + assert!(!s.prefs().shortcuts.contains_key(&shortcut)); + assert!(!s.prefs().alternate_shortcuts.contains_key(&shortcut)); + assert_eq!(s.actions.list.iter().filter(|action| action.name == "Invert Colors").count(), 2); + s.execute("actions.undoLibrary", json!({})).unwrap(); + assert_eq!(s.prefs().shortcuts[&shortcut], "F2"); + assert_eq!(s.prefs().alternate_shortcuts[&shortcut], ["F3"]); + s.sync_preset_store(); + + let mut attached = Session::new(); + attached.actions.list.push(Action::new("Invert Colors", Vec::new())); + attached.edit_prefs(|prefs| { + prefs.shortcuts.insert(shortcut.clone(), "F2".into()); + prefs.alternate_shortcuts.insert(shortcut.clone(), vec!["F3".into()]); + }); + attached.attach_preset_store(open(Box::new(store))); + assert_eq!(attached.actions.list.iter().filter(|action| action.name == "Invert Colors").count(), 2); + assert!(!attached.prefs().shortcuts.contains_key(&shortcut)); + assert!(!attached.prefs().alternate_shortcuts.contains_key(&shortcut)); + assert_eq!(attached.execute("actions.get", json!({"action":"Invert Colors"})).unwrap()["set"], serde_json::Value::Null); +} + +/// 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(); + let mut archive = set("Repeated", Some(("Child", 0))); + let child = Action::new("Child", Vec::new()); + let parent = Action::new("Parent", vec![("actions.play".into(), json!({"action":"Child"}))]); + let (second, _) = crate::atn_cmds::export("Repeated", &[&child, &parent], &[], false).unwrap(); + archive.extend_from_slice(&second[4..]); + s.execute("actions.replace", json!({"confirm":true,"data":photocraft_paint::tile::b64_encode(&archive)})).unwrap(); + assert_eq!(s.actions.list[0].name, "Child"); + assert_ne!(s.actions.list[1].name, "Child"); + assert_eq!(s.actions.list[2].steps[0].1["action"], s.actions.list[1].name.as_str()); +} diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index 6339ad0bbff..b97ca6e30ee 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -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::discard_ambiguous_shortcuts(s); 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; @@ -46,6 +47,9 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { next += usize::from(keep); keep }); + if next != slots.len() { + s.actions.set_rows_revision = s.actions.set_rows_revision.wrapping_add(1); + } for action in &mut s.actions.list { action.set_slot = action.set_slot.and_then(|slot| slots.get(slot).copied().flatten()); } @@ -158,8 +162,11 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { (DEFAULT_SET.to_string(), s.actions.list.iter().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 ambiguous = crate::actions_cmds::ambiguous_shortcut_names(&s.actions.list); + let keys: Vec<(String, String)> = s.prefs().shortcuts.iter().filter_map(|(k, v)| { + let name = k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX)?; + (!ambiguous.contains(name)).then(|| (name.to_string(), v.clone())) + }).collect(); let (bytes, skipped) = export(&set, &actions, &keys, skip).map_err(|e| bad(cmd, e))?; let 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}); diff --git a/crates/engine/src/cmd/atn_cmds/files/replacement.rs b/crates/engine/src/cmd/atn_cmds/files/replacement.rs index c800da38e01..69c577ea358 100644 --- a/crates/engine/src/cmd/atn_cmds/files/replacement.rs +++ b/crates/engine/src/cmd/atn_cmds/files/replacement.rs @@ -68,8 +68,10 @@ impl Replacement { _ => None, } .or_else(|| params.get("set").filter(|value| !value.is_null())); + // An unqualified call in this archive first looks in its original folder. + // Legacy callers outside this import still use their existing name lookup. let renamed = match scope { - None => first.get(name), + None => action.set_slot.and_then(|slot| local.get(&(slot, name.to_string()))).or_else(|| first.get(name)), Some(value) => value.as_str().and_then(|set| { let row = action.set_slot.filter(|_| action.set.as_deref() == Some(set)); row.and_then(|slot| local.get(&(slot, name.to_string()))).or_else(|| scoped.get(&(set.to_string(), name.to_string()))) diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index 260055077f6..8afc5a1087a 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -1187,6 +1187,7 @@ impl Session { lib.sort_by_key(|p| pos.get(&p.name.to_lowercase()).copied().unwrap_or(usize::MAX)); } 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. if self.actions.list.is_empty() && self.actions.sets.is_empty() && self.actions.set_rows.is_empty() && self.actions.library_undo.is_none() { @@ -1214,6 +1215,7 @@ impl Session { self.actions.library_undo = None; self.actions.rev = self.actions.rev.saturating_add(1).max(1); } + crate::actions_cmds::discard_ambiguous_shortcuts(self); self.brush_presets_changed(); self.sync_preset_store(); // A brush remembered from the previous run (or picked before the store loaded) may be diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index dcff8d4d2c0..7e98b6b8005 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -48,7 +48,9 @@ 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 ambiguous = photocraft_engine::actions_cmds::ambiguous_shortcut_names(&app.session.actions.list); + let action_ids: Vec = app.session.actions.list.iter().filter(|a| !ambiguous.contains(a.name.as_str())) + .map(|a| crate::actions::shortcut_id(&a.name)).collect(); let actions = action_ids.iter().map(|id| (id.as_str(), prefs.shortcut(id, None).map(str::to_string))); // 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 @@ -98,6 +100,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 id.strip_prefix(crate::actions::SHORTCUT_PREFIX).is_some_and(|name| ambiguous.contains(name)) { + 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))); @@ -375,8 +380,9 @@ pub fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) { 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 ambiguous = action.is_some_and(|name| photocraft_engine::actions_cmds::ambiguous_shortcut_names(&app.session.actions.list).contains(name)); + let outcome = if ambiguous || !crate::menus::is_enabled(app, command_id) { + let why = if ambiguous { "Multiple Actions use this name".into() } else { disabled_reason(app, command_id) }; let 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; diff --git a/crates/ui-egui/src/input/shortcuts/tests.rs b/crates/ui-egui/src/input/shortcuts/tests.rs index cfb3203f104..bd4c88e076f 100644 --- a/crates/ui-egui/src/input/shortcuts/tests.rs +++ b/crates/ui-egui/src/input/shortcuts/tests.rs @@ -143,6 +143,7 @@ fn pen_custom_undo_binding_and_menu_retract_pending_points() { crate::vector_ui::pen_down(&mut app, x, y, false); crate::vector_ui::pen_up(&mut app); } + app.run("actions.reset", serde_json::json!({"confirm":true,"mode":"append"})).unwrap(); app.session.prefs.edit(|p| p.shortcuts.insert("edit.undo".into(), "Cmd+Shift+Y".into())); let ctx = egui::Context::default(); let press = |app: &mut PhotocraftApp, key: Key, modifiers: Modifiers| { @@ -159,8 +160,11 @@ fn pen_custom_undo_binding_and_menu_retract_pending_points() { press(&mut app, Key::Y, Modifiers::COMMAND | Modifiers::SHIFT); assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 1); assert!(crate::menus::is_enabled(&app, "edit.undo")); + let undo_label = |app: &PhotocraftApp| crate::menus::menu_items(app).into_iter().find(|item| item.id == "edit.undo").unwrap().label; + assert_ne!(undo_label(&app), "Undo Reset Actions"); crate::menus::invoke(&mut app, &ctx, "edit.undo", serde_json::json!({})).unwrap(); assert!(app.ui.pen.is_none()); + assert_eq!(undo_label(&app), "Undo Reset Actions"); } /// A 200×200 document for the ⌘⇧↩ / ⌘⌥↩ tests. diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 6c90424c814..90565f94022 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -99,7 +99,7 @@ fn invoke_early_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, if id == "edit.undo" && crate::vector_ui::pen_undo_last_point(app) { return Some(Ok(Value::Null)); } - if id == "edit.undo" && photocraft_engine::actions_edit_cmds::undo_library_label(&app.session).is_some() { + if id == "edit.undo" && crate::actions::library::edit_undo_label(app).is_some() { return Some(crate::actions::library::undo(app)); } // Image › Crop while the Crop tool has a pending frame commits that frame (#1918). diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index f55df03568e..dff7c452d90 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -241,7 +241,7 @@ pub fn menu_items(app: &PhotocraftApp) -> Vec { item.label = "Release Clipping Mask".into(); item.enabled = is_enabled(app, &item.id); } - if let Some(label) = photocraft_engine::actions_edit_cmds::undo_library_label(&app.session) + if let Some(label) = crate::actions::library::edit_undo_label(app) && let Some(item) = items.iter_mut().find(|item| item.id == "edit.undo") { item.label = label.into(); diff --git a/crates/ui-egui/src/menus/native_menu.rs b/crates/ui-egui/src/menus/native_menu.rs index 1deb857b36d..e6c3663caf0 100644 --- a/crates/ui-egui/src/menus/native_menu.rs +++ b/crates/ui-egui/src/menus/native_menu.rs @@ -755,7 +755,7 @@ pub(crate) fn state_hash(app: &PhotocraftApp, input: Option) -> u64 { s.clipboard.is_some().hash(&mut h); // A running job greys the commands that would change its document. s.has_jobs().hash(&mut h); - photocraft_engine::actions_edit_cmds::undo_library_label(s).hash(&mut h); + (crate::actions::library::edit_undo_label(app), crate::vector_ui::pen_can_undo(app)).hash(&mut h); if let Some(d) = s.active() { (d.doc.id.0, d.revision, d.active_layer.map(|l| l.0), d.selected_layers.len(), d.isolated_layers.len()).hash(&mut h); } diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 18b8695b52f..31637420543 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -13,10 +13,10 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { return crate::symmetry_ui::can_transform(app); } // Draft Pen points can be undone even when the document has no History entries. - if id == "edit.undo" && app.ui.pen.as_ref().is_some_and(|pen| !pen.knots.is_empty()) { + if id == "edit.undo" && crate::vector_ui::pen_can_undo(app) { return true; } - if id == "edit.undo" && photocraft_engine::actions_edit_cmds::undo_library_label(&app.session).is_some() { + if id == "edit.undo" && crate::actions::library::edit_undo_label(app).is_some() { return true; } // Photoshop greys these for the Background layer, other layer kinds or single-layer documents. diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 34b6fa7d809..7e6b4ab7410 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -23,6 +23,7 @@ pub(crate) fn library_selection_changed(app: &mut PhotocraftApp) { ui.selected_step = None; ui.selected_set = None; ui.selected_set_slot = None; + ui.slot_revision = app.session.actions.set_rows_revision; ui.collapsed_set_slots.clear(); ui.expanded.clear(); ui.renaming = None; @@ -33,6 +34,7 @@ pub(crate) fn library_slots_changed(app: &mut PhotocraftApp) { if app.ui.actions.selected_set_slot.take().is_some() { app.ui.actions.selected_set = None; } + app.ui.actions.slot_revision = app.session.actions.set_rows_revision; app.ui.actions.collapsed_set_slots.clear(); } @@ -56,6 +58,8 @@ pub struct ActionsUi { #[serde(skip)] selected_set_slot: Option, #[serde(skip)] + slot_revision: u64, + #[serde(skip)] collapsed_set_slots: Vec, #[serde(skip)] reveal_recording: Option<(usize, usize)>, @@ -123,7 +127,9 @@ fn selected_set(app: &PhotocraftApp) -> Option<&str> { } let set = app.ui.actions.selected_set.as_deref()?; if let Some(slot) = app.ui.actions.selected_set_slot { - return (app.session.actions.set_rows.get(slot).map(String::as_str) == Some(set)).then_some(set); + return (app.ui.actions.slot_revision == app.session.actions.set_rows_revision + && app.session.actions.set_rows.get(slot).map(String::as_str) == Some(set)) + .then_some(set); } photocraft_engine::actions_edit_cmds::set_names(&app.session).iter().any(|n| n == set).then_some(set) } @@ -144,7 +150,8 @@ fn selected_set_actions(app: &PhotocraftApp) -> Vec { /// What Play plays: the selected action; with a set folder selected, every action of that set in /// order, as Photoshop plays a selected set (nothing for an empty set); else the first action. fn playback_targets(app: &PhotocraftApp) -> Vec { - if selected_set(app).is_some() { + // A stale physical selection must not play the first unrelated action before repaint. + if app.ui.actions.selected_set_slot.is_some() || selected_set(app).is_some() { return selected_set_actions(app); } playback_selection(app).into_iter().collect() @@ -227,6 +234,9 @@ pub(crate) fn shortcut_id(name: &str) -> String { } pub(crate) fn assign_shortcut(app: &mut PhotocraftApp, name: &str, shortcut: &str) -> Result { + if actions_cmds::ambiguous_shortcut_names(&app.session.actions.list).contains(name) { + return Err(tl!("Rename the action before assigning it a shortcut.").into()); + } let id = shortcut_id(name); let mut set = serde_json::Map::new(); // A function key belongs to only one action. Ordinary menu bindings remain @@ -1548,7 +1558,7 @@ struct DragRow { } /// Drops use an insertion line, converted to the final index expected by actions.move. -fn drag_row(ui: &egui::Ui, response: &egui::Response, row: DragRow, t: &Tokens) -> Option<(DragRow, usize)> { +fn drag_row(ui: &egui::Ui, response: &egui::Response, row: DragRow, t: &Tokens) -> Option<(DragRow, usize, usize)> { response.dnd_set_drag_payload(row); let source = response.dnd_hover_payload::()?; if source.step.is_some() != row.step.is_some() || (source.step.is_some() && source.action != row.action) { @@ -1561,10 +1571,12 @@ fn drag_row(ui: &egui::Ui, response: &egui::Response, row: DragRow, t: &Tokens) let to = if from < slot { slot.saturating_sub(1) } else { slot }; let y = if after { response.rect.bottom() } else { response.rect.top() }; ui.painter().line_segment([pos2(response.rect.left() + 22.0, y), pos2(response.rect.right(), y)], Stroke::new(2.0, t.accent)); - response.dnd_release_payload::().map(|source| (*source, to)) + response.dnd_release_payload::().map(|source| (*source, to, row.action)) } -fn move_row(app: &mut PhotocraftApp, source: DragRow, to: usize) { +fn move_row(app: &mut PhotocraftApp, source: DragRow, to: usize, target: usize) { + let Some(target) = app.session.actions.list.get(target) else { return }; + let (set, slot) = (target.set.clone(), target.set_slot); let mut params = json!({"action": source.action, "to": to}); if let Some(step) = source.step { params["step"] = json!(step); @@ -1581,12 +1593,8 @@ fn move_row(app: &mut PhotocraftApp, source: DragRow, to: usize) { app.ui.actions.expanded.insert(to, expanded); } app.ui.actions.select(to, None); - // Dropped among another set's actions: the action joins that set (the row above wins). - let list = &app.session.actions.list; - let neighbour = to.checked_sub(1).and_then(|j| list.get(j)).or_else(|| list.get(to + 1)); - let set = neighbour.and_then(|a| a.set.clone()); - let slot = neighbour.and_then(|a| a.set_slot); - if list.get(to).is_some_and(|a| a.set != set || a.set_slot != slot) { + // The displayed target owns the drop even when raw list positions interleave folders. + if app.session.actions.list.get(to).is_some_and(|a| a.set != set || a.set_slot != slot) { let _ = app.run("actions.assignSet", json!({"action": to, "set": set, "setSlot": slot})); } } @@ -1755,26 +1763,31 @@ 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, name: &str, swatch: &str, ambiguous: bool) { 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(); - } + if ambiguous { + ui.label(tl!("Rename the action before assigning it a shortcut.")); } - 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.add_enabled_ui(!ambiguous, |ui| { + 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(); + } } + 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| { @@ -1798,8 +1811,13 @@ fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index } pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + if app.ui.actions.slot_revision != app.session.actions.set_rows_revision { + library_slots_changed(app); + } let t = Tokens::get(ui.ctx()); let recording = app.session.actions.recording; + let ambiguous: std::collections::HashSet = actions_cmds::ambiguous_shortcut_names(&app.session.actions.list) + .into_iter().map(str::to_string).collect(); let rows: Vec = app .session .actions @@ -1929,7 +1947,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { .prefs() .shortcuts .get(&shortcut_id(name)) - .filter(|s| !s.is_empty()) + .filter(|s| !s.is_empty() && !ambiguous.contains(name.as_str())) .map_or_else(|| step_count(nsteps, disabled.len()), |key| format!("{key} · {}", step_count(nsteps, disabled.len()))), egui::FontId::proportional(11.0), t.text_faint, @@ -1953,7 +1971,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, name, swatch, ambiguous.contains(name.as_str())); 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)) { @@ -1984,6 +2002,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.actions.selected_step = None; app.ui.actions.selected_set = Some(set.name.clone()); app.ui.actions.selected_set_slot = set.slot; + app.ui.actions.slot_revision = app.session.actions.set_rows_revision; } // The disclosure triangle collapses or expands the set and leaves the selection alone. if toggle { @@ -2010,8 +2029,8 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some((index, name)) = renamed { rename_action(app, index, name); } - if let Some((source, to)) = moved { - move_row(app, source, to); + if let Some((source, to, target)) = moved { + move_row(app, source, to, target); } ui.add_space(4.0); ui.horizontal(|ui| { @@ -2102,7 +2121,7 @@ struct StepRowsContext<'a> { #[derive(Default)] struct StepRowEvents { - moved: Option<(DragRow, usize)>, + moved: Option<(DragRow, usize, usize)>, toggled: Option<(usize, usize)>, dialog_toggled: Option<(usize, usize)>, } diff --git a/crates/ui-egui/src/panels/actions/library.rs b/crates/ui-egui/src/panels/actions/library.rs index 8486546143d..4acd1159bc0 100644 --- a/crates/ui-egui/src/panels/actions/library.rs +++ b/crates/ui-egui/src/panels/actions/library.rs @@ -36,22 +36,32 @@ impl Kind { } } +/// The revision, authorization, and chosen payload a pending confirmation may use. pub(crate) struct Held { id: u64, kind: Kind, revision: u64, gate: Option, automated: bool, - replace_data: Option<(String, usize, String)>, + replace_data: Option, append: bool, accept: bool, choice_append: bool, } +struct Replacement { + name: String, + count: usize, + params: Value, + path: Option, +} + +/// Identify dialogs owned by the Classic Actions library controller. pub(crate) fn owns(fields: &Map) -> bool { fields.contains_key(MARK) } +/// Refuse library edits while its store, recording, or playback owns the definitions. pub(crate) fn idle(app: &PhotocraftApp, command: &str) -> Result<(), String> { super::suspended_guard(app, command)?; if app.services.preset_store.is_some() { @@ -63,8 +73,14 @@ pub(crate) fn idle(app: &PhotocraftApp, command: &str) -> Result<(), String> { Ok(()) } +fn effective_gate(app: &PhotocraftApp, captured: Option, automated: bool) -> Result, String> { + let service = if automated || app.automation_input { app.services.automation_authorize } else { None }; + let live = super::continuation_gate(app.session.authorize, service)?; + super::continuation_gate(captured, live) +} + fn authorize(app: &PhotocraftApp, command: &str, params: &Value, gate: Option, automated: bool) -> Result<(), String> { - let gate = super::continuation_gate(gate, app.session.authorize)?; + let gate = effective_gate(app, gate, automated)?; if let Some(gate) = gate { gate(command, params).map_err(|error| error.to_string())?; } @@ -76,6 +92,7 @@ fn authorize(app: &PhotocraftApp, command: &str, params: &Value, gate: Option Result { let command = kind.command(); idle(app, command)?; @@ -83,8 +100,8 @@ pub(super) fn open(app: &mut PhotocraftApp, kind: Kind) -> Result return Err(tl!("Confirm or cancel the pending Actions library change first.").into()); } let revision = app.session.actions.rev; - let gate = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None }); - let automated = app.automation_input || gate.is_some(); + let automated = app.automation_input; + let gate = effective_gate(app, None, automated)?; let authorize = |params: &Value| self::authorize(app, command, params, gate, automated); let mut held = Held { id: 0, kind, revision, gate, automated, replace_data: None, append: false, accept: true, choice_append: false }; if kind == Kind::Reset { @@ -94,7 +111,7 @@ pub(super) fn open(app: &mut PhotocraftApp, kind: Kind) -> Result if !held.append { replace?; } - } else { + } else if kind == Kind::Clear { authorize(&json!({"confirm":true}))?; } if kind != Kind::Replace { @@ -105,22 +122,23 @@ pub(super) fn open(app: &mut PhotocraftApp, kind: Kind) -> Result if app.session.actions.rev != revision || app.held_actions_library.is_some() { return Err(tl!("The actions changed. Request Replace Actions again.").into()); } - let (name, bytes) = match answer { + let (name, bytes, path) = match answer { FileDialogAnswer::Paths(paths) => { let path = paths.into_iter().next().ok_or("cancelled")?; self::authorize(app, command, &json!({"confirm":true,"path":path}), gate, automated)?; let bytes = photocraft_format::read_file_limited(std::path::Path::new(&path), MAX_PICKED_BYTES).map_err(|error| format!("{path}: {error}"))?; - (path, bytes) + (crate::file_open::display_name(&path), bytes, Some(path)) } - FileDialogAnswer::Contents(name, bytes) => (name, bytes), + FileDialogAnswer::Contents(name, bytes) => (crate::file_open::display_name(&name), bytes, None), _ => return Err(tl!("Choose one Actions file.").into()), }; if bytes.len() as u64 > MAX_PICKED_BYTES { return Err(tl!("The Actions file is too large.").into()); } + let params = json!({"confirm":true,"data":photocraft_engine::paint::tile::b64_encode(&bytes)}); + self::authorize(app, command, ¶ms, gate, automated)?; let count = photocraft_engine::atn_cmds::validate_replacement(&bytes)?; - let data = photocraft_engine::paint::tile::b64_encode(&bytes); - held.replace_data = Some((crate::file_open::display_name(&name), count, data)); + held.replace_data = Some(Replacement { name, count, params, path }); Ok(prompt(app, held)) }) } @@ -135,11 +153,15 @@ fn prompt(app: &mut PhotocraftApp, mut held: Held) -> Value { json!({"dialog":id}) } +/// Draw the warning for the exact held library edit. pub(crate) fn body(app: &PhotocraftApp, ui: &mut egui::Ui, id: u64) { let Some(held) = app.held_actions_library.as_ref().filter(|held| held.id == id) else { return }; match &held.replace_data { - Some((name, count, _)) => { - ui.label(crate::i18n::fmt(tl!("Replace all actions with {count} actions from {file}?"), &[("count", &count.to_string()), ("file", name)])); + Some(replacement) => { + ui.label(crate::i18n::fmt( + tl!("Replace all actions with {count} actions from {file}?"), + &[("count", &replacement.count.to_string()), ("file", &replacement.name)], + )); } None if held.kind == Kind::Reset => { ui.label(tl!("Replace the current actions?")); @@ -150,10 +172,12 @@ pub(crate) fn body(app: &PhotocraftApp, ui: &mut egui::Ui, id: u64) { } } +/// Whether OK is available for this still-owned dialog. pub(crate) fn can_confirm(app: &PhotocraftApp, id: u64) -> bool { app.held_actions_library.as_ref().is_some_and(|held| held.id == id && held.accept) } +/// Draw the destructive choices and retain which Reset button was pressed. pub(crate) fn buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: u64) -> Option { let held = app.held_actions_library.as_mut().filter(|held| held.id == id)?; let ok = DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0).enabled(held.accept); @@ -167,6 +191,7 @@ pub(crate) fn buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: u64) -> Op clicked } +/// Recheck the held source and payload against the current authorization before dispatch. pub(crate) fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { if !app.held_actions_library.as_ref().is_some_and(|held| held.id == id) { return Err(tl!("No Actions library change belongs to this dialog.").into()); @@ -186,26 +211,41 @@ pub(crate) fn confirm(app: &mut PhotocraftApp, id: u64) -> Result json!({"confirm":true,"mode":if held.choice_append { "append" } else { "replace" }}) } Kind::Replace => { - let (_, _, data) = held.replace_data.ok_or("missing validated Actions file")?; - let mut params = json!({"confirm":true}); - params["data"] = Value::String(data); - params + let replacement = held.replace_data.ok_or("missing validated Actions file")?; + if let Some(path) = replacement.path { + authorize(app, command, &json!({"confirm":true,"path":path}), held.gate, held.automated)?; + } + replacement.params } }; authorize(app, command, ¶ms, held.gate, held.automated)?; let saved = app.session.authorize; - app.session.authorize = super::continuation_gate(held.gate, saved)?; + app.session.authorize = effective_gate(app, held.gate, held.automated)?; let result = app.run(command, params); app.session.authorize = saved; result } +/// Discard only the matching dialog's held edit. pub(crate) fn cancel(app: &mut PhotocraftApp, id: u64) { if app.held_actions_library.as_ref().is_some_and(|held| held.id == id) { app.held_actions_library = None; } } +/// The library label is shown only when Edit Undo will reach the library. +pub(crate) fn edit_undo_label(app: &PhotocraftApp) -> Option<&'static str> { + if crate::vector_ui::pen_can_undo(app) + || crate::transform_tool::is_enabled(app, "edit.undo").is_some() + || crate::crop_ui::is_enabled(app, "edit.undo").is_some() + || idle(app, "actions.undoLibrary").is_err() + { + return None; + } + photocraft_engine::actions_edit_cmds::undo_library_label(&app.session) +} + +/// Route an eligible Edit Undo through normal command authorization. pub(crate) fn undo(app: &mut PhotocraftApp) -> Result { app.run("actions.undoLibrary", json!({})) } diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index c9925aa6bd5..f435b20a49c 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -19,6 +19,13 @@ fn library_dialog_cancel_stale_and_undo_leave_document_history_untouched() { crate::dialogs::confirm(&mut app, id).unwrap(); assert!(app.session.actions.sets.is_empty()); let ctx = egui::Context::default(); + assert_eq!(library::edit_undo_label(&app), Some("Undo Clear All Actions")); + app.run("layer.new.layer", json!({})).unwrap(); + assert!(library::edit_undo_label(&app).is_none()); + crate::menus::invoke(&mut app, &ctx, "edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().history.past_len(), history); + assert!(app.session.actions.sets.is_empty(), "the newer document edit was undone first"); + assert_eq!(library::edit_undo_label(&app), Some("Undo Clear All Actions")); crate::menus::invoke(&mut app, &ctx, "edit.undo", json!({})).unwrap(); assert_eq!(app.session.actions.sets, ["Keep", "Newer"]); assert_eq!(app.session.active().unwrap().history.past_len(), history); @@ -50,8 +57,18 @@ fn repeated_factory_rows_select_and_play_independently() { assert!(matches!(&displayed[3], PanelRow::Set(Folder { slot: Some(1), .. }, 2))); app.ui.actions.selected_set = Some("PhotoCraft Basics".into()); app.ui.actions.selected_set_slot = Some(1); + app.ui.actions.slot_revision = app.session.actions.set_rows_revision; assert_eq!(playback_targets(&app), [2, 3]); assert_eq!(new_action_set(&app).unwrap().slot, Some(1)); + + // An older or manually edited preferences file can still contain a name-only key. + let id = shortcut_id("Invert Colors"); + app.session.edit_prefs(|prefs| { + prefs.shortcuts.insert(id.clone(), "F2".into()); + prefs.alternate_shortcuts.insert(id.clone(), vec!["F3".into()]); + }); + assert!(!crate::shortcut_dispatch::bindings(&app).iter().any(|(bound, _)| bound == &id)); + assert!(assign_shortcut(&mut app, "Invert Colors", "F4").is_err()); } #[test] @@ -1832,13 +1849,13 @@ fn moving_an_action_next_to_another_set_joins_it() { app.session.actions.list.push(b); app.session.actions.list.push(Action::new("C", vec![])); // C dropped below B: it joins B's set, "Two". - move_row(&mut app, DragRow { action: 2, step: None }, 2); + move_row(&mut app, DragRow { action: 2, step: None }, 2, 1); assert_eq!(app.session.actions.list[2].set.as_deref(), Some("Two")); // B dropped to the top, above A: the row below decides when there is none above. - move_row(&mut app, DragRow { action: 1, step: None }, 0); + move_row(&mut app, DragRow { action: 1, step: None }, 0, 0); assert_eq!((app.session.actions.list[0].name.as_str(), app.session.actions.list[0].set.as_deref()), ("B", Some("One"))); - // C dropped between A (One) and nothing: the row above wins. - move_row(&mut app, DragRow { action: 2, step: None }, 2); + // C dropped below the displayed A row: it joins A's set. + move_row(&mut app, DragRow { action: 2, step: None }, 2, 1); assert_eq!((app.session.actions.list[2].name.as_str(), app.session.actions.list[2].set.as_deref()), ("C", Some("One"))); } @@ -2989,3 +3006,80 @@ fn bulk_load_summary_counts_unsupported_steps_of_surviving_sets() { assert_eq!(names, ["A", "B"]); assert!(app.session.actions.list[0].steps.iter().any(|(id, _)| id == "actions.photoshopStep")); } + +/// Source-dependent policies can open the picker, refuse a path before reading it, and +/// withdraw authorization between validating an allowed payload and confirming it. +#[test] +fn replace_picker_checks_selected_source_and_rechecks_payload_on_confirm() { + use crate::file_dialog::{FileDialogAnswer, fake}; + use std::{cell::Cell, rc::Rc}; + let (file_dialog, _) = fake(vec![ + Some(FileDialogAnswer::Paths(vec!["blocked-actions.atn".into()])), + Some(FileDialogAnswer::Contents("replacement.atn".into(), action_set_bytes("Replacement", "Invert"))), + ]); + let permit_data = Rc::new(Cell::new(true)); + let policy = Rc::clone(&permit_data); + let automation_command = Box::new(move |id: &str, p: &Value| -> Result<(), String> { + if id != "actions.replace" { + return Ok(()); + } + if p.get("path").is_some() { + return Err("path denied by policy".into()); + } + if p.get("data").is_some() && policy.get() { + Ok(()) + } else { + Err("payload denied by policy".into()) + } + }); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { + file_dialog: Some(file_dialog), automation_command: Some(automation_command), ..Default::default() + }); + app.run("actions.newSet", json!({"name":"Keep"})).unwrap(); + let ctx = egui::Context::default(); + for attempt in 0..2 { + app.automation_input = true; + assert!(library::open(&mut app, library::Kind::Replace).is_ok()); + app.automation_input = false; + app.poll_file_dialog(&ctx, None); + app.poll_file_dialog(&ctx, None); + if attempt == 0 { + assert!(app.ui.status.contains("path denied by policy"), "{}", app.ui.status); + assert!(app.held_actions_library.is_none()); + } + } + let dialog = app.ui.dialogs.iter().find(|dialog| library::owns(&dialog.fields)).unwrap().id; + permit_data.set(false); + assert!(crate::dialogs::confirm(&mut app, dialog).is_err()); + assert_eq!(app.session.actions.sets, ["Keep"]); + assert!(app.session.actions.set_rows.is_empty()); +} + +/// A nested Load may compact slots without going through the app's top-level Load hook. +#[test] +fn stale_same_caption_selection_does_not_follow_a_compacted_slot() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.actions.set_rows = vec!["Remove".into(), "Same".into(), "Same".into()]; + app.ui.actions.selected_set = Some("Same".into()); + app.ui.actions.selected_set_slot = Some(1); + assert_eq!(selected_set(&app), Some("Same")); + let archive = action_set_bytes("Remove", "Loaded"); + app.session.execute("actions.load", json!({"data":photocraft_engine::paint::tile::b64_encode(&archive)})).unwrap(); + assert_eq!(app.session.actions.set_rows[1], "Same"); + assert!(selected_set(&app).is_none()); + assert!(playback_targets(&app).is_empty()); +} + +/// An insertion line at the end of a displayed occurrence keeps that target's membership +/// even when a different same-caption occurrence is immediately above it in the raw list. +#[test] +fn dragging_uses_the_displayed_folder_occurrence() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.actions.set_rows = vec!["Same".into(), "Same".into()]; + app.session.actions.list = [("A", 0), ("B", 1), ("C", 0)].into_iter().map(|(name, slot)| { + Action { set: Some("Same".into()), set_slot: Some(slot), ..Action::new(name, Vec::new()) } + }).collect(); + move_row(&mut app, DragRow { action: 0, step: None }, 1, 2); + assert_eq!(app.session.actions.list[1].name, "A"); + assert_eq!(app.session.actions.list[1].set_slot, Some(0)); +} diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 0749b874340..134e475ed73 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -287,6 +287,13 @@ use path_ops::{selected_document_geometry, targeted_vector_mask_id}; pub(crate) use pen::{finish_pen_if_left, freeform_finish_owned}; use shapes::{fill_param, stroke_param}; +/// Whether Edit Undo currently belongs to a live Pen draft. +pub(crate) fn pen_can_undo(app: &PhotocraftApp) -> bool { + app.ui.pen.as_ref().is_some_and(|pen| { + pen.owner.as_ref().is_some_and(|owner| owner.valid(app)) && (!pen.knots.is_empty() || pen.resumes.is_some()) + }) +} + /// Commit a valid source-owned draft on a tab switch; otherwise cancel with an actionable diagnostic. pub(crate) fn cancel_stale_pen(app: &mut PhotocraftApp) -> bool { let Some(pen) = app.ui.pen.as_ref() else { return false }; diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rs index b863eb8fffa..a4a4aafd324 100644 --- a/crates/ui-egui/src/transform_undo_tests.rs +++ b/crates/ui-egui/src/transform_undo_tests.rs @@ -117,6 +117,7 @@ fn free_transform_starts_where_the_selected_pixels_were_moved() { #[test] fn undo_steps_back_through_the_transform_not_the_document() { let mut h = harness(); + h.state_mut().run("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); let steps = history(&h); begin(&mut h); let q0 = quad(&h); @@ -153,6 +154,9 @@ fn undo_steps_back_through_the_transform_not_the_document() { // Outside the transform, ⌘Z is the document's Undo again. key(&mut h, Modifiers::COMMAND, Key::Z); assert_eq!(width(&h), 100, "the committed transform is undone"); + assert_eq!(h.state().session.actions.set_rows.len(), 1); + key(&mut h, Modifiers::COMMAND, Key::Z); + assert!(h.state().session.actions.set_rows.is_empty(), "the preceding library edit is next"); } /// `engine.execute` over the control channel (and MCP, which goes through it) as a programmatic From 19722cf5a4c4ea03ee33eb4e284e7806fd3dc67e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 6 Nov 2026 10:07:32 -0800 Subject: [PATCH 2/4] Keep Actions shortcuts bound to their rows --- Cargo.lock | 3 + crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/actions_cmds.rs | 52 ++++--- .../engine/src/cmd/actions_cmds/identity.rs | 133 ++++++++++++++++++ .../cmd/actions_edit_cmds/library_commands.rs | 51 ++++--- .../library_commands/tests.rs | 67 +++++++-- crates/engine/src/cmd/atn_cmds/convert.rs | 41 ++++-- crates/engine/src/cmd/atn_cmds/files.rs | 35 ++--- .../src/cmd/atn_cmds/files/replacement.rs | 2 +- crates/engine/src/preset_store.rs | 1 + crates/engine/src/shortcut_sets.rs | 2 +- crates/ui-egui/src/input/shortcut_dispatch.rs | 33 +++-- .../src/input/shortcut_dispatch/tests.rs | 89 ++++++++++-- crates/ui-egui/src/panels/actions.rs | 70 +++++---- crates/ui-egui/src/panels/actions/tests.rs | 31 ++-- .../src/prefs/prefs_ui/shortcut_set_tests.rs | 4 +- 16 files changed, 442 insertions(+), 173 deletions(-) create mode 100644 crates/engine/src/cmd/actions_cmds/identity.rs diff --git a/Cargo.lock b/Cargo.lock index dc725c05f31..c724b246937 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2658,9 +2658,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 5.3.0", "wasip2", + "wasm-bindgen", ] [[package]] @@ -5312,6 +5314,7 @@ dependencies = [ "craft-print", "exr", "flate2", + "getrandom 0.3.4", "photocraft-affinity", "photocraft-algo", "photocraft-cms", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 6d6700dc91f..f97d38fbfee 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -36,6 +36,7 @@ base64 = "0.22" blake3 = { version = "1.8", default-features = false, features = ["pure"] } photocraft-codecs = { workspace = true } flate2 = { workspace = true } +getrandom = { workspace = true, features = ["wasm_js"] } craft-print = { workspace = true } # Photoshop `.kys` shortcut sets (`edit.keyboardShortcuts` `importKys`); already in the tree diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index ae38d885dc7..cf11a43f7ac 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -24,9 +24,12 @@ use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; mod history; +mod identity; pub(crate) use history::ActionHistory; pub use history::{ActionHistoryContinuation, finish_pending_history, suspend_history}; pub(crate) use history::{before_edit as before_action_edit, begin_document_history, finish_document_history, history_rows, reconcile_history_removal}; +pub use identity::{action_shortcut, commit_action_id, is_action_key, occurrence_key, prepare_action_id, shortcut_row}; +pub(crate) use identity::{invalidate_duplicate_ids, pin_shortcut, remove_shortcuts}; fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } @@ -37,6 +40,9 @@ fn bad(cmd: &str, msg: impl Into) -> EngineError { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Action { pub name: String, + /// Stable identity for occurrence shortcuts and stored calls. Legacy rows have no ID. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub action_id: Option, #[serde(default)] pub steps: Vec<(String, Value)>, /// Indices of steps excluded from playback (unchecked in the Actions panel). @@ -64,7 +70,7 @@ pub const BUTTON_COLORS: [&str; 8] = ["", "red", "orange", "yellow", "green", "b impl Action { pub fn new(name: impl Into, steps: Vec<(String, Value)>) -> Self { - Self { name: name.into(), steps, disabled: BTreeSet::new(), dialogs: BTreeSet::new(), set: None, set_slot: None, color: String::new() } + Self { name: name.into(), action_id: None, steps, disabled: BTreeSet::new(), dialogs: BTreeSet::new(), set: None, set_slot: None, color: String::new() } } /// Apply `f` to every per-step index set (`disabled`, `dialogs`) after steps moved. @@ -278,7 +284,13 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> { if s.actions.playing > 0 && s.actions.playback_stack.is_empty() { return Err(bad("actions.play", "an action is already playing")); } - let idx = resolve(&s.actions.list, p, "actions.play")?; + let idx = match p.get("actionId") { + Some(id) => id + .as_str() + .and_then(|id| identity::resolve_action_id(&s.actions.list, id)) + .ok_or_else(|| bad("actions.play", "invalid, missing, or duplicate action ID"))?, + None => resolve(&s.actions.list, p, "actions.play")?, + }; let action = s.actions.list.get(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?; if s.actions.playback_stack.iter().any(|name| name == &action.name) || s.actions.recording.is_some_and(|(_, i)| i == idx) { return Err(bad("actions.play", format!("recursive action call to `{}`", action.name))); @@ -848,6 +860,20 @@ fn move_item(s: &mut Session, p: &Value) -> Result { if to >= s.actions.list.len() { return Err(bad("actions.move", "destination is out of range")); } + let name = &s.actions.list[idx].name; + let first = s.actions.list.iter().position(|action| &action.name == name).unwrap_or(idx); + let changes_owner = if first == idx { to > idx && s.actions.list[idx + 1..=to].iter().any(|action| &action.name == name) } else { to <= first }; + if changes_owner { + let mut shortcuts = s.prefs().shortcuts.clone(); + let mut alternates = s.prefs().alternate_shortcuts.clone(); + pin_shortcut(&mut s.actions.list, first, &mut shortcuts, &mut alternates)?; + if shortcuts != s.prefs().shortcuts || alternates != s.prefs().alternate_shortcuts { + s.edit_prefs(|prefs| { + prefs.shortcuts = shortcuts; + prefs.alternate_shortcuts = alternates; + }); + } + } let moved = s.actions.list.remove(idx); let result = json!({"action": moved.name, "index": to}); s.actions.list.insert(to, moved); @@ -904,16 +930,9 @@ fn delete(s: &mut Session, p: &Value) -> Result { if s.actions.recording.is_some() { return Err(bad("actions.delete", "stop recording before deleting an action")); } + remove_shortcuts(s, |row, _| row == idx); let name = s.actions.list.remove(idx).name; s.actions.touch(); - // Its function key goes with it, or the next action given the same name would inherit it. - let key = format!("{PLAY_SHORTCUT_PREFIX}{name}"); - if s.prefs().shortcuts.contains_key(&key) || s.prefs().alternate_shortcuts.contains_key(&key) { - s.edit_prefs(|prefs| { - prefs.shortcuts.remove(&key); - prefs.alternate_shortcuts.remove(&key); - }); - } Ok(json!({"deleted": name})) } @@ -1012,7 +1031,6 @@ fn rename(s: &mut Session, p: &Value) -> Result { // rename only if it resolved to this action before it, so one reaching the other stays put. let before = s.actions.list.clone(); let by_name = resolve(&before, &json!({"action": old}), "actions.rename").ok() == Some(idx); - let ambiguous_binding = ambiguous_shortcut_names(&before).contains(old.as_str()); let calls = s.actions.list.iter_mut().flat_map(|a| a.steps.iter_mut()).chain(s.journal.iter_mut().skip(pending)); for (id, params) in calls { let keys: &[&str] = match id.as_str() { @@ -1034,15 +1052,13 @@ fn rename(s: &mut Session, p: &Value) -> Result { } s.actions.touch(); let (from, to) = (format!("{PLAY_SHORTCUT_PREFIX}{old}"), format!("{PLAY_SHORTCUT_PREFIX}{name}")); - if s.prefs().shortcuts.contains_key(&from) || (ambiguous_binding && s.prefs().alternate_shortcuts.contains_key(&from)) { + if by_name && (s.prefs().shortcuts.contains_key(&from) || s.prefs().alternate_shortcuts.contains_key(&from)) { s.edit_prefs(|prefs| { - if let Some(key) = prefs.shortcuts.remove(&from) - && !ambiguous_binding - { - prefs.shortcuts.insert(to, key); + if let Some(key) = prefs.shortcuts.remove(&from) { + prefs.shortcuts.insert(to.clone(), key); } - if ambiguous_binding { - prefs.alternate_shortcuts.remove(&from); + if let Some(keys) = prefs.alternate_shortcuts.remove(&from) { + prefs.alternate_shortcuts.insert(to, keys); } }); } diff --git a/crates/engine/src/cmd/actions_cmds/identity.rs b/crates/engine/src/cmd/actions_cmds/identity.rs new file mode 100644 index 00000000000..02acc136933 --- /dev/null +++ b/crates/engine/src/cmd/actions_cmds/identity.rs @@ -0,0 +1,133 @@ +//! Persisted action occurrences are independent of name, list order, and folder position. +use std::collections::{BTreeMap, HashSet}; + +use super::{Action, PLAY_SHORTCUT_PREFIX, bad}; +use crate::{Result, Session}; + +const OCCURRENCE_PREFIX: &str = "actions.playById:"; +const COMMAND: &str = "action shortcut"; + +pub fn is_action_key(key: &str) -> bool { + key.starts_with(PLAY_SHORTCUT_PREFIX) || key.starts_with(OCCURRENCE_PREFIX) +} + +pub fn occurrence_key(id: &str) -> String { + format!("{OCCURRENCE_PREFIX}{id}") +} + +pub(crate) fn resolve_action_id(list: &[Action], id: &str) -> Option { + if id.len() != 32 || !id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { + return None; + } + let mut matches = list.iter().enumerate().filter(|(_, action)| action.action_id.as_deref() == Some(id)); + let (index, _) = matches.next()?; + matches.next().is_none().then_some(index) +} + +/// Never let a duplicated on-disk ID become valid just because one of its rows is removed. +pub(crate) fn invalidate_duplicate_ids(list: &mut [Action]) { + let mut seen = HashSet::new(); + let mut duplicates = HashSet::new(); + for id in list.iter().filter_map(|action| action.action_id.as_ref()) { + if !seen.insert(id) { + duplicates.insert(id.clone()); + } + } + for action in list { + if action.action_id.as_ref().is_some_and(|id| duplicates.contains(id)) { + action.action_id = Some(String::new()); + } + } +} + +pub fn shortcut_row(list: &[Action], key: &str) -> Option { + if let Some(id) = key.strip_prefix(OCCURRENCE_PREFIX) { + return resolve_action_id(list, id); + } + let name = key.strip_prefix(PLAY_SHORTCUT_PREFIX)?; + list.iter().position(|action| action.name == name) +} + +/// Prepare an ID without changing the library, so a denied shortcut edit leaves it untouched. +pub fn prepare_action_id(list: &[Action], index: usize) -> Result { + let action = list.get(index).ok_or_else(|| bad(COMMAND, "action no longer exists"))?; + if let Some(id) = &action.action_id { + return if resolve_action_id(list, id) == Some(index) { Ok(id.clone()) } else { Err(bad(COMMAND, "invalid or duplicate action ID")) }; + } + let mut bytes = [0; 16]; + getrandom::fill(&mut bytes).map_err(|error| bad(COMMAND, format!("could not create an action ID: {error}")))?; + let id = format!("{:032x}", u128::from_be_bytes(bytes)); + if list.iter().any(|a| a.action_id.as_deref() == Some(id.as_str())) { + return Err(bad(COMMAND, "duplicate generated action ID")); + } + Ok(id) +} + +/// Complete a successful shortcut edit. The shortcut command only edits preferences. +pub fn commit_action_id(s: &mut Session, index: usize, id: String) { + if s.actions.list[index].action_id.is_none() { + s.actions.list[index].action_id = Some(id); + s.actions.touch(); + s.sync_preset_store(); + } +} + +/// A valid explicit key takes precedence over a legacy key for the same row. +pub fn action_shortcut(s: &Session, index: usize) -> Option<&str> { + let list = &s.actions.list; + let action = list.get(index)?; + let keys = &s.prefs().shortcuts; + if let Some(id) = action.action_id.as_deref().filter(|id| resolve_action_id(list, id) == Some(index)) + && let Some(key) = keys.get(&occurrence_key(id)) + { + return Some(key.as_str()); + } + let legacy = format!("{PLAY_SHORTCUT_PREFIX}{}", action.name); + (shortcut_row(list, &legacy) == Some(index)).then(|| keys.get(&legacy)).flatten().map(String::as_str) +} + +/// Move a legacy binding to its already resolved row before an edit changes name lookup. +pub(crate) fn pin_shortcut( + list: &mut [Action], + index: usize, + shortcuts: &mut BTreeMap, + alternates: &mut BTreeMap>, +) -> Result<()> { + let legacy = format!("{PLAY_SHORTCUT_PREFIX}{}", list[index].name); + if shortcut_row(list, &legacy) != Some(index) || !(shortcuts.contains_key(&legacy) || alternates.contains_key(&legacy)) { + return Ok(()); + } + let id = prepare_action_id(list, index)?; + let key = occurrence_key(&id); + list[index].action_id = Some(id); + if let Some(binding) = shortcuts.remove(&legacy) { + shortcuts.entry(key.clone()).or_insert(binding); + } + if let Some(bindings) = alternates.remove(&legacy) { + alternates.entry(key).or_insert(bindings); + } + Ok(()) +} + +/// Remove only the bindings owned by the deleted rows, before the indices or first match change. +pub(crate) fn remove_shortcuts(s: &mut Session, remove: impl Fn(usize, &Action) -> bool) { + let list = &s.actions.list; + let mut keys = s + .prefs() + .shortcuts + .keys() + .chain(s.prefs().alternate_shortcuts.keys()) + .filter(|key| shortcut_row(list, key).is_some_and(|row| remove(row, &list[row]))) + .cloned() + .peekable(); + if keys.peek().is_none() { + return; + } + let keys: Vec<_> = keys.collect(); + s.edit_prefs(|prefs| { + for key in keys { + prefs.shortcuts.remove(&key); + prefs.alternate_shortcuts.remove(&key); + } + }); +} diff --git a/crates/engine/src/cmd/actions_edit_cmds/library_commands.rs b/crates/engine/src/cmd/actions_edit_cmds/library_commands.rs index 7be7a5277dc..1291dc8016c 100644 --- a/crates/engine/src/cmd/actions_edit_cmds/library_commands.rs +++ b/crates/engine/src/cmd/actions_edit_cmds/library_commands.rs @@ -5,7 +5,7 @@ use std::io::{self, Write}; use serde::Serialize; use serde_json::{Value, json}; -use crate::actions_cmds::{Action, PLAY_SHORTCUT_PREFIX, ambiguous_shortcut_names, not_playing}; +use crate::actions_cmds::{Action, is_action_key, not_playing, pin_shortcut}; use crate::{Result, Session}; use super::bad; @@ -51,13 +51,13 @@ pub(crate) fn confirmed_idle(s: &Session, p: &Value, cmd: &str) -> Result<()> { } fn action_bindings(bindings: &BTreeMap) -> BTreeMap { - bindings.iter().filter(|(id, _)| id.starts_with(PLAY_SHORTCUT_PREFIX)).map(|(id, value)| (id.clone(), value.clone())).collect() + bindings.iter().filter(|(id, _)| is_action_key(id)).map(|(id, value)| (id.clone(), value.clone())).collect() } fn replace_bindings(s: &mut Session, shortcuts: Shortcuts, alternates: Alternates) { s.edit_prefs(|prefs| { - prefs.shortcuts.retain(|id, _| !id.starts_with(PLAY_SHORTCUT_PREFIX)); - prefs.alternate_shortcuts.retain(|id, _| !id.starts_with(PLAY_SHORTCUT_PREFIX)); + prefs.shortcuts.retain(|id, _| !is_action_key(id)); + prefs.alternate_shortcuts.retain(|id, _| !is_action_key(id)); prefs.shortcuts.extend(shortcuts); prefs.alternate_shortcuts.extend(alternates); }); @@ -89,28 +89,34 @@ pub(crate) fn check_library_size(list: &[Action], sets: &[String], rows: &[Strin } /// Replace library definitions and remember both shortcut maps for the one-step undo. -/// Append retains unambiguous shortcuts and drops names that no longer identify one action. -pub(crate) fn publish_library(s: &mut Session, list: Vec, sets: Vec, rows: Vec, new_shortcuts: Option, label: &'static str) { +/// Append pins an existing legacy binding before adding a namesake. +pub(crate) fn publish_library( + s: &mut Session, + mut list: Vec, + sets: Vec, + rows: Vec, + new_shortcuts: Option, + label: &'static str, + cmd: &str, +) -> Result<()> { let shortcuts = action_bindings(&s.prefs().shortcuts); let alternates = action_bindings(&s.prefs().alternate_shortcuts); let (after_shortcuts, after_alternates) = match new_shortcuts { - Some(keys) => { - replace_bindings(s, keys.clone(), Alternates::new()); - (keys, Alternates::new()) - } + Some(keys) => (keys, Alternates::new()), None => { - let ambiguous = ambiguous_shortcut_names(&list); - let keep = |id: &str| id.strip_prefix(PLAY_SHORTCUT_PREFIX).is_none_or(|name| !ambiguous.contains(name)); - let mut keys = shortcuts.clone(); - let mut alternate_keys = alternates.clone(); - keys.retain(|id, _| keep(id)); - alternate_keys.retain(|id, _| keep(id)); - if keys != shortcuts || alternate_keys != alternates { - replace_bindings(s, keys.clone(), alternate_keys.clone()); + let (mut keys, mut alternate_keys) = (shortcuts.clone(), alternates.clone()); + let count = s.actions.list.len(); + let owners: Vec<_> = list[count..].iter().filter_map(|action| list[..count].iter().position(|prior| prior.name == action.name)).collect(); + for owner in owners { + pin_shortcut(&mut list, owner, &mut keys, &mut alternate_keys)?; } (keys, alternate_keys) } }; + check_library_size(&list, &sets, &rows, cmd)?; + if after_shortcuts != shortcuts || after_alternates != alternates { + replace_bindings(s, after_shortcuts.clone(), after_alternates.clone()); + } let document_history = s.documents().iter().map(|st| (st.doc.id, st.history.row_ids().max().unwrap_or(0), st.history.is_cleared())).collect(); // A document edit after a library command must start a new undo step. for st in &mut s.docs { @@ -130,13 +136,14 @@ pub(crate) fn publish_library(s: &mut Session, list: Vec, sets: Vec Result { confirmed_idle(s, p, "actions.clearAll")?; let count = s.actions.list.len(); if count != 0 || !s.actions.sets.is_empty() || !s.actions.set_rows.is_empty() { - publish_library(s, Vec::new(), Vec::new(), Vec::new(), Some(Shortcuts::new()), "Undo Clear All Actions"); + publish_library(s, Vec::new(), Vec::new(), Vec::new(), Some(Shortcuts::new()), "Undo Clear All Actions", "actions.clearAll")?; } Ok(json!({"cleared":count})) } @@ -158,8 +165,7 @@ pub(super) fn reset(s: &mut Session, p: &Value) -> Result { for (name, command) in [("Invert Colors", "image.adjustments.invert"), ("Desaturate", "image.adjustments.desaturate")] { list.push(Action { set: Some(NAME.into()), set_slot: Some(slot), ..Action::new(name, vec![(command.into(), json!({}))]) }); } - check_library_size(&list, &sets, &rows, CMD)?; - publish_library(s, list, sets, rows, (!append).then(Shortcuts::new), "Undo Reset Actions"); + publish_library(s, list, sets, rows, (!append).then(Shortcuts::new), "Undo Reset Actions", CMD)?; Ok(json!({"set":NAME,"slot":slot,"appended":append,"actions":2})) } @@ -177,8 +183,7 @@ fn undo_state(s: &Session) -> Result<&LibraryUndo> { pub fn undo_library_label(s: &Session) -> Option<&'static str> { let undo = undo_state(s).ok()?; if let Some(st) = s.active().filter(|st| st.history.can_undo()) { - let (_, last_id, was_cleared) = - undo.document_history.iter().find(|(id, _, _)| *id == st.doc.id).copied().unwrap_or((st.doc.id, 0, false)); + let (_, last_id, was_cleared) = undo.document_history.iter().find(|(id, _, _)| *id == st.doc.id).copied().unwrap_or((st.doc.id, 0, false)); let current_id = st.history.row_id(st.history.past_len()).unwrap_or(0); if current_id > last_id || (st.history.is_cleared() && !was_cleared) { return None; diff --git a/crates/engine/src/cmd/actions_edit_cmds/library_commands/tests.rs b/crates/engine/src/cmd/actions_edit_cmds/library_commands/tests.rs index 26c9750969f..b93f673129f 100644 --- a/crates/engine/src/cmd/actions_edit_cmds/library_commands/tests.rs +++ b/crates/engine/src/cmd/actions_edit_cmds/library_commands/tests.rs @@ -125,36 +125,73 @@ fn recording_and_assignment_infer_only_unambiguous_folder_occurrences() { /// Repeated factory actions keep their display names. A name-only shortcut is removed /// when that name ceases to identify a physical row, and Undo restores the binding. #[test] -fn repeated_reset_and_store_attachment_do_not_retarget_shortcuts() { +fn repeated_reset_pins_existing_shortcuts_and_undo_restores_legacy_keys() { let mut s = Session::new(); - let store = MemBackend::default(); - s.attach_preset_store(open(Box::new(store.clone()))); s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); let shortcut = format!("{PLAY_SHORTCUT_PREFIX}Invert Colors"); s.edit_prefs(|prefs| { prefs.shortcuts.insert(shortcut.clone(), "F2".into()); prefs.alternate_shortcuts.insert(shortcut.clone(), vec!["F3".into()]); }); + let before = s.actions.list.clone(); + let prefs = s.prefs().clone(); + assert!(s.execute("actions.reset", json!({"confirm":false,"mode":"append"})).is_err()); + assert_eq!(s.actions.list, before); + assert_eq!(s.prefs().shortcuts, prefs.shortcuts); + assert_eq!(s.prefs().alternate_shortcuts, prefs.alternate_shortcuts); + s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); + let key = crate::actions_cmds::occurrence_key(s.actions.list[0].action_id.as_deref().unwrap()); + assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &key), Some(0)); + assert_eq!(s.prefs().shortcuts[&key], "F2"); + assert_eq!(s.prefs().alternate_shortcuts[&key], ["F3"]); assert!(!s.prefs().shortcuts.contains_key(&shortcut)); assert!(!s.prefs().alternate_shortcuts.contains_key(&shortcut)); assert_eq!(s.actions.list.iter().filter(|action| action.name == "Invert Colors").count(), 2); + s.execute("actions.undoLibrary", json!({})).unwrap(); + assert_eq!(s.actions.list, before); assert_eq!(s.prefs().shortcuts[&shortcut], "F2"); assert_eq!(s.prefs().alternate_shortcuts[&shortcut], ["F3"]); - s.sync_preset_store(); + assert!(!s.prefs().shortcuts.contains_key(&key)); +} - let mut attached = Session::new(); - attached.actions.list.push(Action::new("Invert Colors", Vec::new())); - attached.edit_prefs(|prefs| { - prefs.shortcuts.insert(shortcut.clone(), "F2".into()); - prefs.alternate_shortcuts.insert(shortcut.clone(), vec!["F3".into()]); - }); - attached.attach_preset_store(open(Box::new(store))); - assert_eq!(attached.actions.list.iter().filter(|action| action.name == "Invert Colors").count(), 2); - assert!(!attached.prefs().shortcuts.contains_key(&shortcut)); - assert!(!attached.prefs().alternate_shortcuts.contains_key(&shortcut)); - assert_eq!(attached.execute("actions.get", json!({"action":"Invert Colors"})).unwrap()["set"], serde_json::Value::Null); +#[test] +fn duplicate_stored_ids_stay_unplayable_after_deleting_one_row() { + use crate::preset_store::{ACTIONS_FILE, PresetBackend}; + + let store = MemBackend::default(); + let id = "0".repeat(32); + let file = json!({"version":1,"actions":[{"name":"First","action_id":id},{"name":"Second","action_id":id}]}); + store.write(ACTIONS_FILE, file.to_string().as_bytes()).unwrap(); + let mut s = Session::new(); + s.attach_preset_store(open(Box::new(store))); + let key = crate::actions_cmds::occurrence_key(&id); + assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &key), None); + s.execute("actions.delete", json!({"action":"First"})).unwrap(); + assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &key), None); + assert!(s.execute("actions.play", json!({"actionId":id,"action":"Second"})).is_err()); + assert!(s.execute("actions.play", json!({"actionId":"invalid","action":"Second"})).is_err()); + assert_eq!(s.execute("actions.play", json!({"action":"Second"})).unwrap()["ran"], 0); +} + +#[test] +fn atn_export_and_load_keep_function_keys_of_duplicate_rows_separate() { + let mut s = Session::new(); + for _ in 0..2 { + s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); + } + for (row, key) in [(0, "F2"), (2, "F3")] { + let id = crate::actions_cmds::prepare_action_id(&s.actions.list, row).unwrap(); + s.edit_prefs(|prefs| prefs.shortcuts.insert(crate::actions_cmds::occurrence_key(&id), key.into())); + crate::actions_cmds::commit_action_id(&mut s, row, id); + } + let archive = s.execute("actions.save", json!({"set":"PhotoCraft Basics","skipUnsupported":true})).unwrap(); + let mut loaded = Session::new(); + let result = loaded.execute("actions.load", json!({"data":archive["data"]})).unwrap(); + assert_eq!(result["functionKeys"], json!([{"action":"Invert Colors","key":"F2"},{"action":"Invert Colors 2","key":"F3"}])); + assert_eq!(crate::actions_cmds::action_shortcut(&loaded, 0), Some("F2")); + assert_eq!(crate::actions_cmds::action_shortcut(&loaded, 2), Some("F3")); } /// Imported calls follow a local physical folder before falling back to the first archive name. diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index 8b2e82125ea..2ca6c33f4f1 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -120,21 +120,25 @@ pub(super) struct ReplacementSet { pub keys: Vec<(usize, String)>, } +pub(super) fn import_first_with_keys(bytes: &[u8], encoding: Option<&str>) -> std::result::Result { + let file = atn::parse_with_encoding(bytes, encoding).map_err(|error| error.to_string())?; + Ok(convert_with_keys(&file)) +} + pub(super) fn import_sets(bytes: &[u8], encoding: Option<&str>) -> std::result::Result, String> { let files = atn::parse_sets_with_encoding(bytes, encoding).map_err(|error| error.to_string())?; - Ok(files + Ok(files.iter().map(convert_with_keys).collect()) +} + +fn convert_with_keys(file: &AtnFile) -> ReplacementSet { + let keys = file + .actions .iter() - .map(|file| { - let keys = file - .actions - .iter() - .enumerate() - .filter(|(_, action)| action.function_key > 0) - .map(|(index, action)| (index, function_key_name(action.function_key, action.shift, action.command))) - .collect(); - ReplacementSet { imported: convert_set(file), keys } - }) - .collect()) + .enumerate() + .filter(|(_, action)| action.function_key > 0) + .map(|(index, action)| (index, function_key_name(action.function_key, action.shift, action.command))) + .collect(); + ReplacementSet { imported: convert_set(file), keys } } fn convert_set(file: &AtnFile) -> Imported { @@ -252,12 +256,21 @@ pub fn export( actions: &[&Action], function_keys: &[(String, String)], skip_unsupported: bool, +) -> std::result::Result<(Vec, Vec), String> { + export_with_keys(set, actions, |_, action| function_keys.iter().find(|(name, _)| name == &action.name).map(|(_, key)| key.as_str()), skip_unsupported) +} + +pub(super) fn export_with_keys<'a>( + set: &str, + actions: &[&Action], + key: impl Fn(usize, &Action) -> Option<&'a str>, + skip_unsupported: bool, ) -> std::result::Result<(Vec, Vec), String> { let mut skipped = Vec::new(); let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new(), ..Default::default() }; - for a in actions { + for (index, a) in actions.iter().enumerate() { let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() }; - if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) { + if let Some((n, shift, command)) = key(index, a).and_then(parse_function_key) { (out.function_key, out.shift, out.command) = (n, shift, command); } for (i, (id, params)) in a.steps.iter().enumerate() { diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index b97ca6e30ee..e8c55ed9ac5 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -1,4 +1,4 @@ -use super::convert::{UniqueNames, export, import_with_encoding}; +use super::convert::{ReplacementSet, UniqueNames, export_with_keys, import_first_with_keys}; use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json}; mod replacement; @@ -19,7 +19,7 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(cmd, "encoding must be \"auto\" or a label such as shift_jis, gbk, big5, euc-kr, windows-1252, macintosh")), }; let (bytes, _) = crate::preset_import_cmds::file_bytes(p, cmd, ".atn file")?; - let mut imp = import_with_encoding(&bytes, encoding).map_err(|e| bad(cmd, e))?; + let ReplacementSet { imported: mut imp, keys: function_keys } = import_first_with_keys(&bytes, encoding).map_err(|e| bad(cmd, e))?; let original_set = imp.set.clone(); match p.get("set") { None | Some(Value::Null) => {} @@ -37,7 +37,7 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(cmd, "`replace` must be true or false")), }; if replace { - crate::actions_cmds::discard_ambiguous_shortcuts(s); + crate::actions_cmds::remove_shortcuts(s, |_, action| action.set.as_deref() == Some(imp.set.as_str())); s.actions.list.retain(|a| a.set.as_deref() != Some(imp.set.as_str())); let mut slots = Vec::with_capacity(s.actions.set_rows.len()); let mut next = 0; @@ -100,12 +100,12 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { if !s.actions.list.iter().any(|a| a.set.as_deref() == Some(imp.set.as_str())) && !s.actions.sets.contains(&imp.set) { s.actions.sets.push(imp.set.clone()); } - let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect(); + let keys: Vec<_> = function_keys.into_iter().map(|(index, key)| (names[index].clone(), key)).collect(); if !keys.is_empty() { s.edit_prefs(|prefs| { for (name, key) in &keys { // A function key belongs to one action. - prefs.shortcuts.retain(|k, v| !(k.starts_with(crate::actions_cmds::PLAY_SHORTCUT_PREFIX) && v == key)); + prefs.shortcuts.retain(|k, v| !(crate::actions_cmds::is_action_key(k) && v == key)); prefs.shortcuts.insert(format!("{}{name}", crate::actions_cmds::PLAY_SHORTCUT_PREFIX), key.clone()); } }); @@ -142,13 +142,19 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { if set_slot.is_some() && p.get("action").is_some() { return Err(bad(cmd, "select a folder occurrence or an action")); } - let (set, actions): (String, Vec<&Action>) = if p.get("action").is_some() { + let (set, indices): (String, Vec) = if p.get("action").is_some() { let idx = crate::actions_cmds::resolve(&s.actions.list, p, cmd)?; let a = &s.actions.list[idx]; - (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a]) + (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![idx]) } else if let Some(set) = set_param { - let list: Vec<&Action> = - s.actions.list.iter().filter(|a| a.set.as_deref() == Some(set.as_str()) && (p.get("setSlot").is_none() || a.set_slot == set_slot)).collect(); + let list: Vec = s + .actions + .list + .iter() + .enumerate() + .filter(|(_, a)| a.set.as_deref() == Some(set.as_str()) && (p.get("setSlot").is_none() || a.set_slot == set_slot)) + .map(|(index, _)| index) + .collect(); // An empty set New Set made is written with no actions, as Photoshop saves one. let known_row = p.get("setSlot").is_none() && s.actions.set_rows.contains(&set); if list.is_empty() && set_slot.is_none() && !known_row && !s.actions.sets.contains(&set) { @@ -159,15 +165,12 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { if s.actions.list.is_empty() { return Err(bad(cmd, "there are no actions to save")); } - (DEFAULT_SET.to_string(), s.actions.list.iter().collect()) + (DEFAULT_SET.to_string(), (0..s.actions.list.len()).collect()) }; + let actions: Vec<&Action> = indices.iter().map(|&index| &s.actions.list[index]).collect(); let names: Vec = actions.iter().map(|a| a.name.clone()).collect(); - let ambiguous = crate::actions_cmds::ambiguous_shortcut_names(&s.actions.list); - let keys: Vec<(String, String)> = s.prefs().shortcuts.iter().filter_map(|(k, v)| { - let name = k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX)?; - (!ambiguous.contains(name)).then(|| (name.to_string(), v.clone())) - }).collect(); - let (bytes, skipped) = export(&set, &actions, &keys, skip).map_err(|e| bad(cmd, e))?; + let key = |index, _: &Action| crate::actions_cmds::action_shortcut(s, indices[index]); + let (bytes, skipped) = export_with_keys(&set, &actions, key, skip).map_err(|e| bad(cmd, e))?; let steps: usize = actions.iter().map(|a| a.steps.len()).sum::().saturating_sub(skipped.len()); let mut out = json!({"set": set, "actions": names, "steps": steps, "bytes": bytes.len(), "skipped": skipped}); match p.get("path") { diff --git a/crates/engine/src/cmd/atn_cmds/files/replacement.rs b/crates/engine/src/cmd/atn_cmds/files/replacement.rs index 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/preset_store.rs b/crates/engine/src/preset_store.rs index 8afc5a1087a..38db8e4f298 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -754,6 +754,7 @@ fn load_actions(backend: &dyn PresetBackend, warnings: &mut Vec) -> Opti }; match serde_json::from_slice::(&bytes) { Ok(mut file) if file.version == 1 => { + crate::actions_cmds::invalidate_duplicate_ids(&mut file.actions); for action in &mut file.actions { action.set_slot = action.set_slot.filter(|&slot| action.set.is_some() && file.set_rows.get(slot) == action.set.as_ref()); } diff --git a/crates/engine/src/shortcut_sets.rs b/crates/engine/src/shortcut_sets.rs index 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 7e98b6b8005..f8bffa8800c 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -8,6 +8,7 @@ //! silently, as the greyed menu item shows. use egui::{Key, KeyboardShortcut}; +use photocraft_engine::actions_cmds; use serde_json::json; use crate::PhotocraftApp; @@ -48,10 +49,8 @@ pub fn take_log(ctx: &egui::Context) -> Vec<(String, Outcome)> { /// their overrides apply. Held temporary tools (Space…) are not here: see [`crate::hold_keys`]. pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> { let prefs = app.session.prefs(); - let ambiguous = photocraft_engine::actions_cmds::ambiguous_shortcut_names(&app.session.actions.list); - let action_ids: Vec = app.session.actions.list.iter().filter(|a| !ambiguous.contains(a.name.as_str())) - .map(|a| crate::actions::shortcut_id(&a.name)).collect(); - let actions = action_ids.iter().map(|id| (id.as_str(), prefs.shortcut(id, None).map(str::to_string))); + let action_row = |key: &str| actions_cmds::shortcut_row(&app.session.actions.list, key); + let actions = prefs.shortcuts.keys().filter(|id| action_row(id.as_str()).is_some()).map(|id| (id.as_str(), prefs.shortcut(id, None).map(str::to_string))); // The Keyboard Shortcuts dialog lists Photoshop's Window › item (`window.panel.*`) // in place of the shell command it runs (`window.toggle.*`, see `menus::panel_alias`), so an // edit to that row reassigns or removes the shell command's default too (#1272). @@ -77,7 +76,7 @@ pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> { .iter() .filter(|(id, sc)| { !sc.is_empty() - && !id.starts_with(crate::actions::SHORTCUT_PREFIX) + && !actions_cmds::is_action_key(id) && photocraft_engine::commands::find(id).is_none() && !crate::menus::UI_COMMANDS.iter().any(|c| c.0 == id.as_str()) && !crate::hold_keys::is_temporary(id) @@ -100,7 +99,7 @@ pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> { let alternate_ids: std::collections::BTreeSet<&str> = photocraft_engine::prefs::ALTERNATE_SHORTCUTS.iter().map(|(id, _)| *id).chain(prefs.alternate_shortcuts.keys().map(String::as_str)).collect(); for id in alternate_ids { - if id.strip_prefix(crate::actions::SHORTCUT_PREFIX).is_some_and(|name| ambiguous.contains(name)) { + if actions_cmds::is_action_key(id) && action_row(id).is_none() { continue; } let main = prefs.shortcut(id, crate::shortcuts::default_shortcut(id).as_deref()).map(str::to_string); @@ -378,11 +377,12 @@ pub fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) { /// [`dispatch`]; with `last`, an adjustment dialog opens at its last confirmed settings. fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: bool) { - let action = id.strip_prefix(crate::actions::SHORTCUT_PREFIX); - let command_id = if action.is_some() { "actions.play" } else { id }; - let ambiguous = action.is_some_and(|name| photocraft_engine::actions_cmds::ambiguous_shortcut_names(&app.session.actions.list).contains(name)); - let outcome = if ambiguous || !crate::menus::is_enabled(app, command_id) { - let why = if ambiguous { "Multiple Actions use this name".into() } else { disabled_reason(app, command_id) }; + let is_action = actions_cmds::is_action_key(id); + let action = actions_cmds::shortcut_row(&app.session.actions.list, id).map(|row| &app.session.actions.list[row]); + let command_id = if is_action { "actions.play" } else { id }; + let missing = is_action && action.is_none(); + let outcome = if missing || !crate::menus::is_enabled(app, command_id) { + let why = if missing { "The Action no longer exists".into() } else { disabled_reason(app, command_id) }; let template = "{label} is not available: {reason}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("label", crate::i18n::tr_id(crate::i18n::current(), id, &label(id))), ("reason", tl!(&why))]); app.ui.status_error = true; @@ -390,10 +390,13 @@ fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: boo } else if ctx.data(|d| d.get_temp::(dry_run_id())).unwrap_or(false) { Outcome::Ran } else { - let r = if let Some(name) = action { - // Use the normal command path: synthetic input and every nested action - // step must still pass the automation authorizer. - crate::menus::invoke(app, ctx, "actions.play", json!({"action": name})).and_then(|v| { + let r = if let Some(action) = action { + let target = match id.strip_prefix(actions_cmds::PLAY_SHORTCUT_PREFIX) { + Some(name) => json!({"action": name}), + None => json!({"actionId": action.action_id}), + }; + // Synthetic input and every nested action still pass the automation authorizer. + crate::menus::invoke(app, ctx, "actions.play", target).and_then(|v| { crate::actions::report_play(app, &v); if v.get("failed").is_some_and(|f| f.is_object()) { Err(app.ui.status.clone()) } else { Ok(v) } }) diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index ce7e3fcc392..34fa63b4a00 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -7,6 +7,7 @@ use egui::{Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use photocraft_doc::LayerContent; +use photocraft_engine::actions_cmds; use serde_json::json; use super::{Focus, Outcome, bindings, set_dry_run, take_log}; @@ -782,6 +783,71 @@ fn clip_key_toggles_several_selected_layers() { assert!(!is_clipped(&h, paint) && !is_clipped(&h, top) && !is_clipped(&h, base)); } +fn action_key(h: &Harness<'_, PhotocraftApp>, index: usize) -> String { + actions_cmds::occurrence_key(h.state().session.actions.list[index].action_id.as_deref().unwrap()) +} + +fn repeated_reset_shortcuts(h: &mut Harness<'_, PhotocraftApp>) { + for _ in 0..2 { + h.state_mut().run("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); + } + for (index, key, name) in [(0, "F2", "first occurrence"), (2, "F3", "second occurrence")] { + h.state_mut().session.actions.list[index].steps = vec![("layer.new.layer".into(), json!({"name":name}))]; + crate::actions::assign_shortcut(h.state_mut(), index, key).unwrap(); + } +} + +#[test] +fn f2_dispatches_only_the_first_same_named_action() { + let mut h = harness(); + repeated_reset_shortcuts(&mut h); + let count = h.state().session.active().unwrap().doc.layers.len(); + press(&mut h, "F2"); + assert_eq!(active_name(&h), "first occurrence"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), count + 1); +} + +#[test] +fn f3_dispatches_only_the_second_same_named_action_after_reorder_and_reopen() { + use photocraft_engine::preset_store::{MemBackend, open}; + + let mut h = harness(); + let store = MemBackend::default(); + h.state_mut().session.attach_preset_store(open(Box::new(store.clone()))); + repeated_reset_shortcuts(&mut h); + let first_key = action_key(&h, 0); + let second_key = action_key(&h, 2); + h.state_mut().run("actions.move", json!({"action":2,"to":0})).unwrap(); + h.state_mut().session.sync_preset_store(); + let prefs = h.state().session.prefs_to_json(); + + let mut h = harness(); + h.state_mut().session.load_prefs_json(&prefs).unwrap(); + h.state_mut().session.attach_preset_store(open(Box::new(store))); + assert_eq!(action_key(&h, 0), second_key); + let count = h.state().session.active().unwrap().doc.layers.len(); + press(&mut h, "F3"); + assert_eq!(active_name(&h), "second occurrence"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), count + 1); + h.state_mut().run("actions.delete", json!({"action":1})).unwrap(); + assert!(!h.state().session.prefs().shortcuts.contains_key(&first_key)); + assert_eq!(h.state().session.prefs().shortcuts[&second_key], "F3"); + press(&mut h, "F2"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), count + 1); +} + +#[test] +fn denied_shortcut_assignment_leaves_identity_and_bindings_unmodified() { + let mut h = harness(); + h.state_mut().session.actions.list.push(actions_cmds::Action::new("Action", Vec::new())); + h.state_mut().services.automation_command = Some(Box::new(|_, _| Err("denied shortcut edit".into()))); + h.state_mut().automation_input = true; + let prefs = h.state().session.prefs().shortcuts.clone(); + assert!(crate::actions::assign_shortcut(h.state_mut(), 0, "F2").is_err()); + assert!(h.state().session.actions.list[0].action_id.is_none()); + assert_eq!(h.state().session.prefs().shortcuts, prefs); +} + #[test] fn named_action_function_key_replays_and_survives_preferences_roundtrip() { let mut h = harness(); @@ -792,7 +858,7 @@ fn named_action_function_key_replays_and_survives_preferences_roundtrip() { ..Default::default() }; h.state_mut().session.actions.list.push(action); - crate::actions::assign_shortcut(h.state_mut(), "LivePrint 2R", "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); let saved = serde_json::to_value(h.state().session.prefs()).unwrap(); let restored = serde_json::from_value(saved).unwrap(); h.state_mut().session.edit_prefs(|p| *p = restored); @@ -801,9 +867,9 @@ fn named_action_function_key_replays_and_survives_preferences_roundtrip() { assert_eq!(active_name(&h), "F6 overlay"); assert_eq!(h.state().ui.status, "Played 1 step"); assert!(!h.state().ui.status_error); - assert_eq!(take_log(&h.ctx), vec![(crate::actions::shortcut_id("LivePrint 2R"), Outcome::Ran)]); + assert_eq!(take_log(&h.ctx), vec![(action_key(&h, 0), Outcome::Ran)]); h.state_mut().run("actions.delete", json!({"action": "LivePrint 2R"})).unwrap(); - assert!(bindings(h.state()).iter().all(|(id, _)| !id.starts_with(crate::actions::SHORTCUT_PREFIX))); + assert!(bindings(h.state()).iter().all(|(id, _)| !actions_cmds::is_action_key(id))); assert!(bindings(h.state()).iter().any(|(_, sc)| *sc == parse("F6").unwrap())); } @@ -818,14 +884,14 @@ fn assigning_action_function_key_moves_it_and_reports_failed_steps() { ..Default::default() }); } - crate::actions::assign_shortcut(h.state_mut(), "first", "F6").unwrap(); - crate::actions::assign_shortcut(h.state_mut(), "second", "F6").unwrap(); - assert_eq!(h.state().session.prefs().shortcuts[&crate::actions::shortcut_id("first")], ""); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 1, "F6").unwrap(); + assert_eq!(h.state().session.prefs().shortcuts[&action_key(&h, 0)], ""); h.state_mut().ui.actions.selected = Some(0); press(&mut h, "F6"); assert!(h.state().ui.status_error); assert!(h.state().ui.status.contains("Step 1 (no.such.command) failed")); - assert!(matches!(&take_log(&h.ctx)[..], [(id, Outcome::Failed(_))] if id == "actions.play:second")); + assert!(matches!(&take_log(&h.ctx)[..], [(id, Outcome::Failed(_))] if id == &action_key(&h, 1))); } #[test] @@ -837,10 +903,11 @@ fn action_function_key_checks_automation_authorization() { disabled: Default::default(), ..Default::default() }); - crate::actions::assign_shortcut(h.state_mut(), "restricted", "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); h.state_mut().services.automation_command = Some(Box::new(|id, _| if id == "actions.play" { Err("denied action playback".into()) } else { Ok(()) })); h.state_mut().automation_input = true; - super::dispatch(h.state_mut(), &egui::Context::default(), "actions.play:restricted"); + let id = action_key(&h, 0); + super::dispatch(h.state_mut(), &egui::Context::default(), &id); assert_eq!(h.state().ui.status, "denied action playback"); assert_eq!(active_name(&h), "paint"); } @@ -855,7 +922,7 @@ fn fit_shortcut_records_and_f6_fits_the_resized_canvas() { assert_eq!(h.state().session.actions.list[0].steps.iter().map(|s| s.0.as_str()).collect::>(), ["image.canvasSize", "view.fitOnScreen"]); let item = crate::menus::menu_items(h.state()).into_iter().find(|i| i.id == "view.fitOnScreen").unwrap(); assert_eq!(item.shortcut.as_deref(), Some("Cmd+0")); - crate::actions::assign_shortcut(h.state_mut(), "Resize and fit", "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); h.state_mut().ui.views[0].zoom = 0.1; h.state_mut().ui.views[0].center = [0.0, 0.0]; press(&mut h, "F6"); @@ -875,7 +942,7 @@ fn f6_while_recording_records_a_named_call_not_the_child_steps() { disabled: Default::default(), ..Default::default() }); - crate::actions::assign_shortcut(h.state_mut(), "LivePrint 2R", "F6").unwrap(); + crate::actions::assign_shortcut(h.state_mut(), 0, "F6").unwrap(); h.state_mut().run("actions.record", json!({"name":"Action 2"})).unwrap(); press(&mut h, "F6"); assert_eq!(active_name(&h), "Nested overlay"); diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 7e6b4ab7410..34b1f901d0c 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -225,29 +225,35 @@ pub fn action_steps(action: &Action) -> Vec { action.enabled_steps().map(|(_, (id, p))| json!([id, p])).collect() } -/// Named action bindings use the existing persisted shortcut overrides. Keeping the -/// name in the key means selecting or deleting another row cannot retarget F6. -pub(crate) const SHORTCUT_PREFIX: &str = actions_cmds::PLAY_SHORTCUT_PREFIX; - -pub(crate) fn shortcut_id(name: &str) -> String { - format!("{SHORTCUT_PREFIX}{name}") -} - -pub(crate) fn assign_shortcut(app: &mut PhotocraftApp, name: &str, shortcut: &str) -> Result { - if actions_cmds::ambiguous_shortcut_names(&app.session.actions.list).contains(name) { - return Err(tl!("Rename the action before assigning it a shortcut.").into()); - } - let id = shortcut_id(name); +pub(crate) fn assign_shortcut(app: &mut PhotocraftApp, index: usize, shortcut: &str) -> Result { + let list = &app.session.actions.list; + let action_id = actions_cmds::prepare_action_id(list, index).map_err(|error| error.to_string())?; + let id = actions_cmds::occurrence_key(&action_id); + let legacy = format!("{}{}", actions_cmds::PLAY_SHORTCUT_PREFIX, list[index].name); + let prefs = app.session.prefs(); let mut set = serde_json::Map::new(); - // A function key belongs to only one action. Ordinary menu bindings remain - // intact and become available again when the action binding is removed. - for (other, assigned) in &app.session.prefs().shortcuts { - if other.starts_with(SHORTCUT_PREFIX) && other != &id && assigned == shortcut && !shortcut.is_empty() { + let mut alternates = serde_json::Map::new(); + // A function key belongs to only one action. Ordinary menu bindings remain intact. + for (other, assigned) in &prefs.shortcuts { + if actions_cmds::is_action_key(other) && other != &id && assigned == shortcut && !shortcut.is_empty() { set.insert(other.clone(), json!("")); } } + if actions_cmds::shortcut_row(list, &legacy) == Some(index) { + if prefs.shortcuts.contains_key(&legacy) { + set.insert(legacy.clone(), Value::Null); + } + if let Some(keys) = prefs.alternate_shortcuts.get(&legacy) { + if !prefs.alternate_shortcuts.contains_key(&id) { + alternates.insert(id.clone(), json!(keys)); + } + alternates.insert(legacy, Value::Null); + } + } set.insert(id, json!(shortcut)); - app.run("edit.keyboardShortcuts", json!({"set": set, "allowUnknown": true, "removeConflicts": false})) + let result = app.run("edit.keyboardShortcuts", json!({"set": set, "alternates": alternates, "allowUnknown": true, "removeConflicts": false}))?; + actions_cmds::commit_action_id(&mut app.session, index, action_id); + Ok(result) } /// Replay edits synchronously, with view steps handled by the shell in the same order. @@ -1763,21 +1769,18 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, se SetHeaderResult { toggled, picked, save } } -fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index: usize, name: &str, swatch: &str, ambiguous: bool) { +fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index: usize, swatch: &str) { egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { ui.label(tl!("Keyboard Shortcuts")); - if ambiguous { - ui.label(tl!("Rename the action before assigning it a shortcut.")); - } - ui.add_enabled_ui(!ambiguous, |ui| { - let current = app.session.prefs().shortcuts.get(&shortcut_id(name)).cloned().unwrap_or_default(); + { + let current = actions_cmds::action_shortcut(&app.session, index).unwrap_or_default(); // Photoshop's Action Options: a function key, with Shift and Command (#7646). - let (key, mut shift, mut command) = photocraft_engine::atn_cmds::parse_function_key(¤t).unwrap_or((0, false, false)); + let (key, mut shift, mut command) = photocraft_engine::atn_cmds::parse_function_key(current).unwrap_or((0, false, false)); for number in std::iter::once(0).chain(1..=12) { let label = if number == 0 { tl!("None").to_string() } else { format!("F{number}") }; if ui.selectable_label(key == number, label).clicked() { let chosen = if number == 0 { String::new() } else { photocraft_engine::atn_cmds::function_key_name(number, shift, command) }; - let _ = assign_shortcut(app, name, &chosen); + let _ = assign_shortcut(app, index, &chosen); ui.close(); } } @@ -1785,10 +1788,10 @@ fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index let command_label = if cfg!(target_os = "macos") { tl!("Command") } else { tl!("Ctrl") }; let toggled = ui.checkbox(&mut shift, tl!("Shift")).changed() | ui.checkbox(&mut command, command_label).changed(); if toggled { - let _ = assign_shortcut(app, name, &photocraft_engine::atn_cmds::function_key_name(key, shift, command)); + let _ = assign_shortcut(app, index, &photocraft_engine::atn_cmds::function_key_name(key, shift, command)); } }); - }); + } ui.separator(); ui.menu_button(tl!("Color"), |ui| { for (id, label) in [ @@ -1816,8 +1819,6 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } let t = Tokens::get(ui.ctx()); let recording = app.session.actions.recording; - let ambiguous: std::collections::HashSet = actions_cmds::ambiguous_shortcut_names(&app.session.actions.list) - .into_iter().map(str::to_string).collect(); let rows: Vec = app .session .actions @@ -1943,11 +1944,8 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.painter().text( pos2(rect.right() - 8.0, rect.center().y), Align2::RIGHT_CENTER, - app.session - .prefs() - .shortcuts - .get(&shortcut_id(name)) - .filter(|s| !s.is_empty() && !ambiguous.contains(name.as_str())) + actions_cmds::action_shortcut(&app.session, i) + .filter(|key| !key.is_empty()) .map_or_else(|| step_count(nsteps, disabled.len()), |key| format!("{key} · {}", step_count(nsteps, disabled.len()))), egui::FontId::proportional(11.0), t.text_faint, @@ -1971,7 +1969,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } // Clicks inside stay open, so Shift and Command can both be ticked; every item that // finishes closes the menu itself. - action_context_menu(app, &resp, i, name, swatch, ambiguous.contains(name.as_str())); + action_context_menu(app, &resp, i, swatch); if resp.double_clicked() && !button_mode { // Photoshop renames in place when the name itself is double-clicked. if resp.interact_pointer_pos().is_some_and(|p| name_rect.expand2(vec2(4.0, 13.0)).contains(p)) { diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index f435b20a49c..39488b0a0f2 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -60,15 +60,6 @@ fn repeated_factory_rows_select_and_play_independently() { app.ui.actions.slot_revision = app.session.actions.set_rows_revision; assert_eq!(playback_targets(&app), [2, 3]); assert_eq!(new_action_set(&app).unwrap().slot, Some(1)); - - // An older or manually edited preferences file can still contain a name-only key. - let id = shortcut_id("Invert Colors"); - app.session.edit_prefs(|prefs| { - prefs.shortcuts.insert(id.clone(), "F2".into()); - prefs.alternate_shortcuts.insert(id.clone(), vec!["F3".into()]); - }); - assert!(!crate::shortcut_dispatch::bindings(&app).iter().any(|(bound, _)| bound == &id)); - assert!(assign_shortcut(&mut app, "Invert Colors", "F4").is_err()); } #[test] @@ -510,7 +501,7 @@ fn a_function_key_with_shift_and_command_plays_its_action() { }); let key = photocraft_engine::atn_cmds::function_key_name(2, true, true); assert_eq!(key, "Cmd+Shift+F2"); - assign_shortcut(&mut app, "Action 1", &key).unwrap(); + assign_shortcut(&mut app, 0, &key).unwrap(); let ctx = egui::Context::default(); let press = |app: &mut PhotocraftApp, modifiers| { ctx.begin_pass(egui::RawInput { @@ -3026,15 +3017,12 @@ fn replace_picker_checks_selected_source_and_rechecks_payload_on_confirm() { if p.get("path").is_some() { return Err("path denied by policy".into()); } - if p.get("data").is_some() && policy.get() { - Ok(()) - } else { - Err("payload denied by policy".into()) - } - }); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { - file_dialog: Some(file_dialog), automation_command: Some(automation_command), ..Default::default() + if p.get("data").is_some() && policy.get() { Ok(()) } else { Err("payload denied by policy".into()) } }); + let mut app = PhotocraftApp::new( + photocraft_engine::Session::new(), + crate::Services { file_dialog: Some(file_dialog), automation_command: Some(automation_command), ..Default::default() }, + ); app.run("actions.newSet", json!({"name":"Keep"})).unwrap(); let ctx = egui::Context::default(); for attempt in 0..2 { @@ -3076,9 +3064,10 @@ fn stale_same_caption_selection_does_not_follow_a_compacted_slot() { fn dragging_uses_the_displayed_folder_occurrence() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.session.actions.set_rows = vec!["Same".into(), "Same".into()]; - app.session.actions.list = [("A", 0), ("B", 1), ("C", 0)].into_iter().map(|(name, slot)| { - Action { set: Some("Same".into()), set_slot: Some(slot), ..Action::new(name, Vec::new()) } - }).collect(); + app.session.actions.list = [("A", 0), ("B", 1), ("C", 0)] + .into_iter() + .map(|(name, slot)| Action { set: Some("Same".into()), set_slot: Some(slot), ..Action::new(name, Vec::new()) }) + .collect(); move_row(&mut app, DragRow { action: 0, step: None }, 1, 2); assert_eq!(app.session.actions.list[1].name, "A"); assert_eq!(app.session.actions.list[1].set_slot, Some(0)); diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs index 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); From beb42e396b066f590b1b30dca416ae2ae82c7957 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 6 Nov 2026 10:14:33 -0800 Subject: [PATCH 3/4] Preserve saved action targets during preset attachment --- crates/engine/src/cmd/actions_cmds.rs | 206 ++++++++++-------- .../engine/src/cmd/actions_cmds/identity.rs | 14 +- crates/engine/src/cmd/actions_edit_cmds.rs | 23 +- .../library_commands/tests.rs | 26 +++ crates/engine/src/cmd/atn_cmds/convert.rs | 29 ++- crates/engine/src/cmd/file_cmds/batch_run.rs | 15 +- crates/engine/src/cmd/file_cmds/tests.rs | 14 +- crates/engine/src/preset_store.rs | 12 +- crates/engine/src/preset_store/actions.rs | 111 ++++++++++ .../src/input/shortcut_dispatch/tests.rs | 40 ++++ crates/ui-egui/src/panels/actions.rs | 77 ++++--- 11 files changed, 405 insertions(+), 162 deletions(-) create mode 100644 crates/engine/src/preset_store/actions.rs diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index cf11a43f7ac..ebee883e6b9 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -28,8 +28,8 @@ mod identity; pub(crate) use history::ActionHistory; pub use history::{ActionHistoryContinuation, finish_pending_history, suspend_history}; pub(crate) use history::{before_edit as before_action_edit, begin_document_history, finish_document_history, history_rows, reconcile_history_removal}; -pub use identity::{action_shortcut, commit_action_id, is_action_key, occurrence_key, prepare_action_id, shortcut_row}; -pub(crate) use identity::{invalidate_duplicate_ids, pin_shortcut, remove_shortcuts}; +pub use identity::{action_shortcut, commit_action_id, is_action_key, occurrence_key, playback_row, prepare_action_id, shortcut_row}; +pub(crate) use identity::{invalidate_duplicate_ids, pin_shortcut, remove_shortcuts, resolve_action_id, valid_action_id}; fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } @@ -89,6 +89,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 { @@ -113,9 +135,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, @@ -284,15 +306,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 = match p.get("actionId") { - Some(id) => id - .as_str() - .and_then(|id| identity::resolve_action_id(&s.actions.list, id)) - .ok_or_else(|| bad("actions.play", "invalid, missing, or duplicate action ID"))?, - None => resolve(&s.actions.list, p, "actions.play")?, - }; + let 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 { @@ -302,6 +318,43 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> { Ok((action, from)) } +/// Visit calls in the current namespace, leaving embedded inline Batch scopes untouched. +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()); + if id == "file.automate.batch" { + let inline = if params.get("steps").is_some() { Some("steps") } else { params.get("action").is_some_and(Value::is_array).then_some("action") }; + if let Some(key) = inline { + if scoped { + continue; + } + // A present invalid `steps` still wins over `action`, just as at runtime. + let Some(steps) = params.get_mut(key).and_then(Value::as_array_mut) else { continue }; + for step in steps.iter_mut().rev() { + let call = match step { + Value::Array(a) => { + let Some(id) = a.first().and_then(Value::as_str).map(str::to_owned) else { continue }; + a.get_mut(1).map(|params| (id, params)) + } + Value::Object(o) => { + let Some(id) = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).map(str::to_owned) else { continue }; + o.get_mut("params").map(|params| (id, params)) + } + // String steps and omitted params use `{}`, with no action target. + _ => None, + }; + if let Some(call) = call { + pending.push(call); + } + } + continue; + } + } + f(&id, params, scoped); + } +} + /// Capture transitive Play Action, Conditional and Batch dependencies for a standalone droplet /// (#2794, #6804). Ordinary references become names; normalized copies keep source-list order. /// A named Batch with its own action list selects an untouched source copy at an exported index, @@ -310,43 +363,7 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, 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) } - } - /// 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)) { - 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()); - if id == "file.automate.batch" { - let inline = if params.get("steps").is_some() { Some("steps") } else { params.get("action").is_some_and(Value::is_array).then_some("action") }; - if let Some(key) = inline { - if scoped { - continue; - } - // A present invalid `steps` still wins over `action`, just as at runtime. - let Some(steps) = params.get_mut(key).and_then(Value::as_array_mut) else { continue }; - for step in steps.iter_mut().rev() { - let call = match step { - Value::Array(a) => { - let Some(id) = a.first().and_then(Value::as_str).map(str::to_owned) else { continue }; - a.get_mut(1).map(|params| (id, params)) - } - Value::Object(o) => { - let Some(id) = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).map(str::to_owned) else { continue }; - o.get_mut("params").map(|params| (id, params)) - } - // String steps and omitted params use `{}`, with no action target. - _ => None, - }; - if let Some(call) = call { - pending.push(call); - } - } - continue; - } - } - f(&id, params, scoped); - } + 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) { @@ -365,8 +382,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)); } } @@ -401,7 +419,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"); + } return; } // Appended source copies must not make an originally missing numeric target valid. @@ -462,6 +489,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)")); @@ -741,7 +794,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 @@ -978,35 +1041,6 @@ fn toggle(s: &mut Session, p: &Value) -> Result { /// Prefix of the persisted shortcut override that plays a named action (`actions.play:`). pub const PLAY_SHORTCUT_PREFIX: &str = "actions.play:"; -/// Names whose legacy shortcut key cannot select a particular physical occurrence. -/// Legacy libraries without explicit slots keep their original first-match lookup. -pub fn ambiguous_shortcut_names(list: &[Action]) -> HashSet<&str> { - if !list.iter().any(|action| action.set_slot.is_some()) { - return HashSet::new(); - } - let mut seen = HashMap::new(); - let mut ambiguous = HashSet::new(); - for action in list { - let name = action.name.as_str(); - let slotted = action.set_slot.is_some(); - if seen.insert(name, slotted).is_some_and(|prior| prior || slotted) { - ambiguous.insert(name); - } - } - ambiguous -} - -/// Clear bindings for ambiguous physical occurrences before they could be retargeted. -pub(crate) fn discard_ambiguous_shortcuts(s: &mut Session) { - let ids: HashSet<_> = ambiguous_shortcut_names(&s.actions.list).into_iter().map(|name| format!("{PLAY_SHORTCUT_PREFIX}{name}")).collect(); - if ids.iter().any(|id| s.prefs().shortcuts.contains_key(id) || s.prefs().alternate_shortcuts.contains_key(id)) { - s.edit_prefs(|prefs| { - prefs.shortcuts.retain(|id, _| !ids.contains(id)); - prefs.alternate_shortcuts.retain(|id, _| !ids.contains(id)); - }); - } -} - /// Rename an action in place. Nested `actions.play` steps, named Batch steps and `actions.conditional` branches /// that call it by name, and its function-key binding, follow the new name so nothing silently /// stops working. diff --git a/crates/engine/src/cmd/actions_cmds/identity.rs b/crates/engine/src/cmd/actions_cmds/identity.rs index 02acc136933..2d5b1d8341b 100644 --- a/crates/engine/src/cmd/actions_cmds/identity.rs +++ b/crates/engine/src/cmd/actions_cmds/identity.rs @@ -15,8 +15,12 @@ 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 id.len() != 32 || !id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { + if !valid_action_id(id) { return None; } let mut matches = list.iter().enumerate().filter(|(_, action)| action.action_id.as_deref() == Some(id)); @@ -40,6 +44,14 @@ pub(crate) fn invalidate_duplicate_ids(list: &mut [Action]) { } } +/// 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); diff --git a/crates/engine/src/cmd/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index 5840f045ea4..51b481b98c8 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -171,9 +171,7 @@ pub(crate) fn assignment_slot(s: &Session, p: &Value, name: Option<&str>, cmd: & return set_slot(s, p, name, cmd); } let Some(name) = name else { return Ok(None) }; - if s.actions.sets.iter().any(|set| set == name) - || s.actions.list.iter().any(|action| action.set_slot.is_none() && action.set.as_deref() == Some(name)) - { + if s.actions.sets.iter().any(|set| set == name) || s.actions.list.iter().any(|action| action.set_slot.is_none() && action.set.as_deref() == Some(name)) { return Ok(None); } let mut matches = s.actions.set_rows.iter().enumerate().filter(|(_, caption)| caption.as_str() == name); @@ -295,25 +293,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/tests.rs b/crates/engine/src/cmd/actions_edit_cmds/library_commands/tests.rs index b93f673129f..75144cbab12 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 @@ -194,6 +194,32 @@ fn atn_export_and_load_keep_function_keys_of_duplicate_rows_separate() { 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); +} + /// 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() { diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index 2ca6c33f4f1..6bb6ad48a3d 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -249,6 +249,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( @@ -274,7 +301,7 @@ pub(super) fn export_with_keys<'a>( (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/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 6f97374126a..8166d670ddd 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()); @@ -2743,7 +2743,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}"); @@ -2799,14 +2799,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 38db8e4f298..bf261bc0398 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}; @@ -1149,7 +1150,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(); @@ -1189,8 +1190,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; @@ -1200,6 +1201,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 { @@ -1208,15 +1210,15 @@ 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() || !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); } - crate::actions_cmds::discard_ambiguous_shortcuts(self); self.brush_presets_changed(); self.sync_preset_store(); // A brush remembered from the previous run (or picked before the store loaded) may be diff --git a/crates/engine/src/preset_store/actions.rs b/crates/engine/src/preset_store/actions.rs new file mode 100644 index 00000000000..4bb8077c939 --- /dev/null +++ b/crates/engine/src/preset_store/actions.rs @@ -0,0 +1,111 @@ +//! 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, pin_shortcut, 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; + + // A legacy shortcut read with the saved preferences belongs to the first disk match. + // The current Action Options path already gives a newly assigned in-memory binding an ID. + let (mut keys, mut alternates) = (s.prefs().shortcuts.clone(), s.prefs().alternate_shortcuts.clone()); + let owners: Vec<_> = keys + .keys() + .chain(alternates.keys()) + .filter_map(|key| { + let name = key.strip_prefix(PLAY_SHORTCUT_PREFIX)?; + memory.iter().any(|action| action.name == name).then(|| shortcut_row(disk, key)).flatten().map(|row| (key.clone(), row)) + }) + .collect(); + for (key, row) in owners { + if let Err(error) = pin_shortcut(disk, row, &mut keys, &mut alternates) { + // The original target cannot be identified. The legacy key must not play a memory row. + keys.remove(&key); + alternates.remove(&key); + warnings.push(format!("actions: {error}")); + } + } + + 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 Ok(target) = resolve(disk) + { + params["actionId"] = pin_target(disk, target, 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 Ok(target) = resolve_play_target(disk, &target, command) + { + params[field] = pin_target(disk, target, warnings); + } + } + } + _ => {} + }); + disk[row].steps = steps; + } + if keys != s.prefs().shortcuts || alternates != s.prefs().alternate_shortcuts { + s.edit_prefs(|prefs| { + prefs.shortcuts = keys; + prefs.alternate_shortcuts = alternates; + }); + } +} + +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/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 34fa63b4a00..f1894722df8 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -836,6 +836,46 @@ fn f3_dispatches_only_the_second_same_named_action_after_reorder_and_reopen() { 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 = action_key(&h, 1); + 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 denied_shortcut_assignment_leaves_identity_and_bindings_unmodified() { let mut h = harness(); diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 34b1f901d0c..563336e0a8b 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -326,11 +326,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})), }) @@ -352,28 +360,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) } @@ -401,7 +407,7 @@ fn stop_step(app: &mut PhotocraftApp, action: &Action, i: usize, p: &Value) -> C /// 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) => { @@ -421,7 +427,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; @@ -1064,14 +1070,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. @@ -1080,7 +1083,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()); } } @@ -1141,8 +1144,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. @@ -1164,8 +1166,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, } @@ -1357,15 +1358,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 { @@ -1379,11 +1378,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()); @@ -1394,11 +1390,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; From cc19b9899bd3952d1a20119ea9001bf1ef55476c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 6 Nov 2026 10:21:53 -0800 Subject: [PATCH 4/4] Preserve legacy shortcuts and unresolved calls on store failure --- crates/engine/src/cmd/actions_cmds.rs | 51 ++++++++----- .../engine/src/cmd/actions_cmds/identity.rs | 50 ++++++------ .../cmd/actions_edit_cmds/library_commands.rs | 13 ++-- .../library_commands/tests.rs | 43 +++++++++-- crates/engine/src/preset_store.rs | 44 +++++++---- crates/engine/src/preset_store/actions.rs | 48 +++++------- crates/ui-egui/src/input/shortcut_dispatch.rs | 34 +++++++-- .../src/input/shortcut_dispatch/tests.rs | 76 ++++++++++++++++++- crates/ui-egui/src/panels/actions.rs | 40 ++++++---- crates/ui-egui/src/panels/actions/tests.rs | 19 +++++ 10 files changed, 287 insertions(+), 131 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index ebee883e6b9..58406544538 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -29,7 +29,7 @@ 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::{invalidate_duplicate_ids, pin_shortcut, remove_shortcuts, resolve_action_id, valid_action_id}; +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() } @@ -43,6 +43,9 @@ pub struct Action { /// 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). @@ -70,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(), action_id: None, 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. @@ -460,8 +473,12 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec params["action"] = json!(name), } - if let Some(object) = params.as_object_mut() { - object.remove("actionId"); + 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; } @@ -926,15 +943,10 @@ fn move_item(s: &mut Session, p: &Value) -> Result { let name = &s.actions.list[idx].name; let first = s.actions.list.iter().position(|action| &action.name == name).unwrap_or(idx); let changes_owner = if first == idx { to > idx && s.actions.list[idx + 1..=to].iter().any(|action| &action.name == name) } else { to <= first }; - if changes_owner { - let mut shortcuts = s.prefs().shortcuts.clone(); - let mut alternates = s.prefs().alternate_shortcuts.clone(); - pin_shortcut(&mut s.actions.list, first, &mut shortcuts, &mut alternates)?; - if shortcuts != s.prefs().shortcuts || alternates != s.prefs().alternate_shortcuts { - s.edit_prefs(|prefs| { - prefs.shortcuts = shortcuts; - prefs.alternate_shortcuts = alternates; - }); + 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); @@ -1064,18 +1076,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); } @@ -1086,7 +1103,7 @@ 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 by_name && (s.prefs().shortcuts.contains_key(&from) || s.prefs().alternate_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.clone(), key); diff --git a/crates/engine/src/cmd/actions_cmds/identity.rs b/crates/engine/src/cmd/actions_cmds/identity.rs index 2d5b1d8341b..4b744efdc2c 100644 --- a/crates/engine/src/cmd/actions_cmds/identity.rs +++ b/crates/engine/src/cmd/actions_cmds/identity.rs @@ -1,5 +1,5 @@ //! Persisted action occurrences are independent of name, list order, and folder position. -use std::collections::{BTreeMap, HashSet}; +use std::collections::HashSet; use super::{Action, PLAY_SHORTCUT_PREFIX, bad}; use crate::{Result, Session}; @@ -57,6 +57,10 @@ pub fn shortcut_row(list: &[Action], key: &str) -> Option { 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) } @@ -75,13 +79,21 @@ pub fn prepare_action_id(list: &[Action], index: usize) -> Result { Ok(id) } -/// Complete a successful shortcut edit. The shortcut command only edits preferences. -pub fn commit_action_id(s: &mut Session, index: usize, id: String) { - if s.actions.list[index].action_id.is_none() { - s.actions.list[index].action_id = Some(id); - s.actions.touch(); - s.sync_preset_store(); +/// 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<()> { + if s.actions.list[index].action_id.is_some() { + return Ok(()); } + 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. @@ -98,27 +110,9 @@ pub fn action_shortcut(s: &Session, index: usize) -> Option<&str> { (shortcut_row(list, &legacy) == Some(index)).then(|| keys.get(&legacy)).flatten().map(String::as_str) } -/// Move a legacy binding to its already resolved row before an edit changes name lookup. -pub(crate) fn pin_shortcut( - list: &mut [Action], - index: usize, - shortcuts: &mut BTreeMap, - alternates: &mut BTreeMap>, -) -> Result<()> { - let legacy = format!("{PLAY_SHORTCUT_PREFIX}{}", list[index].name); - if shortcut_row(list, &legacy) != Some(index) || !(shortcuts.contains_key(&legacy) || alternates.contains_key(&legacy)) { - return Ok(()); - } - let id = prepare_action_id(list, index)?; - let key = occurrence_key(&id); - list[index].action_id = Some(id); - if let Some(binding) = shortcuts.remove(&legacy) { - shortcuts.entry(key.clone()).or_insert(binding); - } - if let Some(bindings) = alternates.remove(&legacy) { - alternates.entry(key).or_insert(bindings); - } - Ok(()) +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. 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 1291dc8016c..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, is_action_key, not_playing, pin_shortcut}; +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; @@ -104,13 +104,16 @@ pub(crate) fn publish_library( let (after_shortcuts, after_alternates) = match new_shortcuts { Some(keys) => (keys, Alternates::new()), None => { - let (mut keys, mut alternate_keys) = (shortcuts.clone(), alternates.clone()); let count = s.actions.list.len(); - let owners: Vec<_> = list[count..].iter().filter_map(|action| list[..count].iter().position(|prior| prior.name == action.name)).collect(); + 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 { - pin_shortcut(&mut list, owner, &mut keys, &mut alternate_keys)?; + list[owner].legacy_shortcut_owner = true; } - (keys, alternate_keys) + (shortcuts.clone(), alternates.clone()) } }; check_library_size(&list, &sets, &rows, cmd)?; 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 75144cbab12..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 @@ -141,19 +141,16 @@ fn repeated_reset_pins_existing_shortcuts_and_undo_restores_legacy_keys() { assert_eq!(s.prefs().alternate_shortcuts, prefs.alternate_shortcuts); s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); - let key = crate::actions_cmds::occurrence_key(s.actions.list[0].action_id.as_deref().unwrap()); - assert_eq!(crate::actions_cmds::shortcut_row(&s.actions.list, &key), Some(0)); - assert_eq!(s.prefs().shortcuts[&key], "F2"); - assert_eq!(s.prefs().alternate_shortcuts[&key], ["F3"]); - assert!(!s.prefs().shortcuts.contains_key(&shortcut)); - assert!(!s.prefs().alternate_shortcuts.contains_key(&shortcut)); + assert!(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"]); - assert!(!s.prefs().shortcuts.contains_key(&key)); } #[test] @@ -184,7 +181,7 @@ fn atn_export_and_load_keep_function_keys_of_duplicate_rows_separate() { 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); + 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(); @@ -220,6 +217,36 @@ fn attachment_keeps_disk_batch_targets_and_does_not_resolve_foreign_ids() { 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() { diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index bf261bc0398..3a8958c02d9 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -1108,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] { @@ -1210,7 +1218,11 @@ impl Session { } } for mut action in disk { - if action.set_slot.is_some() || action.action_id.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); } diff --git a/crates/engine/src/preset_store/actions.rs b/crates/engine/src/preset_store/actions.rs index 4bb8077c939..8128238235c 100644 --- a/crates/engine/src/preset_store/actions.rs +++ b/crates/engine/src/preset_store/actions.rs @@ -5,8 +5,7 @@ use serde_json::{Value, json}; use crate::Session; use crate::actions_cmds::{ - Action, PLAY_SHORTCUT_PREFIX, branch_id_field, conditional_branch, pin_shortcut, prepare_action_id, resolve_play_target, shortcut_row, valid_action_id, - visit_calls, + 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. @@ -38,23 +37,16 @@ pub(super) fn pin_disk_targets(s: &mut Session, disk: &mut [Action], warnings: & block_unknown_ids(disk); let memory = &s.actions.list; - // A legacy shortcut read with the saved preferences belongs to the first disk match. - // The current Action Options path already gives a newly assigned in-memory binding an ID. - let (mut keys, mut alternates) = (s.prefs().shortcuts.clone(), s.prefs().alternate_shortcuts.clone()); - let owners: Vec<_> = keys - .keys() - .chain(alternates.keys()) - .filter_map(|key| { - let name = key.strip_prefix(PLAY_SHORTCUT_PREFIX)?; - memory.iter().any(|action| action.name == name).then(|| shortcut_row(disk, key)).flatten().map(|row| (key.clone(), row)) - }) - .collect(); - for (key, row) in owners { - if let Err(error) = pin_shortcut(disk, row, &mut keys, &mut alternates) { - // The original target cannot be identified. The legacy key must not play a memory row. - keys.remove(&key); - alternates.remove(&key); - warnings.push(format!("actions: {error}")); + // 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; } } @@ -65,10 +57,10 @@ pub(super) fn pin_disk_targets(s: &mut Session, disk: &mut [Action], warnings: & 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 Ok(target) = resolve(disk) - { - params["actionId"] = pin_target(disk, target, warnings); + 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" => { @@ -79,9 +71,9 @@ pub(super) fn pin_disk_targets(s: &mut Session, disk: &mut [Action], warnings: & } if let Ok(Some(target)) = conditional_branch(params, branch) && resolve_play_target(memory, &target, command).is_ok() - && let Ok(target) = resolve_play_target(disk, &target, command) { - params[field] = pin_target(disk, target, warnings); + let original = resolve_play_target(disk, &target, command); + params[field] = original.map_or(Value::Null, |row| pin_target(disk, row, warnings)); } } } @@ -89,12 +81,6 @@ pub(super) fn pin_disk_targets(s: &mut Session, disk: &mut [Action], warnings: & }); disk[row].steps = steps; } - if keys != s.prefs().shortcuts || alternates != s.prefs().alternate_shortcuts { - s.edit_prefs(|prefs| { - prefs.shortcuts = keys; - prefs.alternate_shortcuts = alternates; - }); - } } fn pin_target(list: &mut [Action], index: usize, warnings: &mut Vec) -> Value { diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index f8bffa8800c..937c0ce54d5 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -49,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_row = |key: &str| actions_cmds::shortcut_row(&app.session.actions.list, key); - let actions = prefs.shortcuts.keys().filter(|id| action_row(id.as_str()).is_some()).map(|id| (id.as_str(), prefs.shortcut(id, None).map(str::to_string))); + 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). @@ -99,7 +110,7 @@ pub fn bindings(app: &PhotocraftApp) -> Vec<(String, KeyboardShortcut)> { let alternate_ids: std::collections::BTreeSet<&str> = photocraft_engine::prefs::ALTERNATE_SHORTCUTS.iter().map(|(id, _)| *id).chain(prefs.alternate_shortcuts.keys().map(String::as_str)).collect(); for id in alternate_ids { - if actions_cmds::is_action_key(id) && action_row(id).is_none() { + 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); @@ -375,10 +386,17 @@ 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 is_action = actions_cmds::is_action_key(id); - let action = actions_cmds::shortcut_row(&app.session.actions.list, id).map(|row| &app.session.actions.list[row]); + let 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) { @@ -390,10 +408,12 @@ 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(action) = action { + 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) => json!({"action": name}), - None => json!({"actionId": action.action_id}), + 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| { diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index f1894722df8..eb38d03054d 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -814,10 +814,15 @@ fn f3_dispatches_only_the_second_same_named_action_after_reorder_and_reopen() { 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(); @@ -852,9 +857,10 @@ fn attachment_preserves_disk_keys_and_calls_without_changing_name_lookup() { 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 = action_key(&h, 1); - assert_eq!(h.state().session.prefs().shortcuts[&disk_key], "F2"); - assert_eq!(h.state().session.prefs().alternate_shortcuts[&disk_key], ["F3"]); + 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"); @@ -876,6 +882,70 @@ fn attachment_preserves_disk_keys_and_calls_without_changing_name_lookup() { } } +#[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(); diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 563336e0a8b..d5ffa52803e 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -231,28 +231,36 @@ pub(crate) fn assign_shortcut(app: &mut PhotocraftApp, index: usize, shortcut: & 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(); - let mut alternates = serde_json::Map::new(); - // A function key belongs to only one action. Ordinary menu bindings remain intact. + // 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() { + 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!("")); } } - if actions_cmds::shortcut_row(list, &legacy) == Some(index) { - if prefs.shortcuts.contains_key(&legacy) { - set.insert(legacy.clone(), Value::Null); - } - if let Some(keys) = prefs.alternate_shortcuts.get(&legacy) { - if !prefs.alternate_shortcuts.contains_key(&id) { - alternates.insert(id.clone(), json!(keys)); - } - alternates.insert(legacy, Value::Null); - } - } set.insert(id, json!(shortcut)); - let result = app.run("edit.keyboardShortcuts", json!({"set": set, "alternates": alternates, "allowUnknown": true, "removeConflicts": false}))?; - actions_cmds::commit_action_id(&mut app.session, index, action_id); + 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) } diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 39488b0a0f2..bc88b84b1d5 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -2146,6 +2146,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();