Skip to content

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

Actions: record File › Save and Save As steps and replay them (#2032) (#2746)

Valentin Klein6ff2a03f33db
diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rs
index 30fe5c7d6..e454d31c4 100644
--- a/crates/engine/src/actions_cmds.rs
+++ b/crates/engine/src/actions_cmds.rs
@@ -67,7 +67,15 @@ impl ActionState {
pub fn replayable(id: &str) -> bool {
// Again journals its concrete transform too; recording the wrapper would replay it twice.
id == "actions.play"
- || (!id.starts_with("actions.") && id != "edit.transform.again" && (shell_view_command(id) || crate::commands::find(id).is_some_and(|c| c.journal)))
+ || (!id.starts_with("actions.")
+ && id != "edit.transform.again"
+ && (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal)))
+}
+
+/// File › Save and Save As, recorded by the desktop shell once the save has a path (#2032).
+/// The shell replays them; batch and droplets write to their destination folder instead.
+pub fn shell_save_command(id: &str) -> bool {
+ matches!(id, "file.save" | "file.saveAs")
}
/// View-only menu commands recorded by the desktop shell. Headless playback reports
diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/automate_cmds.rs
index d3196b932..36c68d151 100644
--- a/crates/engine/src/automate_cmds.rs
+++ b/crates/engine/src/automate_cmds.rs
@@ -291,7 +291,9 @@ fn create_droplet(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.automate.createDroplet";
let path = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| bad(cmd, "missing \"path\" (where to save the droplet)"))?;
let steps_v = p.get("steps").or_else(|| p.get("action")).ok_or_else(|| bad(cmd, "missing \"steps\" (the action to run)"))?;
- let steps = parse_steps(steps_v, cmd)?;
+ let mut steps = parse_steps(steps_v, cmd)?;
+ // The droplet's output folder replaces recorded saves, as in batch.
+ steps.retain(|(id, _)| !crate::actions_cmds::shell_save_command(id));
check_known(&steps, cmd)?;
let path = if path.ends_with(".pcdroplet") || path.ends_with(".json") { path.to_string() } else { format!("{path}.pcdroplet") };
let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&path));
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 32ddb42b4..dcb6bd2b3 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -772,8 +772,11 @@ impl OutputClaims {
fn batch(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.automate.batch";
- let steps =
+ let mut steps =
parse_steps(p.get("steps").or_else(|| p.get("action")).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: "missing \"steps\"".into() })?)?;
+ // Each result goes to the destination folder, which overrides the action's recorded Save /
+ // Save As steps (Photoshop's "Override Action 'Save As' Commands").
+ steps.retain(|(id, _)| !crate::actions_cmds::shell_save_command(id));
if let Some((id, _)) = steps.iter().find(|(id, _)| crate::commands::find(id).is_none()) {
return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unknown command `{id}` in the action") });
}
diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rs
index 67ac9f59e..e072bae84 100644
--- a/crates/ui-egui/src/actions.rs
+++ b/crates/ui-egui/src/actions.rs
@@ -88,6 +88,13 @@ pub(crate) fn play(app: &mut PhotocraftApp, params: &Value) -> Result<Value, Str
}
if id == "actions.play" {
play(app, p)
+ } else if actions_cmds::shell_save_command(id) {
+ // Write synchronously, so the next step doesn't meet a document locked by a
+ // background save.
+ let background = std::mem::replace(&mut app.background_jobs, false);
+ let r = app.replay_save(id, p);
+ app.background_jobs = background;
+ r
} else if actions_cmds::shell_view_command(id) {
app.sync_views();
app.run(id, p.clone())
@@ -680,4 +687,36 @@ mod tests {
assert_eq!(d.layers.len(), 2);
assert_eq!(d.layers[1].surface().unwrap().pixel(5, 5), vec![1.0, 0.0, 0.0, 1.0]);
}
+
+ #[test]
+ fn recorded_save_as_and_save_replay_and_write_the_file() {
+ let written = std::rc::Rc::new(std::cell::RefCell::new(Vec::<String>::new()));
+ let log = written.clone();
+ let services = crate::Services {
+ export: Some(Box::new(|doc, path, _| {
+ photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string())
+ })),
+ write: Some(Box::new(move |path, _| {
+ log.borrow_mut().push(path.to_string());
+ Ok(())
+ })),
+ ..Default::default()
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
+ let ctx = egui::Context::default();
+ app.run("file.new", json!({"width": 16, "height": 16})).unwrap();
+ app.run("actions.record", json!({})).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ crate::menus::invoke(&mut app, &ctx, "file.saveAs", json!({"path": "out/result.psd"})).unwrap();
+ crate::menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();
+ app.run("actions.stop", json!({})).unwrap();
+ let steps = &app.session.actions.list[0].steps;
+ assert_eq!(steps, &[("layer.new.layer".into(), json!({})), ("file.saveAs".into(), json!({"path": "out/result.psd"})), ("file.save".into(), json!({}))]);
+ written.borrow_mut().clear();
+ app.run("file.new", json!({"width": 16, "height": 16})).unwrap();
+ let played = app.run("actions.play", json!({"action": 0})).unwrap();
+ assert!(played.get("failed").is_none(), "{played}");
+ assert_eq!(*written.borrow(), ["out/result.psd", "out/result.psd"]);
+ assert_eq!(app.session.active().unwrap().path.as_deref(), Some("out/result.psd"));
+ }
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 797182973..84bdf03bc 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -1092,19 +1092,69 @@ impl PhotocraftApp {
/// [`Self::save_as`] once the path is known.
fn save_to(&mut self, path: String) -> Result<Value, String> {
// A layered TIFF asks about its layers first (Preferences › File Handling); the save
- // continues from the prompt.
+ // continues from the prompt, which records the step once answered.
if tiff_options_ui::wants_prompt(self, &path) {
tiff_options_ui::park(self, path.clone())?;
return Ok(serde_json::json!({"path": path, "warnings": []}));
}
+ self.save_as_step(path, None)
+ }
+
+ /// File › Save back to the document's own layered file, recorded as a `file.save` step.
+ pub(crate) fn save_in_place(&mut self, path: String) -> Result<Value, String> {
+ if self.tiff_options.is_some() {
+ return Err("Answer TIFF Options before starting another save".into());
+ }
+ let r = self.write_save(path, None)?;
+ self.session.journal.push(("file.save".into(), Value::Object(Default::default())));
+ Ok(r)
+ }
+
+ /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF
+ /// answer), so an action being recorded keeps it (#2032).
+ fn save_as_step(&mut self, path: String, tiff_layers: Option<bool>) -> Result<Value, String> {
+ let r = self.write_save(path.clone(), tiff_layers)?;
+ let mut step = serde_json::json!({"path": path});
+ if let Some(layers) = tiff_layers {
+ step["tiffLayers"] = layers.into();
+ }
+ self.session.journal.push(("file.saveAs".into(), step));
+ Ok(r)
+ }
+
+ /// Replays a recorded `file.save` / `file.saveAs` step: no dialog or prompt, and the
+ /// recorded TIFF answer (if any) stands in for the TIFF Options prompt.
+ pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result<Value, String> {
+ if self.tiff_options.is_some() {
+ return Err("Answer TIFF Options before starting another save".into());
+ }
+ if id == "file.save" {
+ let path = self
+ .session
+ .active()
+ .ok_or("no document")?
+ .path
+ .clone()
+ .filter(|p| photocraft_engine::file_cmds::saves_in_place(p))
+ .ok_or("Save writes back only to the document's own PSD, PSB or .pcraft file")?;
+ return self.save_in_place(path);
+ }
+ let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?;
+ self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool))
+ }
+
+ /// Writes the active document to a known path. `tiff_layers` is the TIFF Options answer:
+ /// `Some(false)` discards the layers and saves a copy.
+ fn write_save(&mut self, path: String, tiff_layers: Option<bool>) -> Result<Value, String> {
// A flat file that can't hold the document (its layers, or the layered file it lives in)
// is written as a copy, as in Photoshop: the document keeps its file, so Save still
// writes the layered original and the edits stay unsaved (#2550).
let st = self.session.active().ok_or("no document")?;
let layered =
|p: &str| photocraft_engine::file_cmds::saves_in_place(p) || matches!(photocraft_engine::file_cmds::extension(p).as_deref(), Some("tif" | "tiff"));
- let copy = !layered(&path) && (plain_raster(&st.doc).is_none() || st.path.as_deref().is_some_and(layered));
- match self.write_document(path.clone(), &ExportSettings::default(), copy)? {
+ let copy = tiff_layers == Some(false) || (!layered(&path) && (plain_raster(&st.doc).is_none() || st.path.as_deref().is_some_and(layered)));
+ let settings = ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), ..Default::default() };
+ match self.write_document(path.clone(), &settings, copy)? {
Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})),
None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})),
}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 348698a67..8d584b5fc 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -269,12 +269,13 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
}
"file.save" => {
// Writes back only to a layered file; a flat one goes through Save As.
- let path = params
- .get("path")
- .and_then(Value::as_str)
- .map(str::to_string)
- .or_else(|| app.session.active().and_then(|d| d.path.clone()).filter(|p| photocraft_engine::file_cmds::saves_in_place(p)));
- app.save_as(path)
+ match params.get("path").and_then(Value::as_str) {
+ Some(path) => app.save_as(Some(path.to_string())),
+ None => match app.session.active().and_then(|d| d.path.clone()).filter(|p| photocraft_engine::file_cmds::saves_in_place(p)) {
+ Some(path) => app.save_in_place(path),
+ None => app.save_as(None),
+ },
+ }
}
"file.exit" => {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
diff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/tiff_options_ui.rs
index 163c71714..260bac152 100644
--- a/crates/ui-egui/src/tiff_options_ui.rs
+++ b/crates/ui-egui/src/tiff_options_ui.rs
@@ -71,7 +71,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
app.session.edit_prefs(|prefs| prefs.file_handling.ask_before_saving_layered_tiff = false);
}
let settings = ExportSettings { tiff_layers: !p.discard_layers, ..Default::default() };
- match app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.discard_layers)) {
+ let step = serde_json::json!({"path": p.path, "tiffLayers": !p.discard_layers});
+ let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.discard_layers));
+ if written.is_ok() {
+ // An action being recorded keeps the Save As with this answer (#2032).
+ app.session.journal.push(("file.saveAs".into(), step));
+ }
+ match written {
Err(e) => {
app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);
app.ui.status_error = true;