Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Actions: a command that runs other commands is recorded once (#3067) (#3072)

Valentin Kleind7e2f171f3b1
diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rs
index 348011f75..9b4a758d9 100644
--- a/crates/engine/src/actions_cmds.rs
+++ b/crates/engine/src/actions_cmds.rs
@@ -3,10 +3,12 @@
//!
//! The list lives on [`Session`] so the panel, the CLI, the control channel and MCP share one
//! copy. Recording copies replayable journal entries (commands whose [`CommandSpec::journal`] is
-//! set, except action-editing commands and the already-expanded `edit.transform.again`) into an
-//! action. Playback runs those steps with [`Session::execute`]
-//! and stops at the first error, leaving one history step per step that ran. Steps switched off
-//! with `actions.toggle` (the Actions panel check marks) are skipped by playback, Batch and droplets.
+//! set, except action-editing commands and the already-expanded `edit.transform.again` and
+//! `edit.transform.againCopy`) into an action. A replayable command's journal entry replaces the
+//! entries of the commands it ran on its own behalf, so they are recorded once (#3067). Playback
+//! runs those steps with [`Session::execute`] and stops at the first error, leaving one history
+//! step per step that ran. Steps switched off with `actions.toggle` (the Actions panel check
+//! marks) are skipped by playback, Batch and droplets.
//!
//! An untrusted session installs [`Session::authorize`]. `actions.play` calls it for every nested
//! step, because the outer `actions.play` id would otherwise hide a recorded `file.*` command from
@@ -86,14 +88,15 @@ impl ActionState {
/// Replay commands and named action calls, excluding edits to the action definitions and the
/// already-expanded Again wrapper.
pub fn replayable(id: &str) -> bool {
- // Again journals its concrete transform too; recording the wrapper would replay it twice.
+ // Again and Again on a Copy journal their concrete steps (`edit.transform`, after
+ // `layer.duplicate` for the copy) and record those: the wrappers look up the last transform in
+ // the journal, so they fail where no transform ran yet, e.g. an action played in a new session.
id == "actions.play"
|| (!id.starts_with("actions.")
// Browse executes its steps through Session::execute, so those concrete
// commands are already journaled. Recording the wrapper as well replays
// every script edit twice (#3057).
- && id != "edit.transform.again"
- && id != "file.scripts.browse"
+ && !matches!(id, "edit.transform.again" | "edit.transform.againCopy" | "file.scripts.browse")
&& (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal)))
}
@@ -760,6 +763,79 @@ mod tests {
}
}
+ #[test]
+ fn record_transform_again_on_a_copy_replays_in_a_session_without_a_transform() {
+ for depth in [8, 16] {
+ let mut s = Session::new();
+ translated_square(&mut s, depth);
+ s.execute("actions.record", json!({"name": "Step"})).unwrap();
+ s.execute("edit.transform.againCopy", json!({})).unwrap();
+ s.execute("actions.stop", json!({})).unwrap();
+ let got = s.execute("actions.get", json!({"action": "Step"})).unwrap();
+ let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect();
+ assert_eq!(ids, ["layer.duplicate", "edit.transform"], "depth {depth}: the concrete steps, not the wrapper");
+ let action = s.actions.list[0].clone();
+
+ // A new session has no transform to repeat: the concrete steps still play.
+ let mut fresh = Session::new();
+ fresh.execute("file.new", json!({"width": 20, "height": 8, "depth": depth, "background": "transparent"})).unwrap();
+ fresh
+ .edit("red square", |doc, _| {
+ doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(4, 2, 6, 4), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ fresh.actions.list.push(action);
+ let played = fresh.execute("actions.play", json!({"action": "Step"})).unwrap();
+ assert!(played.get("failed").is_none(), "depth {depth}: {played}");
+ assert_eq!(played["ran"], 2, "depth {depth}");
+ assert_eq!(fresh.active().unwrap().doc.layers.len(), 2, "depth {depth}: one copy");
+ assert_eq!(pixel(&fresh, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the original stays");
+ assert_eq!(pixel(&fresh, 1, 8, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the copy moved four pixels");
+ assert_eq!(pixel(&fresh, 1, 4, 2), vec![0.0; 4], "depth {depth}: moved once");
+ }
+ }
+
+ #[test]
+ fn record_drops_the_steps_of_a_command_that_failed_and_was_taken_back() {
+ // Transform Again on a Copy of a position-locked layer duplicates it, fails to move the
+ // copy and takes the copy back: nothing is left to record.
+ let mut s = Session::new();
+ translated_square(&mut s, 8);
+ let id = s.active().unwrap().active_layer.unwrap();
+ s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap();
+ s.execute("actions.record", json!({"name": "Locked"})).unwrap();
+ assert!(s.execute("edit.transform.againCopy", json!({})).is_err());
+ assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no Duplicate step for a copy that was taken back");
+
+ // Straighten rolls back when its crop is refused after the rotation ran.
+ ruled_background(&mut s, 8);
+ s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
+ s.authorize = Some(|id, _| if id == "image.crop" { Err(EngineError::Other("refused".into())) } else { Ok(()) });
+ s.execute("actions.record", json!({"name": "Refused"})).unwrap();
+ assert!(s.execute("image.analysis.straightenLayer", json!({})).is_err());
+ assert_eq!(s.active().unwrap().doc.size.width, 80, "the rotation was taken back");
+ assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no rotation step for a rotation that was taken back");
+ }
+
+ #[test]
+ fn record_script_that_plays_an_action_keeps_each_step_once() {
+ let mut s = Session::new();
+ translated_square(&mut s, 8);
+ s.execute("actions.record", json!({"name": "Inner"})).unwrap();
+ s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "interpolation": "nearest"})).unwrap();
+ s.execute("actions.stop", json!({})).unwrap();
+
+ // Browse records the concrete steps it ran, not itself (#3057): the script's transform and
+ // the action call, each once, in order.
+ let script = json!({"steps": [["edit.transform", {"matrix": [1, 0, 0, 1, 2, 0], "interpolation": "nearest"}], ["actions.play", {"action": "Inner"}]]});
+ s.execute("actions.record", json!({"name": "Outer"})).unwrap();
+ s.execute("file.scripts.browse", script.clone()).unwrap();
+ s.execute("actions.stop", json!({})).unwrap();
+ let got = s.execute("actions.get", json!({"action": "Outer"})).unwrap();
+ assert_eq!(got["steps"], script["steps"]);
+ }
+
#[test]
fn record_explicit_transform_keeps_one_replayable_step() {
let mut s = Session::new();
@@ -780,6 +856,46 @@ mod tests {
assert_eq!(pixel(&s, 0, 12, 2), vec![0.0; 4]);
}
+ /// A Background with a red bar and a slanted ruler line, ready for Straighten.
+ fn ruled_background(s: &mut Session, depth: u32) {
+ s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap();
+ s.edit("red bar", |doc, _| {
+ doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 20, 60, 8), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ }
+
+ #[test]
+ fn record_command_that_runs_commands_replays_it_once() {
+ // Straighten Layer runs Image Rotation and Crop itself: only its own call is recorded,
+ // so playback rotates once, not three times (rotate, crop, then straighten again).
+ for depth in [8, 16] {
+ let mut s = Session::new();
+ ruled_background(&mut s, depth);
+ s.execute("actions.record", json!({"name": "Level"})).unwrap();
+ s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
+ s.execute("image.analysis.straightenLayer", json!({})).unwrap();
+ s.execute("actions.stop", json!({})).unwrap();
+ let got = s.execute("actions.get", json!({"action": "Level"})).unwrap();
+ let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect();
+ assert_eq!(ids, ["image.analysis.rulerTool", "image.analysis.straightenLayer"], "depth {depth}");
+ let direct = s.active().unwrap().doc.clone();
+
+ ruled_background(&mut s, depth);
+ let before = s.active().unwrap().history.past_len();
+ let played = s.execute("actions.play", json!({"action": "Level"})).unwrap();
+ assert!(played.get("failed").is_none(), "depth {depth}: {played}");
+ assert_eq!(played["ran"], 2, "depth {depth}");
+ assert_eq!(s.active().unwrap().history.past_len(), before + 1, "depth {depth}: one Straighten step (the ruler is no step)");
+ let replayed = s.active().unwrap().doc.clone();
+ assert_eq!(replayed.size, direct.size, "depth {depth}: rotated and cropped once");
+ let r = photocraft_geom::Rect::new(0, 0, direct.size.width as i32, direct.size.height as i32);
+ let px = |d: &photocraft_doc::Document| d.layers[0].surface().unwrap().read_region(r);
+ assert_eq!(px(&replayed), px(&direct), "depth {depth}: same pixels as the direct run");
+ }
+ }
+
#[test]
fn record_keeps_only_replayable_steps() {
let mut s = Session::new();
diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rs
index d9cb687b8..b369479ce 100644
--- a/crates/engine/src/analysis_cmds.rs
+++ b/crates/engine/src/analysis_cmds.rs
@@ -171,14 +171,20 @@ fn set_quiet(s: &mut Session, f: impl FnOnce(&mut Document)) -> Result<()> {
Ok(())
}
-/// Run several commands as one history step labelled `label`.
+/// Run several commands as one history step labelled `label`. On failure the document goes back
+/// as it was and the journal forgets the commands `f` ran, so an action being recorded does not
+/// replay an edit that was taken back.
pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result<R>) -> Result<R> {
let st = s.active().ok_or(EngineError::NoDocument)?;
let (before, history, prior) = (st.doc.clone(), st.history.clone(), st.layer_target());
+ let journal = s.journal.len();
// Color Sampler points are view state a step may move (crop, rotation): roll them back too, so
// a failed second step can't leave them pinned to pixels the restored document no longer has.
let samplers = st.color_samplers.clone();
let r = f(s);
+ if r.is_err() {
+ s.journal.truncate(journal);
+ }
let st = s.active_mut().ok_or(EngineError::NoDocument)?;
st.history = history;
match r {
diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs
index 499040bfe..4fc878364 100644
--- a/crates/engine/src/edit_cmds.rs
+++ b/crates/engine/src/edit_cmds.rs
@@ -533,7 +533,11 @@ fn transform_again(s: &mut Session) -> Result<Value> {
fn transform_again_copy(s: &mut Session) -> Result<Value> {
let p = transform_again_params(s)?;
let id = active_id(s)?;
- s.execute("layer.duplicate", json!({"layer": id.0}))?;
+ let journal = s.journal.len();
+ // The steps are recorded (Again on a Copy is not replayable itself): with one layer selected,
+ // "duplicate the current layer" plays back on any document, a layer id only on this one.
+ let dup = if crate::layer_multi_cmds::multi(s, &Value::Null) { json!({"layer": id.0}) } else { json!({}) };
+ s.execute("layer.duplicate", dup)?;
match s.execute("edit.transform", p) {
Ok(r) => {
let st = s.active_mut().ok_or(EngineError::NoDocument)?;
@@ -543,8 +547,9 @@ fn transform_again_copy(s: &mut Session) -> Result<Value> {
}
Err(e) => {
// The copy (e.g. of a layer whose position is locked) couldn't be transformed: take
- // it back, leaving nothing to redo.
+ // it back, leaving nothing to redo and no Duplicate step to record.
s.undo();
+ s.journal.truncate(journal);
if let Some(st) = s.active_mut() {
st.history.clear_redo();
}
diff --git a/crates/engine/src/frame_cmds.rs b/crates/engine/src/frame_cmds.rs
index 75c24df7c..df84bdcfd 100644
--- a/crates/engine/src/frame_cmds.rs
+++ b/crates/engine/src/frame_cmds.rs
@@ -41,6 +41,7 @@ fn frame_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(name) = p.get("name") {
gp.insert("name".into(), name.clone());
}
+ let journal = s.journal.len();
let grouped = s.execute("layer.new.groupFromLayers", Value::Object(gp))?;
match frame_group(s, &grouped) {
Ok(r) => {
@@ -51,8 +52,10 @@ fn frame_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
Ok(r)
}
Err(e) => {
- // The group couldn't be framed: take the grouping back, leaving nothing to redo.
+ // The group couldn't be framed: take the grouping back, leaving nothing to redo and
+ // no grouping step to record.
s.undo();
+ s.journal.truncate(journal);
if let Some(st) = s.active_mut() {
st.history.clear_redo();
}
diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs
index 9b612e3c4..7b567530d 100644
--- a/crates/engine/src/jobs.rs
+++ b/crates/engine/src/jobs.rs
@@ -638,11 +638,20 @@ impl Session {
self.coalesce_request = params.get("coalesce").and_then(Value::as_str).map(str::to_string);
self.color_restrict = crate::channel_cmds::color_restriction(self, id, &run_params);
self.jobs.spawn = background;
+ // Commands this one runs on its own behalf journal after this mark (#3067).
+ let nested_from = self.journal.len();
+ // A replayable command is recorded as one step, so recording pauses while it runs: an
+ // action it plays (a script step) must not flush the steps it ran so far into the action
+ // being recorded, nor move the recording mark past the entries it is about to replace.
+ let recording = if spec.journal && crate::actions_cmds::replayable(id) { self.actions.recording.take() } else { None };
// Last-resort guard (AGENTS.md, Never crash): a command that panics anyway fails with an
// error instead of taking the app down. `edit` only commits a document after its closure
// returns, so the documents are unchanged.
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (spec.run)(self, &run_params)))
.unwrap_or_else(|_| Err(EngineError::Other(format!("`{id}` failed with an internal error (logged); the document is unchanged"))));
+ if self.actions.recording.is_none() {
+ self.actions.recording = recording;
+ }
self.jobs.spawn = false;
self.coalesce_request = None;
self.color_restrict = None;
@@ -662,14 +671,20 @@ impl Session {
Ok(Started::Job(jid))
}
(Ok(v), None) => {
- self.after_command(id, params, spec.journal);
+ self.after_command(id, params, spec.journal, Some(nested_from));
Ok(Started::Done(v))
}
}
}
/// Bookkeeping after a command (or a job's apply) succeeded.
- fn after_command(&mut self, id: &str, params: Value, journal: bool) {
+ ///
+ /// `nested_from` is the journal length when the command started. A replayable command stands
+ /// for the commands it ran itself (Straighten runs Image Rotation and Crop): their entries are
+ /// dropped, so a recorded action replays the command once, not its steps as well (#3067).
+ /// Edit › Transform › Again (and Again on a Copy) is not replayable and keeps the concrete
+ /// steps it ran instead.
+ fn after_command(&mut self, id: &str, params: Value, journal: bool, nested_from: Option<usize>) {
// A layer-mask view ends when another layer becomes active (#196).
if let Some(st) = self.active_mut() {
crate::mask_view_cmds::fix(st);
@@ -677,7 +692,13 @@ impl Session {
crate::edit_menu_cmds::after_command(self, id);
crate::automate_cmds::after_command(self, id);
self.sync_preset_store();
- if journal && !crate::brush_cmds::coalesce_journal(self, id, &params) {
+ if !journal {
+ return;
+ }
+ if let Some(from) = nested_from.filter(|_| crate::actions_cmds::replayable(id)) {
+ self.journal.truncate(from);
+ }
+ if !crate::brush_cmds::coalesce_journal(self, id, &params) {
self.journal.push((id.to_string(), params));
}
}
@@ -727,7 +748,7 @@ impl Session {
// Restoring the viewed document first would attribute Fade and slice updates
// to that document instead, when the user switched tabs mid-job.
if r.is_ok() {
- self.after_command(command, params.clone(), *journal);
+ self.after_command(command, params.clone(), *journal, None);
}
// Keep the user's active document unless the job opened a new one.
// This also restores the selection when the apply step returned an error.