Skip to content

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

refactor: confirm damaged PSD opens without restricting saves

David Bonnierd1c1d8819f75
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index 9a1a6c138..082506e92 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -363,19 +363,6 @@ 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,
@@ -550,8 +537,6 @@ 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.rs
index 45c298d00..5f3a5edec 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -540,9 +540,6 @@ 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.
@@ -550,14 +547,7 @@ 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 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)?
- };
+ let warnings = save_doc(&doc, &path, SaveOpts::from_params(s, p, "file.saveACopy")?)?;
Ok(json!({"path": path, "warnings": warnings}))
}
@@ -1461,15 +1451,7 @@ 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 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 names = export_layers_with(s, p, |name, bytes| write_file(&join(&dir, name), bytes))?;
let files: Vec<String> = names.iter().map(|name| join(&dir, name)).collect();
Ok(json!({"files": files}))
}
@@ -1641,11 +1623,7 @@ 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) => {
- 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())?;
- }
+ write_file(path, cube.as_bytes())?;
Ok(json!({"path": path, "size": size, "layerCount": count}))
}
None => Ok(json!({"cube": cube, "size": size, "layerCount": count})),
@@ -1947,24 +1925,3 @@ 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.rs
index c97cab6b0..02f3c2c26 100644
--- a/crates/engine/src/jobs.rs
+++ b/crates/engine/src/jobs.rs
@@ -510,14 +510,14 @@ impl Session {
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.
+ /// Interactive opening: hold a damaged PSD until the user answers a damage
+ /// confirmation, without changing import or subsequent save behaviour.
+ /// Headless callers keep using [`Self::start_open`].
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> {
+ fn start_open_inner(&mut self, name: &str, source: OpenSource, confirm_damage: bool) -> Result<Started> {
let label = format!("Opening {name}");
let name_w = name.to_string();
let name_a = name.to_string();
@@ -536,32 +536,26 @@ impl Session {
ctx.check()?;
ctx.progress(0.02, "Decoding");
let imported = ctx
- .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)
- }
- })
+ .stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&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()),
})?;
ctx.progress(0.95, "Preparing layers");
- warm_layer_bounds(&imported.document, || ctx.check())?;
+ warm_layer_bounds(&imported.0.document, || ctx.check())?;
Ok(imported)
},
- move |s, mut r: photocraft_io::ImportResult| {
+ move |s, (mut r, damaged): (photocraft_io::ImportResult, bool)| {
// File Handling's ACEScg option, before the colour prompt looks at the profile.
crate::file_cmds::tag_exr_colorspace(s, &name_a, &mut r.document);
// 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));
- let recovery = offer_recovery && r.source_read_only && r.warnings.iter().any(|w| w.starts_with("PSD/PSB RECOVERY:"));
+ let damaged = confirm_damage && damaged;
let question = s.color.open_question(&r.document).filter(|_| !raw);
- if recovery || question.is_some() {
+ if damaged || 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, "recovery": recovery}));
+ return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question, "damaged": damaged}));
}
let (index, color) = s.open_document(r.document, None);
if let Some(st) = s.active_mut() {
@@ -1022,3 +1016,50 @@ pub fn specs() -> Vec<crate::commands::CommandSpec> {
#[cfg(test)]
#[path = "jobs_tests.rs"]
mod tests;
+
+#[cfg(test)]
+#[path = "../../io/tests/support/recovery_psd.rs"]
+mod psd_open_fixture;
+
+#[cfg(test)]
+mod psd_open_confirmation_tests {
+ use super::*;
+
+ fn result(s: &mut Session, started: Started) -> Value {
+ match started {
+ Started::Done(v) => v,
+ Started::Job(id) => s.wait_job(id).unwrap(),
+ }
+ }
+
+ #[test]
+ fn headless_open_keeps_best_effort_psd_import() {
+ let mut s = Session::new();
+ let started = s.start_open("damaged.psd", OpenSource::Bytes(Arc::new(super::psd_open_fixture::make_psd(true)))).unwrap();
+ let v = result(&mut s, started);
+ assert!(v.get("document").is_some(), "{v}");
+ assert!(v.get("held").is_none(), "no new prompt for a headless caller");
+ assert!(!s.active().unwrap().source_read_only);
+ assert!(v["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("could not be decoded")));
+ }
+
+ #[test]
+ fn interactive_open_holds_only_a_damaged_psd() {
+ for corrupt in [false, true] {
+ let mut s = Session::new();
+ let started = s.start_open_for_user("file.psd", OpenSource::Bytes(Arc::new(super::psd_open_fixture::make_psd(corrupt)))).unwrap();
+ let v = result(&mut s, started);
+ if corrupt {
+ assert_eq!(v["damaged"], true);
+ assert!(s.documents().is_empty());
+ let held = v["held"].as_u64().unwrap();
+ let (doc, read_only) = s.take_held_open(held).unwrap();
+ assert_eq!(doc.layers.len(), 2);
+ assert!(!read_only);
+ } else {
+ assert!(v.get("document").is_some(), "{v}");
+ assert!(!s.active().unwrap().source_read_only);
+ }
+ }
+ }
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 87d79cf46..5a7aa83df 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -208,9 +208,6 @@ 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,
@@ -276,7 +273,6 @@ 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.rs
index 5184dc061..37227fff8 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -61,8 +61,6 @@ 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;
@@ -304,94 +302,32 @@ pub fn import_with_svg_group_depth_and_interrupt(
max_group_depth: usize,
ctl: &photocraft_raster::Interrupt,
) -> Result<ImportResult, IoError> {
- ctl.check().map_err(|_| IoError::Cancelled)?;
- let r = import_stages(name, bytes, ctl, max_group_depth)?;
- ctl.check().map_err(|_| IoError::Cancelled)?;
- ctl.progress(1.0);
- Ok(r)
+ import_for_open_with(name, bytes, max_group_depth, ctl).map(|(result, _)| result)
}
-/// Import a damaged PSD/PSB for explicit recovery. Unlike [`import`], this
-/// permits partially decoded layers, but marks the result source-read-only.
+/// The ordinary import result plus whether PSD/PSB decoding encountered damaged data.
+/// Interactive callers can ask whether to continue before adding the document. This is
+/// information, not a save policy: accepting it opens an ordinary, writable document.
+/// Non-interactive callers keep using [`import`], which still returns readable content
+/// and warnings without requiring confirmation.
///
-/// 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)
+/// The flag is independent of the wording of `warnings`. An ordinary compatibility
+/// warning does not set it. No file is decoded a second time to obtain this information.
+pub fn import_for_open(name: &str, bytes: &[u8], max_group_depth: usize) -> Result<(ImportResult, bool), IoError> {
+ import_for_open_with(name, bytes, max_group_depth, &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()));
- }
+/// [`import_for_open`] with cancellation and progress, shared with [`import_with`].
+pub fn import_for_open_with(name: &str, bytes: &[u8], max_group_depth: usize, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
- let result = import_stages_with_psd_recovery(name, bytes, ctl, photocraft_doc::MAX_GROUP_DEPTH, true)?;
+ let mut damaged = false;
+ let result = import_stages(name, bytes, ctl, max_group_depth, &mut damaged)?;
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)
+ Ok((result, damaged))
}
-fn import_stages_with_psd_recovery(
- name: &str,
- bytes: &[u8],
- ctl: &photocraft_raster::Interrupt,
- max_group_depth: usize,
- recovery_requested: bool,
-) -> Result<ImportResult, IoError> {
+fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, max_group_depth: usize, damaged: &mut 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)?;
@@ -409,27 +345,11 @@ fn import_stages_with_psd_recovery(
psd_import::check_group_depth(&file)?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(0.05);
- 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());
- }
+ let (mut document, warnings, psd_damaged) = psd_import::psd_to_document_decoded_integrity(&file, ctl, merged).ok_or(IoError::Cancelled)?;
+ *damaged = psd_damaged;
document.name = name.to_string();
text_import::prepare(&mut document);
- return Ok(ImportResult { document, warnings, source_read_only: unsafe_for_editing, preview_only: false });
+ return Ok(ImportResult { document, warnings, source_read_only: false, preview_only: false });
}
if affinity::is_affinity(bytes) || affinity::has_extension(name) {
return affinity::import(name, bytes);
@@ -684,7 +604,7 @@ pub fn merged_composite(file: &PsdFile) -> Result<Vec<[f32; 4]>, IoError> {
#[cfg(test)]
mod tests {
- use super::{IoError, import, is_svg_input};
+ use super::{import, import_for_open, is_svg_input};
use photocraft_psd::{Compression, Version, testgen};
#[test]
@@ -695,78 +615,30 @@ mod tests {
}
#[test]
- fn unreadable_psd_channel_is_rejected_before_editing() {
+ fn unreadable_psd_channel_keeps_best_effort_import_and_reports_damage() {
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")));
+ let imported = import("damaged.psd", &bytes).unwrap();
+ assert!(!imported.source_read_only);
+ assert!(imported.warnings.iter().any(|w| w.contains("could not be decoded")));
+ let (opened, damaged) = import_for_open("damaged.psd", &bytes, photocraft_doc::MAX_GROUP_DEPTH).unwrap();
+ assert!(damaged);
+ assert!(!opened.source_read_only);
+ assert!(!opened.preview_only);
+ assert_eq!(opened.warnings, imported.warnings);
+ assert_eq!(opened.document.layers.len(), imported.document.layers.len());
}
#[test]
- fn recovery_import_of_valid_psd_remains_editable() {
+ fn valid_psd_does_not_request_damage_confirmation() {
let bytes = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap();
- let result = super::import_psd_for_recovery("valid.psd", &bytes).unwrap();
+ let (result, damaged) = import_for_open("valid.psd", &bytes, photocraft_doc::MAX_GROUP_DEPTH).unwrap();
+ assert!(!damaged);
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() {
let webp_header = b"RIFF\x04\0\0\0WEBP";
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs
index 2acfab577..6e8bebe67 100644
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@ -51,8 +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,
+ /// Decoding encountered damaged PSD data; interactive opens ask whether to continue.
+ pub damaged: 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).
@@ -135,7 +135,7 @@ impl Ctx<'_> {
}
fn warn_unreadable_data(&mut self, s: impl Into<String>) {
- self.unsafe_for_editing = true;
+ self.damaged = true;
self.warn(s);
}
@@ -837,8 +837,8 @@ pub(crate) fn psd_to_document_decoded(
}
/// 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.
+/// Interactive opens use this to ask whether to continue. Both ordinary imports and
+/// the low-level conversion API retain their existing best-effort behaviour.
pub(crate) fn psd_to_document_decoded_integrity(
file: &PsdFile,
ctl: &photocraft_raster::Interrupt,
@@ -910,9 +910,9 @@ pub(crate) fn psd_to_document_decoded_integrity(
// 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;
+ let mut damaged = false;
if let Some((b, e)) = file.unreadable_layer_block() {
- unsafe_for_editing = true;
+ damaged = 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()
@@ -937,7 +937,7 @@ pub(crate) fn psd_to_document_decoded_integrity(
cc,
cmyk: fmt.mode == ColorMode::Cmyk,
warnings,
- unsafe_for_editing,
+ damaged,
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(),
@@ -985,7 +985,7 @@ pub(crate) fn psd_to_document_decoded_integrity(
Some(m)
} else {
if let Some(Err(e)) = decoded {
- cx.warn(format!("merged image could not be decoded; opened the available layers instead: {e}"));
+ cx.warn_unreadable_data(format!("merged image could not be decoded; opened the available layers instead: {e}"));
}
None
};
@@ -1163,7 +1163,7 @@ pub(crate) fn psd_to_document_decoded_integrity(
return None;
}
ctl.progress(1.0);
- Some((doc, cx.warnings, cx.unsafe_for_editing))
+ Some((doc, cx.warnings, cx.damaged))
}
#[cfg(test)]
@@ -1209,33 +1209,33 @@ mod tests {
}
#[test]
- fn unreadable_layer_channel_marks_conversion_unsafe_for_editing() {
+ fn unreadable_layer_channel_marks_conversion_damaged() {
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);
+ let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap();
+ assert!(damaged);
assert!(warnings.iter().any(|w| w.contains("could not be decoded")));
}
#[test]
- fn unreadable_mask_channel_marks_conversion_unsafe_for_editing() {
+ fn unreadable_mask_channel_marks_conversion_damaged() {
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);
+ let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap();
+ assert!(damaged);
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:?}");
+ let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap();
+ assert!(!damaged, "unexpectedly marked good PSD damaged: {warnings:?}");
}
#[test]
diff --git a/crates/io/src/recovery.rs b/crates/io/src/recovery.rs
deleted file mode 100644
index bc3c5c55e..000000000
--- a/crates/io/src/recovery.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-//! 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 crate::IoError;
-use std::path::Path;
-
-#[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(&copy, b"recovered").unwrap();
- assert_eq!(std::fs::read(&copy).unwrap(), b"recovered");
- assert!(write_recovery_copy_bytes(&copy, b"overwritten").is_err());
- assert_eq!(std::fs::read(&copy).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.rs
index 2eaa62de0..13479a843 100644
--- a/crates/io/tests/psd_recovery_generated.rs
+++ b/crates/io/tests/psd_recovery_generated.rs
@@ -7,7 +7,7 @@
#[path = "support/recovery_psd.rs"]
mod recovery_psd;
-use photocraft_io::{IoError, import, import_psd_for_recovery};
+use photocraft_io::{import, import_for_open};
use photocraft_psd::PsdFile;
#[test]
@@ -18,10 +18,12 @@ fn valid_generated_psd_opens_normally() {
assert!(!result.source_read_only);
assert!(!result.preview_only);
assert_eq!(result.document.layers.len(), 2);
+ let (_, damaged) = import_for_open("valid-two-layers.psd", &bytes, photocraft_doc::MAX_GROUP_DEPTH).unwrap();
+ assert!(!damaged);
}
#[test]
-fn corrupt_generated_rle_channel_requires_opt_in_recovery() {
+fn corrupt_generated_rle_channel_keeps_best_effort_import_and_reports_damage() {
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");
@@ -32,15 +34,49 @@ fn corrupt_generated_rle_channel_requires_opt_in_recovery() {
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 imported = import("corrupt-green-rle.psd", &bytes).expect("headless imports keep readable content");
+ assert!(!imported.source_read_only);
+ assert!(!imported.preview_only);
+ assert_eq!(imported.document.layers.len(), 2);
+ assert!(imported.warnings.iter().any(|w| w.contains("could not be decoded")));
- 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")));
+ let (opened, damaged) = import_for_open("corrupt-green-rle.psd", &bytes, photocraft_doc::MAX_GROUP_DEPTH).unwrap();
+ assert!(damaged, "interactive opening must ask whether to continue");
+ assert!(!opened.source_read_only, "the flag does not introduce a save restriction");
+ assert_eq!(opened.warnings, imported.warnings);
+ assert_eq!(opened.document.layers.len(), imported.document.layers.len());
+}
+
+#[test]
+fn damaged_composite_keeps_layers_and_requests_interactive_confirmation() {
+ let mut file = PsdFile::from_bytes(&recovery_psd::make_psd(false)).unwrap();
+ file.image_data.data.truncate(file.image_data.data.len() / 2);
+ let bytes = file.to_bytes().unwrap();
+ let imported = import("damaged-preview.psd", &bytes).expect("intact layers are still usable");
+ assert_eq!(imported.document.layers.len(), 2);
+ assert!(!imported.source_read_only);
+ let (opened, damaged) = import_for_open("damaged-preview.psd", &bytes, photocraft_doc::MAX_GROUP_DEPTH).unwrap();
+ assert!(damaged);
+ assert_eq!(opened.warnings, imported.warnings);
+ assert!(opened.warnings.iter().any(|w| w.contains("merged image")));
+}
+
+#[test]
+fn ordinary_compatibility_warning_does_not_mean_damaged() {
+ use photocraft_psd::{ImageResource, ResolutionInfo, resources::ids};
+ let mut file = PsdFile::from_bytes(&recovery_psd::make_psd(false)).unwrap();
+ let resolution = ResolutionInfo { v_res_fixed: ResolutionInfo::from_dpi(150.0).v_res_fixed, ..ResolutionInfo::from_dpi(300.0) };
+ file.resources.push(ImageResource::new(ids::RESOLUTION_INFO, resolution.to_bytes()));
+ let (opened, damaged) = import_for_open("resolution.psd", &file.to_bytes().unwrap(), photocraft_doc::MAX_GROUP_DEPTH).unwrap();
+ assert!(!damaged);
+ assert!(opened.warnings.iter().any(|w| w.contains("vertical resolution")));
+}
+
+#[test]
+fn fatal_parse_errors_are_not_turned_into_confirmation_requests() {
+ let bytes = b"8BPS\0";
+ assert!(import("truncated.psd", bytes).is_err());
+ assert!(import_for_open("truncated.psd", bytes, photocraft_doc::MAX_GROUP_DEPTH).is_err());
}
/// Generate the same two PSDs on demand for manual testing in the GUI.
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 182930232..52a4cfc49 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -315,6 +315,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
ui.add_space(8.0);
about_tab_body(app, ui, chosen);
}
+ DialogKind::Command if crate::open_prompt::owns_damage(&fields) => crate::open_prompt::damage_body(ui, &fields),
DialogKind::Command if crate::guide_layout_ui::owns(&fields) => outcome = crate::guide_layout_ui::body(app, ui, &mut fields, interactive),
DialogKind::Command if crate::brush_preset_dialog::owns(&fields) => {
outcome = crate::brush_preset_dialog::body(app, ui, &mut fields, interactive)
@@ -414,6 +415,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
} else {
let ok_label = if d.kind == DialogKind::NewDocument {
tl!("Create")
+ } else if crate::open_prompt::owns_damage(&d.fields) {
+ tl!("Continue")
} else if crate::delete_layer_prompt::owns(&d.fields) {
tl!("Delete")
} else if crate::disk_change_prompt::owns(&d.fields) {
@@ -622,6 +625,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
}
r
}
+ DialogKind::Command if crate::open_prompt::owns_damage(&d.fields) => crate::open_prompt::answer_damage(app, true),
DialogKind::Command if crate::guide_layout_ui::owns(&d.fields) => crate::guide_layout_ui::confirm(app, &d.fields),
DialogKind::Command if crate::brush_preset_dialog::owns(&d.fields) => crate::brush_preset_dialog::confirm(app, &d.fields),
DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields),
@@ -687,7 +691,9 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id));
}
// Cancel on a profile prompt opens neither its file nor the ones still to come.
- if crate::open_prompt::owns(&closed.fields) {
+ if crate::open_prompt::owns_damage(&closed.fields) {
+ crate::open_prompt::answer_damage(app, false)?;
+ } else if crate::open_prompt::owns(&closed.fields) {
crate::open_prompt::answer(app, None)?;
}
app.ui.dialogs.retain(|d| !crate::layer_style::color_picker::child_of(&d.fields, id));
diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs
index 4e5745ade..32f97bc4e 100644
--- a/crates/ui-egui/src/file_ui.rs
+++ b/crates/ui-egui/src/file_ui.rs
@@ -696,9 +696,6 @@ 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.rs
index e836692fd..bd7c16ace 100644
--- a/crates/ui-egui/src/jobs_ui.rs
+++ b/crates/ui-egui/src/jobs_ui.rs
@@ -552,8 +552,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu
let 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),
+ damage_pending: v.get("damaged").and_then(Value::as_bool).unwrap_or(false),
name: name.to_string(),
path: path.map(str::to_string),
warnings: warnings.clone(),
@@ -565,7 +564,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu
// Held back for the profile prompt (Ask When Opening).
if let Some(id) = v.get("held").and_then(Value::as_u64) {
let (doc, read_only) = app.session.take_held_open(id).ok_or("the open job's document is gone")?;
- crate::open_prompt::arrive(app, held(doc, read_only, v.get("color").cloned(), false));
+ crate::open_prompt::arrive(app, held(doc, read_only, v.get("color").filter(|q| !q.is_null()).cloned(), false));
return Ok(());
}
let mut index = v.get("document").and_then(Value::as_u64).ok_or("the open job returned no document")? as usize;
@@ -609,11 +608,8 @@ pub(crate) fn after_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>
} else {
notices::io_warnings(app, &opened, warnings);
}
- // 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);
- }
+ // Script events bound to "Open Document".
+ 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.rs
index 0bc7b47c1..f108ef8bd 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -526,10 +526,6 @@ 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>,
@@ -1459,13 +1455,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, 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),
+ let (doc, warnings, damaged) = if photocraft_io::is_psd(bytes) {
+ // Read PSD damage as structured information in the same decode, not by
+ // retrying an error or matching the text of a compatibility warning.
+ let (r, damaged) = photocraft_io::import_for_open(name, bytes, max_svg_group_depth).map_err(|e| e.to_string())?;
+ (r.document, r.warnings, damaged)
+ } else {
+ let (doc, warnings) = import(name, bytes, max_svg_group_depth)?;
+ (doc, warnings, false)
};
// 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`).
@@ -1479,9 +1476,8 @@ impl PhotocraftApp {
self,
open_prompt::Held {
doc,
- read_only: recovery_mode || photocraft_io::affinity::is_affinity(bytes),
- recovery_mode,
- recovery_pending: recovery_mode,
+ read_only: photocraft_io::affinity::is_affinity(bytes),
+ damage_pending: damaged,
name: name.to_string(),
path: path.map(str::to_string),
warnings: warnings.clone(),
@@ -1553,7 +1549,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.active().is_some_and(|st| st.recovery_mode) && self.session.is_enabled("layer.smartObjects.saveContents") {
+ if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") {
self.run("layer.smartObjects.saveContents", serde_json::json!({}))?;
return Ok(serde_json::json!({"path": "smart object", "warnings": []}));
}
@@ -1575,21 +1571,16 @@ impl PhotocraftApp {
|| (e == "ora" && holds_ora)
|| (flat && photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write))
});
- 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 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 doc = st.doc.id;
@@ -1771,23 +1762,6 @@ 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()
{
@@ -1825,12 +1799,7 @@ impl PhotocraftApp {
(false, holds)
}
};
- 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)])
- };
+ self.ui.status = 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).
@@ -1912,11 +1881,6 @@ 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).
@@ -2234,7 +2198,6 @@ 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);
@@ -2979,6 +2942,8 @@ mod transform_undo_tests;
#[cfg(test)]
mod transform_type_tests;
+#[cfg(test)]
+mod psd_open_tests;
#[cfg(test)]
mod save_identity_tests;
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 77373d6b0..63b46f442 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -13,8 +13,7 @@ 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() && !app.held_opens.front().is_some_and(|h| h.recovery_pending))
- || crate::shortcuts::NAV_COMMANDS.contains(&id)
+ (app.ui.dialogs.is_empty() && app.discard.is_none()) || 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.rs
index 3a86e2019..39f4dee8a 100644
--- a/crates/ui-egui/src/open_prompt.rs
+++ b/crates/ui-egui/src/open_prompt.rs
@@ -1,8 +1,9 @@
-//! Ask When Opening (Edit › Color Settings): a file whose embedded profile doesn't match the
-//! working space (or that has none) is held back while a prompt asks what to do, as Photoshop
-//! does: one prompt at a time, naming its file, before that file opens. OK applies the answer to
-//! that file and opens it, then asks about the next; Cancel opens neither it nor the files still
-//! to come. Files that finish reading while a prompt is up wait their turn, so they open in order.
+//! Interactive opening confirmations: damaged PSD data and Color Settings questions.
+//! A decoded file is held back while its standard, agent-accessible dialog asks what to do.
+//! Damage confirmation comes first; Continue admits the file normally once any profile question
+//! is answered, with no persistent save restriction. Cancelling damage discards just that file;
+//! cancelling a profile question retains its existing behaviour of cancelling the whole queue.
+//! Files that finish reading while a prompt is up wait their turn.
use std::sync::Arc;
@@ -13,16 +14,18 @@ use crate::PhotocraftApp;
/// The field that marks a prompt as this module's.
const FIELD: &str = "__heldOpen";
+/// A regular dialog: agents see it in `ui.inspect` and answer through
+/// `ui.dialog.confirm` / `ui.dialog.cancel`, just like the profile prompt.
+const DAMAGE_FIELD: &str = "__psdDamagedOpen";
/// A file read and decoded, waiting to open.
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,
+ /// Ask whether to continue before adding a damaged PSD or showing its profile prompt.
+ /// Discarded after the answer: it does not become a document or save restriction.
+ pub damage_pending: bool,
pub name: String,
pub path: Option<String>,
pub warnings: Vec<String>,
@@ -52,8 +55,11 @@ 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.damage_pending {
+ if !app.ui.dialogs.iter().any(|d| owns_damage(&d.fields)) {
+ show_damage(app);
+ }
+ return;
}
if front.question.is_some() {
if !app.ui.dialogs.iter().any(|d| d.fields.contains_key(FIELD)) {
@@ -119,8 +125,8 @@ 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());
+ if app.held_opens.front().is_some_and(|h| h.damage_pending) {
+ return Err("answer the damaged PSD confirmation first".into());
}
let Some(action) = action else {
let dropped = app.held_opens.len();
@@ -144,8 +150,8 @@ 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());
+ if app.held_opens.front().is_some_and(|h| h.damage_pending) {
+ return Err("answer the damaged PSD 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 {
@@ -155,9 +161,7 @@ pub fn answer_remembering(app: &mut PhotocraftApp, action: &str) -> Result<Value
};
app.run("edit.colorSettings", json!({key: policy, "askOnMismatch": false}))?;
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))
+ !h.damage_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));
@@ -171,58 +175,68 @@ pub fn answer_remembering(app: &mut PhotocraftApp, action: &str) -> Result<Value
r
}
-/// 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);
+/// Whether the fields belong to the damage confirmation (not the profile prompt).
+pub(crate) fn owns_damage(fields: &serde_json::Map<String, Value>) -> bool {
+ fields.contains_key(DAMAGE_FIELD)
+}
+
+fn show_damage(app: &mut PhotocraftApp) {
+ let Some(front) = app.held_opens.front().filter(|h| h.damage_pending) else { return };
+ let message = format!(
+ "{}\n\n{}\n\n{}",
+ crate::i18n::fmt(tl!("The document “{name}” may be damaged."), &[("name", &front.name)]),
+ tl!("Some layers, pixels or masks could not be read. Do you want to continue opening it?"),
+ tl!("If you continue, saving over the original may permanently discard unreadable data. Save a copy to keep the original."),
+ );
+ let fields = [
+ (DAMAGE_FIELD.into(), json!(true)),
+ ("__label".into(), json!("Damaged Photoshop document")),
+ ("name".into(), json!(front.name)),
+ ("message".into(), json!(message)),
+ ("warnings".into(), json!(front.warnings)),
+ ]
+ .into_iter()
+ .collect();
+ app.ui.open_dialog(crate::state::DialogKind::Command, fields);
+}
+
+/// Body of the standard modal; the same fields are visible to automation.
+pub(crate) fn damage_body(ui: &mut egui::Ui, fields: &serde_json::Map<String, Value>) {
+ ui.label(fields.get("message").and_then(Value::as_str).unwrap_or_default());
+ if let Some(warnings) = fields.get("warnings").and_then(Value::as_array) {
+ egui::ScrollArea::vertical().max_height(140.0).show(ui, |ui| {
+ for warning in warnings.iter().filter_map(Value::as_str) {
+ ui.label(warning);
}
});
- });
- 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;
- }
+/// Continue or discard this file only, then move the queue forward. Accepting does not
+/// mark the document read-only: Save, Export, scripts and web downloads work normally.
+pub(crate) fn answer_damage(app: &mut PhotocraftApp, accept: bool) -> Result<Value, String> {
+ let Some(front) = app.held_opens.front_mut().filter(|h| h.damage_pending) else {
+ return Err("no damaged PSD is waiting for confirmation".into());
+ };
+ let name = front.name.clone();
if accept {
- if let Some(front) = app.held_opens.front_mut() {
- front.recovery_pending = false;
- }
+ front.damage_pending = false;
} else {
app.held_opens.pop_front();
+ app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]);
+ app.ui.status_error = false;
}
advance(app);
+ Ok(json!({"name": name, "continued": accept}))
}
/// 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> {
- if held.recovery_pending {
- return Err("damaged PSD cannot be opened before recovery consent".into());
+ if held.damage_pending {
+ return Err("damaged PSD cannot be opened before confirmation".into());
}
- let Held { mut doc, read_only, recovery_mode, recovery_pending: _, name, path, warnings, bytes, slot, question, policy_applied } = held;
+ let Held { mut doc, read_only, damage_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)
@@ -236,7 +250,6 @@ 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) => app
diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs
new file mode 100644
index 000000000..4a5149de4
--- /dev/null
+++ b/crates/ui-egui/src/psd_open_tests.rs
@@ -0,0 +1,187 @@
+//! Damaged PSD confirmation is an opening decision, not a persistent save policy.
+//! The exact same generated files exercise IO, the synchronous web-style path,
+//! background opening and the agent-visible dialog commands.
+
+#[path = "../../io/tests/support/recovery_psd.rs"]
+mod recovery_psd;
+
+use crate::{PhotocraftApp, Services, control};
+use photocraft_engine::Session;
+use serde_json::{Value, json};
+use std::{cell::RefCell, rc::Rc};
+
+fn app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(
+ Session::new(),
+ Services {
+ import: Some(Box::new(|name, bytes, depth| {
+ photocraft_io::import_with_svg_group_depth(name, bytes, depth).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string())
+ })),
+ 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(|_, _| Ok(()))),
+ automation_write: Some(Box::new(|_, _| Ok(()))),
+ ..Default::default()
+ },
+ );
+ app.background_jobs = false;
+ app
+}
+
+fn call(app: &mut PhotocraftApp, method: &str, params: Value) -> Value {
+ let (req, _rx) = control::ControlRequest::new(method, params);
+ match control::handle(app, &egui::Context::default(), &req) {
+ control::Outcome::Done(v) => v,
+ _ => panic!("{method}: expected an immediate reply"),
+ }
+}
+
+fn damage_dialog(app: &mut PhotocraftApp) -> u64 {
+ let inspected = call(app, "ui.inspect", json!({}));
+ assert_eq!(inspected["ok"], true);
+ let dialogs = inspected["result"]["dialogs"].as_array().unwrap();
+ assert_eq!(dialogs.len(), 1, "only the damage confirmation: {dialogs:?}");
+ assert_eq!(dialogs[0]["fields"]["__psdDamagedOpen"], true);
+ assert!(dialogs[0]["fields"]["message"].as_str().unwrap().contains("saving over the original"));
+ dialogs[0]["id"].as_u64().unwrap()
+}
+
+#[test]
+fn healthy_psd_opens_without_a_damage_prompt() {
+ let mut app = app();
+ app.open_bytes("valid-two-layers.psd", &recovery_psd::make_psd(false)).unwrap();
+ assert_eq!(app.session.documents().len(), 1);
+ assert!(app.ui.dialogs.is_empty());
+ assert!(!app.session.active().unwrap().source_read_only);
+}
+
+#[test]
+fn damaged_psd_can_be_cancelled_or_accepted_through_agent_dialog_commands() {
+ let mut app = app();
+ let bytes = recovery_psd::make_psd(true);
+ app.open_bytes("corrupt-green-rle.psd", &bytes).unwrap();
+ assert!(app.session.documents().is_empty());
+ let id = damage_dialog(&mut app);
+ assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": id}))["ok"], true);
+ assert!(app.session.documents().is_empty());
+ assert!(app.ui.dialogs.is_empty());
+
+ app.open_bytes("corrupt-green-rle.psd", &bytes).unwrap();
+ let id = damage_dialog(&mut app);
+ assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": id}))["ok"], true);
+ assert_eq!(app.session.documents().len(), 1);
+ assert!(!app.session.active().unwrap().source_read_only);
+ assert!(app.ui.dialogs.is_empty());
+}
+
+#[test]
+fn accepted_psd_keeps_its_source_path_and_uses_the_normal_save_writer() {
+ let mut app = app();
+ let path = "original.psd";
+ let stored = Rc::new(RefCell::new(recovery_psd::make_psd(true)));
+ let original = stored.borrow().clone();
+ let destination = stored.clone();
+ app.services.write = Some(Box::new(move |p, bytes| {
+ assert_eq!(p, path);
+ *destination.borrow_mut() = bytes.to_vec();
+ Ok(())
+ }));
+ app.open_bytes_from(path, &original, Some(path)).unwrap();
+ assert_eq!(*stored.borrow(), original, "nothing written while waiting for consent");
+ let id = damage_dialog(&mut app);
+ assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": id}))["ok"], true);
+ assert_eq!(app.session.active().unwrap().path.as_deref(), Some(path));
+ assert_eq!(*stored.borrow(), original, "accepting the open is not a save");
+
+ for _ in 0..2 {
+ app.run("layer.new.layer", json!({})).unwrap();
+ crate::menus::invoke(&mut app, &egui::Context::default(), "file.save", json!({})).unwrap();
+ assert_eq!(app.session.active().unwrap().path.as_deref(), Some(path));
+ assert!(!app.session.active().unwrap().is_dirty());
+ assert!(photocraft_io::import(path, &stored.borrow()).is_ok());
+ }
+ assert_ne!(*stored.borrow(), original, "ordinary Save can replace the source after consent");
+ assert!(app.save_automation(Some("automated-copy.psd".into())).is_ok());
+}
+
+#[test]
+fn accepted_psd_uses_web_download_semantics_without_a_special_writer() {
+ let mut app = app();
+ app.services.write_unconfirmed = true;
+ app.open_bytes("corrupt-green-rle.psd", &recovery_psd::make_psd(true)).unwrap();
+ let id = damage_dialog(&mut app);
+ assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": id}))["ok"], true);
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.save_as(Some("download.psd".into())).unwrap();
+ assert_eq!(app.session.active().unwrap().path.as_deref(), Some("download.psd"));
+ assert!(app.session.active().unwrap().is_dirty(), "an unconfirmed browser download is not a confirmed save");
+}
+
+#[test]
+fn damaged_psd_automation_import_does_not_require_interactive_confirmation() {
+ let mut app = app();
+ let warnings = app.open_automation_bytes("corrupt-green-rle.psd", &recovery_psd::make_psd(true)).unwrap();
+ assert_eq!(app.session.documents().len(), 1);
+ assert!(!app.session.active().unwrap().source_read_only);
+ assert!(app.ui.dialogs.is_empty());
+ assert!(warnings.iter().any(|w| w.contains("could not be decoded")));
+}
+
+#[test]
+fn cancelling_one_damaged_open_does_not_open_the_next_damaged_file_without_consent() {
+ let mut app = app();
+ let bytes = recovery_psd::make_psd(true);
+ for name in ["first.psd", "second.psd"] {
+ app.open_bytes(name, &bytes).unwrap();
+ }
+ let first = damage_dialog(&mut app);
+ assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": first}))["ok"], true);
+ assert!(app.session.documents().is_empty());
+ let second = damage_dialog(&mut app);
+ assert_ne!(first, second);
+ assert_eq!(app.ui.dialogs[0].fields["name"], "second.psd");
+ assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": second}))["ok"], true);
+ assert_eq!(app.session.documents().len(), 1);
+ assert_eq!(app.session.active().unwrap().doc.name, "second.psd");
+}
+
+#[test]
+fn damage_confirmation_precedes_the_profile_question() {
+ let mut app = app();
+ app.run("edit.colorSettings", json!({"askOnMismatch": true, "policyRgb": "preserve"})).unwrap();
+ let (mut file, _) = photocraft_psd::PsdFile::from_bytes_and_merged(&recovery_psd::make_psd(true), |_| false).unwrap();
+ file.resources.push(photocraft_psd::ImageResource::new(
+ photocraft_psd::resources::ids::ICC_PROFILE,
+ photocraft_cms::Builtin::from_id("adobe-rgb-compat").unwrap().profile().to_bytes().to_vec(),
+ ));
+ app.open_bytes("profile.psd", &file.to_bytes().unwrap()).unwrap();
+ let id = damage_dialog(&mut app);
+ assert!(crate::open_prompt::answer(&mut app, Some("preserve")).is_err(), "a profile answer cannot bypass the damage confirmation");
+ assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": id}))["ok"], true);
+ assert!(app.session.documents().is_empty(), "the profile question still needs its own answer");
+ assert_eq!(app.ui.dialogs.len(), 1);
+ assert!(!crate::open_prompt::owns_damage(&app.ui.dialogs[0].fields));
+ let profile = app.ui.dialogs[0].id;
+ assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": profile}))["ok"], true);
+ assert_eq!(app.session.documents().len(), 1);
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn background_damage_only_open_does_not_create_a_spurious_profile_question() {
+ let mut app = app();
+ app.background_jobs = true;
+ app.open_bytes("corrupt-green-rle.psd", &recovery_psd::make_psd(true)).unwrap();
+ // Wait deterministically for the worker, then let the normal UI completion path run.
+ let jobs: Vec<_> = app.session.jobs().iter().map(|j| j.id).collect();
+ for id in jobs {
+ app.session.wait_job(id).unwrap();
+ }
+ crate::jobs_ui::tick(&mut app, &egui::Context::default());
+ assert!(app.session.documents().is_empty());
+ let id = damage_dialog(&mut app);
+ assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": id}))["ok"], true);
+ assert_eq!(app.session.documents().len(), 1);
+ assert!(app.ui.dialogs.is_empty(), "color:null is not a profile question");
+}
diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rs
index 166de4c8a..3396dfcdd 100644
--- a/crates/ui-egui/src/save_identity_tests.rs
+++ b/crates/ui-egui/src/save_identity_tests.rs
@@ -272,65 +272,3 @@ 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.rs
index bfab75a50..7fffcf784 100644
--- a/crates/ui-egui/src/view_cmds.rs
+++ b/crates/ui-egui/src/view_cmds.rs
@@ -1469,11 +1469,9 @@ 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 st = app.session.active().ok_or("no document")?;
- let recovered = st.recovery_mode;
- let doc = st.doc.clone();
+ let doc = app.session.active().ok_or("no document")?.doc.clone();
let stem = doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(a, _)| a);
- let suggested = if recovered { format!("{stem} recovered.psd") } else { format!("{stem} copy.psd") };
+ let suggested = 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;
@@ -1492,7 +1490,7 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {
if parked {
return Ok(json!({"path": path, "warnings": []}));
}
- let r = write_copy_with_mode(app, &doc, &path, crate::FormatChoices::default(), recovered)?;
+ let r = write_copy(app, &doc, &path, crate::FormatChoices::default())?;
app.session.journal.push(("file.saveACopy".into(), json!({"path": path})));
Ok(r)
})
@@ -1501,25 +1499,10 @@ 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 = 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")?
- };
+ let write = 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)]);
@@ -1532,16 +1515,11 @@ fn write_copy_with_mode(
/// 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 = 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")?
- };
+ let write = 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)]);