diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index 662d8f45a0..a96e668244 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -548,6 +548,11 @@ fn get(s: &mut Session, p: &Value) -> Result { /// Start capture into the selected or newly created definition while refusing incompatible playback state. fn record(s: &mut Session, p: &Value) -> Result { + let destination = library::RowBinding::requested(&s.actions, p, library::placement::SelectorUse::NewAction).map_err(|error| bad("actions.record", error))?; + if p.get("action").is_some() && (p.get("set").is_some() || p.get("name").is_some()) { + return Err(bad("actions.record", "record an existing action without replacement name/set fields")); + } + if destination.is_some() { library::placement::idle(s, "actions.record")?; } not_playing(s, "actions.record")?; if s.actions.recording_active() { return Err(bad("actions.record", "already recording; stop first")); @@ -578,9 +583,18 @@ 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")), }; - s.actions.list.push(Action { set, ..Action::new(name, Vec::new()) }); - s.actions.touch(); - s.actions.list.len() - 1 + let value = Action { set, ..Action::new(name, Vec::new()) }; + if let Some(destination) = destination { + let prepared = library::placement::prepare(&s.actions, &s.prefs().shortcuts, &s.prefs().alternate_shortcuts, + library::placement::Edit::Insert { destination, action:value }).map_err(|error| bad("actions.record", error))?; + let index = prepared.result["index"].as_u64().and_then(|value| usize::try_from(value).ok()).ok_or_else(|| bad("actions.record", "missing prepared action index"))?; + prepared.publish(s); + index + } else { + s.actions.list.push(value); + s.actions.touch(); + s.actions.list.len() - 1 + } }; s.actions.recording = Some((s.journal.len(), idx)); s.actions.take = s.actions.take.wrapping_add(1); @@ -906,6 +920,15 @@ fn move_item(s: &mut Session, p: &Value) -> Result { let moved = s.actions.list.remove(idx); let result = json!({"action": moved.name, "index": to}); s.actions.list.insert(to, moved); + // A direct list reorder follows the same known numeric call surface as physical moves. + let count = s.actions.list.len(); + for (id, params) in s.actions.list.iter_mut().flat_map(|action| &mut action.steps) { + for &key in call_keys(id) { + let Some(old) = params.get(key).and_then(num).and_then(|value| usize::try_from(value).ok()).filter(|&old| old < count) else { continue }; + let new = moved_index(old, idx, to); + if new != old { params[key] = json!(new); } + } + } if let Some((_, recording)) = s.actions.recording.as_mut() { *recording = moved_index(*recording, idx, to); } @@ -929,6 +952,13 @@ pub fn moved_index(index: usize, from: usize, to: usize) -> usize { /// Delete the selected set, action or step with the appropriate playback and recording guards. fn delete(s: &mut Session, p: &Value) -> Result { + let physical = library::RowBinding::requested(&s.actions, p, library::placement::SelectorUse::Folder).map_err(|error| bad("actions.delete", error))?; + if let Some(source) = physical { + library::placement::idle(s, "actions.delete")?; + let prepared = library::placement::prepare(&s.actions, &s.prefs().shortcuts, &s.prefs().alternate_shortcuts, + library::placement::Edit::Delete { source }).map_err(|error| bad("actions.delete", error))?; + return Ok(prepared.publish(s)); + } not_playing(s, "actions.delete")?; if p.get("set").is_some() { if p.get("action").is_some() || p.get("step").is_some() { @@ -1226,7 +1256,7 @@ pub fn specs() -> Vec { label: "Record Action", menu: &[], shortcut: None, - params: r##"{"name":str? (new action, default "Action N"),"set":name? (the set it goes in, as New Action records into the selected set)} or {"action":name|index} (append) → {action, index}"##, + params: r##"{"name":str? (new action, default "Action N"),"set":name?,"setSlot":current physical slot? (new action destination; exact optional caption)} or {"action":name|index} (append) → {action, index}"##, enabled: always, run: record, journal: false, @@ -1256,7 +1286,7 @@ pub fn specs() -> Vec { label: "Delete Action", menu: &[], shortcut: None, - params: r##"{"action":name|index, "step":index?} or {"set":name} → {deleted:name} or {action,deletedStep,steps} or {deletedSet,deleted:[name…]}. Step is 0-based, including pending recorded steps. Deleting a folder also deletes its contents, including an empty folder. Whole-action/folder deletion requires recording to be stopped. Calls to survivors keep their target; calls to deleted actions become invalid."##, + params: r##"{"action":name|index, "step":index?} or {"set":name?,"setSlot":current physical slot?} → {deleted:name} or {action,deletedStep,steps} or {deletedSet,deleted:[name…]}. Step is 0-based, including pending recorded steps. Deleting a folder also deletes its contents, including an empty folder. Whole-action/folder deletion requires recording to be stopped. Calls to survivors keep their target; calls to deleted actions become invalid."##, enabled: always, run: delete, journal: false, diff --git a/crates/engine/src/cmd/actions_cmds/editor.rs b/crates/engine/src/cmd/actions_cmds/editor.rs index 08aaee1ace..4371dc5b24 100644 --- a/crates/engine/src/cmd/actions_cmds/editor.rs +++ b/crates/engine/src/cmd/actions_cmds/editor.rs @@ -88,13 +88,13 @@ pub(super) fn preview_value(s: &Session, id: u64) -> Result { /// Require both this draft identity and its unchanged staged value before an owned preview resumes. pub(super) fn preview_matches(s: &Session, id: u64, snapshot: &Action) -> bool { - s.actions.editor.as_ref().is_some_and(|draft| draft.id == id && &draft.value == snapshot) + s.actions.editor.as_ref().is_some_and(|draft| draft.id == id && &draft.value == snapshot && super::library::same_placement(&draft.value, snapshot)) } /// Structured inspection serializes the complete Action, not a metadata whitelist. fn view(draft: &Draft, value: &Action) -> Value { json!({"draft":draft.id, "action":value, "shortcut":draft.shortcut, - "dirty": value != &draft.opening || draft.shortcut != draft.opening_shortcut, + "dirty": value != &draft.opening || !super::library::same_placement(value, &draft.opening) || draft.shortcut != draft.opening_shortcut, "recording":draft.recording.is_some(), "source":draft.source, "libraryRevision":draft.library_revision}) } @@ -133,7 +133,8 @@ fn new_value(s: &Session, p: &Value) -> Result { /// Open one complete action clone, without changing the library, shortcuts or preset store. fn open(s: &mut Session, p: &Value) -> Result { - fields(p, &["action", "name", "set"], OPEN)?; + fields(p, &["action", "name", "set", "setSlot"], OPEN)?; + let destination = super::library::RowBinding::requested(&s.actions, p, super::library::placement::SelectorUse::NewAction).map_err(|error| bad(OPEN, error))?; not_playing(s, OPEN)?; if s.actions.editor.is_some() || s.actions.recording_active() { return Err(bad(OPEN, "close the open editor or stop recording first")); @@ -142,10 +143,11 @@ fn open(s: &mut Session, p: &Value) -> Result { if source.is_some() && (p.get("name").is_some() || p.get("set").is_some()) { return Err(bad(OPEN, "open an existing action without replacement name/set fields")); } - let value = match source { + let mut value = match source { Some(index) => s.actions.list.get(index).cloned().ok_or_else(|| bad(OPEN, "no such action"))?, None => new_value(s, p)?, }; + if let Some(destination) = destination { destination.apply(&mut value); } let id = s.actions.take.checked_add(1).ok_or_else(|| bad(OPEN, "recording identities exhausted"))?; let shortcut = s.prefs().shortcuts.get(&format!("{}{}", super::PLAY_SHORTCUT_PREFIX, value.name)).cloned().unwrap_or_default(); let draft = Draft { @@ -407,7 +409,8 @@ fn stop(s: &mut Session, p: &Value) -> Result { /// Reject external library/shortcut edits before preparing any definition publication. fn unchanged(s: &Session, draft: &Draft) -> Result<()> { - let source_changed = draft.source.is_some_and(|index| s.actions.list.get(index) != Some(&draft.opening)); + let source_changed = draft.source.is_some_and(|index| s.actions.list.get(index).is_none_or(|value| + value != &draft.opening || !super::library::same_placement(value, &draft.opening))); if s.actions.rev != draft.library_revision || source_changed || action_keys(&s.prefs().shortcuts) != draft.keys @@ -488,7 +491,8 @@ fn save(s: &mut Session, p: &Value) -> Result { } unchanged(s, draft)?; let mut value = visible(s, draft)?; - if value == draft.opening && draft.shortcut == draft.opening_shortcut { + if let Some(destination) = &value.library_row { destination.slot(&s.actions).map_err(|error| bad(SAVE, error))?; } + if value == draft.opening && super::library::same_placement(&value, &draft.opening) && draft.shortcut == draft.opening_shortcut { // Save closes this capture even when it has no completed steps. The committed // library, shortcut maps and their revisions still remain exactly unchanged. let mut next = draft.clone(); @@ -513,47 +517,43 @@ fn save(s: &mut Session, p: &Value) -> Result { .chain(draft.source.is_none().then_some(&value)), ) .map_err(|error| bad(SAVE, error))?; - let (keys, alternates) = bindings(s, draft, &value); - let target = draft.source.unwrap_or(s.actions.list.len()); - let changed = draft.source.is_none() || value != draft.opening || !changes.is_empty(); - let prefs_changed = keys != s.prefs().shortcuts || alternates != s.prefs().alternate_shortcuts; + let (mut keys, mut alternates) = bindings(s, draft, &value); + let changed = draft.source.is_none() || value != draft.opening || !super::library::same_placement(&value, &draft.opening) || !changes.is_empty(); + let mut proposed = super::library::definition_copy(&s.actions); + // Renamed callers and the edited action remain one preflighted transaction. + for (action, step, params) in changes { + if let Some((_, old)) = proposed.list.get_mut(action).and_then(|action| action.steps.get_mut(step)) { *old = params; } + } + let target; + if draft.source.is_none() && value.library_row.is_some() { + let destination = value.library_row.clone().ok_or_else(|| bad(SAVE, "missing draft destination"))?; + let prepared = super::library::placement::prepare(&proposed, &keys, &alternates, + super::library::placement::Edit::Insert { destination, action:value }).map_err(|error| bad(SAVE, error))?; + target = prepared.result["index"].as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad(SAVE, "missing prepared action index"))?; + proposed = prepared.definition; + keys = prepared.shortcuts; + alternates = prepared.alternates; + } else { + target = draft.source.unwrap_or(proposed.list.len()); + if target == proposed.list.len() { + proposed.list.try_reserve(1).map_err(|_| bad(SAVE, "not enough memory for the action"))?; + proposed.list.push(value); + } else if let Some(old) = proposed.list.get_mut(target) { *old = value; } + super::library::check_definition(&proposed, &keys).map_err(|error| bad(SAVE, error))?; + } + // The prepared insertion may remap this value's numeric calls; acknowledge that exact value. + let published = proposed.list.get(target).cloned().ok_or_else(|| bad(SAVE, "missing prepared definition"))?; let mut next = draft.clone(); - next.value = value.clone(); - next.opening = value.clone(); + next.value = published.clone(); + next.opening = published.clone(); next.source = Some(target); next.library_revision = if changed { s.actions.rev.saturating_add(1) } else { s.actions.rev }; next.opening_shortcut = next.shortcut.clone(); next.keys = action_keys(&keys); next.alternates = action_keys(&alternates); next.recording = None; - let response = view(&next, &value); - let mut proposed = super::library::definition_copy(&s.actions); - if target == proposed.list.len() { - proposed.list.try_reserve(1).map_err(|_| bad(SAVE, "not enough memory for the action"))?; - } - // Include renamed callers in the same encoded candidate as the edited action. - for (action, step, params) in changes { - if let Some((_, old)) = proposed.list.get_mut(action).and_then(|action| action.steps.get_mut(step)) { - *old = params; - } - } - if target == proposed.list.len() { - proposed.list.push(value); - } else if let Some(old) = proposed.list.get_mut(target) { - *old = value; - } - super::library::check_definition(&proposed, &keys).map_err(|error| bad(SAVE, error))?; - // Encoding succeeded. Publish definitions without replacing the live capture/owner state. - s.actions.list = proposed.list; - if changed { - s.actions.touch(); - } - if prefs_changed { - s.edit_prefs(|prefs| { - prefs.shortcuts = keys; - prefs.alternate_shortcuts = alternates; - }); - } + let response = view(&next, &published); + super::library::placement::publish(s, proposed, keys, alternates, changed); s.actions.editor = Some(next); Ok(response) } @@ -578,7 +578,7 @@ pub(super) fn specs() -> Vec { command( OPEN, "Open Action Draft", - r#"{"action":name|index?} or {"name":str?,"set":str?} → draft view. One unpublished complete Action; untouched New Save is a no-op."#, + r#"{"action":name|index?} or {"name":str?,"set":str?,"setSlot":current physical slot?} → draft view. One unpublished complete Action; untouched New Save is a no-op."#, open, ), command( diff --git a/crates/engine/src/cmd/actions_cmds/library.rs b/crates/engine/src/cmd/actions_cmds/library.rs index 6266ea7504..4a670482ee 100644 --- a/crates/engine/src/cmd/actions_cmds/library.rs +++ b/crates/engine/src/cmd/actions_cmds/library.rs @@ -10,7 +10,7 @@ use super::{Action, ActionState, color_to_atn}; use crate::atn_cmds::{self, sidecar}; pub(crate) mod placement; -pub use placement::RowBinding; +pub use placement::{RowBinding, same_placement}; type Result = std::result::Result; const MAX_BYTES: usize = crate::preset_store::MAX_ACTIONS_BYTES as usize; diff --git a/crates/engine/src/cmd/actions_cmds/library/placement.rs b/crates/engine/src/cmd/actions_cmds/library/placement.rs index 48d458903e..64854cc477 100644 --- a/crates/engine/src/cmd/actions_cmds/library/placement.rs +++ b/crates/engine/src/cmd/actions_cmds/library/placement.rs @@ -1,4 +1,4 @@ -//! Isolated checked physical-placement prototype. No public command adapter is installed here. +//! Checked physical placement used by existing Actions command adapters. //! Prepared candidates own definitions/maps only; callers must retain their normal lifetime gates. use std::{collections::{BTreeMap, HashMap, HashSet}, sync::Arc}; use super::{Action, ActionState, RowOrigin, Result, atn_cmds, sidecar}; @@ -55,13 +55,62 @@ impl RowBinding { Ok(slot) } - fn apply(&self, action: &mut Action) { + pub(crate) fn apply(&self, action: &mut Action) { action.set = Some(self.name.clone()); action.library_row = Some(self.clone()); sidecar::place_metadata(action, self.carrier.clone()); } } +impl RowBinding { + /// Placement-only no-op detection uses the current checked context, not Action::PartialEq. + pub(crate) fn contains(&self, state: &ActionState, action: &Action) -> Result { + self.slot(state)?; + let raw = state.library.row_index(&state.sets).source(action)?; + Ok(atn_cmds::logical_set_name(action.set.as_deref()) == self.name + && raw.as_ref().map(RowOrigin::key) == self.row.as_ref().map(RowOrigin::key)) + } +} + +/// Runtime snapshot comparison only; ordinary Action equality retains its reload contract. +pub fn same_placement(left: &Action, right: &Action) -> bool { + let row = |action: &Action| action.library_row.as_ref().map(|binding| binding.row.as_ref().map(RowOrigin::key)) + .unwrap_or_else(|| action.library_origin.as_ref().map(|origin| origin.row.key())); + if atn_cmds::logical_set_name(left.set.as_deref()) != atn_cmds::logical_set_name(right.set.as_deref()) || row(left) != row(right) { return false; } + match (&left.library_row, &right.library_row) { + (Some(left), Some(right)) => left.carrier == right.carrier, + _ => true, + } +} + +/// Publish a fully validated candidate without replacing capture, editor, Owner or counters. +pub(crate) fn publish(s: &mut crate::Session, definition: ActionState, shortcuts: Keys, alternates: Alternates, changed: bool) { + s.actions.list = definition.list; + s.actions.sets = definition.sets; + s.actions.library = definition.library; + s.actions.atn_set_rows = definition.atn_set_rows; + if shortcuts != s.prefs().shortcuts || alternates != s.prefs().alternate_shortcuts { + s.edit_prefs(|prefs| { prefs.shortcuts = shortcuts; prefs.alternate_shortcuts = alternates; }); + } + if changed { s.actions.touch(); } +} + +impl Prepared { + pub(crate) fn publish(self, s: &mut crate::Session) -> Value { + publish(s, self.definition, self.shortcuts, self.alternates, true); + self.result + } +} + +/// Moving indices while a capture/job owns them must fail before any recording flush. +pub(crate) fn idle(s: &crate::Session, command: &str) -> crate::Result<()> { + super::super::not_playing(s, command)?; + if s.actions.recording_active() || s.has_recording_job() { + return Err(super::super::bad(command, "finish recording and its pending step before editing a physical folder")); + } + Ok(()) +} + /// All readers use the same checked destination and current row-local carrier. /// Temporary indexes preserve linear validation even when many actions share a caption. pub(crate) fn validate(state: &ActionState) -> Result<()> { @@ -229,9 +278,10 @@ pub(crate) fn prepare(state: &ActionState, shortcuts: &Keys, alternates: &Altern value }).collect(); let count = copied.len(); + let copied_names: Vec<_> = copied.iter().map(|action| action.name.clone()).collect(); definition.list.splice(at..at, copied); crate::actions_edit_cmds::shift_action_calls(&mut definition.list, at, count); - json!({"index":at,"set":name,"slot":destination_slot,"actions":count}) + json!({"index":at,"set":name,"slot":destination_slot,"actions":copied_names}) } Edit::Delete { source } => { let slot = source.slot(state)?; diff --git a/crates/engine/src/cmd/actions_cmds/playback.rs b/crates/engine/src/cmd/actions_cmds/playback.rs index d305188a55..95a179944e 100644 --- a/crates/engine/src/cmd/actions_cmds/playback.rs +++ b/crates/engine/src/cmd/actions_cmds/playback.rs @@ -22,7 +22,7 @@ pub struct Owner { /// Restore a Classic recorder only to one unchanged definition, allowing reorder but rejecting ambiguity. fn classic_index(s: &Session, action: &Action) -> Option { - let mut matches = s.actions.list.iter().enumerate().filter(|(_, candidate)| *candidate == action).map(|(index, _)| index); + let mut matches = s.actions.list.iter().enumerate().filter(|(_, candidate)| *candidate == action && super::library::same_placement(candidate, action)).map(|(index, _)| index); let index = matches.next()?; matches.next().is_none().then_some(index) } diff --git a/crates/engine/src/cmd/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index dff45a9810..92d578f555 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -171,7 +171,7 @@ pub(crate) fn shift_action_calls(actions: &mut [Action], at: usize, count: usize fn duplicate(s: &mut Session, p: &Value) -> Result { let cmd = "actions.duplicate"; not_playing(s, cmd)?; - if p.get("set").is_some() { + if p.get("set").is_some() || p.get("setSlot").is_some() { return duplicate_set(s, p); } let idx = resolve(&s.actions.list, p, cmd)?; @@ -219,6 +219,16 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { /// Copy a folder below its source, using the existing first-appearance order and empty-set model. fn duplicate_set(s: &mut Session, p: &Value) -> Result { let cmd = "actions.duplicate"; + use crate::actions_cmds::library::{RowBinding, placement}; + let physical = RowBinding::requested(&s.actions, p, placement::SelectorUse::Folder).map_err(|error| bad(cmd, error))?; + if let Some(source) = physical { + placement::idle(s, cmd)?; + let mut names = crate::atn_cmds::UniqueNames::new(set_names(s)); + let name = names.claim(&format!("{} copy", source.name)); + let prepared = placement::prepare(&s.actions, &s.prefs().shortcuts, &s.prefs().alternate_shortcuts, + placement::Edit::Duplicate { source, name }).map_err(|error| bad(cmd, error))?; + return Ok(prepared.publish(s)); + } if p.get("action").is_some() || p.get("step").is_some() { return Err(bad(cmd, "select either a set or an action/step")); } @@ -243,6 +253,7 @@ fn duplicate_set(s: &mut Session, p: &Value) -> Result { .map(|mut a| { a.name = names.claim(&format!("{} copy", a.name)); a.set = Some(name.clone()); + if let Some(binding) = &mut a.library_row { binding.name = name.clone(); } a }) .collect(); @@ -327,6 +338,19 @@ fn dialog(s: &mut Session, p: &Value) -> Result { fn assign_set(s: &mut Session, p: &Value) -> Result { let cmd = "actions.assignSet"; + use crate::actions_cmds::library::{RowBinding, placement}; + let physical = RowBinding::requested(&s.actions, p, placement::SelectorUse::Assign).map_err(|error| bad(cmd, error))?; + if let Some(destination) = physical { + placement::idle(s, cmd)?; + let index = resolve(&s.actions.list, p, cmd)?; + if destination.contains(&s.actions, &s.actions.list[index]).map_err(|error| bad(cmd, error))? { + return Ok(json!({"action":s.actions.list[index].name,"set":destination.name,"index":index,"slot":destination.slot(&s.actions).map_err(|error| bad(cmd, error))?})); + } + let mut prepared = placement::prepare(&s.actions, &s.prefs().shortcuts, &s.prefs().alternate_shortcuts, + placement::Edit::Assign { destination, action:index }).map_err(|error| bad(cmd, error))?; + prepared.result["action"] = json!(s.actions.list[index].name); + return Ok(prepared.publish(s)); + } not_playing(s, cmd)?; let idx = resolve(&s.actions.list, p, cmd)?; let set = match p.get("set") { @@ -337,6 +361,7 @@ fn assign_set(s: &mut Session, p: &Value) -> Result { }; crate::atn_cmds::sidecar::assign_set_metadata(&mut s.actions, idx, set.as_deref()); let action = &mut s.actions.list[idx]; + if crate::atn_cmds::logical_set_name(action.set.as_deref()) != crate::atn_cmds::logical_set_name(set.as_deref()) { action.library_row = None; } action.set = set; let result = json!({"action": action.name, "set": action.set}); s.actions.touch(); @@ -576,7 +601,7 @@ pub fn specs() -> Vec { label: "Duplicate Action", menu: &[], shortcut: None, - params: r##"{"action":name|index, "step":index?} or {"set":name} → {action,index,steps} or {set,actions,index}. Copies a step, action or entire folder below its source, retaining settings and flags. Whole-action/folder copies require recording to be stopped; original function keys stay with their original actions."##, + params: r##"{"action":name|index, "step":index?} or {"set":name?,"setSlot":current physical slot?} → {action,index,steps} or {set,actions,index}. Copies a step, action or entire folder below its source, retaining settings and flags. Whole-action/folder copies require recording to be stopped; original function keys stay with their original actions."##, enabled: always, run: duplicate, journal: false, @@ -616,7 +641,7 @@ pub fn specs() -> Vec { label: "Move to Set", menu: &[], shortcut: None, - params: r##"{"action":name|index, "set":name|null} → {action, set}. The set folder the Actions panel shows the action under (what Load Actions fills and Save Actions writes); null takes it out of any set."##, + params: r##"{"action":name|index, "set":name|null?, "setSlot":current physical slot?} → {action, set, index?, slot?}. The set folder the Actions panel shows the action under (what Load Actions fills and Save Actions writes); null takes it out of any set."##, enabled: always, run: assign_set, journal: false, diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index d28b1315fe..b8959b6f39 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -169,6 +169,8 @@ fn import_actions(s: &mut Session, p: &Value, whole: bool) -> Result { /// Encode the selected action or library while retaining its physical source and metadata. pub(super) fn save(s: &mut Session, p: &Value) -> Result { let cmd = "actions.save"; + let physical = crate::actions_cmds::library::RowBinding::requested(&s.actions, p, + crate::actions_cmds::library::placement::SelectorUse::Folder).map_err(|error| bad(cmd, error))?; crate::actions_cmds::flush_recording(s)?; let skip = match p.get("skipUnsupported") { None | Some(Value::Null) => false, @@ -183,14 +185,7 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), }; - let physical_slot = match p.get("setSlot") { - None | Some(Value::Null) => None, - Some(value) => Some(value.as_u64().and_then(|slot| usize::try_from(slot).ok()) - .filter(|slot| s.actions.sets.get(*slot).is_some()).ok_or_else(|| bad(cmd, "`setSlot` is not a current physical folder slot"))?), - }; - if physical_slot.is_some() && p.get("action").is_some() { - return Err(bad(cmd, "select either a physical folder or an action")); - } + let physical_slot = physical.as_ref().map(|binding| binding.slot(&s.actions)).transpose().map_err(|error| bad(cmd, error))?; let mut groups = if let Some(slot) = physical_slot { let name = s.actions.sets.get(slot).ok_or_else(|| bad(cmd, "the action folder no longer exists"))?; if set_param.as_ref().is_some_and(|selected| selected != name) { return Err(bad(cmd, "the physical folder name changed")); } diff --git a/crates/engine/tests/it/actions_panel_menu.rs b/crates/engine/tests/it/actions_panel_menu.rs index 2c70c3d360..819680e492 100644 --- a/crates/engine/tests/it/actions_panel_menu.rs +++ b/crates/engine/tests/it/actions_panel_menu.rs @@ -262,3 +262,132 @@ fn tool_recording_opt_in_has_the_same_journal_policy_in_both_recorders() { assert_eq!(s.journal.iter().filter(|(id, _)| id == "paint.stroke").count(), 3); } } + + +fn physical_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":8,"height":6})).unwrap(); + for _ in 0..2 { s.execute("actions.reset", json!({"mode":"append","confirm":true})).unwrap(); } + s +} +fn physical_counts(s: &Session) -> Vec { + actions_edit_cmds::set_occurrences(s).unwrap().iter().map(|row| row.actions.len()).collect() +} + +/// Registered recorder/new-draft adapters retain the chosen physical occurrence through Save. +#[test] +fn physical_record_and_new_draft_save_keep_destinations_and_runtime_counters() { + let mut s = physical_session(); + s.actions.playback_nonce = 73; + s.actions.playback_steps = 19; + let recorded = s.execute("actions.record", json!({"name":"Earlier recorder","setSlot":0,"set":actions_edit_cmds::DEFAULT_SET_NAME})).unwrap(); + assert_eq!(recorded["index"],2); + s.execute("image.adjustments.invert",json!({})).unwrap(); + s.execute("actions.stop",json!({})).unwrap(); + assert_eq!(physical_counts(&s),[3,2]); + let id = s.execute("actions.editor.open",json!({"name":"Second draft","setSlot":1})).unwrap()["draft"].as_u64().unwrap(); + let take = s.actions.take; + s.execute("actions.editor.update",json!({"draft":id,"description":"Published only by Save"})).unwrap(); + let saved = s.execute("actions.editor.save",json!({"draft":id})).unwrap(); + assert_eq!(saved["source"],5); + assert_eq!(saved["dirty"],false); + assert_eq!(physical_counts(&s),[3,3]); + assert_eq!(s.actions.take,take); + assert_eq!((s.actions.playback_nonce,s.actions.playback_steps),(73,19)); + let revision = s.actions.rev; + s.execute("actions.editor.save",json!({"draft":id})).unwrap(); + assert_eq!(s.actions.rev,revision,"unchanged Save is still a no-op"); + s.execute("actions.editor.discard",json!({"draft":id})).unwrap(); + let before = s.actions.list.len(); + let id = s.execute("actions.editor.open",json!({"name":"Untouched new draft","setSlot":0})).unwrap()["draft"].as_u64().unwrap(); + s.execute("actions.editor.save",json!({"draft":id})).unwrap(); + assert_eq!(s.actions.list.len(),before,"unchanged New Save keeps C's no-publication contract"); +} + +/// A placement-only move changes revision despite logical equality; occurrence deletion owns both maps. +#[test] +fn physical_assign_duplicate_delete_preserve_namesakes_and_both_binding_maps() { + let mut s = physical_session(); + let index = s.execute("actions.record",json!({"name":"Move me","setSlot":1})).unwrap()["index"].as_u64().unwrap() as usize; + s.execute("select.all",json!({})).unwrap(); + s.execute("actions.stop",json!({})).unwrap(); + s.prefs.edit(|prefs| { + prefs.shortcuts.insert("actions.play:Move me".into(),"F4".into()); + prefs.alternate_shortcuts.insert("actions.play:Move me".into(),vec!["F5".into()]); + prefs.shortcuts.insert("actions.play:Invert Colors".into(),"F6".into()); + }); + let old = s.actions.list[index].clone(); + let revision = s.actions.rev; + let moved = s.execute("actions.assignSet",json!({"action":index,"setSlot":0})).unwrap(); + let moved_index = moved["index"].as_u64().unwrap() as usize; + assert_eq!(s.actions.list[moved_index],old,"ordinary logical equality remains unchanged"); + assert!(!photocraft_engine::actions_cmds::library::same_placement(&s.actions.list[moved_index],&old)); + assert!(s.actions.rev > revision); + assert_eq!(physical_counts(&s),[3,2]); + let revision = s.actions.rev; + s.execute("actions.assignSet",json!({"action":moved_index,"setSlot":0})).unwrap(); + assert_eq!(s.actions.rev,revision,"same actual occurrence is a no-op"); + let document = s.active().unwrap().doc.clone(); + let take = s.actions.take; + let copied = s.execute("actions.duplicate",json!({"setSlot":1})).unwrap(); + assert_eq!(copied["actions"].as_array().unwrap().len(),2); + assert_eq!(physical_counts(&s),[3,2,2]); + s.execute("actions.delete",json!({"setSlot":0})).unwrap(); + assert_eq!(physical_counts(&s),[2,2]); + assert!(!s.prefs().shortcuts.contains_key("actions.play:Move me")); + assert!(!s.prefs().alternate_shortcuts.contains_key("actions.play:Move me")); + assert!(s.prefs().shortcuts.contains_key("actions.play:Invert Colors"),"the other namesake still owns this name"); + assert!(std::sync::Arc::ptr_eq(&document,&s.active().unwrap().doc)); + assert_eq!(s.actions.take,take); + // Set-only remains a logical group operation, including actions carrying explicit placement. + s.execute("actions.duplicate",json!({"set":copied["set"]})).unwrap(); +} + +/// Invalid selectors and stale Saves never flush or consume the active Classic/draft capture. +#[test] +fn physical_adapter_refusals_preserve_capture_and_stale_draft() { + let mut s = physical_session(); + s.execute("actions.record",json!({"action":0})).unwrap(); + s.execute("select.all",json!({})).unwrap(); + let cursor = s.actions.recording; + let take = s.actions.take; + let definitions = s.actions.list.clone(); + for params in [json!({"setSlot":99}),json!({"setSlot":null}),json!({"setSlot":0,"set":null}),json!({"setSlot":0,"action":0})] { + assert!(s.execute("actions.record",params.clone()).is_err()); + assert!(s.execute("actions.editor.open",params.clone()).is_err()); + assert!(s.execute("actions.save",params).is_err()); + assert_eq!(s.actions.recording,cursor); + assert_eq!(s.actions.take,take); + assert_eq!(s.actions.list,definitions); + } + assert!(s.execute("actions.assignSet",json!({"action":0,"setSlot":1})).is_err()); + assert!(s.execute("actions.delete",json!({"setSlot":1})).is_err()); + s.execute("actions.stop",json!({})).unwrap(); + let id = s.execute("actions.editor.open",json!({"name":"Held destination","setSlot":1})).unwrap()["draft"].as_u64().unwrap(); + s.execute("actions.editor.update",json!({"draft":id,"description":"Still unpublished"})).unwrap(); + let draft = s.actions.editor.clone(); + let take = s.actions.take; + s.execute("actions.newSet",json!({"name":"External change"})).unwrap(); + let definitions = s.actions.list.clone(); + assert!(s.execute("actions.editor.save",json!({"draft":id})).is_err()); + assert_eq!(s.actions.editor,draft); + assert_eq!(s.actions.take,take); + assert_eq!(s.actions.list,definitions); +} + +/// Direct list reorder follows numeric Conditional branches as well as Play. +#[test] +fn list_reorder_remaps_both_call_forms_without_traversing_foreign_json() { + let mut s = physical_session(); + let foreign = json!({"actions":[{"steps":[["actions.play",{"action":0}]]}]}); + s.actions.list[1].steps.extend([ + ("actions.play".into(),json!({"action":0})), + ("actions.conditional".into(),json!({"if":"always","then":0,"else":1})), + ("file.automate.batch".into(),foreign.clone()), + ]); + s.execute("actions.move",json!({"action":0,"to":1})).unwrap(); + let steps = &s.actions.list[0].steps; + assert_eq!(steps[1].1,json!({"action":1})); + assert_eq!(steps[2].1,json!({"if":"always","then":1,"else":0})); + assert_eq!(steps[3].1,foreign); +} diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index d9b7ffd4e6..8099e5e016 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -149,6 +149,14 @@ impl FolderSelection { if matches.next().is_some() { return Err("the selected Actions folder is ambiguous".into()); } row.slot.ok_or_else(|| "the selected Actions folder has no physical slot".into()) } + + fn checked_params(&self, app: &PhotocraftApp, revision: u64) -> Result { + if self.slot.is_some() { return Ok(json!({"set":self.name,"setSlot":self.checked_slot(app, revision)?})); } + if app.session.actions.rev != revision { return Err("the selected Actions folder changed".into()); } + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session)?; + if rows.iter().filter(|row| self.matches(row)).count() != 1 { return Err("the selected Actions folder changed or is ambiguous".into()); } + Ok(json!({"set":self.name})) + } } fn selected_occurrence(app: &PhotocraftApp) -> Option { @@ -728,6 +736,21 @@ fn new_action_set(app: &PhotocraftApp) -> Option { } } +/// Resolve the actual selected occurrence before opening a recorder or a delayed new draft. +fn new_action_params(app: &PhotocraftApp) -> Result { + let revision = app.session.actions.rev; + if app.ui.actions.selected.is_none() && let Some(key) = &app.ui.actions.selected_folder { + return key.checked_params(app, revision); + } + if let Some(index) = app.ui.actions.selected.filter(|&index| index < app.session.actions.list.len()) { + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session)?; + if let Some(row) = rows.iter().find(|row| row.actions.contains(&index)) { + if row.slot.is_some() { return FolderSelection::from_row(row).checked_params(app, revision); } + } + } + Ok(new_action_set(app).map_or(json!({}), |set| json!({"set":set}))) +} + fn begin_recording(app: &mut PhotocraftApp, append: bool) { if app.session.actions.recording_active() { return; @@ -736,19 +759,29 @@ fn begin_recording(app: &mut PhotocraftApp, append: bool) { // new action like New Action does, in the selected set. let params = match app.ui.actions.selected { Some(i) if append => json!({"action": i}), - _ => new_action_set(app).map_or(json!({}), |set| json!({"set": set})), + _ => match new_action_params(app) { + Ok(params) => params, + Err(error) => { app.ui.status = error; app.ui.status_error = true; return; } + }, }; + let old_count = app.session.actions.list.len(); let Ok(v) = app.run("actions.record", params) else { return }; let Some(i) = v.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()) else { return }; app.ui.actions.select(i, None); - if app.ui.actions.expanded.len() <= i { - app.ui.actions.expanded.resize(i + 1, false); + if app.session.actions.list.len() > old_count { + app.ui.actions.expanded.resize(old_count, false); + app.ui.actions.expanded.insert(i, true); + } else { + app.ui.actions.expanded.resize(app.session.actions.list.len(), false); + if let Some(expanded) = app.ui.actions.expanded.get_mut(i) { *expanded = true; } } - app.ui.actions.expanded[i] = true; - // Its set too, in case its folder is collapsed. - if let Some(action) = app.session.actions.list.get(i) { - let set = photocraft_engine::atn_cmds::logical_set_name(action.set.as_deref()); - app.ui.actions.collapsed_sets.retain(|c| c != set); + // Reveal only the actual recording folder, retaining independent namesake disclosure. + if let Ok(rows) = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session) { + if let Some(row) = rows.iter().find(|row| row.actions.contains(&i)) { + let key = FolderSelection::from_row(row); + app.ui.actions.collapsed_folders.retain(|old| old != &key); + if row.origin.is_none() { app.ui.actions.collapsed_sets.retain(|name| name != &row.name); } + } } } @@ -1649,7 +1682,7 @@ fn classic_panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if ui.add_enabled(can_delete || (!recording && selected_set(app).is_some()), egui::Button::new(tl!("Duplicate"))).clicked() { act = Some("duplicate"); } - if ui.add_enabled(can_delete, egui::Button::new(tl!("Delete"))).clicked() { + if ui.add_enabled(can_delete || (!recording && selected_set(app).is_some()), egui::Button::new(tl!("Delete"))).clicked() { act = Some("delete"); } if ui.add_enabled(any, egui::Button::new(tl!("Play"))).clicked() { @@ -1720,10 +1753,7 @@ fn classic_panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { v.unwrap_or(Value::Null) }) } - "delete" => { - delete_selection(app); - Ok(Value::Null) - } + "delete" => request_delete(app), "duplicate" => duplicate_selection(app), "recordAgain" => record_again::open(app), "toolRecording" => app.run("actions.allowToolRecording", json!({"enabled": !app.session.actions.record_tools})), @@ -1752,6 +1782,8 @@ fn classic_panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { struct DragRow { action: usize, step: Option, + revision: u64, + origin: Option<(usize, usize)>, } /// Drops use an insertion line, converted to the final index expected by actions.move. @@ -1772,6 +1804,45 @@ fn drag_row(ui: &egui::Ui, response: &egui::Response, row: DragRow, t: &Tokens) } fn move_row(app: &mut PhotocraftApp, source: DragRow, to: usize) { + let checked = (|| -> Result, String> { + if source.revision != app.session.actions.rev { return Err("The dragged action changed; drag it again".into()); } + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session)?; + let source_row = rows.iter().find(|row| row.actions.contains(&source.action)).ok_or("The dragged action no longer exists")?; + if source_row.origin != source.origin { return Err("The dragged action folder changed".into()); } + if source.step.is_some() { return Ok(None); } + if to >= app.session.actions.list.len() { return Err("The drop position changed".into()); } + let mut order: Vec<_> = (0..app.session.actions.list.len()).filter(|&index| index != source.action).collect(); + order.insert(to, source.action); + let neighbour = to.checked_sub(1).and_then(|index| order.get(index)).or_else(|| order.get(to + 1)); + let Some(target) = neighbour.and_then(|index| rows.iter().find(|row| row.actions.contains(index))) else { return Ok(None) }; + let key = FolderSelection::from_row(target); + if !key.matches(source_row) && (source_row.origin.is_some() || target.origin.is_some()) { + let mut params = key.checked_params(app, source.revision)?; + if params.get("setSlot").is_none() { return Err("The target folder has no physical slot".into()); } + params["action"] = json!(source.action); + return Ok(Some((params, source.action))); + } + Ok(None) + })(); + match checked { + Err(error) => { app.ui.status = error; app.ui.status_error = true; return; } + Ok(Some((params, from))) => { + match app.run("actions.assignSet", params) { + Ok(result) => { + if let Some(index) = result.get("index").and_then(Value::as_u64).and_then(|index| usize::try_from(index).ok()) { + app.ui.actions.expanded.resize(app.session.actions.list.len(), false); + if from < app.ui.actions.expanded.len() && index < app.ui.actions.expanded.len() { + let expanded = app.ui.actions.expanded.remove(from); app.ui.actions.expanded.insert(index, expanded); + } + app.ui.actions.select(index, None); + } + } + Err(error) => { app.ui.status = error; app.ui.status_error = true; } + } + return; + } + Ok(None) => {} + } let mut params = json!({"action": source.action, "to": to}); if let Some(step) = source.step { params["step"] = json!(step); @@ -1802,11 +1873,20 @@ fn move_row(app: &mut PhotocraftApp, source: DragRow, to: usize) { /// Keep the selection and disclosure rows on the new copy after the engine edits the list. fn duplicate_selection(app: &mut PhotocraftApp) -> Result { if let Some(set) = selected_set(app).map(str::to_string) { + let params = match &app.ui.actions.selected_folder { + Some(key) => key.checked_params(app, app.session.actions.rev)?, + None => json!({"set":set}), + }; let old_len = app.session.actions.list.len(); - let result = app.run("actions.duplicate", json!({"set":set}))?; + let result = app.run("actions.duplicate", params)?; app.ui.actions.selected = None; app.ui.actions.selected_step = None; app.ui.actions.selected_set = result.get("set").and_then(Value::as_str).map(str::to_string); + app.ui.actions.selected_folder = None; + if let Some(slot) = result.get("slot").and_then(Value::as_u64).and_then(|slot| usize::try_from(slot).ok()) { + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session)?; + if let Some(row) = rows.iter().find(|row| row.slot == Some(slot)) { app.ui.actions.select_folder(FolderSelection::from_row(row)); } + } let index = result.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).unwrap_or(old_len); let count = app.session.actions.list.len().saturating_sub(old_len); app.ui.actions.expanded.resize(old_len, false); @@ -1840,6 +1920,20 @@ fn duplicate_selection(app: &mut PhotocraftApp) -> Result { Ok(result) } +fn request_delete(app: &mut PhotocraftApp) -> Result { + if app.ui.actions.selected.is_some() { delete_selection(app); return Ok(Value::Null); } + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session)?; + let key = if let Some(key) = &app.ui.actions.selected_folder { key.clone() } else { + let name = selected_set(app).ok_or("Select an action folder first")?; + let mut matches = rows.iter().filter(|row| row.name == name); + let row = matches.next().ok_or("The selected folder no longer exists")?; + if matches.next().is_some() { return Err("The selected folder is ambiguous".into()); } + FolderSelection::from_row(row) + }; + key.checked_params(app, app.session.actions.rev)?; + modern::ask_delete(app, None, Some(key)) +} + fn delete_selection(app: &mut PhotocraftApp) { let Some(action) = app.ui.actions.selected else { return }; let step = app.ui.actions.selected_step; @@ -2165,7 +2259,7 @@ fn classic_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } else if resp.hovered() { ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); } - if let Some(change) = drag_row(ui, &resp, DragRow { action: i, step: None }, &t) { + if let Some(change) = drag_row(ui, &resp, DragRow { action: i, step: None, revision:app.session.actions.rev, origin:folder.and_then(|folder| folder.origin) }, &t) { moved = Some(change); } let expanded = app.ui.actions.expanded.get(i).copied().unwrap_or(false) && !button_mode; @@ -2234,7 +2328,7 @@ fn classic_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } if expanded { - let context = StepRowsContext { action: i, x0, steps, disabled, dialogs, reveal, tokens: &t }; + let context = StepRowsContext { action: i, x0, steps, disabled, dialogs, reveal, tokens: &t, origin:folder.and_then(|folder| folder.origin) }; let events = draw_step_rows(app, ui, &context); moved = moved.or(events.moved); toggled = toggled.or(events.toggled); @@ -2298,13 +2392,11 @@ fn classic_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new action")).clicked() && !recording_now { begin_recording(app, false); } - let can_delete = app.ui.actions.selected.is_some() && (!recording_now || app.ui.actions.selected_step.is_some()); + let can_delete = (app.ui.actions.selected.is_some() && (!recording_now || app.ui.actions.selected_step.is_some())) || (!recording_now && selected_set(app).is_some()); ui.add_enabled_ui(can_delete, |ui| { let response = crate::icons::button(ui, "trash", 24.0, false, tl!("Delete")); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, can_delete, tl!("Delete"))); - if response.clicked() { - delete_selection(app); - } + if response.clicked() && let Err(error) = request_delete(app) { app.ui.status = error; app.ui.status_error = true; } }); let mode_label = if app.ui.actions.button_mode { tl!("Button Mode On") } else { tl!("Button Mode") }; let mode_button = ui.add_enabled(!recording_now, egui::Button::new(mode_label).small()).on_hover_text(tl!("Button Mode")); @@ -2354,6 +2446,7 @@ struct StepRowsContext<'a> { dialogs: &'a std::collections::BTreeSet, reveal: Option<(usize, usize)>, tokens: &'a Tokens, + origin: Option<(usize, usize)>, } #[derive(Default)] @@ -2372,7 +2465,7 @@ fn draw_step_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, context: &StepRows } let label = step_label(id, params); draw_step_label(app, ui, rect, &response, step, &label, context); - events.moved = drag_row(ui, &response, DragRow { action: context.action, step: Some(step) }, context.tokens).or(events.moved); + events.moved = drag_row(ui, &response, DragRow { action: context.action, step: Some(step), revision:app.session.actions.rev, origin:context.origin }, context.tokens).or(events.moved); let (check, dialog) = draw_step_controls(ui, rect, step, &label, context); if check.clicked() { events.toggled = Some((context.action, step)); diff --git a/crates/ui-egui/src/panels/actions/modern.rs b/crates/ui-egui/src/panels/actions/modern.rs index ee2c5a0d6a..7ce522793a 100644 --- a/crates/ui-egui/src/panels/actions/modern.rs +++ b/crates/ui-egui/src/panels/actions/modern.rs @@ -39,7 +39,7 @@ struct Progress { enum Delete { Action(Box), - Group(String, Vec, u64), + Group(super::FolderSelection, Vec, u64), } /// Include backend drafts and suspended playback so layout/navigation guards cannot bypass hidden owners. @@ -300,6 +300,7 @@ fn export(app: &mut PhotocraftApp) -> Result { struct DragAction { index: usize, source: Action, + revision: u64, } enum Operation { @@ -308,12 +309,13 @@ enum Operation { Play(Vec), Duplicate(Value), DeleteAction(usize), - DeleteGroup(String), - Assign(Box, String), + DuplicateGroup(super::FolderSelection, u64), + DeleteGroup(super::FolderSelection, u64), + Assign(Box, super::FolderSelection), NewGroup, } -fn context(ui: &mut egui::Ui, action: Option, group: Option<&str>, play: Vec, group_mutable: bool) -> Option { +fn context(ui: &mut egui::Ui, action: Option, group: Option<&super::FolderSelection>, play: Vec, revision: u64) -> Option { let mut operation = None; if ui.add_enabled(action.is_some(), egui::Button::new(tl!("Edit Action"))).clicked() { operation = action.map(Operation::Edit); @@ -325,16 +327,16 @@ fn context(ui: &mut egui::Ui, action: Option, group: Option<&str>, play: ui.add_enabled(false, egui::Button::new(tl!(label))); } let duplicate = if group.is_some() { tl!("Duplicate group") } else { tl!("Duplicate action") }; - if ui.add_enabled(group_mutable, egui::Button::new(duplicate)).clicked() { - operation = Some(Operation::Duplicate(match group { - Some(group) => json!({"set":group}), - None => json!({"action":action}), - })); + if ui.button(duplicate).clicked() { + operation = Some(match group { + Some(group) => Operation::DuplicateGroup(group.clone(), revision), + None => Operation::Duplicate(json!({"action":action})), + }); } let delete = if group.is_some() { tl!("Delete group") } else { tl!("Delete action") }; - if ui.add_enabled(group_mutable, egui::Button::new(delete)).clicked() { + if ui.button(delete).clicked() { operation = match group { - Some(group) => Some(Operation::DeleteGroup(group.into())), + Some(group) => Some(Operation::DeleteGroup(group.clone(), revision)), None => action.map(Operation::DeleteAction), }; } @@ -369,7 +371,7 @@ fn action_row(app: &mut PhotocraftApp, ui: &mut egui::Ui, index: usize, action: operation = Some(Operation::Play(vec![index])); } if tile.drag_started() { - tile.dnd_set_drag_payload(DragAction { index, source: action.clone() }); + tile.dnd_set_drag_payload(DragAction { index, source: action.clone(), revision:app.session.actions.rev }); } let name = ui .add_sized(vec2((ui.available_width() - 60.0).max(20.0), size), egui::Button::new(&action.name).frame(false).sense(Sense::click_and_drag())) @@ -379,18 +381,18 @@ fn action_row(app: &mut PhotocraftApp, ui: &mut egui::Ui, index: usize, action: operation = Some(Operation::Play(vec![index])); } if name.drag_started() { - name.dnd_set_drag_payload(DragAction { index, source: action.clone() }); + name.dnd_set_drag_payload(DragAction { index, source: action.clone(), revision:app.session.actions.rev }); } if (hovered || app.ui.actions.selected == Some(index)) && icons::button(ui, "settings", 24.0, false, tl!("Edit action")).clicked() { operation = Some(Operation::Edit(index)); } let menu = icons::button(ui, "ellipsis", 24.0, false, tl!("Actions")); egui::Popup::menu(&menu).show(|ui| { - operation = context(ui, Some(index), None, vec![index], true).or(operation.take()); + operation = context(ui, Some(index), None, vec![index], app.session.actions.rev).or(operation.take()); }); }); row.response.context_menu(|ui| { - operation = context(ui, Some(index), None, vec![index], true).or(operation.take()); + operation = context(ui, Some(index), None, vec![index], app.session.actions.rev).or(operation.take()); }); operation } @@ -462,8 +464,6 @@ pub(super) fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ranks.get(folder.name.as_str()).copied().unwrap_or(usize::MAX), )); } - let mut occurrences = std::collections::HashMap::new(); - for folder in &folders { *occurrences.entry(folder.name.as_str()).or_insert(0usize) += 1; } app.ui.actions.collapsed_folders.retain(|key| folders.iter().any(|row| key.matches(row))); if app.ui.actions.selected_folder.as_ref().is_some_and(|key| !folders.iter().any(|row| key.matches(row))) { app.ui.actions.selected_folder = None; @@ -488,9 +488,6 @@ pub(super) fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } let key = super::FolderSelection::from_row(folder); let collapsed = app.ui.actions.folder_collapsed(&key); - // The existing group mutation commands accept a logical caption. Until the - // serialized slot-selector extension lands, they cannot mutate one namesake. - let group_mutable = occurrences.get(group.as_str()) == Some(&1); ui.push_id(("modern-physical-folder", key.origin, key.slot, group), |ui| { let header = ui.horizontal(|ui| { if icons::button(ui, if collapsed { "chevron-right" } else { "chevron-down" }, 20.0, false, group).clicked() { @@ -502,14 +499,14 @@ pub(super) fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } let menu = icons::button(ui, "ellipsis", 24.0, false, tl!("Actions")); egui::Popup::menu(&menu).show(|ui| { - operation = context(ui, None, Some(group), members.clone(), group_mutable).or(operation.take()); + operation = context(ui, None, Some(&key), members.clone(), app.session.actions.rev).or(operation.take()); }); }); - if group_mutable && let Some(drag) = header.response.dnd_release_payload::() { - operation = Some(Operation::Assign(Box::new((*drag).clone()), group.clone())); + if let Some(drag) = header.response.dnd_release_payload::() { + operation = Some(Operation::Assign(Box::new((*drag).clone()), key.clone())); } header.response.context_menu(|ui| { - operation = context(ui, None, Some(group), members.clone(), group_mutable).or(operation.take()); + operation = context(ui, None, Some(&key), members.clone(), app.session.actions.rev).or(operation.take()); }); if !collapsed || !query.is_empty() { for &index in members { @@ -530,20 +527,24 @@ pub(super) fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); if let Some(operation) = operation { let result = match operation { - Operation::New => { - let set = app.ui.actions.selected_set.clone(); - open(app, json!({"set":set})) - } + Operation::New => super::new_action_params(app).and_then(|params| open(app, params)), Operation::Edit(index) => open(app, json!({"action":index})), Operation::Play(indices) => start_library(app, &indices), Operation::Duplicate(params) => app.run("actions.duplicate", params), Operation::DeleteAction(index) => ask_delete(app, Some(index), None), - Operation::DeleteGroup(group) => ask_delete(app, None, Some(group)), + Operation::DuplicateGroup(group, revision) => group.checked_params(app, revision).and_then(|params| app.run("actions.duplicate", params)), + Operation::DeleteGroup(group, revision) => group.checked_params(app, revision).and_then(|_| ask_delete(app, None, Some(group))), Operation::Assign(drag, group) => { - if app.session.actions.list.get(drag.index) != Some(&drag.source) { + if app.session.actions.rev != drag.revision || app.session.actions.list.get(drag.index).is_none_or(|value| + value != &drag.source || !actions_cmds::library::same_placement(value, &drag.source)) { Err(tl!("The dragged action changed; drag it again").into()) } else { - app.run("actions.assignSet", json!({"action":drag.index,"set":group})) + group.checked_params(app, drag.revision).and_then(|mut params| { + params["action"] = json!(drag.index); + app.run("actions.assignSet", params).inspect(|result| { + if let Some(index) = result.get("index").and_then(Value::as_u64).and_then(|index| usize::try_from(index).ok()) { app.ui.actions.select(index, None); } + }) + }) } } Operation::NewGroup => new_group(app), @@ -729,7 +730,7 @@ fn tick_with_quantum(app: &mut PhotocraftApp, ctx: &egui::Context, quantum: usiz } ctx.request_repaint(); } else { - let indices: Option> = task.then.iter().map(|action| app.session.actions.list.iter().position(|current| current == action)).collect(); + let indices: Option> = task.then.iter().map(|action| app.session.actions.list.iter().position(|current| current == action && actions_cmds::library::same_placement(current, action))).collect(); let result = indices.ok_or("A group action changed during playback".to_string()).and_then(|indices| start_library(app, &indices)); if result.is_err() { app.actions_runtime.progress = None; @@ -832,7 +833,7 @@ pub(crate) fn owns_delete(fields: &serde_json::Map) -> bool { } /// Capture the selected definition or group revision and authorization gate before opening its delete question. -fn ask_delete(app: &mut PhotocraftApp, index: Option, group: Option) -> Result { +pub(super) fn ask_delete(app: &mut PhotocraftApp, index: Option, group: Option) -> Result { if app.actions_runtime.delete.is_some() { return Err("Answer the open delete question first".into()); } @@ -841,19 +842,13 @@ fn ask_delete(app: &mut PhotocraftApp, index: Option, group: Option { - if !photocraft_engine::actions_edit_cmds::set_names(&app.session).contains(&group) { - return Err("The selected group no longer exists".into()); - } - let members = app - .session - .actions - .list - .iter() - .filter(|action| photocraft_engine::atn_cmds::logical_set_name(action.set.as_deref()) == group) - .cloned() - .collect(); - let message = crate::i18n::fmt(tl!("Delete the group \"{name}\"?"), &[("name", &group)]); - (Delete::Group(group, members, app.session.actions.rev), message) + let revision = app.session.actions.rev; + group.checked_params(app, revision)?; + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session)?; + let row = rows.iter().find(|row| group.matches(row)).ok_or("The selected group no longer exists")?; + let members = row.actions.iter().filter_map(|&index| app.session.actions.list.get(index).cloned()).collect(); + let message = crate::i18n::fmt(tl!("Delete the group \"{name}\"?"), &[("name", &group.name)]); + (Delete::Group(group, members, revision), message) } None => { let action = index.and_then(|index| app.session.actions.list.get(index)).cloned().ok_or("The selected action no longer exists")?; @@ -887,28 +882,27 @@ pub(crate) fn delete_confirm(app: &mut PhotocraftApp, fields: &serde_json::Map { - let mut matches = app.session.actions.list.iter().enumerate().filter(|(_, current)| *current == action.as_ref()).map(|(index, _)| index); + let mut matches = app.session.actions.list.iter().enumerate().filter(|(_, current)| *current == action.as_ref() && actions_cmds::library::same_placement(current, &action)).map(|(index, _)| index); let index = matches.next().ok_or("The selected action changed; select it again")?; if matches.next().is_some() { return Err("The selected action is ambiguous".into()); } + removed.push(index); json!({"action":index}) } Delete::Group(group, members, revision) => { - let current: Vec<_> = app - .session - .actions - .list - .iter() - .filter(|action| photocraft_engine::atn_cmds::logical_set_name(action.set.as_deref()) == group) - .cloned() - .collect(); - if app.session.actions.rev != revision || current != members || !photocraft_engine::actions_edit_cmds::set_names(&app.session).contains(&group) { + let params = group.checked_params(app, revision)?; + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session)?; + let row = rows.iter().find(|row| group.matches(row)).ok_or("The selected group changed; select it again")?; + removed = row.actions.clone(); + let current: Vec<_> = row.actions.iter().filter_map(|&index| app.session.actions.list.get(index)).collect(); + if current.len() != members.len() || current.iter().zip(&members).any(|(current, old)| *current != old || !actions_cmds::library::same_placement(current, old)) { return Err("The selected group changed; select it again".into()); } - json!({"set":group}) + params } }; let saved = app.session.authorize; @@ -916,9 +910,13 @@ pub(crate) fn delete_confirm(app: &mut PhotocraftApp, fields: &serde_json::Map 24.0)); } + + +/// The real Modern New entry point retains its selected occurrence through backend Save/delete. +#[test] +fn modern_new_draft_and_delete_question_keep_selected_namesake() { + let mut app = app(); + for _ in 0..2 { app.session.execute("actions.reset",json!({"mode":"append","confirm":true})).unwrap(); } + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session).unwrap(); + app.ui.actions.select_folder(super::super::FolderSelection::from_row(&rows[1])); + let mut h = harness(app); + h.get_by_label("Create new action").click(); + h.run_steps(3); + let id = h.state().session.actions.editor.as_ref().unwrap().id(); + h.state_mut().run("actions.editor.update",json!({"draft":id,"description":"Modern selected row"})).unwrap(); + h.state_mut().run("actions.editor.save",json!({"draft":id})).unwrap(); + h.state_mut().run("actions.editor.discard",json!({"draft":id})).unwrap(); + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&h.state().session).unwrap(); + assert_eq!(rows.iter().map(|row| row.actions.len()).collect::>(),[2,3]); + let target = super::super::FolderSelection::from_row(&rows[1]); + let dialog = ask_delete(h.state_mut(),None,Some(target)).unwrap()["dialog"].as_u64().unwrap(); + crate::dialogs::confirm(h.state_mut(),dialog).unwrap(); + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&h.state().session).unwrap(); + assert_eq!(rows.len(),1); + assert_eq!(rows[0].actions.len(),2); +} diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index aa90b7710b..5eb91d5237 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -1784,13 +1784,16 @@ 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); + let drag = DragRow { action: 2, step: None, revision:app.session.actions.rev, origin:None }; + move_row(&mut app, drag, 2); 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); + let drag = DragRow { action: 1, step: None, revision:app.session.actions.rev, origin:None }; + move_row(&mut app, drag, 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); + let drag = DragRow { action: 2, step: None, revision:app.session.actions.rev, origin:None }; + move_row(&mut app, drag, 2); assert_eq!((app.session.actions.list[2].name.as_str(), app.session.actions.list[2].set.as_deref()), ("C", Some("One"))); } @@ -3056,3 +3059,44 @@ fn bulk_load_contents_budget_does_not_limit_native_paths() { assert!(!app.ui.status_error, "{}", app.ui.status); assert_eq!(app.session.actions.list[0].name, "From disk"); } + + +/// Classic recorder, Duplicate and Delete dispatch the selected occurrence's current slot. +#[test] +fn classic_physical_folder_adapters_keep_new_record_copy_and_delete_local() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new",json!({"width":8,"height":8})).unwrap(); + for _ in 0..2 { app.session.execute("actions.reset",json!({"mode":"append","confirm":true})).unwrap(); } + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session).unwrap(); + app.ui.actions.collapsed_folders = rows.iter().map(FolderSelection::from_row).collect(); + app.ui.actions.select_folder(FolderSelection::from_row(&rows[1])); + begin_recording(&mut app,false); + assert_eq!(app.ui.actions.collapsed_folders.len(),1,"recording reveals only its actual folder"); + app.run("actions.stop",json!({})).unwrap(); + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session).unwrap(); + assert_eq!(rows.iter().map(|row| row.actions.len()).collect::>(),[2,3]); + app.ui.actions.select_folder(FolderSelection::from_row(&rows[0])); + duplicate_selection(&mut app).unwrap(); + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session).unwrap(); + assert_eq!(rows.iter().map(|row| row.actions.len()).collect::>(),[2,2,3]); + let dialog = request_delete(&mut app).unwrap()["dialog"].as_u64().unwrap(); + crate::dialogs::confirm(&mut app,dialog).unwrap(); + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session).unwrap(); + assert_eq!(rows.iter().map(|row| row.actions.len()).collect::>(),[2,3]); + assert_eq!(rows[0].name,rows[1].name,"the two original namesakes remain"); +} + +/// A delayed Classic drag refuses a same-caption replacement before any move or assignment. +#[test] +fn classic_physical_drag_refuses_changed_revision_without_partial_reorder() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for _ in 0..2 { app.session.execute("actions.reset",json!({"mode":"append","confirm":true})).unwrap(); } + let rows = photocraft_engine::actions_edit_cmds::set_occurrences(&app.session).unwrap(); + let drag = DragRow { action:2,step:None,revision:app.session.actions.rev,origin:rows[1].origin }; + app.session.execute("actions.reset",json!({"mode":"replace","confirm":true})).unwrap(); + let definitions = app.session.actions.list.clone(); + move_row(&mut app,drag,0); + assert!(app.ui.status_error); + assert_eq!(app.session.actions.list,definitions); +} diff --git a/docs/development.md b/docs/development.md index 5787680c91..15c182f961 100644 --- a/docs/development.md +++ b/docs/development.md @@ -674,6 +674,16 @@ matches an existing folder. The warning's OK replaces the library; Append adds t Edit > Undo Reset Actions restores only the latest unchanged Reset's definitions and both shortcut maps, independently of document History and active recording/playback state. +The existing record, new-draft Open, Assign Set, Duplicate, Delete and Save commands accept +`setSlot` to select one current physical folder; an optional `set` must match its exact current +caption. A bare slot is current-state selection, not a stable identifier. The panel retains +revision and row origin across delayed operations. Set-only calls keep logical caption-wide +behavior. Physical creation and assignment use contiguous blocks and preserve numeric Play +and Conditional targets; unrepresentable order or a changed first-name target is refused +before publication. Destination placement does not replace raw action/event provenance or +change logical `Action` equality. New-draft Save retains its opening destination and publishes +only validated definitions and intended shortcut maps. + `actions.insertPath` snapshots the exact selected work, layer or saved path as a native `path.set` work-path step, retaining cubic controls, operations, fill rule and inversion. The measured Photoshop `set`/`WrPt` descriptor mapping represents non-inverted, even-odd-fill