Skip to content

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

Merge PR #6658: fix(ui): confirm opening damaged PSD/PSB documents

David Mann6aa27edb06cb
diff --cc crates/engine/src/jobs.rs
index 57846617d,a540a6644..707468be1
--- a/crates/engine/src/jobs.rs
+++ b/crates/engine/src/jobs.rs
@@@ -541,14 -542,14 +554,13 @@@ impl Session
};
ctx.check()?;
ctx.progress(0.02, "Decoding");
- let imported = ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_with_options_and_interrupt(&name_w, &bytes, &opts, ctl)).map_err(
- |e| match e {
- let imported = ctx
- .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 {
++ let imported =
++ ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, 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())?;
// Type layers need the shared text engine, whose first use waits for the
// installed-font scan started at launch (minutes on some machines). Wait here,
// so the shell's missing-font check after the open finds it ready instead of
@@@ -560,20 -561,19 +572,22 @@@
}
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);
+ crate::file_cmds::raw_defaults(s, &r.warnings, &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));
- if let Some(question) = s.color.open_question(&r.document).filter(|_| !raw) {
+ let damaged = confirm_damage && damaged;
+ let question = s.color.open_question(&r.document).filter(|_| !raw);
+ 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}));
+ return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question, "damaged": damaged}));
}
let (index, color) = s.open_document(r.document, None);
+ // Persisted IDs can collide: report the identity the session actually admitted.
+ let id = s.documents().get(index).ok_or(EngineError::NoDocument)?.doc.id;
if let Some(st) = s.active_mut() {
st.source_read_only = r.source_read_only;
}
diff --cc crates/io/src/lib.rs
index 3230e075f,77b7d7944..253ea6e43
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@@ -319,39 -318,32 +319,57 @@@ pub fn import_with_svg_group_depth_and_
max_group_depth: usize,
ctl: &photocraft_raster::Interrupt,
) -> Result<ImportResult, IoError> {
- import_for_open_with(name, bytes, max_group_depth, ctl).map(|(result, _)| result)
+ import_with_options_and_interrupt(name, bytes, &ImportOptions { max_group_depth, ..Default::default() }, ctl)
+}
+
+/// The user's settings that shape an import.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct ImportOptions {
+ /// SVG groups nested deeper than this are rasterised.
+ pub max_group_depth: usize,
+ /// The demosaic method camera raws are developed with.
+ pub demosaic: raw::Demosaic,
+}
+
+impl Default for ImportOptions {
+ fn default() -> Self {
+ ImportOptions { max_group_depth: photocraft_doc::MAX_GROUP_DEPTH, demosaic: raw::Demosaic::default() }
+ }
+}
+
+/// [`import`] with the user's import settings.
+pub fn import_with_options(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result<ImportResult, IoError> {
+ import_with_options_and_interrupt(name, bytes, opts, &photocraft_raster::Interrupt::NONE)
+}
+
+/// [`import_with`] with the user's import settings.
+pub fn import_with_options_and_interrupt(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &photocraft_raster::Interrupt) -> Result<ImportResult, IoError> {
++ import_for_open_with(name, bytes, opts, ctl).map(|(result, _)| result)
+ }
+
+ /// 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.
+ ///
+ /// 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)
++pub fn import_for_open(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result<(ImportResult, bool), IoError> {
++ import_for_open_with(name, bytes, opts, &photocraft_raster::Interrupt::NONE)
+ }
+
-/// [`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> {
++/// [`import_for_open`] with cancellation and progress, shared with [`import_with_options_and_interrupt`].
++pub fn import_for_open_with(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
- let r = import_stages(name, bytes, ctl, opts)?;
+ let mut damaged = false;
- let result = import_stages(name, bytes, ctl, max_group_depth, &mut damaged)?;
++ let result = import_stages(name, bytes, ctl, opts, &mut damaged)?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(1.0);
- Ok(r)
+ Ok((result, damaged))
}
- fn import_psd(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -> Result<ImportResult, IoError> {
+ fn import_psd(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, damaged: &mut bool) -> Result<ImportResult, IoError> {
// A merged image the import reads is decoded with the parse: a ZIP one is inflated once.
let (file, merged) = PsdFile::from_bytes_and_merged_recovering(
bytes,
@@@ -369,7 -362,9 +388,9 @@@
Ok(ImportResult { document, warnings, source_read_only: false, preview_only: false })
}
- fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions) -> Result<ImportResult, IoError> {
+ /// Dispatches format-specific importers and propagates a structured PSD damage
+ /// flag alongside the ordinary best-effort import result.
-fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, max_group_depth: usize, damaged: &mut bool) -> Result<ImportResult, IoError> {
++fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, 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)?;
@@@ -642,7 -637,44 +663,44 @@@ pub fn merged_composite(file: &PsdFile
#[cfg(test)]
mod tests {
- use super::{import, is_psd_input, is_svg_input};
- use super::{import, import_for_open, is_psd_input, is_svg_input};
++ use super::{ImportOptions, import, import_for_open, is_psd_input, is_svg_input};
+ use photocraft_psd::{Compression, Version, testgen};
+
+ /// Verifies a valid PSD remains editable after import.
+ #[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);
+ }
+
+ /// Verifies corrupt PSD channels produce warnings and an interactive damage flag
+ /// without rejecting otherwise readable headless imports.
+ #[test]
+ 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();
+ 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();
++ let (opened, damaged) = import_for_open("damaged.psd", &bytes, &ImportOptions::default()).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());
+ }
+
+ /// Verifies healthy PSD data never requires damage confirmation.
+ #[test]
+ fn valid_psd_does_not_request_damage_confirmation() {
+ let bytes = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap();
- let (result, damaged) = import_for_open("valid.psd", &bytes, photocraft_doc::MAX_GROUP_DEPTH).unwrap();
++ let (result, damaged) = import_for_open("valid.psd", &bytes, &ImportOptions::default()).unwrap();
+ assert!(!damaged);
+ assert!(!result.source_read_only);
+ }
#[test]
fn svg_extension_does_not_override_another_format_signature() {
diff --cc crates/io/tests/it/main.rs
index 662d37c30,000000000..2558e0957
mode 100644,000000..100644
--- a/crates/io/tests/it/main.rs
+++ b/crates/io/tests/it/main.rs
@@@ -1,76 -1,0 +1,77 @@@
+//! The crate's integration tests, linked into one test binary.
+
+mod adjust_blend_roundtrip;
+mod adjust_warnings;
+mod affinity;
+mod affinity_artboards;
+mod affinity_corpus;
+mod annotations;
+mod artboard_guide_order;
+mod banded;
+mod cancel;
+mod channels;
+mod cmyk_composite_export;
+mod color;
+mod common;
+mod composite;
+mod comps_artboards;
+mod corpus;
+mod corpus_regressions;
+mod effects_multi;
+mod exif_resolution;
+mod export_progress;
+mod exr_part_profile;
+mod flat;
+mod gif_frames;
+mod guides_v2;
+mod heif;
+mod heif_unsupported;
+mod krita_corpus;
+mod lab16;
+mod large_files;
+mod large_psb;
+mod layer_labels;
+mod layer_xmp;
+mod modes;
+mod multichannel;
+mod orientation;
+mod pattern_fill_psd;
+mod pcraft_manifest_name;
+mod pdn_corpus;
+mod png_text_metadata;
+mod psd16_merged_transparency;
+mod psd32_export;
+mod psd_background;
+mod psd_block_alignment;
+mod psd_block_layout;
+mod psd_damaged_merged;
+mod psd_empty_channels;
+mod psd_font_identity;
+mod psd_kerning;
+mod psd_layer_block_length;
+mod psd_maximize_compatibility;
+mod psd_noise_fill_roundtrip;
++mod psd_recovery_generated;
+mod psd_roundtrip_bytes;
+mod psd_structure;
+mod psd_style_sheets;
+mod psd_thumbnail;
+mod psd_type_bounds;
+mod psd_type_photoshop_bytes;
+mod psd_unknown_adjustment;
+mod psd_vertical_type;
+mod raw;
+mod resolution_axes;
+mod roundtrip;
+mod smart_contents_identity;
+mod smart_corpus;
+mod svg;
+mod text_corpus;
+mod text_styles;
+mod tiff_corpus;
+mod tiff_layers;
+mod tiff_pages;
+mod tiff_type_geometry;
+mod vector;
+mod xcf;
+mod xmp_export;
diff --cc crates/io/tests/it/psd_recovery_generated.rs
index 000000000,72aae0ab8..1e096b622
mode 000000,100644..100644
--- a/crates/io/tests/it/psd_recovery_generated.rs
+++ b/crates/io/tests/it/psd_recovery_generated.rs
@@@ -1,0 -1,106 +1,106 @@@
+ //! 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"]
++#[path = "../support/recovery_psd.rs"]
+ mod recovery_psd;
+
-use photocraft_io::{import, import_for_open};
++use photocraft_io::{ImportOptions, import, import_for_open};
+ use photocraft_psd::PsdFile;
+
+ /// Verifies a generated, two-layer PSD opens without source restrictions or damage prompts.
+ #[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);
- let (_, damaged) = import_for_open("valid-two-layers.psd", &bytes, photocraft_doc::MAX_GROUP_DEPTH).unwrap();
++ let (_, damaged) = import_for_open("valid-two-layers.psd", &bytes, &ImportOptions::default()).unwrap();
+ assert!(!damaged);
+ }
+
+ /// Verifies a truncated green PackBits row leaves the PSD container and merged image
+ /// readable, while normal import reports a warning and interactive open reports damage.
+ #[test]
+ 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");
+ 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 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 (opened, damaged) = import_for_open("corrupt-green-rle.psd", &bytes, photocraft_doc::MAX_GROUP_DEPTH).unwrap();
++ let (opened, damaged) = import_for_open("corrupt-green-rle.psd", &bytes, &ImportOptions::default()).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());
+ }
+
+ /// Verifies a truncated merged preview triggers confirmation without losing intact layers.
+ #[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();
++ let (opened, damaged) = import_for_open("damaged-preview.psd", &bytes, &ImportOptions::default()).unwrap();
+ assert!(damaged);
+ assert_eq!(opened.warnings, imported.warnings);
+ assert!(opened.warnings.iter().any(|w| w.contains("merged image")));
+ }
+
+ /// Verifies mismatched resolution metadata produces a warning but no damage prompt.
+ #[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();
++ let (opened, damaged) = import_for_open("resolution.psd", &file.to_bytes().unwrap(), &ImportOptions::default()).unwrap();
+ assert!(!damaged);
+ assert!(opened.warnings.iter().any(|w| w.contains("vertical resolution")));
+ }
+
+ /// Verifies a structurally unparseable PSD still fails instead of offering recovery.
+ #[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());
++ assert!(import_for_open("truncated.psd", bytes, &ImportOptions::default()).is_err());
+ }
+
+ /// 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 --cc crates/ui-egui/src/dialogs.rs
index acf77870e,e6ef3ef68..ca83d115e
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -502,9 -420,11 +503,11 @@@ pub fn show(app: &mut PhotocraftApp, ct
} 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) {
+ } else if crate::disk_change_prompt::owns(&d.fields) || crate::replace_prompt::owns(&d.fields) {
tl!("Replace")
} else if d.fields.contains_key("__export") {
tl!("Export")
@@@ -792,13 -709,11 +796,15 @@@ pub fn cancel(app: &mut PhotocraftApp,
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)?;
}
+ // Cancel on the question whether to replace a file writes nothing.
+ if crate::replace_prompt::owns(&closed.fields) {
+ crate::replace_prompt::cancel(app)?;
+ }
app.ui.dialogs.retain(|d| !crate::layer_style::color_picker::child_of(&d.fields, id));
app.filter_preview = None;
app.color_range = None;
diff --cc crates/ui-egui/src/i18n/tr.tsv
index 94e0ed0f5,c365bb4f2..a0c0e4677
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@@ -2151,9 -2144,13 +2151,13 @@@
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Seçim yapılabilecek yol yok: Kalem aracıyla bir yol çizin veya Yollar panelinden birini seçin.
Cancel opening Açılışı iptal et
Cancelled opening {name} {name} açılışı iptal edildi
+ Damaged Photoshop document Hasarlı Photoshop belgesi
+ The document “{name}” may be damaged. “{name}” belgesi hasarlı olabilir.
+ Some layers, pixels or masks could not be read. Do you want to continue opening it? Bazı katmanlar, pikseller veya maskeler okunamadı. Açmaya devam etmek istiyor musunuz?
+ If you continue, saving over the original may permanently discard unreadable data. Save a copy to keep the original. Devam ederseniz, orijinalin üzerine kaydetmek okunamayan verileri kalıcı olarak silebilir. Orijinali korumak için bir kopya kaydedin.
The document “{name}” does not have an embedded {mode} profile. '{name}' belgesinde gömülü bir {mode} profili yok.
- The document “{name}” has an embedded color profile that does not match the current {mode} working space. '{name}' belgesinin gömülü renk profili geçerli {mode} çalışma alanıyla eşleşmiyor.
- Working: {working} Çalışma alanı: {working}
+ The document “{name}” has an embedded color profile that does not match the current {mode} working space. “{name}” belgesinin gömülü renk profili geçerli {mode} çalışma renk uzayıyla eşleşmiyor.
+ Working: {working} Çalışma renk uzayı: {working}
Developing {name} {name} geliştiriliyor
Cancelled {label} {label} iptal edildi
Esc to cancel İptal etmek için Esc
diff --cc crates/ui-egui/src/jobs_ui.rs
index 259eca761,bd7c16ace..980aff20e
--- a/crates/ui-egui/src/jobs_ui.rs
+++ b/crates/ui-egui/src/jobs_ui.rs
@@@ -563,14 -564,11 +564,14 @@@ fn finish_open(app: &mut PhotocraftApp
// 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;
- // An earlier file is waiting on its prompt: this one opens after it, in order.
+ // poll_jobs applies all ready jobs before the shell handles their events. An earlier
+ // handler may have moved or closed tabs, so the apply-time index is no longer authority.
+ let document = v.get("docId").and_then(Value::as_u64).map(DocId).ok_or("the open job returned no document identity")?;
+ let index = app.session.documents().iter().position(|st| st.doc.id == document).ok_or("the open job's document is missing")?;
+ // An earlier file is waiting on its prompt: this document waits after it, in order.
if crate::open_prompt::waiting(app)
&& let Some(st) = app.session.close(index)
{
diff --cc crates/ui-egui/src/lib.rs
index 409e4f79d,531ca4263..a36ea18d2
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -1604,10 -1520,16 +1604,18 @@@ impl PhotocraftApp
return Ok(Vec::new());
}
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, damaged) = if photocraft_io::is_psd(bytes) {
+ let opts = photocraft_engine::jobs::import_options(self.session.prefs());
- let (mut doc, warnings) = import(name, bytes, &opts)?;
++ let (mut 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())?;
++ let (r, damaged) = photocraft_io::import_for_open(name, bytes, &opts).map_err(|e| e.to_string())?;
+ (r.document, r.warnings, damaged)
+ } else {
- let (doc, warnings) = import(name, bytes, max_svg_group_depth)?;
++ let (doc, warnings) = import(name, bytes, &opts)?;
+ (doc, warnings, false)
+ };
+ // Preferences › Raw Defaults › Resolution, as the engine's open applies it.
+ photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc);
// 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).
diff --cc crates/ui-egui/src/psd_open_tests.rs
index 000000000,da188be36..1c40f898b
mode 000000,100644..100644
--- a/crates/ui-egui/src/psd_open_tests.rs
+++ b/crates/ui-egui/src/psd_open_tests.rs
@@@ -1,0 -1,199 +1,199 @@@
+ //! 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};
+
+ /// Creates a minimal UI application with in-memory import/export services for PSD tests.
+ 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())
++ import: Some(Box::new(|name, bytes, opts| {
++ photocraft_io::import_with_options(name, bytes, opts).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
+ }
+
+ /// Runs an agent-facing control command synchronously and returns its JSON result.
+ 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"),
+ }
+ }
+
+ /// Inspects the active damage prompt and returns its agent-visible dialog ID.
+ 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()
+ }
+
+ /// Verifies valid layered PSD files open immediately without a confirmation dialog.
+ #[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);
+ }
+
+ /// Verifies agents can cancel or confirm a damaged PSD using standard dialog commands.
+ #[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());
+ }
+
+ /// Verifies consent retains the original save path and restores ordinary Save behavior.
+ #[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());
+ }
+
+ /// Verifies browser-style downloads keep their existing unconfirmed-save semantics.
+ #[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");
+ }
+
+ /// Verifies non-interactive automation imports recover readable content without a dialog.
+ #[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")));
+ }
+
+ /// Verifies queued damaged PSD files each require independent user confirmation.
+ #[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");
+ }
+
+ /// Verifies the damage prompt cannot be bypassed with a color-profile answer and
+ /// that the profile question is still shown after accepting the damage.
+ #[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);
+ }
+
+ /// Verifies background decoding shows only the damage prompt when no profile question exists.
+ #[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");
+ }