diff --git a/crates/engine/src/cmd/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index 1f9cce3431b..5290299ae5d 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -1,14 +1,15 @@ //! Editing an action's steps and its set, as the Actions panel does beyond recording: //! `actions.insert` (Photoshop's Insert Stop… and Insert Menu Item…), `actions.dialog` (the //! panel's dialog toggle column) and `actions.assignSet` (which set folder an action sits in). +//! `actions.duplicate` copies an action or step below its source, retaining settings and flags. //! -//! All three refuse to run during playback, commit pending recorded steps first, and keep the +//! Definition edits refuse to run during playback, commit pending recorded steps first, and keep the //! per-step flag sets (`disabled`, `dialogs`) in step with the moved indices, like //! `actions.move` and `actions.delete`. use serde_json::{Value, json}; -use crate::actions_cmds::{flush_recording, not_playing, pending_steps, resolve}; +use crate::actions_cmds::{Action, flush_recording, not_playing, pending_steps, resolve}; use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; @@ -65,11 +66,79 @@ fn insert(s: &mut Session, p: &Value) -> Result { if s.actions.recording.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } + Ok(insert_step(s, idx, at, (id, params))) +} + +/// Insert an already validated step without normalizing a copied step's payload. +fn insert_step(s: &mut Session, idx: usize, at: usize, step: (String, Value)) -> Value { let action = &mut s.actions.list[idx]; - action.steps.insert(at, (id.clone(), params)); + let id = step.0.clone(); + action.steps.insert(at, step); action.remap_steps(|i| Some(if i >= at { i + 1 } else { i })); let result = json!({"action": action.name, "step": at, "id": id, "steps": action.steps.len()}); s.actions.touch(); + result +} + +/// Keep session-list Play Action targets stable when a copied action inserts a row. +/// Other commands' nested JSON may own a separate action library and is not traversed. +fn shift_action_calls(actions: &mut [Action], at: usize) { + for (id, params) in actions.iter_mut().flat_map(|a| &mut a.steps) { + if id != "actions.play" { + continue; + } + let Some(Value::Number(n)) = params.get("action") else { continue }; + let shifted = if let Some(n) = n.as_u64() { + if n >= at as u64 { n.checked_add(1).map(Value::from) } else { None } + } else { + // `actions.play` also accepts floating indices, rounding them before lookup. + n.as_f64().filter(|n| n.round() >= at as f64).map(|n| Value::from(n + 1.0)) + }; + if let Some(value) = shifted { + params["action"] = value; + } + } +} + +/// Duplicate a step or action below its source, preserving settings and per-step flags. +fn duplicate(s: &mut Session, p: &Value) -> Result { + let cmd = "actions.duplicate"; + not_playing(s, cmd)?; + let idx = resolve(&s.actions.list, p, cmd)?; + if let Some(step) = index(p, "step", cmd)? { + let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count()); + if step >= len { + return Err(bad(cmd, "step is out of range")); + } + if s.actions.recording.is_some_and(|(_, i)| i == idx) { + flush_recording(s)?; + } + let action = &s.actions.list[idx]; + let copied = action.steps.get(step).cloned().ok_or_else(|| bad(cmd, "step is out of range"))?; + let (disabled, dialog) = (action.disabled.contains(&step), action.dialogs.contains(&step)); + let at = step + 1; + let mut result = insert_step(s, idx, at, copied); + let action = &mut s.actions.list[idx]; + if disabled { + action.disabled.insert(at); + } + if dialog { + action.dialogs.insert(at); + } + result["index"] = json!(idx); + return Ok(result); + } + if s.actions.recording.is_some() { + return Err(bad(cmd, "stop recording before duplicating an action")); + } + let mut copied = s.actions.list[idx].clone(); + let mut names = crate::atn_cmds::UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone())); + copied.name = names.claim(&format!("{} copy", copied.name)); + let at = idx + 1; + let result = json!({"action": copied.name, "index": at, "steps": copied.steps.len()}); + s.actions.list.insert(at, copied); + shift_action_calls(&mut s.actions.list, at); + s.actions.touch(); Ok(result) } @@ -245,6 +314,16 @@ fn conditional(s: &mut Session, p: &Value) -> Result { pub fn specs() -> Vec { vec![ + CommandSpec { + id: "actions.duplicate", + label: "Duplicate", + menu: &[], + shortcut: None, + params: r##"{"action":name|index,"step":index?} → {action,index,step?,steps}. Duplicate the action, or one step, directly below its source. Action names gain " copy" and a unique numeric suffix if needed; settings, flags, set and color are retained. Function-key bindings stay with their original action. Stop recording before duplicating a whole action. Set duplication is not supported."##, + enabled: always, + run: duplicate, + journal: false, + }, CommandSpec { id: "actions.insert", label: "Insert Step", diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 1b1af71e614..a7e38f93006 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -41,6 +41,7 @@ mod tables; #[cfg(test)] use adjustments::{levels_from, selective_from}; +pub(crate) use convert::UniqueNames; pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, parse_function_key}; #[cfg(test)] use convert::{MAX_NAME_CHARS, export_item, normalise}; diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index fe89ab2dfb9..d2fe8571de8 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -250,18 +250,18 @@ pub fn export( /// Assigns names not already used, as `name`, `name 2`, `name 3`… A plain linear scan of the /// taken list per candidate is cubic when an action file repeats one base name many times, so /// membership uses a set and the next suffix to try is cached per base name. -pub(super) struct UniqueNames { +pub(crate) struct UniqueNames { taken: std::collections::HashSet, next_suffix: std::collections::HashMap, } impl UniqueNames { - pub(super) fn new>(existing: I) -> Self { + pub(crate) fn new>(existing: I) -> Self { UniqueNames { taken: existing.into_iter().collect(), next_suffix: std::collections::HashMap::new() } } /// Reserves and returns a unique name derived from `name`, recording it as taken. - pub(super) fn claim(&mut self, name: &str) -> String { + pub(crate) fn claim(&mut self, name: &str) -> String { if self.taken.insert(name.to_string()) { return name.to_string(); } diff --git a/crates/engine/tests/it/actions_duplicate.rs b/crates/engine/tests/it/actions_duplicate.rs new file mode 100644 index 00000000000..e5c97d294d3 --- /dev/null +++ b/crates/engine/tests/it/actions_duplicate.rs @@ -0,0 +1,122 @@ +//! Duplicate keeps action identities, complete settings and per-step flags stable. +use photocraft_engine::{Session, actions_cmds::Action}; +use serde_json::{Value, json}; + +/// A tiny document to distinguish definition edits from document mutations and playback. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 6})).unwrap(); + s +} + +#[test] +fn action_copies_follow_the_source_without_retargeting_calls_or_function_keys() { + let mut s = session(); + let mut source = Action::new("Source", vec![("actions.play".into(), json!({"action": 1})), ("layer.select".into(), json!({"layer": "Photo"}))]); + source.disabled.insert(1); + source.dialogs.insert(0); + source.set = Some("Retouch".into()); + source.color = "red".into(); + let foreign = json!({"actions": [{"name": "Foreign", "steps": [["actions.play", {"action": 1}]]}]}); + s.actions.list = vec![ + source.clone(), + Action::new("Target", vec![("select.all".into(), json!({}))]), + Action::new( + "Caller", + vec![ + ("actions.play".into(), json!({"action": 1})), + ("actions.play".into(), json!({"action": 3})), // Unresolved before and after insertion. + ("actions.play".into(), json!({"action": 1.0})), + ("file.automate.batch".into(), foreign.clone()), + ("actions.conditional".into(), json!({"if": "always", "then": "Target", "else": "Source"})), + ], + ), + ]; + s.prefs.edit(|p| { + p.shortcuts.insert("actions.play:Source".into(), "F6".into()); + }); + let revision = s.active().unwrap().revision; + let result = s.execute("actions.duplicate", json!({"action": "Source"})).unwrap(); + assert_eq!(result["index"], 1); + assert_eq!(s.actions.list.iter().map(|a| a.name.as_str()).collect::>(), ["Source", "Source copy", "Target", "Caller"]); + let mut expected = source; + expected.name = "Source copy".into(); + expected.steps[0].1["action"] = json!(2); + assert_eq!(s.actions.list[1], expected); + assert_eq!(s.actions.list[0].steps[0].1["action"], 2); + let caller = &s.actions.list[3]; + assert_eq!(caller.steps[0].1["action"], 2); + assert_eq!(caller.steps[1].1["action"], 4); + assert_eq!(caller.steps[2].1["action"], 2.0); + assert_eq!(caller.steps[3].1, foreign, "embedded libraries keep their own indices"); + assert_eq!(caller.steps[4].1, json!({"if": "always", "then": "Target", "else": "Source"})); + assert_eq!(s.prefs().shortcuts.get("actions.play:Source").map(String::as_str), Some("F6")); + assert!(!s.prefs().shortcuts.contains_key("actions.play:Source copy")); + assert_eq!(s.active().unwrap().revision, revision); + let played = s.execute("actions.play", json!({"action": "Source copy"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert!(s.active().unwrap().doc.selection.is_some(), "the copied call still plays Target rather than itself"); + s.execute("actions.duplicate", json!({"action": 0})).unwrap(); + assert_eq!(s.actions.list[1].name, "Source copy 2"); + assert_eq!(s.actions.list[2].name, "Source copy"); + assert_eq!(s.actions.list[1].steps[0].1["action"], 3); +} + +#[test] +fn step_copies_preserve_payloads_and_shift_both_flag_columns() { + let mut s = session(); + let payload = json!({"layer": "Photo", "_actionLayer": {"name": "Photo", "ordinal": 2}}); + let mut a = Action::new("Steps", vec![("layer.select".into(), payload.clone()), ("select.all".into(), Value::Null), ("select.deselect".into(), json!({}))]); + a.disabled.extend([0, 2]); + a.dialogs.extend([0, 1]); + s.actions.list.push(a); + let revision = s.active().unwrap().revision; + let result = s.execute("actions.duplicate", json!({"action": 0, "step": 0})).unwrap(); + assert_eq!(result["step"], 1); + assert_eq!(result["index"], 0); + let a = &s.actions.list[0]; + assert_eq!(a.name, "Steps"); + assert_eq!(a.steps[0], a.steps[1]); + assert_eq!(a.disabled.iter().copied().collect::>(), [0, 1, 3]); + assert_eq!(a.dialogs.iter().copied().collect::>(), [0, 1, 2]); + s.execute("actions.duplicate", json!({"action": 0, "step": 2})).unwrap(); + assert!(s.actions.list[0].steps[2].1.is_null()); + assert!(s.actions.list[0].steps[3].1.is_null(), "copying does not normalize null settings to an empty object"); + s.actions.list[0].steps[1].1["layer"] = json!(99); + assert_eq!(s.actions.list[0].steps[0].1, payload, "the copy owns its settings"); + assert_eq!(s.active().unwrap().revision, revision); +} + +#[test] +fn invalid_copies_do_not_flush_recording_and_valid_step_copies_keep_recording() { + let mut s = session(); + s.execute("actions.record", json!({"name": "Recording"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + let before = s.actions.list.clone(); + let recording = s.actions.recording; + let revision = s.active().unwrap().revision; + for params in [ + json!({}), + json!({"action": 9}), + json!({"action": 0}), + json!({"action": 0, "step": -1}), + json!({"action": 0, "step": 5}), + json!({"action": 0, "step": "x"}), + ] { + assert!(s.execute("actions.duplicate", params.clone()).is_err(), "{params}"); + assert_eq!(s.actions.list, before); + assert_eq!(s.actions.recording, recording); + assert_eq!(s.active().unwrap().revision, revision); + } + s.execute("actions.duplicate", json!({"action": 0, "step": 0})).unwrap(); + assert_eq!(s.actions.list[0].steps, vec![("select.all".into(), json!({})); 2]); + assert!(s.actions.recording.is_some()); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps.len(), 3); + s.actions.list.push(Action::new("Edit during playback", vec![("actions.duplicate".into(), json!({"action": 0}))])); + let before = s.actions.list.clone(); + let played = s.execute("actions.play", json!({"action": "Edit during playback"})).unwrap(); + assert!(played["failed"]["error"].as_str().is_some_and(|e| e.contains("playback")), "{played}"); + assert_eq!(s.actions.list, before); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 382287a9c75..7528a8c580c 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -1,5 +1,6 @@ //! The crate's integration tests, linked into one test binary. +mod actions_duplicate; mod affinity; mod artboard_export_names; mod atn_crystallize_cell_size; diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 5683afd88ae..f096ef49523 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -560,11 +560,11 @@ fn suspended(app: &PhotocraftApp) -> bool { } /// While a step dialog holds a suspended recording, refuse what would lose its call: a new -/// recording (the restore would find recording taken) or deleting/moving actions (the recorded +/// recording (the restore would find recording taken) or deleting/moving/duplicating actions (the recorded /// action could go away or change place). The engine checks these against `recording`, which /// is `None` then. pub(crate) fn suspended_guard(app: &PhotocraftApp, id: &str) -> Result<(), String> { - if matches!(id, "actions.record" | "actions.delete" | "actions.move") && suspended(app) { + if matches!(id, "actions.record" | "actions.delete" | "actions.move" | "actions.duplicate") && suspended(app) { return Err(tl!("Confirm or cancel the open action step dialog first").into()); } Ok(()) @@ -681,6 +681,9 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if ui.add_enabled(!recording, egui::Button::new(tl!("New Action…"))).clicked() { act = Some("new"); } + if ui.add_enabled(can_delete, egui::Button::new(tl!("Duplicate"))).clicked() { + act = Some("duplicate"); + } if ui.add_enabled(any, egui::Button::new(tl!("Play"))).clicked() { act = Some("play"); } @@ -726,6 +729,7 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { delete_selection(app); Ok(Value::Null) } + "duplicate" => duplicate_selection(app), "load" => load_dialog(app), "stop" => insert_stop_dialog(app), _ => save_dialog(app, None), @@ -789,6 +793,30 @@ 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 { + let action = app.ui.actions.selected.ok_or_else(|| tl!("Select an action first").to_string())?; + let step = app.ui.actions.selected_step; + let count = app.session.actions.list.len(); + let expanded = app.ui.actions.expanded.get(action).copied().unwrap_or(false); + let result = app.run("actions.duplicate", json!({"action": action, "step": step}))?; + let index = result["index"].as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("the copy has no action index")?; + app.ui.actions.selected = Some(index); + app.ui.actions.selected_step = result.get("step").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + if step.is_none() { + app.ui.actions.expanded.resize(count, false); + if index <= app.ui.actions.expanded.len() { + app.ui.actions.expanded.insert(index, expanded); + } + } else { + app.ui.actions.expanded.resize(count, false); + if let Some(expanded) = app.ui.actions.expanded.get_mut(index) { + *expanded = true; + } + } + Ok(result) +} + fn delete_selection(app: &mut PhotocraftApp) { let Some(action) = app.ui.actions.selected else { return }; let step = app.ui.actions.selected_step; diff --git a/crates/ui-egui/tests/it/actions_duplicate.rs b/crates/ui-egui/tests/it/actions_duplicate.rs new file mode 100644 index 00000000000..a9f9aeb206b --- /dev/null +++ b/crates/ui-egui/tests/it/actions_duplicate.rs @@ -0,0 +1,53 @@ +//! The panel duplicates the selected action/step and keeps its new row selected. +use egui_kittest::{Harness, kittest::Queryable}; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; +use photocraft_ui_egui::{PhotocraftApp, actions, dialogs}; +use serde_json::json; + +#[test] +fn duplicate_menu_selects_the_new_action_and_then_the_new_step() { + let mut app = PhotocraftApp::new(Session::new(), Default::default()); + let mut a = Action::new("Source", vec![("select.all".into(), json!({}))]); + a.disabled.insert(0); + a.dialogs.insert(0); + app.session.actions.list.push(a); + app.ui.actions.selected = Some(0); + app.ui.actions.expanded = vec![true]; + let mut h = Harness::builder().with_size(egui::vec2(360.0, 460.0)).build_ui_state(|ui, app| actions::panel_menu(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(3); + h.get_by_label("Duplicate").click(); + h.run_steps(3); + assert_eq!(h.state().session.actions.list.len(), 2); + assert_eq!(h.state().session.actions.list[1].name, "Source copy"); + assert_eq!(h.state().ui.actions.selected, Some(1)); + assert_eq!(h.state().ui.actions.selected_step, None); + assert_eq!(h.state().ui.actions.expanded, [true, true]); + h.state_mut().ui.actions.selected_step = Some(0); + h.get_by_label("Duplicate").click(); + h.run_steps(3); + assert_eq!(h.state().ui.actions.selected, Some(1)); + assert_eq!(h.state().ui.actions.selected_step, Some(1)); + let copied = &h.state().session.actions.list[1]; + assert_eq!(copied.steps.len(), 2); + assert_eq!(copied.disabled.iter().copied().collect::>(), [0, 1]); + assert_eq!(copied.dialogs.iter().copied().collect::>(), [0, 1]); +} + +#[test] +fn duplicate_cannot_shift_the_owner_of_a_suspended_recording() { + let mut app = PhotocraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 8, "height": 6})).unwrap(); + app.session.actions.list.push(Action::new("Menu", vec![(atn_cmds::MENU_ITEM.into(), json!({"id": "image.imageSize"}))])); + app.run("actions.record", json!({"name": "Owner"})).unwrap(); + let result = app.run("actions.play", json!({"action": "Menu"})).unwrap(); + let dialog = result["paused"]["dialog"].as_u64().unwrap(); + let list = app.session.actions.list.clone(); + assert!(app.session.actions.recording.is_none()); + let error = app.run("actions.duplicate", json!({"action": "Menu"})).unwrap_err(); + assert!(error.contains("Confirm or cancel"), "{error}"); + assert_eq!(app.session.actions.list, list); + dialogs::cancel(&mut app, dialog).unwrap(); + assert_eq!(app.session.actions.recording.map(|(_, i)| i), Some(1)); + app.run("actions.stop", json!({})).unwrap(); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index eb6c9f19330..61be475d521 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -1,5 +1,6 @@ //! The crate's integration tests, linked into one test binary. +mod actions_duplicate; mod adjust_preview_gpu; mod arbitrary_rotation_preview; mod atn_menu_item;