diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 97b012e770..d20f382521 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; -use photocraft_engine::{Session, command_specs}; +use photocraft_engine::{Session, command_specs, file_cmds}; use photocraft_format::PcraftWriter; use photocraft_io::ExportOptions; use serde_json::{Value, json}; @@ -91,7 +91,18 @@ impl Headless { }; let target: PathBuf = match (path, stored_path.as_deref()) { (Some(p), _) => p.to_path_buf(), - (None, Some(p)) => PathBuf::from(p), + // Like the desktop's File › Save: without a new path, only a layered file is written + // back, in its own format; a flattened or converted copy never replaces it (#416). + (None, Some(p)) => { + let own = file_cmds::extension(p); + let written = format.map(|f| f.trim_start_matches('.').to_ascii_lowercase()).or_else(|| own.clone()); + if !file_cmds::saves_in_place(p) || written != own { + return Err(AutomationError::BadRequest(format!( + "pass `path`: without one, only a PSD, PSB or .pcraft file is written back, in its own format, so `{p}` was left unchanged" + ))); + } + PathBuf::from(p) + } (None, None) => { return Err(AutomationError::BadRequest("document has no path; pass `path`".into())); } diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index bae49ea2e1..69a55a34dc 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -72,7 +72,9 @@ pub struct NewParams { #[derive(Debug, Default, Deserialize, JsonSchema)] pub struct SaveParams { /// Forward-slash relative target beneath the configured automation write root. - /// The extension selects the format. Omit to save to the document's own relative path. + /// The extension selects the format. Omit to write back to the document's own file, which + /// works only for a PSD, PSB or .pcraft file kept in its own format; any other save needs + /// `path`, so a flattened or converted copy never replaces the opened file. #[serde(default)] pub path: Option, /// Format override as an extension (pcraft, psd, png, jpg, tif, webp, exr, …). @@ -396,7 +398,7 @@ impl PhotocraftMcp { } #[tool(description = "Save the document. `.pcraft` is the lossless native format (incremental); other extensions \ - (psd, png, jpg, tif, webp, exr, …) export. Returns warnings about anything the format cannot hold.")] + (psd, png, jpg, tif, webp, exr, …) export. Without `path` only a PSD, PSB or .pcraft document is written back to its own file. Returns warnings about anything the format cannot hold.")] async fn doc_save(&self, Parameters(p): Parameters) -> Result { self.save_impl(p).await } diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs index 162458b759..d7fcfe3b24 100644 --- a/crates/automation/tests/mcp.rs +++ b/crates/automation/tests/mcp.rs @@ -254,6 +254,57 @@ async fn open_png_and_inspect() { cleanup(&dir); } +fn write_image(dir: &std::path::Path, name: &str, format: photocraft_codecs::Format) -> Vec { + let img = photocraft_codecs::Image::from_u8(16, 8, photocraft_codecs::ChannelLayout::Rgb, (0..384).map(|i| (i * 7 % 251) as u8).collect()).unwrap(); + let bytes = photocraft_codecs::encode(&img, format, &Default::default()).unwrap(); + std::fs::write(dir.join(name), &bytes).unwrap(); + bytes +} + +/// A save without `path` writes back only to a layered file in its own format (#416). +#[tokio::test(flavor = "multi_thread")] +async fn save_without_path_never_flattens_over_the_opened_file() { + let dir = tmp("save-in-place"); + let png = write_image(&dir, "seed.png", photocraft_codecs::Format::Png); + let jpg = write_image(&dir, "seed.jpg", photocraft_codecs::Format::Jpeg); + let client = connect(headless_in(&dir)).await; + let refused = |r: &CallToolResult| r.is_error == Some(true) && text(r).contains("pass `path`"); + + // A flat file, edited or not, is left unchanged. + json_of(&call(&client, "doc_open", json!({"path": "seed.png"})).await); + json_of(&call(&client, "command_run", json!({"id": "layer.newAdjustmentLayer.curves", "params": {"points": [[0, 0], [128, 170], [255, 255]]}})).await); + let r = call(&client, "doc_save", json!({})).await; + assert!(refused(&r), "{}", text(&r)); + assert_eq!(std::fs::read(dir.join("seed.png")).unwrap(), png); + json_of(&call(&client, "doc_open", json!({"path": "seed.jpg"})).await); + let r = call(&client, "doc_save", json!({})).await; + assert!(refused(&r), "{}", text(&r)); + assert_eq!(std::fs::read(dir.join("seed.jpg")).unwrap(), jpg); + + // An explicit path, even the opened file's own, still writes and reports what was lost. + let r = json_of(&call(&client, "doc_save", json!({"path": "seed.jpg"})).await); + assert!(r["warnings"].to_string().contains("lossy"), "{r}"); + + // A layered file saves in place in its own format, but not converted over itself. + json_of(&call(&client, "doc_select", json!({"index": 0})).await); + json_of(&call(&client, "doc_save", json!({"path": "layered.psd"})).await); + json_of(&call(&client, "doc_open", json!({"path": "layered.psd"})).await); + let psd = std::fs::read(dir.join("layered.psd")).unwrap(); + let r = call(&client, "doc_save", json!({"format": "png"})).await; + assert!(refused(&r), "{}", text(&r)); + assert_eq!(std::fs::read(dir.join("layered.psd")).unwrap(), psd); + assert_eq!(json_of(&call(&client, "doc_save", json!({})).await)["path"], "layered.psd"); + assert!(photocraft_io::is_psd(&std::fs::read(dir.join("layered.psd")).unwrap())); + + // Once saved as .pcraft, a flat-born document saves in place there. + json_of(&call(&client, "doc_select", json!({"index": 0})).await); + json_of(&call(&client, "doc_save", json!({"path": "work.pcraft"})).await); + assert_eq!(json_of(&call(&client, "doc_save", json!({})).await)["path"], "work.pcraft"); + assert_eq!(std::fs::read(dir.join("seed.png")).unwrap(), png); + client.cancel().await.unwrap(); + cleanup(&dir); +} + #[tokio::test(flavor = "multi_thread")] async fn filesystem_policy_rejects_absolute_and_escaping_paths_before_effects() { let base = tmp("filesystem-policy"); diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 674619b326..c2e4b93017 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -122,6 +122,17 @@ pub(crate) fn file_name(path: &str) -> String { path.rsplit(['/', '\\']).next().unwrap_or(path).to_string() } +/// The lower-case extension of the file name in `path` (none for `.hidden` or `name`). +pub fn extension(path: &str) -> Option { + file_name(path).rsplit_once('.').filter(|(base, ext)| !base.is_empty() && !ext.is_empty()).map(|(_, ext)| ext.to_ascii_lowercase()) +} + +/// Whether a save without a new path may write back to `path`: only layered files (PSD, PSB, +/// .pcraft). A flat file goes through Save As instead, so it is never flattened over the original. +pub fn saves_in_place(path: &str) -> bool { + extension(path).is_some_and(|ext| matches!(ext.as_str(), "psd" | "psb" | "pcraft")) +} + pub(crate) fn stem(path: &str) -> String { let n = file_name(path); match n.rfind('.') { diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs index 762cd018f6..6ed1f819ca 100644 --- a/crates/engine/src/file_cmds/tests.rs +++ b/crates/engine/src/file_cmds/tests.rs @@ -377,3 +377,16 @@ fn guide_layouts() { assert_eq!(g.vertical, vec![10.0, 30.0, 50.0]); assert_eq!(g.horizontal, vec![10.0, 20.0, 30.0]); } + +#[test] +fn only_layered_files_save_in_place() { + for path in ["a.psd", "dir/a.PSB", r"C:\w\a.pcraft", "my.dir/a.psd"] { + assert!(saves_in_place(path), "{path}"); + } + // Flat formats, no extension, a dotted folder with an extensionless file, a dot file. + for path in ["a.png", "a.jpg", "a", "my.psd/a", ".psd", "a.", ""] { + assert!(!saves_in_place(path), "{path}"); + } + assert_eq!(extension("dir/Photo.JPEG").as_deref(), Some("jpeg")); + assert_eq!(extension("my.dir/name"), None); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 8d51a89ac6..60640b8f8c 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -733,5 +733,14 @@ mod tests { let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"})); assert_eq!(r["result"], json!({"path": "out.png", "warnings": ["Layers were flattened"]}), "{r}"); assert_eq!(*written.borrow(), vec!["out.png".to_string()]); + // Without `path`, only a layered file is written back, like File › Save (#416). + call(&mut app, &ctx, "app.open", json!({"path": "in/flat.jpg"})); + let r = call(&mut app, &ctx, "app.save", json!({})); + assert!(r["error"].as_str().unwrap().contains("pass `path`"), "{r}"); + assert_eq!(written.borrow().len(), 1, "nothing written over the JPEG"); + call(&mut app, &ctx, "app.open", json!({"path": "in/layered.psd"})); + let r = call(&mut app, &ctx, "app.save", json!({})); + assert_eq!(r["result"]["path"], "in/layered.psd", "{r}"); + assert_eq!(written.borrow().last().map(String::as_str), Some("in/layered.psd")); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index deff3fa87f..95ac2eb9ac 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -711,7 +711,10 @@ impl PhotocraftApp { /// written and the export warnings (also shown to the user). pub fn save_automation(&mut self, path: Option) -> Result<(String, Vec), String> { let state = self.session.active().ok_or("no document")?; - let target = path.or_else(|| state.path.clone()).ok_or("document has no relative path; pass `path`")?; + // As File › Save: without `path` only a layered file is written back (#416). + let target = path + .or_else(|| state.path.clone().filter(|p| photocraft_engine::file_cmds::saves_in_place(p))) + .ok_or("pass `path`: a save without one writes back only to the document's own PSD, PSB or .pcraft file")?; let export = self.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(&state.doc, &target, &ExportSettings::default())?; let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 35fb6fd469..d56a8ebfe8 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -225,11 +225,12 @@ 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| saves_in_place(p))); + .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).map(|(p, w)| json!({"path": p, "warnings": w})) } "file.exit" => { @@ -430,13 +431,6 @@ fn open_path(app: &mut PhotocraftApp, path: &str) -> Result { app.open_path(path).map(|w| json!({"warnings": w})) } -/// File › Save writes back to the document's own file for layered formats (PSD, PSB, .pcraft); -/// flat files go through Save As, like Photoshop. -fn saves_in_place(path: &str) -> bool { - let ext = path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); - matches!(ext.as_str(), "psd" | "psb" | "pcraft") -} - pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { // Photoshop greys these for the Background layer, other layer kinds or single-layer documents. if crate::enable_rules::disabled(app, id) { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c4be38630c..8499455d19 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -51,7 +51,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i base64 PNG data; a path is relative to the automation write root. Raises the window first (default) because occluded macOS windows stop rendering - `ui.focus`: bring the main window to the front -- `app.open {path}` / `app.save {path}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name`, `app.save` the `path` written. Automation opens and saves never fire script events. `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` reply with `warnings` the same way +- `app.open {path}` / `app.save {path}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name`, `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. Automation opens and saves never fire script events. `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` reply with `warnings` the same way - `app.quit` ## Engine commands @@ -199,7 +199,7 @@ no MCP framing, no app start-up per command. Configure its file access with the | `engine.commands` | `{filter?}`: registry with params docs and enablement | | `session.list` | open documents and the active index | | `doc.open` / `doc.new` | `{path}` / `file.new` params | -| `doc.save` | `{path?, format?, quality?, index?}` (`.pcraft` native, else export by extension) | +| `doc.save` | `{path?, format?, quality?, index?}` (`.pcraft` native, else export by extension). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` |