Preserve saved action targets during preset attachment

This commit is contained in:
yoriswind committed 2026-11-06 10:14:33 -08:00
1 parent 19722cf5a4
commit beb42e396b
11 files changed
+405 -162

No files matched your search

+120 -86
View File
@@ -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<String>) -> 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<String>,
}
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<String>,
pub playback_stack: Vec<PlaybackTarget>,
/// 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<Action> {
/// Resolve in the current namespace before capture rewrites the reference.
fn target(list: &[Action], params: &Value, id: &str) -> Result<usize> {
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<usize>) {
@@ -365,8 +382,9 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec<Act
}
"actions.conditional" => {
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<Act
for i in scoped {
if let Some(action) = list.get(i) {
slots.insert(i, found.len() + originals.len());
originals.push(action.clone());
let mut original = action.clone();
if exported.contains_key(&i) {
// The scoped caller already selects this copy by index.
original.action_id = None;
}
originals.push(original);
}
}
// A named Batch selects from the caller before switching to its embedded list. Its source
@@ -419,6 +442,7 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec<Act
// The pinned source slot identifies its set; a numeric Batch choice cannot carry a named set.
if let Some(object) = params.as_object_mut() {
object.remove("set");
object.remove("actionId");
}
return;
}
@@ -436,6 +460,9 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec<Act
}
_ => 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<i64> {
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<usize> {
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<Option<Value>> {
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<usize> {
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<Option<(usize,
}
let recording = s.actions.recording.take();
s.actions.playing = s.actions.playing.saturating_add(1);
s.actions.playback_stack.push(action.name.clone());
s.actions.playback_stack.push(PlaybackTarget::from(action));
Ok(recording)
}
@@ -753,18 +806,28 @@ pub fn finish_playback(s: &mut Session, recording: Option<(usize, usize)>, 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<Value> {
/// Prefix of the persisted shortcut override that plays a named action (`actions.play:<name>`).
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.
+13 -1
View File
@@ -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<usize> {
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<usize> {
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<usize> {
if let Some(id) = key.strip_prefix(OCCURRENCE_PREFIX) {
return resolve_action_id(list, id);
+7 -16
View File
@@ -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<Value> {
Some(Value::String(c)) => c.clone(),
_ => return Err(bad(cmd, format!("needs `if`, one of {}", CONDITIONS.join("|")))),
};
let branch = |key: &str| -> Result<Option<String>> {
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)
}
@@ -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() {
+28 -1
View File
@@ -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<Vec<AtnItem>> {
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, &params, 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;
+9 -6
View File
@@ -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<usize> {
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<Value> {
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<Value> {
// 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<Value> {
// 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<Value> {
}
}
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 },
+7 -7
View File
@@ -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.
+7 -5
View File
@@ -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<String> {
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
+111
View File
@@ -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<String>) {
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<String>) -> 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
}
}
}
@@ -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();
+37 -40
View File
@@ -326,11 +326,19 @@ fn end_at(c: Called, ran: &mut u64, failed: &mut Option<Value>, 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<Called> {
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<Called> {
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<Player> {
/// 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<Value, String> {
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, &params)?;
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<Value>, inner: &[(String, usize)]) -> Result<Value, String> {
fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option<Value>, inner: &[(&Action, usize)]) -> Result<Value, String> {
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<Value>,
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<Value>,
history: Option<actions_cmds::ActionHistoryContinuation>,
/// 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<Action>,
/// 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<Action>,
}
@@ -1357,15 +1358,13 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map<String, Value>)
}
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<String, Value>)
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<String, Value>)
}
// 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;