PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(io/ui): allow explicit PSD recovery with non-overwriting Save a Copy
David Bonnieraa1a77b9dac0
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rsindex 082506e92..1b26a3bcd 100644--- a/apps/photocraft/src/services.rs+++ b/apps/photocraft/src/services.rs@@ -363,6 +363,19 @@ fn save_through(Ok(r.warnings)}+fn recovery_save_file(+ doc: &Document,+ path: &str,+ settings: &photocraft_ui_egui::ExportSettings,+ ctl: &photocraft_ui_egui::jobs_ui::SaveCtl,+) -> Result<Vec<String>, String> {+ save_through(doc, path, settings, ctl, |p, b, progress| {+ photocraft_io::write_recovery_copy_bytes(Path::new(p), b).map_err(|e| e.to_string())?;+ progress(1.0);+ Ok(())+ })+}+fn save_file(doc: &Document,path: &str,@@ -537,6 +550,10 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->crate::crash_guard::guard("Export", || photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()))})),save_file: Some(Arc::new(save_file)),+ recovery_save_file: Some(Arc::new(recovery_save_file)),+ recovery_write: Some(Box::new(|path: &str, bytes: &[u8]| {+ photocraft_io::write_recovery_copy_bytes(Path::new(path), bytes).map_err(|e| e.to_string())+ })),file_dialog: Some(Box::new(show_file_dialog)),write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))),file_stamp: Some(Box::new(|path: &str| {diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex 5f3a5edec..45c298d00 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -540,6 +540,9 @@ fn save_a_copy(s: &mut Session, p: &Value) -> Result<Value> {msg: "`path` is the document's own file, so the copy would replace it: choose another path, or pass \"overwrite\": true".into(),});}+ // Engine commands can be replayed from scripts. Recovery mode is never+ // allowed to use the ordinary replacement writer, even for Save a Copy.+ let recovery = d.recovery_mode;let mut doc = (*d.doc).clone();if p.get("layers").and_then(Value::as_bool) == Some(false) {// "Layers" unchecked in Save a Copy: write the flattened image.@@ -547,7 +550,14 @@ fn save_a_copy(s: &mut Session, p: &Value) -> Result<Value> {let px = flattened(&doc, fmt);doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))];}- let warnings = save_doc(&doc, &path, SaveOpts::from_params(s, p, "file.saveACopy")?)?;+ let opts = SaveOpts::from_params(s, p, "file.saveACopy")?;+ let warnings = if recovery {+ let (bytes, warnings) = encode(&doc, &path, opts)?;+ photocraft_io::write_recovery_copy_bytes(std::path::Path::new(&path), &bytes).map_err(|e| EngineError::Other(e.to_string()))?;+ warnings+ } else {+ save_doc(&doc, &path, opts)?+ };Ok(json!({"path": path, "warnings": warnings}))}@@ -1451,7 +1461,15 @@ fn flatten_all_masks(s: &mut Session) -> Result<Value> {fn layers_to_files(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "file.export.layersToFiles";let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string();- let names = export_layers_with(s, p, |name, bytes| write_file(&join(&dir, name), bytes))?;+ let recovery = s.active().is_some_and(|d| d.recovery_mode);+ let names = export_layers_with(s, p, |name, bytes| {+ let path = join(&dir, name);+ if recovery {+ photocraft_io::write_recovery_copy_bytes(std::path::Path::new(&path), bytes).map_err(|e| EngineError::Other(e.to_string()))+ } else {+ write_file(&path, bytes)+ }+ })?;let files: Vec<String> = names.iter().map(|name| join(&dir, name)).collect();Ok(json!({"files": files}))}@@ -1623,7 +1641,11 @@ fn color_lookup_tables(s: &mut Session, p: &Value) -> Result<Value> {let cube = bake_cube_layers(size as usize, &title, &layers);match p.get("path").and_then(Value::as_str) {Some(path) => {- write_file(path, cube.as_bytes())?;+ if d.recovery_mode {+ photocraft_io::write_recovery_copy_bytes(std::path::Path::new(path), cube.as_bytes()).map_err(|e| EngineError::Other(e.to_string()))?;+ } else {+ write_file(path, cube.as_bytes())?;+ }Ok(json!({"path": path, "size": size, "layerCount": count}))}None => Ok(json!({"cube": cube, "size": size, "layerCount": count})),@@ -1925,3 +1947,24 @@ mod aces_exr_tests {}}}++#[cfg(test)]+mod psd_recovery_tests {+ use super::*;+ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn an_engine_action_does_not_replace_an_existing_file_in_recovery_mode() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 2, "height": 2})).unwrap();+ s.active_mut().unwrap().recovery_mode = true;+ let path = std::env::temp_dir().join(format!(+ "photocraft-engine-recovery-{}-{}",+ std::process::id(),+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()+ ));+ std::fs::write(&path, b"original").unwrap();+ assert!(s.execute("file.saveACopy", json!({"path": path})).is_err());+ assert_eq!(std::fs::read(&path).unwrap(), b"original");+ std::fs::remove_file(path).unwrap();+ }+}diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rsindex 0ee057317..c97cab6b0 100644--- a/crates/engine/src/jobs.rs+++ b/crates/engine/src/jobs.rs@@ -507,6 +507,17 @@ impl Session {/// result is `{held, name, warnings, color}` (`color` the question): take it with/// [`Session::take_held_open`] once answered.pub fn start_open(&mut self, name: &str, source: OpenSource) -> Result<Started> {+ self.start_open_inner(name, source, false)+ }++ /// GUI opening: PSDs are decoded with the opt-in recovery path, but a+ /// damaged result is held back until the user accepts the recovery prompt.+ /// Headless/automation opening keeps the strict default above.+ pub fn start_open_for_user(&mut self, name: &str, source: OpenSource) -> Result<Started> {+ self.start_open_inner(name, source, true)+ }++ fn start_open_inner(&mut self, name: &str, source: OpenSource, offer_recovery: bool) -> Result<Started> {let label = format!("Opening {name}");let name_w = name.to_string();let name_a = name.to_string();@@ -525,7 +536,13 @@ impl Session {ctx.check()?;ctx.progress(0.02, "Decoding");let imported = ctx- .stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_with_svg_group_depth_and_interrupt(&name_w, &bytes, max_svg_group_depth, ctl))+ .stage(0.02, 0.95, "Decoding", |ctl| {+ if offer_recovery && photocraft_io::is_psd(&bytes) {+ photocraft_io::import_psd_for_recovery_with(&name_w, &bytes, ctl)+ } else {+ photocraft_io::import_with_svg_group_depth_and_interrupt(&name_w, &bytes, max_svg_group_depth, ctl)+ }+ }).map_err(|e| match e {photocraft_io::IoError::Cancelled => EngineError::Cancelled,e => EngineError::Other(e.to_string()),@@ -540,9 +557,11 @@ impl Session {// Ask When Opening: held back until the prompt is answered (`take_held_open`). A// developed raw has no embedded profile to ask about.let raw = r.warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE));- if let Some(question) = s.color.open_question(&r.document).filter(|_| !raw) {+ let recovery = offer_recovery && r.source_read_only && r.warnings.iter().any(|w| w.starts_with("PSD/PSB RECOVERY:"));+ let question = s.color.open_question(&r.document).filter(|_| !raw);+ if recovery || question.is_some() {let held = s.hold_open(r.document, r.source_read_only);- return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question}));+ return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question, "recovery": recovery}));}let (index, color) = s.open_document(r.document, None);if let Some(st) = s.active_mut() {diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 5a7aa83df..87d79cf46 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -208,6 +208,9 @@ pub struct DocState {pub path: Option<String>,/// An Affinity document (or its preview) must not acquire the native source as its Save path.pub source_read_only: bool,+ /// This session came from a damaged PSD: every save is a new, no-overwrite copy.+ /// Kept outside history so Undo and Save a Copy cannot remove the restriction.+ pub recovery_mode: bool,/// Increments on every change; UIs re-render when it moves.pub revision: u64,pub saved_revision: u64,@@ -273,6 +276,7 @@ impl DocState {layer_anchor: active_layer,path,source_read_only: false,+ recovery_mode: false,revision: 1,saved_revision: 1,view_revision: 0,diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex fdf783118..5184dc061 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -61,6 +61,8 @@ mod pdn;pub mod pixels;mod psd_export;mod psd_import;+mod recovery;+pub use recovery::write_recovery_copy_bytes;pub mod psd_thumbnail;pub mod raw;pub mod slices_map;@@ -309,7 +311,87 @@ pub fn import_with_svg_group_depth_and_interrupt(Ok(r)}+/// Import a damaged PSD/PSB for explicit recovery. Unlike [`import`], this+/// permits partially decoded layers, but marks the result source-read-only.+///+/// Front ends must show `warnings`, require user consent before editing,+/// keep a session-level recovery flag, and use [`write_recovery_copy_bytes`]+/// for every write: it publishes only NEW file names and never replaces the+/// damaged original (or any existing file). Do not use this API as a drop-in+/// replacement for [`import`].+pub fn import_psd_for_recovery(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {+ import_psd_for_recovery_with(name, bytes, &photocraft_raster::Interrupt::NONE)+}++/// Cancelable version of [`import_psd_for_recovery`].+pub fn import_psd_for_recovery_with(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -> Result<ImportResult, IoError> {+ if !is_psd(bytes) {+ return Err(IoError::Unsupported("recovery import accepts only PSD/PSB files".into()));+ }+ ctl.check().map_err(|_| IoError::Cancelled)?;+ let result = import_stages_with_psd_recovery(name, bytes, ctl, photocraft_doc::MAX_GROUP_DEPTH, true)?;+ ctl.check().map_err(|_| IoError::Cancelled)?;+ ctl.progress(1.0);+ Ok(result)+}++/// Refuse a recovered document's copy destination if it names its source.+/// Canonical paths catch lexical aliases, `..`, relative paths, and symlinks;+/// on Unix, inode/device identity also catches hardlinks. The source must+/// exist, otherwise the check fails closed.+///+/// This validates a destination at one instant; front ends must call it+/// immediately before their atomic write/rename. Callers also need to prevent+/// concurrent destination replacement (TOCTOU), or use a platform-specific+/// no-overwrite file operation.+pub fn validate_recovery_copy_destination(source: &std::path::Path, destination: &std::path::Path) -> Result<(), IoError> {+ use std::io::ErrorKind;+ use std::path::Path;++ let denied = || IoError::Unsupported("recovery copy must not overwrite the original PSD/PSB file".into());+ let source_path = std::fs::canonicalize(source).map_err(|e| IoError::Unsupported(format!("cannot verify original PSD/PSB path: {e}")))?;+ let source_metadata = std::fs::metadata(source).map_err(|e| IoError::Unsupported(format!("cannot stat original PSD/PSB file: {e}")))?;++ let (candidate, exists) = match std::fs::symlink_metadata(destination) {+ Ok(_) => (std::fs::canonicalize(destination).map_err(|e| IoError::Unsupported(format!("cannot resolve recovery destination: {e}")))?, true),+ Err(e) if e.kind() == ErrorKind::NotFound => {+ let parent = destination.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));+ let directory = std::fs::canonicalize(parent).map_err(|e| IoError::Unsupported(format!("cannot resolve recovery destination folder: {e}")))?;+ let filename = destination.file_name().ok_or_else(|| IoError::Unsupported("recovery copy needs a filename".into()))?;+ (directory.join(filename), false)+ }+ Err(e) => return Err(IoError::Unsupported(format!("cannot inspect recovery destination: {e}"))),+ };+ if candidate == source_path {+ return Err(denied());+ }++ // A hard link has a different path but the same inode.+ #[cfg(unix)]+ if exists {+ use std::os::unix::fs::MetadataExt;+ let metadata = std::fs::metadata(destination).map_err(|e| IoError::Unsupported(format!("cannot stat recovery destination: {e}")))?;+ if metadata.dev() == source_metadata.dev() && metadata.ino() == source_metadata.ino() {+ return Err(denied());+ }+ }+ #[cfg(not(unix))]+ let _ = (source_metadata, exists);++ Ok(())+}+fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, max_group_depth: usize) -> Result<ImportResult, IoError> {+ import_stages_with_psd_recovery(name, bytes, ctl, max_group_depth, false)+}++fn import_stages_with_psd_recovery(+ name: &str,+ bytes: &[u8],+ ctl: &photocraft_raster::Interrupt,+ max_group_depth: usize,+ recovery_requested: bool,+) -> Result<ImportResult, IoError> {// A declared native extension must reach its loader so malformed bundles retain format errors.if has_extension(name, photocraft_format::EXTENSION) || photocraft_format::is_pcraft(bytes) {let document = photocraft_format::load_from_bytes(bytes)?;@@ -327,10 +409,27 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, mpsd_import::check_group_depth(&file)?;ctl.check().map_err(|_| IoError::Cancelled)?;ctl.progress(0.05);- let (mut document, warnings) = psd_import::psd_to_document_decoded(&file, ctl, merged).ok_or(IoError::Cancelled)?;+ let (mut document, mut warnings, unsafe_for_editing) = psd_import::psd_to_document_decoded_integrity(&file, ctl, merged).ok_or(IoError::Cancelled)?;+ // An imported document cannot be trusted when channels or layer blocks failed to decode:+ // allowing a normal Save or a Save As targeting the original would destroy the raw data.+ // The normal importer remains fail-closed. Only an explicit recovery request can open+ // partial content, and its caller must enforce validate_recovery_copy_destination().+ if unsafe_for_editing && !recovery_requested {+ return Err(IoError::Unsupported(format!(+ "PSD/PSB contains unreadable image, layer or mask data; editing was refused to protect the source file ({})",+ warnings+ .iter()+ .find(|w| w.contains("could not be decoded") || w.contains("could not be read") || w.contains("not imported"))+ .map(String::as_str)+ .unwrap_or("incomplete import"),+ )));+ }+ if unsafe_for_editing {+ warnings.insert(0, "PSD/PSB RECOVERY: the document is incomplete. The original must never be overwritten. Use Save a Copy to a different file; some layers, masks or channels are missing.".into());+ }document.name = name.to_string();text_import::prepare(&mut document);- return Ok(ImportResult { document, warnings, source_read_only: false, preview_only: false });+ return Ok(ImportResult { document, warnings, source_read_only: unsafe_for_editing, preview_only: false });}if affinity::is_affinity(bytes) || affinity::has_extension(name) {return affinity::import(name, bytes);@@ -585,7 +684,88 @@ pub fn merged_composite(file: &PsdFile) -> Result<Vec<[f32; 4]>, IoError> {#[cfg(test)]mod tests {- use super::is_svg_input;+ use super::{IoError, import, is_svg_input};+ use photocraft_psd::{Compression, Version, testgen};++ #[test]+ fn valid_psd_can_still_be_edited() {+ let bytes = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap();+ let imported = import("valid.psd", &bytes).unwrap();+ assert!(!imported.source_read_only);+ }++ #[test]+ fn unreadable_psd_channel_is_rejected_before_editing() {+ let mut file = testgen::small(Version::Psd, Compression::Raw);+ let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == 0).unwrap();+ channel.data.clear();+ let bytes = file.to_bytes().unwrap();+ assert!(matches!(+ import("damaged.psd", &bytes),+ Err(IoError::Unsupported(reason)) if reason.contains("unreadable")+ ));+ }++ #[test]+ fn explicit_recovery_opens_unreadable_psd_read_only() {+ let mut file = testgen::small(Version::Psd, Compression::Raw);+ let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == 0).unwrap();+ channel.data.clear();+ let bytes = file.to_bytes().unwrap();+ // Existing P0 behaviour: ordinary open is refused.+ assert!(import("damaged.psd", &bytes).is_err());+ // Explicit recovery: a partial document, but never normal source save.+ let recovered = super::import_psd_for_recovery("damaged.psd", &bytes).unwrap();+ assert!(recovered.source_read_only);+ assert!(!recovered.preview_only);+ assert!(recovered.warnings.iter().any(|w| w.contains("RECOVERY")));+ assert!(recovered.warnings.iter().any(|w| w.contains("could not be decoded")));+ }++ #[test]+ fn recovery_import_of_valid_psd_remains_editable() {+ let bytes = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap();+ let result = super::import_psd_for_recovery("valid.psd", &bytes).unwrap();+ assert!(!result.source_read_only);+ }++ #[test]+ fn recovery_import_rejects_other_formats() {+ assert!(super::import_psd_for_recovery("image.png", b"not a PSD").is_err());+ }++ #[test]+ fn recovery_copy_guard_rejects_original_and_aliases() {+ use std::fs;+ use std::time::{SystemTime, UNIX_EPOCH};++ let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();+ let root = std::env::temp_dir().join(format!("photocraft-recovery-{nonce}-{}", std::process::id()));+ fs::create_dir_all(root.join("subdir")).unwrap();+ let source = root.join("original.psd");+ fs::write(&source, b"original unchanged").unwrap();++ assert!(super::validate_recovery_copy_destination(&source, &source).is_err());+ assert!(super::validate_recovery_copy_destination(&source, &root.join("subdir/../original.psd")).is_err());+ assert!(super::validate_recovery_copy_destination(&source, &root.join("recovered.psd")).is_ok());+ assert!(super::validate_recovery_copy_destination(&source, &root.join("subdir/recovered.psd")).is_ok());++ #[cfg(unix)]+ {+ use std::os::unix::fs::symlink;+ let link = root.join("alias.psd");+ symlink(&source, &link).unwrap();+ assert!(super::validate_recovery_copy_destination(&source, &link).is_err());+ let hardlink = root.join("hardlink.psd");+ fs::hard_link(&source, &hardlink).unwrap();+ assert!(super::validate_recovery_copy_destination(&source, &hardlink).is_err());+ let directory_link = root.join("alias_dir");+ symlink(&root, &directory_link).unwrap();+ assert!(super::validate_recovery_copy_destination(&source, &directory_link.join("original.psd")).is_err());+ }+ assert_eq!(fs::read(&source).unwrap(), b"original unchanged");+ fs::remove_dir_all(root).unwrap();+ }#[test]fn svg_extension_does_not_override_another_format_signature() {diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex 8a948aa6e..2acfab577 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -51,6 +51,8 @@ pub(crate) struct Ctx<'a> {pub cc: usize,pub cmyk: bool,pub warnings: Vec<String>,+ /// The import lost source data that cannot be safely written back to PSD/PSB.+ pub unsafe_for_editing: bool,/// Document resolution (type sizes are converted to points with it).pub dpi: f32,/// The parsed `Txt2` block (type settings EngineData lacks, e.g. optical kerning).@@ -132,6 +134,11 @@ impl Ctx<'_> {self.warnings.push(s.into());}+ fn warn_unreadable_data(&mut self, s: impl Into<String>) {+ self.unsafe_for_editing = true;+ self.warn(s);+ }+/// Source id, transform, (Distort/Perspective) projective placement and warp of a placed/// layer that has only a `PlLd` block, as Photoshop CS2 and older write it (#2465). `PlLd`/// stores the placed corners but not the source size, which comes from the embedded file.@@ -167,7 +174,7 @@ impl Ctx<'_> {match rec.decode_channel(id, self.file.header.depth, self.file.header.version) {Ok(p) => Some(p),Err(e) => {- self.warn(format!("layer \"{name}\": channel {id} could not be decoded ({e}); treated as empty"));+ self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded ({e}); treated as empty"));None}}@@ -200,7 +207,7 @@ impl Ctx<'_> {let mut planes: Vec<Option<Vec<u8>>> = Vec::with_capacity(decoded.len());for (&id, p) in ids.iter().zip(decoded) {if p.is_none() && rec.channel(id).is_some() {- self.warn(format!("layer \"{name}\": channel {id} could not be decoded; treated as empty"));+ self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded; treated as empty"));}planes.push(p);}@@ -826,6 +833,17 @@ pub(crate) fn psd_to_document_decoded(ctl: &photocraft_raster::Interrupt,decoded: Option<photocraft_psd::Result<Vec<u8>>>,) -> Option<(Document, Vec<String>)> {+ psd_to_document_decoded_integrity(file, ctl, decoded).map(|(document, warnings, _)| (document, warnings))+}++/// Also reports whether unrecoverable channel, layer or merged-image data was discarded.+/// Normal imports reject that result before exposing the document for editing; callers using+/// the low-level conversion API retain its existing best-effort behaviour.+pub(crate) fn psd_to_document_decoded_integrity(+ file: &PsdFile,+ ctl: &photocraft_raster::Interrupt,+ decoded: Option<photocraft_psd::Result<Vec<u8>>>,+) -> Option<(Document, Vec<String>, bool)> {let h = &file.header;let mut warnings = Vec::new();let mode = doc_mode(h.color_mode).unwrap_or_else(|| {@@ -892,7 +910,9 @@ pub(crate) fn psd_to_document_decoded(// A 16/32-bit file whose layer block can't be parsed would otherwise open as a flattened// file without a word (#2700). The raw block is kept, but a PSD save writes the document's// own layers in its place (see `psd_export`).+ let mut unsafe_for_editing = false;if let Some((b, e)) = file.unreadable_layer_block() {+ unsafe_for_editing = true;warnings.push(format!("the layers ({} block) could not be read ({e}); only the merged image was opened. Saving as PSD replaces the unreadable layer data",b.key_str()@@ -917,6 +937,7 @@ pub(crate) fn psd_to_document_decoded(cc,cmyk: fmt.mode == ColorMode::Cmyk,warnings,+ unsafe_for_editing,dpi: doc.resolution_dpi,txt2: file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)),filter_effects: Vec::new(),@@ -956,9 +977,9 @@ pub(crate) fn psd_to_document_decoded(}ctl.progress(0.1);if let Err(e) = &m {- cx.warn(format!("merged image could not be decoded: {e}"));+ cx.warn_unreadable_data(format!("merged image could not be decoded: {e}"));if can_recover_layers(file) {- cx.warn("extra alpha/spot channels in the merged image could not be recovered");+ cx.warn_unreadable_data("extra alpha/spot channels in the merged image could not be recovered");}}Some(m)@@ -1086,7 +1107,7 @@ pub(crate) fn psd_to_document_decoded(}// A merged image that failed to decode was reported above.Err(_) if matches!(merged, Some(Err(_))) => {}- Err(e) => cx.warn(format!("the image could not be read: {e}")),+ Err(e) => cx.warn_unreadable_data(format!("the image could not be read: {e}")),}}@@ -1101,7 +1122,10 @@ pub(crate) fn psd_to_document_decoded(let skip = usize::from(file.merged_has_alpha() && names.len() == usize::from(h.channels).saturating_sub(cc));let names = names.get(skip..).unwrap_or_default();for (k, idx) in (first..usize::from(h.channels)).enumerate() {- let Some(p) = merged_plane(all, idx, plane) else { break };+ let Some(p) = merged_plane(all, idx, plane) else {+ cx.warn_unreadable_data(format!("merged extra channel {idx} is incomplete and was not imported"));+ break;+ };let mut s = Surface::new(cx.mask_fmt);s.write_interleaved(canvas, &be_to_ne_plane(p, depth, n));s.prune();@@ -1139,7 +1163,7 @@ pub(crate) fn psd_to_document_decoded(return None;}ctl.progress(1.0);- Some((doc, cx.warnings))+ Some((doc, cx.warnings, cx.unsafe_for_editing))}#[cfg(test)]@@ -1184,6 +1208,36 @@ mod tests {assert_eq!(unicode_names(&data), ["A"]);}+ #[test]+ fn unreadable_layer_channel_marks_conversion_unsafe_for_editing() {+ let mut file = testgen::small(Version::Psd, Compression::Raw);+ let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == 0).unwrap();+ channel.data.clear();+ assert!(file.layers()[0].decode_channel(0, file.header.depth, file.header.version).is_err());++ let (_, warnings, unsafe_for_editing) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap();+ assert!(unsafe_for_editing);+ assert!(warnings.iter().any(|w| w.contains("could not be decoded")));+ }++ #[test]+ fn unreadable_mask_channel_marks_conversion_unsafe_for_editing() {+ let mut file = testgen::small(Version::Psd, Compression::Raw);+ let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == CHANNEL_USER_MASK).unwrap();+ channel.data.clear();++ let (_, warnings, unsafe_for_editing) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap();+ assert!(unsafe_for_editing);+ assert!(warnings.iter().any(|w| w.contains("could not be decoded")));+ }++ #[test]+ fn valid_layer_channels_keep_conversion_editable() {+ let file = testgen::small(Version::Psd, Compression::Raw);+ let (_, warnings, unsafe_for_editing) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap();+ assert!(!unsafe_for_editing, "unexpectedly marked good PSD unsafe: {warnings:?}");+ }+#[test]fn merged_plane_checks_offsets() {let all = [1u8, 2, 3, 4];diff --git a/crates/io/src/recovery.rs b/crates/io/src/recovery.rsnew file mode 100644index 000000000..214ae6e10--- /dev/null+++ b/crates/io/src/recovery.rs@@ -0,0 +1,108 @@+//! A recovered PSD may be exported only to a new file. Publishing a completely+//! written temporary inode with `hard_link` gives an atomic, no-replace commit:+//! replacing the original file (including through an alias) is impossible.+//!+//! There is deliberately no fallback to `rename`, which can replace files.++use std::path::Path;+use crate::IoError;++#[cfg(not(target_arch = "wasm32"))]+struct Temporary(std::path::PathBuf);++#[cfg(not(target_arch = "wasm32"))]+impl Drop for Temporary {+ fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); }+}++/// Atomically publish an encoded recovery copy at a **previously unused** name.+/// Unlike a conventional Save As, this NEVER replaces an existing destination.+/// This includes aliases of the original (symlinks/hardlinks) and defeats a+/// race where a destination appears after an earlier `exists()` check.+/// A filesystem that cannot hard-link a same-directory temporary file fails+/// closed rather than falling back to a destructive operation.+#[cfg(not(target_arch = "wasm32"))]+pub fn write_recovery_copy_bytes(destination: &Path, bytes: &[u8]) -> Result<(), IoError> {+ use std::fs::OpenOptions;+ use std::io::Write;+ use std::sync::atomic::{AtomicU64, Ordering};++ static NEXT: AtomicU64 = AtomicU64::new(0);+ let err = |e: std::io::Error| IoError::Unsupported(format!("recovery copy: {e}"));+ let parent = destination.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));+ let name = destination.file_name().filter(|n| !n.is_empty()).ok_or_else(||+ IoError::Unsupported("recovery copy needs a valid file name".into()))?;+ let mut temporary = None;+ for _ in 0..64 {+ let next = NEXT.fetch_add(1, Ordering::Relaxed);+ let mut filename = std::ffi::OsString::from(".photocraft-recovery-");+ filename.push(std::process::id().to_string());+ filename.push(format!("-{next}-"));+ filename.push(name);+ filename.push(".tmp");+ let candidate = parent.join(filename);+ let mut opts = OpenOptions::new();+ opts.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ opts.mode(0o600);+ }+ match opts.open(&candidate) {+ Ok(file) => { temporary = Some((Temporary(candidate), file)); break; }+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,+ Err(e) => return Err(err(e)),+ }+ }+ let (temp, mut file) = temporary.ok_or_else(|| IoError::Unsupported("cannot reserve a temporary recovery file".into()))?;+ file.write_all(bytes).map_err(err)?;+ file.sync_all().map_err(err)?;+ drop(file);+ // The link operation is atomic: EEXIST if ANY file was placed at the+ // destination, even after a previous validation or through a symlink.+ std::fs::hard_link(&temp.0, destination).map_err(|e| {+ if e.kind() == std::io::ErrorKind::AlreadyExists {+ IoError::Unsupported("recovery copy must use a NEW file name; an existing file will never be overwritten".into())+ } else {+ err(e)+ }+ })?;+ // The copy now has its own name and stays intact when the temp name is removed.+ Ok(())+}++#[cfg(target_arch = "wasm32")]+pub fn write_recovery_copy_bytes(_destination: &Path, _bytes: &[u8]) -> Result<(), IoError> {+ Err(IoError::Unsupported("native recovery copy is unavailable on the web".into()))+}++#[cfg(all(test, not(target_arch = "wasm32")))]+mod tests {+ use super::*;++ #[test]+ fn recovered_copy_never_replaces_an_existing_file() {+ let dir = std::env::temp_dir().join(format!("photocraft-copy-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));+ std::fs::create_dir(&dir).unwrap();+ let source = dir.join("original.psd");+ let copy = dir.join("copy.psd");+ std::fs::write(&source, b"valuable original").unwrap();+ assert!(write_recovery_copy_bytes(&source, b"damaged").is_err());+ assert_eq!(std::fs::read(&source).unwrap(), b"valuable original");+ write_recovery_copy_bytes(©, b"recovered").unwrap();+ assert_eq!(std::fs::read(©).unwrap(), b"recovered");+ assert!(write_recovery_copy_bytes(©, b"overwritten").is_err());+ assert_eq!(std::fs::read(©).unwrap(), b"recovered");+ #[cfg(unix)] {+ use std::os::unix::fs::symlink;+ let link = dir.join("symlink.psd");+ symlink(&source, &link).unwrap();+ assert!(write_recovery_copy_bytes(&link, b"symlink overwrite").is_err());+ let hardlink = dir.join("hardlink.psd");+ std::fs::hard_link(&source, &hardlink).unwrap();+ assert!(write_recovery_copy_bytes(&hardlink, b"hardlink overwrite").is_err());+ }+ assert_eq!(std::fs::read(&source).unwrap(), b"valuable original");+ std::fs::remove_dir_all(dir).unwrap();+ }+}diff --git a/crates/io/tests/psd_recovery_generated.rs b/crates/io/tests/psd_recovery_generated.rsnew file mode 100644index 000000000..2eaa62de0--- /dev/null+++ b/crates/io/tests/psd_recovery_generated.rs@@ -0,0 +1,64 @@+//! PSD/PSB recovery regression tests using in-memory Rust-generated fixtures.+//!+//! No `.psd` file is checked into the repository and no Python generator runs.+//! Fixtures are created at the beginning of each test, so parallel test order+//! does not matter. See the ignored test for GUI-ready temporary files.++#[path = "support/recovery_psd.rs"]+mod recovery_psd;++use photocraft_io::{IoError, import, import_psd_for_recovery};+use photocraft_psd::PsdFile;++#[test]+fn valid_generated_psd_opens_normally() {+ let bytes = recovery_psd::make_psd(false);+ assert_eq!(bytes.len(), 74_986, "the fixture should retain the reference PSD layout");+ let result = import("valid-two-layers.psd", &bytes).expect("generated healthy PSD must import");+ assert!(!result.source_read_only);+ assert!(!result.preview_only);+ assert_eq!(result.document.layers.len(), 2);+}++#[test]+fn corrupt_generated_rle_channel_requires_opt_in_recovery() {+ let bytes = recovery_psd::make_psd(true);+ assert_eq!(bytes.len(), 74_986, "the fixture should retain the reference PSD layout");+ let (parsed, _) = PsdFile::from_bytes_and_merged(&bytes, |_| false).expect("the PSD container must stay valid");+ let layer = parsed.layers().iter().find(|layer| layer.name() == "BROKEN orange RLE").expect("generated upper layer exists");++ assert!(layer.decode_channel(0, parsed.header.depth, parsed.header.version).is_ok());+ assert!(layer.decode_channel(1, parsed.header.depth, parsed.header.version).is_err());+ assert!(layer.decode_channel(2, parsed.header.depth, parsed.header.version).is_ok());+ assert!(parsed.decode_merged().is_ok(), "the composite must remain recoverable");++ let error = import("corrupt-green-rle.psd", &bytes).unwrap_err();+ assert!(matches!(error, IoError::Unsupported(_)), "unexpected error: {error}");++ let recovered = import_psd_for_recovery("corrupt-green-rle.psd", &bytes).expect("explicit recovery must return readable layers");+ assert!(recovered.source_read_only, "recovery must not save over the source");+ assert!(!recovered.preview_only);+ assert!(!recovered.document.layers.is_empty());+ assert!(recovered.warnings.iter().any(|w| w.starts_with("PSD/PSB RECOVERY:")));+ assert!(recovered.warnings.iter().any(|w| w.contains("could not be decoded")));+}++/// Generate the same two PSDs on demand for manual testing in the GUI.+///+/// Run with:+/// cargo test -p photocraft-io --test psd_recovery_generated \+/// write_psds_for_manual_gui_test -- --ignored --nocapture+///+/// The files go to the system's temp folder, not into the repository.+#[test]+#[ignore = "writes temporary PSD fixtures only when manual GUI testing is requested"]+fn write_psds_for_manual_gui_test() {+ let output = std::env::temp_dir().join(format!("photocraft-psd-recovery-{}", std::process::id()));+ std::fs::create_dir_all(&output).expect("create temporary fixture directory");++ for (name, corrupt) in [("valid-two-layers.psd", false), ("corrupt-green-rle.psd", true)] {+ let path = output.join(name);+ std::fs::write(&path, recovery_psd::make_psd(corrupt)).expect("write generated temporary PSD");+ println!("{}", path.display());+ }+}diff --git a/crates/io/tests/support/recovery_psd.rs b/crates/io/tests/support/recovery_psd.rsnew file mode 100644index 000000000..aff1632e2--- /dev/null+++ b/crates/io/tests/support/recovery_psd.rs@@ -0,0 +1,191 @@+//! Minimal, deterministic PSD fixtures for the PSD recovery tests.+//!+//! Pure Rust / std: no binary fixtures, external assets, Python, or build script.+//! The damaged fixture has valid layer records and a valid merged composite;+//! only the green channel of the orange layer contains a truncated PackBits run.++const WIDTH: usize = 128;+const HEIGHT: usize = 96;+const PANEL: (usize, usize, usize, usize) = (20, 16, 108, 80);+const PANEL_RGB: [u8; 3] = [244, 156, 28];+const PANEL_ALPHA: u8 = 220;++struct Channel {+ id: i16,+ data: Vec<u8>,+}++struct Layer {+ record: Vec<u8>,+ pixels: Vec<u8>,+}++fn put_len(out: &mut Vec<u8>, len: usize) {+ out.extend_from_slice(&u32::try_from(len).expect("test PSD section fits u32").to_be_bytes());+}++fn background_rgb() -> [Vec<u8>; 3] {+ let mut planes: [Vec<u8>; 3] = std::array::from_fn(|_| Vec::with_capacity(WIDTH * HEIGHT));+ for y in 0..HEIGHT {+ for x in 0..WIDTH {+ let checker = u8::try_from((x / 16 + y / 16) % 2).expect("checker value is 0 or 1");+ planes[0].push(34 + checker * 12);+ planes[1].push(102 + checker * 15);+ planes[2].push(184 + checker * 12);+ }+ }+ planes+}++fn raw_channel(id: i16, pixels: &[u8]) -> Channel {+ let mut data = Vec::with_capacity(2 + pixels.len());+ data.extend_from_slice(&0u16.to_be_bytes()); // 0 = uncompressed+ data.extend_from_slice(pixels);+ Channel { id, data }+}++fn rle_channel(id: i16, sample: u8, width: usize, height: usize, corrupt: bool) -> Channel {+ let mut rows: Vec<Vec<u8>> = Vec::with_capacity(height);+ for y in 0..height {+ if corrupt && y == height / 2 {+ // 0 declares one literal byte, but that byte is missing.+ // Its row-length entry remains valid: this tests the decoder.+ rows.push(vec![0]);+ continue;+ }+ let mut row = Vec::new();+ let mut remaining = width;+ while remaining != 0 {+ let count = remaining.min(128);+ // PackBits negative repeat count -(count - 1), modulo 256.+ let header = u8::try_from(257 - count).expect("PackBits repeat header fits u8");+ row.extend_from_slice(&[header, sample]);+ remaining -= count;+ }+ rows.push(row);+ }+ let mut data = Vec::new();+ data.extend_from_slice(&1u16.to_be_bytes()); // 1 = PackBits/RLE+ for row in &rows {+ data.extend_from_slice(&u16::try_from(row.len()).expect("row fits PSD u16 length").to_be_bytes());+ }+ for row in rows {+ data.extend_from_slice(&row);+ }+ Channel { id, data }+}++fn layer(name: &str, rect: (i32, i32, i32, i32), channels: Vec<Channel>) -> Layer {+ let (left, top, right, bottom) = rect;+ let name_bytes = name.as_bytes();+ let name_len = u8::try_from(name_bytes.len()).expect("layer name fits Pascal string");++ let mut extra = Vec::new();+ extra.extend_from_slice(&0u32.to_be_bytes()); // no layer mask+ extra.extend_from_slice(&0u32.to_be_bytes()); // no blending ranges+ extra.push(name_len);+ extra.extend_from_slice(name_bytes);+ while extra.len() % 4 != 0 {+ extra.push(0);+ }++ let mut record = Vec::new();+ for coordinate in [top, left, bottom, right] {+ record.extend_from_slice(&coordinate.to_be_bytes());+ }+ record.extend_from_slice(&u16::try_from(channels.len()).expect("channel count fits u16").to_be_bytes());+ for channel in &channels {+ record.extend_from_slice(&channel.id.to_be_bytes());+ put_len(&mut record, channel.data.len());+ }+ record.extend_from_slice(b"8BIMnorm");+ record.extend_from_slice(&[255, 0, 0, 0]); // opacity, clipping, flags, filler+ put_len(&mut record, extra.len());+ record.extend_from_slice(&extra);++ let mut pixels = Vec::new();+ for channel in channels {+ pixels.extend_from_slice(&channel.data);+ }+ Layer { record, pixels }+}++fn merged_rgb(background: &[Vec<u8>; 3]) -> Vec<u8> {+ let mut planes = background.clone();+ for y in PANEL.1..PANEL.3 {+ for x in PANEL.0..PANEL.2 {+ let pixel = y * WIDTH + x;+ for channel in 0..3 {+ let fg = u32::from(PANEL_RGB[channel]);+ let bg = u32::from(background[channel][pixel]);+ let alpha = u32::from(PANEL_ALPHA);+ let mixed = (fg * alpha + bg * (255 - alpha) + 127) / 255;+ planes[channel][pixel] = u8::try_from(mixed).expect("composite pixel fits u8");+ }+ }+ }+ let mut data = Vec::new();+ data.extend_from_slice(&0u16.to_be_bytes()); // merged composite: uncompressed+ for plane in &planes {+ data.extend_from_slice(plane);+ }+ data+}++/// Returns a complete PSD file in memory. `corrupt` changes *only* one RLE row+/// in the green channel of the upper layer; the file is otherwise well framed.+pub fn make_psd(corrupt: bool) -> Vec<u8> {+ let background = background_rgb();+ let background_layer = layer(+ "SAFE blue background",+ (0, 0, WIDTH as i32, HEIGHT as i32),+ (0..3).map(|ch| raw_channel(ch, &background[ch as usize])).collect(),+ );++ let panel_width = PANEL.2 - PANEL.0;+ let panel_height = PANEL.3 - PANEL.1;+ let top_layer = layer(+ "BROKEN orange RLE",+ (PANEL.0 as i32, PANEL.1 as i32, PANEL.2 as i32, PANEL.3 as i32),+ vec![+ rle_channel(0, PANEL_RGB[0], panel_width, panel_height, false),+ rle_channel(1, PANEL_RGB[1], panel_width, panel_height, corrupt),+ rle_channel(2, PANEL_RGB[2], panel_width, panel_height, false),+ rle_channel(-1, PANEL_ALPHA, panel_width, panel_height, false),+ ],+ );+ // Photoshop stores the top layer's record first.+ let layers = [top_layer, background_layer];+ let mut layer_info = Vec::new();+ layer_info.extend_from_slice(&2i16.to_be_bytes());+ for layer in &layers {+ layer_info.extend_from_slice(&layer.record);+ }+ for layer in &layers {+ layer_info.extend_from_slice(&layer.pixels);+ }+ if layer_info.len() % 2 != 0 {+ layer_info.push(0); // layer info is padded to an even size+ }++ let mut layer_and_mask = Vec::new();+ put_len(&mut layer_and_mask, layer_info.len());+ layer_and_mask.extend_from_slice(&layer_info);+ layer_and_mask.extend_from_slice(&0u32.to_be_bytes()); // empty global layer mask++ let mut out = Vec::new();+ out.extend_from_slice(b"8BPS");+ out.extend_from_slice(&1u16.to_be_bytes()); // PSD (not PSB)+ out.extend_from_slice(&[0u8; 6]);+ out.extend_from_slice(&3u16.to_be_bytes()); // RGB channels+ out.extend_from_slice(&(HEIGHT as u32).to_be_bytes());+ out.extend_from_slice(&(WIDTH as u32).to_be_bytes());+ out.extend_from_slice(&8u16.to_be_bytes()); // 8 bits per channel+ out.extend_from_slice(&3u16.to_be_bytes()); // RGB colour mode+ out.extend_from_slice(&0u32.to_be_bytes()); // no colour-mode data+ out.extend_from_slice(&0u32.to_be_bytes()); // no image resources+ put_len(&mut out, layer_and_mask.len());+ out.extend_from_slice(&layer_and_mask);+ out.extend_from_slice(&merged_rgb(&background));+ out+}diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rsindex 32f97bc4e..4e5745ade 100644--- a/crates/ui-egui/src/file_ui.rs+++ b/crates/ui-egui/src/file_ui.rs@@ -696,6 +696,9 @@ fn web_confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,/// Runs Save for Web with `p`, which says where to write.fn save_for_web(app: &mut PhotocraftApp, p: Value) -> Result<Value, String> {+ if app.session.active().is_some_and(|st| st.recovery_mode) {+ return Err("PSD recovery: Save for Web is disabled for this document; first save a new recovery copy and reopen it".into());+ }#[cfg(target_arch = "wasm32")]let result = download_for_web(app, p);#[cfg(not(target_arch = "wasm32"))]diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rsindex 45fa60d8a..e836692fd 100644--- a/crates/ui-egui/src/jobs_ui.rs+++ b/crates/ui-egui/src/jobs_ui.rs@@ -200,7 +200,7 @@ pub fn run(app: &mut PhotocraftApp, id: &str, params: Value) -> Result<Value, St/// replaces it when decoded. `path` is remembered for File › Save and Open Recent.pub fn start_open(app: &mut PhotocraftApp, name: &str, path: Option<String>, source: OpenSource) -> Result<(), String> {let name = &app.open_name(name);- match app.session.start_open(name, source).map_err(|e| e.to_string())? {+ match app.session.start_open_for_user(name, source).map_err(|e| e.to_string())? {// Inline (wasm): finish now, like a background open that ended at once.Started::Done(v) => finish_open(app, name, path.as_deref(), &v, None),Started::Job(job) => {@@ -552,6 +552,8 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valulet held = |doc, read_only, question, policy_applied| crate::open_prompt::Held {doc,read_only,+ recovery_mode: v.get("recovery").and_then(Value::as_bool).unwrap_or(false),+ recovery_pending: v.get("recovery").and_then(Value::as_bool).unwrap_or(false),name: name.to_string(),path: path.map(str::to_string),warnings: warnings.clone(),@@ -607,8 +609,11 @@ pub(crate) fn after_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>} else {notices::io_warnings(app, &opened, warnings);}- // Script events bound to "Open Document".- photocraft_engine::automate_cmds::document_opened(&mut app.session);+ // Script event hooks can save a file or run other I/O commands. Do not+ // dispatch them automatically for a recovered, partially decoded PSD.+ if !app.session.active().is_some_and(|st| st.recovery_mode) {+ photocraft_engine::automate_cmds::document_opened(&mut app.session);+ }app.sync_views();}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 8784800dd..0bc7b47c1 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -526,6 +526,10 @@ pub struct Services {/// Encode and write in one step on a worker thread, so a large save doesn't freeze the/// window (#2017). With background jobs on, saves use it instead of `export` and `write`.pub save_file: Option<SaveFileFn>,+ /// Recovery-mode writes publish ONLY new files (no replace, even via aliases).+ pub recovery_write: Option<WriteFn>,+ /// The worker version of `recovery_write`, to keep large PSD copies responsive.+ pub recovery_save_file: Option<SaveFileFn>,/// File access used only by control/MCP requests. Interactive dialogs keep/// using `file_dialog` and `write` with the user's authority.pub automation_read: Option<AutomationReadFn>,@@ -1455,7 +1459,14 @@ impl PhotocraftApp {}let import = self.services.import.as_ref().ok_or("no importer configured")?;let max_svg_group_depth = self.session.prefs().file_handling.rasterize_svg_groups_deeper_than as usize;- let (doc, warnings) = import(name, bytes, max_svg_group_depth)?;+ let (doc, warnings, recovery_mode) = match import(name, bytes, max_svg_group_depth) {+ Ok((doc, warnings)) => (doc, warnings, false),+ Err(error) if photocraft_io::is_psd(bytes) => match photocraft_io::import_psd_for_recovery(name, bytes) {+ Ok(r) if r.source_read_only && r.warnings.iter().any(|w| w.starts_with("PSD/PSB RECOVERY:")) => (r.document, r.warnings, true),+ _ => return Err(error),+ },+ Err(error) => return Err(error),+ };// Edit › Color Settings policies apply on open; Ask When Opening holds the file back// until its prompt is answered, and later files wait behind it (`open_prompt`).// Missing fonts are read from the document itself: it may not be open yet (#4559).@@ -1468,7 +1479,9 @@ impl PhotocraftApp {self,open_prompt::Held {doc,- read_only: photocraft_io::affinity::is_affinity(bytes),+ read_only: recovery_mode || photocraft_io::affinity::is_affinity(bytes),+ recovery_mode,+ recovery_pending: recovery_mode,name: name.to_string(),path: path.map(str::to_string),warnings: warnings.clone(),@@ -1540,7 +1553,7 @@ impl PhotocraftApp {return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());}// Edit Contents documents save back into their smart object.- if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") {+ if path.is_none() && !self.session.active().is_some_and(|st| st.recovery_mode) && self.session.is_enabled("layer.smartObjects.saveContents") {self.run("layer.smartObjects.saveContents", serde_json::json!({}))?;return Ok(serde_json::json!({"path": "smart object", "warnings": []}));}@@ -1562,16 +1575,21 @@ impl PhotocraftApp {|| (e == "ora" && holds_ora)|| (flat && photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write))});- let suggested = match &st.path {- Some(p) if writable => p.clone(),- p => {- let source = p.as_deref().unwrap_or(&st.doc.name);- let ext = match photocraft_engine::file_cmds::extension(source).as_deref() {- Some("pdn") => "pcraft",- Some("kra" | "krz") => "ora",- _ => "psd",- };- std::path::Path::new(source).with_extension(ext).to_string_lossy().into_owned()+ let suggested = if st.recovery_mode {+ let name = st.doc.name.rsplit_once('.').map(|(stem, _)| stem).unwrap_or(&st.doc.name);+ format!("{name} recovered.psd")+ } else {+ match &st.path {+ Some(p) if writable => p.clone(),+ p => {+ let source = p.as_deref().unwrap_or(&st.doc.name);+ let ext = match photocraft_engine::file_cmds::extension(source).as_deref() {+ Some("pdn") => "pcraft",+ Some("kra" | "krz") => "ora",+ _ => "psd",+ };+ std::path::Path::new(source).with_extension(ext).to_string_lossy().into_owned()+ }}};let doc = st.doc.id;@@ -1753,6 +1771,23 @@ impl PhotocraftApp {/// `None` when the save went to a background job (#2017), which finishes it in/// [`jobs_ui::tick`].pub(crate) fn write_document(&mut self, path: String, settings: &ExportSettings, copy: bool) -> Result<Option<(String, Vec<String>)>, String> {+ if self.session.active().is_some_and(|st| st.recovery_mode) {+ // Keep the recovery restriction for the entire session, even after+ // successfully writing a copy. Neither Save nor Save As can replace+ // ANY existing file; only a new copy is possible.+ if self.background_jobs {+ let writer = self.services.recovery_save_file.clone().ok_or("safe recovery-copy writer not available")?;+ return jobs_ui::start_save(self, path, settings.clone(), true, writer, false);+ }+ let st = self.session.active().ok_or("no document")?;+ let (doc, revision) = (st.doc.id, st.revision);+ let export = self.services.export.as_ref().ok_or("no exporter configured")?;+ let (bytes, warnings) = export(&st.doc, &path, settings)?;+ let write = self.services.recovery_write.as_mut().ok_or("safe recovery-copy writer not available")?;+ write(&path, &bytes)?;+ self.saved(doc, revision, &path, &warnings, true);+ return Ok(Some((path, warnings)));+ }if self.background_jobs&& let Some(save) = self.services.save_file.clone(){@@ -1790,7 +1825,12 @@ impl PhotocraftApp {(false, holds)}};- self.ui.status = crate::i18n::fmt(tl!("Saved {name}"), &[("name", path)]);+ let recovery_copy = copy && self.session.documents().iter().any(|st| st.doc.id == doc && st.recovery_mode);+ self.ui.status = if recovery_copy {+ crate::i18n::fmt(tl!("Saved recovered copy as {name}"), &[("name", path)])+ } else {+ crate::i18n::fmt(tl!("Saved {name}"), &[("name", path)])+ };if !copy {// A background save may finish while another document is active (or after its// document was closed, when there is nothing left to record).@@ -1872,6 +1912,11 @@ impl PhotocraftApp {/// Targa's `None`: 32 with an alpha channel or transparency, else 24; a DDS texture's:/// uncompressed without mipmaps). Automation saves never prompt.pub fn save_automation_with(&mut self, path: Option<String>, choices: FormatChoices) -> Result<Value, String> {+ // Automation writes use a capability-scoped writer which may replace a+ // destination. Do not silently downgrade the recovery no-overwrite rule.+ if self.session.active().is_some_and(|st| st.recovery_mode) {+ return Err("PSD recovery: automated saving is disabled for this document; choose File > Save a Copy with a new filename".into());+ }let target = {let state = self.session.active().ok_or("no document")?;// As File › Save: without `path` only a layered file is written back (#416).@@ -2189,6 +2234,7 @@ impl eframe::App for PhotocraftApp {workspace_ui::windows(self, &ctx);palette::show(self, &ctx);dialogs::show(self, &ctx);+ open_prompt::recovery_dialog(self, &ctx);rasterize_prompt::run_pending(self, &ctx);jobs_ui::dialog(self, &ctx);discard_ui::show(self, &ctx);diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 63b46f442..77373d6b0 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -13,7 +13,8 @@ pub(crate) fn modal_allows(app: &PhotocraftApp, id: &str) -> bool {if app.camera_raw.is_some() || crate::crop_ui::blocks(app, id) {return false;}- (app.ui.dialogs.is_empty() && app.discard.is_none()) || crate::shortcuts::NAV_COMMANDS.contains(&id)+ (app.ui.dialogs.is_empty() && app.discard.is_none() && !app.held_opens.front().is_some_and(|h| h.recovery_pending))+ || crate::shortcuts::NAV_COMMANDS.contains(&id)}/// Top-level menus in Photoshop order.diff --git a/crates/ui-egui/src/open_prompt.rs b/crates/ui-egui/src/open_prompt.rsindex a4d93ca05..5234297c8 100644--- a/crates/ui-egui/src/open_prompt.rs+++ b/crates/ui-egui/src/open_prompt.rs@@ -19,6 +19,10 @@ pub struct Held {pub doc: Document,/// The source is read-only (an Affinity file): Save doesn't write back to it.pub read_only: bool,+ /// True for damaged PSDs admitted only through the explicit recovery path.+ pub recovery_mode: bool,+ /// Consent must be obtained before the document is opened or a profile prompt appears.+ pub recovery_pending: bool,pub name: String,pub path: Option<String>,pub warnings: Vec<String>,@@ -48,6 +52,9 @@ pub fn arrive(app: &mut PhotocraftApp, held: Held) {/// Opens queued files in order until one needs its prompt, which is shown if it isn't yet.fn advance(app: &mut PhotocraftApp) {while let Some(front) = app.held_opens.front() {+ if front.recovery_pending {+ return; // The recovery consent window is drawn by recovery_dialog().+ }if front.question.is_some() {if !app.ui.dialogs.iter().any(|d| d.fields.contains_key(FIELD)) {show(app);@@ -112,6 +119,9 @@ pub fn owns(fields: &serde_json::Map<String, Value>) -> bool {/// The prompt's answer: `Some(action)` (OK) opens the first queued file with it and moves on to/// the next; `None` (Cancel) drops every queued file and stops the reads still running.pub fn answer(app: &mut PhotocraftApp, action: Option<&str>) -> Result<Value, String> {+ if app.held_opens.front().is_some_and(|h| h.recovery_pending) {+ return Err("answer the PSD recovery confirmation first".into());+ }let Some(action) = action else {let dropped = app.held_opens.len();let name = app.held_opens.front().map(|h| h.name.clone()).unwrap_or_default();@@ -134,6 +144,9 @@ pub fn answer(app: &mut PhotocraftApp, action: Option<&str>) -> Result<Value, St/// already waiting with a mismatch in the same mode were asked before that and get the same/// answer; any other question still asks.pub fn answer_remembering(app: &mut PhotocraftApp, action: &str) -> Result<Value, String> {+ if app.held_opens.front().is_some_and(|h| h.recovery_pending) {+ return Err("answer the PSD recovery confirmation first".into());+ }let Some(key) = app.held_opens.front().and_then(|h| policy_key(h.doc.mode)) else { return answer(app, Some(action)) };let policy = match action {"convert" => "convert",@@ -141,7 +154,7 @@ pub fn answer_remembering(app: &mut PhotocraftApp, action: &str) -> Result<Value_ => "preserve",};app.run("edit.colorSettings", json!({key: policy, "askOnMismatch": false}))?;- let same = |h: &Held| policy_key(h.doc.mode) == Some(key) && h.question.as_ref().is_some_and(|q| q.get("missing").and_then(Value::as_bool) != Some(true));+ let same = |h: &Held| !h.recovery_pending && policy_key(h.doc.mode) == Some(key) && h.question.as_ref().is_some_and(|q| q.get("missing").and_then(Value::as_bool) != Some(true));let Some(held) = app.held_opens.pop_front() else { return Err("no file is waiting to open".into()) };let r = open(app, held, Some(action));while app.held_opens.front().is_some_and(same) {@@ -154,10 +167,52 @@ pub fn answer_remembering(app: &mut PhotocraftApp, action: &str) -> Result<Valuer}+/// Consent required before opening a damaged PSD as a partially recovered document.+/// Its original has no Save path; all further writes use the no-overwrite writer.+pub(crate) fn recovery_dialog(app: &mut PhotocraftApp, ctx: &egui::Context) {+ let Some(front) = app.held_opens.front().filter(|h| h.recovery_pending) else { return };+ let (name, warnings) = (front.name.clone(), front.warnings.clone());+ let mut choice = None;+ egui::Window::new(tl!("Damaged Photoshop document"))+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])+ .collapsible(false)+ .resizable(false)+ .show(ctx, |ui| {+ ui.set_max_width(500.0);+ ui.label(format!("{name} contains unreadable layers or image data."));+ ui.label("You can open the recoverable parts, but some pixels or masks may be missing.");+ ui.strong("The original file cannot be overwritten. Save a Copy must use a new file name.");+ for warning in warnings.iter().filter(|w| !w.starts_with("PSD/PSB RECOVERY:")).take(5) {+ ui.label(format!("- {warning}"));+ }+ ui.separator();+ ui.horizontal(|ui| {+ if ui.button(tl!("Cancel")).clicked() { choice = Some(false); }+ if ui.button(tl!("Open in Recovery Mode")).clicked() { choice = Some(true); }+ });+ });+ if let Some(accept) = choice { answer_recovery(app, accept); }+}++/// Accept or discard the first pending damaged PSD. This is also the modal's testable+/// transition: no document is opened before `accept` is explicitly true.+pub(crate) fn answer_recovery(app: &mut PhotocraftApp, accept: bool) {+ if !app.held_opens.front().is_some_and(|h| h.recovery_pending) { return; }+ if accept {+ if let Some(front) = app.held_opens.front_mut() { front.recovery_pending = false; }+ } else {+ app.held_opens.pop_front();+ }+ advance(app);+}+/// Opens a queued file, applying `action` (the prompt's answer) or else the Color Settings/// policy, then does what any open does afterwards.fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Value, String> {- let Held { mut doc, read_only, name, path, warnings, bytes, slot, question, policy_applied } = held;+ if held.recovery_pending {+ return Err("damaged PSD cannot be opened before recovery consent".into());+ }+ let Held { mut doc, read_only, recovery_mode, recovery_pending: _, name, path, warnings, bytes, slot, question, policy_applied } = held;let index = if question.is_some() || policy_applied {if let Some(action) = action&& let Err(e) = app.session.color.resolve_open(&mut doc, action)@@ -171,6 +226,7 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Val};if let Some(st) = app.session.active_mut() {st.source_read_only = read_only;+ st.recovery_mode = recovery_mode;}let index = match slot {Some(slot) => appdiff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rsindex 3396dfcdd..166de4c8a 100644--- a/crates/ui-egui/src/save_identity_tests.rs+++ b/crates/ui-egui/src/save_identity_tests.rs@@ -272,3 +272,65 @@ fn unconfirmed_download_names_the_document_but_keeps_it_unsaved() {app.save_as(Some("download.psd".into())).unwrap();assert!(!app.has_unsaved_work());}++#[cfg(not(target_arch = "wasm32"))]+#[test]+fn recovery_session_remains_protected_after_saving_a_copy() {+ let mut app = app();+ let dir = std::env::temp_dir().join(format!(+ "photocraft-recovery-ui-{}-{}",+ std::process::id(),+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()+ ));+ std::fs::create_dir(&dir).unwrap();+ let original = dir.join("original.psd");+ let copy = dir.join("copy.psd");+ std::fs::write(&original, b"valuable original bytes").unwrap();+ app.session.active_mut().unwrap().recovery_mode = true;+ app.session.active_mut().unwrap().source_read_only = true;+ app.services.recovery_write =+ Some(Box::new(|path, bytes| photocraft_io::write_recovery_copy_bytes(std::path::Path::new(path), bytes).map_err(|e| e.to_string())));+ let own = identity(&app);+ assert!(app.save_as(Some(original.to_string_lossy().into_owned())).is_err());+ app.save_as(Some(copy.to_string_lossy().into_owned())).unwrap();+ assert!(copy.is_file());+ assert_eq!(identity(&app), own, "Save a Copy must not retarget the recovered session");+ assert!(app.session.active().unwrap().recovery_mode);+ assert!(app.save_as(Some(copy.to_string_lossy().into_owned())).is_err());+ assert!(app.save_automation(Some(original.to_string_lossy().into_owned())).is_err());+ assert_eq!(std::fs::read(original).unwrap(), b"valuable original bytes");+ std::fs::remove_dir_all(dir).unwrap();+}++#[test]+fn recovery_consent_is_required_before_opening() {+ let mut session = Session::new();+ session.execute("file.new", json!({"width": 2, "height": 2})).unwrap();+ let doc = (*session.active().unwrap().doc).clone();+ session.close(0);+ let mut app = PhotocraftApp::new(session, Services::default());+ let make_held = |doc: photocraft_doc::Document| crate::open_prompt::Held {+ doc,+ read_only: true,+ recovery_mode: true,+ recovery_pending: true,+ name: "damaged.psd".into(),+ path: Some("/tmp/damaged.psd".into()),+ warnings: vec!["PSD/PSB RECOVERY: partial import".into()],+ bytes: None,+ slot: None,+ question: None,+ policy_applied: false,+ };+ crate::open_prompt::arrive(&mut app, make_held(doc.clone()));+ assert_eq!(app.session.documents().len(), 0);+ crate::open_prompt::answer_recovery(&mut app, false);+ assert_eq!(app.session.documents().len(), 0);+ crate::open_prompt::arrive(&mut app, make_held(doc));+ crate::open_prompt::answer_recovery(&mut app, true);+ assert_eq!(app.session.documents().len(), 1);+ let st = app.session.active().unwrap();+ assert!(st.recovery_mode);+ assert!(st.source_read_only);+ assert_eq!(st.path, None);+}diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rsindex 7fffcf784..bfab75a50 100644--- a/crates/ui-egui/src/view_cmds.rs+++ b/crates/ui-egui/src/view_cmds.rs@@ -1469,9 +1469,11 @@ fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value)/// and saved state are untouched. An action being recorded keeps it as a `file.saveACopy` step/// with its path (#4373).fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {- let doc = app.session.active().ok_or("no document")?.doc.clone();+ let st = app.session.active().ok_or("no document")?;+ let recovered = st.recovery_mode;+ let doc = st.doc.clone();let stem = doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(a, _)| a);- let suggested = format!("{stem} copy.psd");+ let suggested = if recovered { format!("{stem} recovered.psd") } else { format!("{stem} copy.psd") };// The copy is of the document as it was when asked.app.pick_save(&suggested, move |app, path| {// An RGB Targa asks for its bits per pixel first, and a DDS texture for its compression;@@ -1490,7 +1492,7 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {if parked {return Ok(json!({"path": path, "warnings": []}));}- let r = write_copy(app, &doc, &path, crate::FormatChoices::default())?;+ let r = write_copy_with_mode(app, &doc, &path, crate::FormatChoices::default(), recovered)?;app.session.journal.push(("file.saveACopy".into(), json!({"path": path})));Ok(r)})@@ -1499,10 +1501,25 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {/// Writes `doc` to `path` as a copy (Save a Copy, and its replayed action step): the document's/// path and saved state are untouched. `choices` are the Targa and DDS answers, when there are any.pub(crate) fn write_copy(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, path: &str, choices: crate::FormatChoices) -> Result<Value, String> {+ let recovered = app.session.documents().iter().any(|st| st.doc.id == doc.id && st.recovery_mode);+ write_copy_with_mode(app, doc, path, choices, recovered)+}++fn write_copy_with_mode(+ app: &mut PhotocraftApp,+ doc: &photocraft_doc::Document,+ path: &str,+ choices: crate::FormatChoices,+ recovered: bool,+) -> Result<Value, String> {let settings = choices.apply(app.save_settings());let export = app.services.export.as_ref().ok_or("no exporter configured")?;let (bytes, warnings) = export(doc, path, &settings)?;- let write = app.services.write.as_mut().ok_or("no writer configured")?;+ let write = if recovered {+ app.services.recovery_write.as_mut().ok_or("safe recovery-copy writer not available")?+ } else {+ app.services.write.as_mut().ok_or("no writer configured")?+ };write(path, &bytes)?;let template = "Saved a copy as {path}";app.ui.status = crate::i18n::fmt(tl!(template), &[("path", path)]);@@ -1515,11 +1532,16 @@ pub(crate) fn write_copy(app: &mut PhotocraftApp, doc: &photocraft_doc::Document/// Layer › Smart Objects › Export Contents: saves the contents file under its own name by default.fn export_contents(app: &mut PhotocraftApp) -> Result<Value, String> {let st = app.session.active().ok_or("no document")?;+ let recovered = st.recovery_mode;let layer = st.active_layer.ok_or("no layer selected")?;// The contents as they were when asked, like Save a Copy.let (name, bytes) = photocraft_engine::smart_cmds::contents_of(&st.doc, layer).map_err(|e| e.to_string())?;app.pick_save(&name.clone(), move |app, path| {- let write = app.services.write.as_mut().ok_or("no writer configured")?;+ let write = if recovered {+ app.services.recovery_write.as_mut().ok_or("safe recovery-copy writer not available")?+ } else {+ app.services.write.as_mut().ok_or("no writer configured")?+ };write(&path, &bytes)?;let template = "Exported contents to {path}";app.ui.status = crate::i18n::fmt(tl!(template), &[("path", &path)]);