From 022cf4f125d1b22ec3e7679ce2ffc38980c11e13 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sat, 7 Nov 2026 21:59:52 -0500 Subject: [PATCH] Open as Smart Object: keep the damage flag, the Smart Object flag and unique names CodeRabbit round 2 on #12212: - 4504550937 (b): a PSD that recovered from damaged data is held for File > Open's confirmation (the app passes confirmDamage; headless callers open it as before). - 4504550942: a document held for its prompt counts when numbering, and the number is re-taken when each document is admitted, so two held files with one stem no longer share a name. - 4504550943 is not changed here (needs colour transforms at regeneration), as are 4504550937 (a), (c) and 4504550953. - 4504550946: the successful reply carries smartObject, so a document queued behind another open prompt is admitted with the Open As Smart Object history label. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/cmd/file_cmds.rs | 2 +- crates/engine/src/cmd/file_cmds/open.rs | 10 +++- .../src/cmd/file_cmds/open_as_smart_object.rs | 37 ++++++++---- .../file_cmds/open_as_smart_object_tests.rs | 56 +++++++++++++++++++ crates/engine/src/jobs.rs | 2 +- crates/engine/src/session/documents.rs | 5 ++ crates/ui-egui/src/jobs_ui.rs | 3 +- 7 files changed, 100 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index b1eed032dd4..b1ec4df7d65 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -293,7 +293,7 @@ pub fn specs() -> Vec { "Open as Smart Object…", &["File"], None, - r##"{"path":str} (opens the file as a new untitled document named "-N" with the file's size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer named after the file) → {document, docId, name, layer, warnings, color} (or {held, name, warnings, color, smartObject} while the profile prompt waits)"##, + r##"{"path":str,"confirmDamage":bool=false (a damaged PSD waits for an answer, as File > Open's does)} (opens the file as a new untitled document named "-N" with the file's size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer named after the file) → {document, docId, name, layer, warnings, color, smartObject} (or {held, name, warnings, color, damaged, smartObject} while a prompt waits)"##, native, open_as_smart_object ), diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index 71b7cfcefba..282eae0e4ee 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -75,8 +75,14 @@ fn import_result(name: &str, bytes: &[u8]) -> Result Result { + import_result_for_open(name, bytes, opts).map(|(r, _)| r) +} + +/// [`import_result_with`], also telling whether a PSD/PSB had damaged data it recovered from, as +/// File › Open's job learns it (`photocraft_io::import_for_open`), so an interactive caller can ask. +pub(super) fn import_result_for_open(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<(photocraft_io::ImportResult, bool)> { crate::allocation::checkpoint("importing document")?; - let r = photocraft_io::import_with_options(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?; + let (r, damaged) = photocraft_io::import_for_open(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?; // Auxiliary imports return only a document and cannot surface the preview's fidelity warning. // Open has its own warning-preserving path; never silently place or process a thumbnail. if r.preview_only { @@ -84,7 +90,7 @@ pub(super) fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io: "{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here" ))); } - Ok(r) + Ok((r, damaged)) } // ---------- close / revert / save a copy / open as ---------- diff --git a/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs b/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs index b32b6bfbcb7..517252b25ac 100644 --- a/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs +++ b/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs @@ -5,7 +5,7 @@ //! size and position `0, 0`) and put into the document before it is admitted, so the opening //! snapshot already shows it. -use super::open::import_result_with; +use super::open::import_result_for_open; use super::paths::{file_name, read_file, stem, untitled_name}; use super::{Affine, Arc, Document, Layer, LayerContent, Result, Session, SmartObject, SmartSource, Value, flattened_checked, json, str_param}; use crate::layer_place::Place; @@ -24,6 +24,8 @@ pub(super) fn open_as_smart_object(s: &mut Session, p: &Value) -> Result let path = str_param(p, "path", CMD)?.to_string(); let name = file_name(&path); let opts = crate::jobs::import_options(s.prefs()); + // An interactive caller (the app) asks before opening a PSD that had damaged data, as File > Open does. + let confirm_damage = p.get("confirmDamage").and_then(Value::as_bool).unwrap_or(false); crate::jobs::run( s, &format!("Opening {name}"), @@ -33,25 +35,33 @@ pub(super) fn open_as_smart_object(s: &mut Session, p: &Value) -> Result let bytes = read_file(&path)?; ctx.check()?; ctx.progress(0.05, "Decoding"); - let r = import_result_with(&name, &bytes, &opts)?; + let (r, damaged) = import_result_for_open(&name, &bytes, &opts)?; ctx.check()?; ctx.progress(0.9, "Flattening"); // The file as one image: the smart object's rendered contents. let pixels = flattened_checked(&r.document, r.document.pixel_format(), CMD)?; - Ok((path, name, Arc::new(bytes), r, pixels)) + Ok((path, name, Arc::new(bytes), r, pixels, confirm_damage && damaged)) }, - |s, (path, name, bytes, r, pixels)| apply(s, &path, &name, bytes, r, pixels), + |s, (path, name, bytes, r, pixels, damaged)| apply(s, &path, &name, bytes, r, pixels, damaged), ) } -fn apply(s: &mut Session, path: &str, file: &str, bytes: Arc>, r: photocraft_io::ImportResult, pixels: photocraft_raster::Surface) -> Result { +fn apply( + s: &mut Session, + path: &str, + file: &str, + bytes: Arc>, + r: photocraft_io::ImportResult, + pixels: photocraft_raster::Surface, + damaged: bool, +) -> Result { let warnings = r.warnings; let mut src = r.document; super::tag_exr_colorspace(s, file, &mut src); super::raw_defaults(s, &warnings, &mut src); let layer_name = stem(path); // "-1", the next free number while a document with that name is open. - let name = untitled_name(&layer_name, |n| s.documents().iter().any(|d| d.doc.name == n)); + let name = untitled_name(&layer_name, |n| s.documents().iter().any(|d| d.doc.name == n) || s.held_open_named(n)); let mut doc = Document::new(name.clone(), src.size, src.mode, src.depth); doc.resolution_dpi = src.resolution_dpi; @@ -70,21 +80,28 @@ fn apply(s: &mut Session, path: &str, file: &str, bytes: Arc>, r: photoc // prompt holds the document, and without a question the Color Settings policy is applied. let raw = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); let question = s.color.open_question(&doc).filter(|_| !raw); - if question.is_some() { + if damaged || question.is_some() { let held = s.hold_open(doc, false); - return Ok(json!({"held": held, "name": name, "warnings": warnings, "color": question, "smartObject": true})); + return Ok(json!({"held": held, "name": name, "warnings": warnings, "color": question, "damaged": damaged, "smartObject": true})); } let color = s.color.open_policy(&mut doc, s.prefs().file_handling.ignore_exif_profile_tag); let index = admit_as_smart_object(s, doc); let id = s.documents().get(index).map(|st| st.doc.id.0); - Ok(json!({"document": index, "docId": id, "name": name, "layer": layer_id.0, "warnings": warnings, "color": color})) + Ok(json!({"document": index, "docId": id, "name": name, "layer": layer_id.0, "warnings": warnings, "color": color, "smartObject": true})) } /// Admits a document built by Open as Smart Object (one smart object layer) as an untitled /// document: the opening snapshot already shows the placed layer, is named after it, and the /// history is the single state "Open As Smart Object", as File › Open's is one state. -pub fn admit_as_smart_object(s: &mut Session, doc: Document) -> usize { +pub fn admit_as_smart_object(s: &mut Session, mut doc: Document) -> usize { let layer_name = doc.layers.first().map(|l| l.name.clone()); + // The number was free when the file was read, but a document held for its prompt did not count + // then: take the next free one now, as each document is admitted. + if let Some(base) = &layer_name + && s.documents().iter().any(|d| d.doc.name == doc.name) + { + doc.name = untitled_name(base, |n| s.documents().iter().any(|d| d.doc.name == n)); + } // Untitled: no path, so Save asks where to save. let index = s.add_document(doc, None); if let Some(st) = s.active_mut() { diff --git a/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs b/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs index 2117d8e5e10..230c75afe80 100644 --- a/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs +++ b/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs @@ -278,3 +278,59 @@ fn ask_when_opening_holds_the_document_like_file_open() { assert_eq!(doc.layers.len(), 1); assert!(matches!(doc.layers[0].content, LayerContent::Smart(_))); } + +#[test] +fn the_reply_flags_a_smart_object_so_a_queued_document_keeps_its_history_label() { + let dir = tmp("flag"); + let path = write_png(&dir, "a_test.png", 16, 12); + let mut s = Session::new(); + let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap(); + assert_eq!(r["smartObject"], true, "{r}"); +} + +#[test] +fn a_damaged_psd_is_held_for_confirmation_when_asked_and_opens_otherwise() { + let dir = tmp("damaged"); + let path = join(&dir, "d.psd"); + std::fs::write(&path, crate::jobs::psd_open_fixture::make_psd(true)).unwrap(); + let mut s = Session::new(); + s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap(); + let r = s.execute("file.openAsSmartObject", json!({"path": path, "confirmDamage": true})).unwrap(); + assert_eq!(r["damaged"], true, "{r}"); + assert_eq!(r["smartObject"], true, "{r}"); + assert!(r["held"].is_u64(), "{r}"); + assert!(s.documents().is_empty(), "held for the damage prompt, not admitted"); + let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap(); + assert!(r["docId"].is_u64(), "a headless caller opens the recovered content: {r}"); +} + +#[test] +fn a_document_held_for_its_prompt_does_not_share_its_name_with_the_next() { + let dir = tmp("held-name"); + let path = write_psd16(&dir, "a_test.psd", 20, 20); + let mut s = Session::new(); + let first = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap(); + let second = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap(); + assert_eq!(first["name"], "a_test-1"); + assert_eq!(second["name"], "a_test-2", "the held document's name is taken: {second}"); + // Both held docs leave the session for the app's queue; admitting them one by one numbers each. + let (a, _) = s.take_held_open(first["held"].as_u64().unwrap()).unwrap(); + let (b, _) = s.take_held_open(second["held"].as_u64().unwrap()).unwrap(); + admit_as_smart_object(&mut s, a); + admit_as_smart_object(&mut s, b); + assert_eq!(names(&s), ["a_test-1", "a_test-2"]); + let mut t = Session::new(); + let (c, _) = { + let r = t.execute("file.openAsSmartObject", json!({"path": path})).unwrap(); + t.take_held_open(r["held"].as_u64().unwrap()).unwrap() + }; + let (d, _) = { + t.execute("edit.colorSettings", json!({"askOnMismatch": true})).unwrap(); + let r = t.execute("file.openAsSmartObject", json!({"path": path})).unwrap(); + t.take_held_open(r["held"].as_u64().unwrap()).unwrap() + }; + assert_eq!(c.name, d.name, "taken out of the session, both are named a_test-1 when read"); + admit_as_smart_object(&mut t, c); + admit_as_smart_object(&mut t, d); + assert_eq!(names(&t), ["a_test-1", "a_test-2"], "the second takes the next free number when admitted"); +} diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 1390e899022..2504bcc3d97 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -2148,7 +2148,7 @@ mod tests; #[cfg(test)] #[path = "../../io/tests/support/recovery_psd.rs"] -mod psd_open_fixture; +pub(crate) mod psd_open_fixture; #[cfg(test)] mod psd_open_confirmation_tests { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 49f8205079a..b5b82a4753a 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -193,6 +193,11 @@ impl Session { self.next_held_open } + /// Whether a document held back for its prompt already has `name`. + pub(crate) fn held_open_named(&self, name: &str) -> bool { + self.held_opens.iter().any(|(_, d, _)| d.name == name) + } + /// Takes a document a background open held back for the profile prompt: the document and /// whether its source is read-only. `None` when there is no such document (already taken). pub fn take_held_open(&mut self, id: u64) -> Option<(Document, bool)> { diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 39008261666..7459f54be6a 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -307,7 +307,8 @@ fn track_open(app: &mut PhotocraftApp, tab: OpenTab) { /// Open Recent is untouched. Inline (background jobs off, or the web) it finishes at once. pub(crate) fn start_open_as_smart_object(app: &mut PhotocraftApp, path: &str, order: Option) -> Result<(), String> { let name = crate::file_open::display_name(path); - let params = json!({"path": path}); + // `confirmDamage`: a damaged PSD waits for the user's answer, as in File › Open. + let params = json!({"path": path, "confirmDamage": true}); let started = if app.background_jobs { app.session.start("file.openAsSmartObject", params).map_err(|e| e.to_string())? } else {