PhotoCraft: An open-source, photo editor written by scratch in pure Rust
docs: add missing Rustdoc comments for PSD recovery
David Bonnier8b2c722dc879
diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rsindex 02f3c2c26..a731cfd59 100644--- a/crates/engine/src/jobs.rs+++ b/crates/engine/src/jobs.rs@@ -517,6 +517,8 @@ impl Session {self.start_open_inner(name, source, true)}+ /// Decodes a file in a job and optionally holds damaged PSD content for+ /// interactive confirmation while leaving headless opens non-interactive.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();@@ -1025,6 +1027,7 @@ mod psd_open_fixture;mod psd_open_confirmation_tests {use super::*;+ /// Collects either an inline open result or the completed background-job result.fn result(s: &mut Session, started: Started) -> Value {match started {Started::Done(v) => v,@@ -1032,6 +1035,7 @@ mod psd_open_confirmation_tests {}}+ /// Verifies headless opens return readable PSD content and warnings without a held prompt.#[test]fn headless_open_keeps_best_effort_psd_import() {let mut s = Session::new();@@ -1043,6 +1047,7 @@ mod psd_open_confirmation_tests {assert!(v["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("could not be decoded")));}+ /// Verifies interactive opens hold damaged PSD files but admit valid files immediately.#[test]fn interactive_open_holds_only_a_damaged_psd() {for corrupt in [false, true] {diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex 37227fff8..22dabaf6a 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -327,6 +327,8 @@ pub fn import_for_open_with(name: &str, bytes: &[u8], max_group_depth: usize, ctOk((result, damaged))}+/// 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> {// 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) {@@ -607,6 +609,7 @@ mod tests {use super::{import, import_for_open, 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();@@ -614,6 +617,8 @@ mod tests {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);@@ -631,6 +636,7 @@ mod tests {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();diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex 6e8bebe67..0d1e7a6c5 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -134,6 +134,8 @@ impl Ctx<'_> {self.warnings.push(s.into());}+ /// Records a PSD decoding failure and marks the import as potentially incomplete.+ /// Unlike compatibility warnings, this requires interactive confirmation.fn warn_unreadable_data(&mut self, s: impl Into<String>) {self.damaged = true;self.warn(s);@@ -169,6 +171,7 @@ impl Ctx<'_> {Placement { id, transform, perspective, warp }}+ /// Decodes a PSD layer channel, marking the document damaged if its data is unreadable.fn channel_plane(&mut self, rec: &LayerRecord, id: i16, name: &str) -> Option<Vec<u8>> {rec.channel(id)?;match rec.decode_channel(id, self.file.header.depth, self.file.header.version) {@@ -187,6 +190,8 @@ impl Ctx<'_> {rec.decode_channel(id, self.file.header.depth, self.file.header.version).ok()}+ /// Builds a raster surface from the layer channels, leaving the surface empty if+ /// any present channel fails to decode rather than inventing replacement pixels.fn record_surface(&mut self, rec: &LayerRecord, name: &str) -> Surface {let r = rec.rect;if r.is_empty() || r.size().is_err() {@@ -238,6 +243,8 @@ impl Ctx<'_> {surf}+ /// Restores the selected user mask from its channel and metadata, recording an+ /// integrity failure if the mask channel cannot be decoded.fn record_mask(&mut self, rec: &LayerRecord, name: &str) -> Option<LayerMask> {let m = rec.layer_mask()?;let (id, rect, default, flags) = match selected_real_mask(rec) {@@ -798,6 +805,7 @@ fn mark_background(file: &PsdFile, layers: &mut [Layer]) {}}+/// Converts a parsed PSD into a document, preserving best-effort recovery warnings.pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {// Never cancelled, so always `Some`; the fallback is unreachable.psd_to_document_with(file, &photocraft_raster::Interrupt::NONE)@@ -1208,6 +1216,7 @@ mod tests {assert_eq!(unicode_names(&data), ["A"]);}+ /// Verifies an unreadable layer channel sets the structured damage indicator.#[test]fn unreadable_layer_channel_marks_conversion_damaged() {let mut file = testgen::small(Version::Psd, Compression::Raw);@@ -1220,6 +1229,7 @@ mod tests {assert!(warnings.iter().any(|w| w.contains("could not be decoded")));}+ /// Verifies an unreadable user-mask channel sets the structured damage indicator.#[test]fn unreadable_mask_channel_marks_conversion_damaged() {let mut file = testgen::small(Version::Psd, Compression::Raw);@@ -1231,6 +1241,7 @@ mod tests {assert!(warnings.iter().any(|w| w.contains("could not be decoded")));}+ /// Verifies healthy layer channels do not mark the PSD as damaged.#[test]fn valid_layer_channels_keep_conversion_editable() {let file = testgen::small(Version::Psd, Compression::Raw);diff --git a/crates/io/tests/psd_recovery_generated.rs b/crates/io/tests/psd_recovery_generated.rsindex 13479a843..72aae0ab8 100644--- a/crates/io/tests/psd_recovery_generated.rs+++ b/crates/io/tests/psd_recovery_generated.rs@@ -10,6 +10,7 @@ mod recovery_psd;use photocraft_io::{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);@@ -22,6 +23,8 @@ fn valid_generated_psd_opens_normally() {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);@@ -47,6 +50,7 @@ fn corrupt_generated_rle_channel_keeps_best_effort_import_and_reports_damage() {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();@@ -61,6 +65,7 @@ fn damaged_composite_keeps_layers_and_requests_interactive_confirmation() {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};@@ -72,6 +77,7 @@ fn ordinary_compatibility_warning_does_not_mean_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";diff --git a/crates/io/tests/support/recovery_psd.rs b/crates/io/tests/support/recovery_psd.rsindex 7febfd94b..4d26bec64 100644--- a/crates/io/tests/support/recovery_psd.rs+++ b/crates/io/tests/support/recovery_psd.rs@@ -20,10 +20,12 @@ struct Layer {pixels: Vec<u8>,}+/// Writes the big-endian 32-bit length of a PSD section to the output buffer.fn put_len(out: &mut Vec<u8>, len: usize) {out.extend_from_slice(&u32::try_from(len).expect("test PSD section fits u32").to_be_bytes());}+/// Builds the three RGB planes of the deterministic blue checkerboard background.fn background_rgb() -> [Vec<u8>; 3] {let mut planes: [Vec<u8>; 3] = std::array::from_fn(|_| Vec::with_capacity(WIDTH * HEIGHT));for y in 0..HEIGHT {@@ -37,6 +39,7 @@ fn background_rgb() -> [Vec<u8>; 3] {planes}+/// Encodes a layer channel without compression, including its PSD compression marker.fn raw_channel(id: i16, pixels: &[u8]) -> Channel {let mut data = Vec::with_capacity(2 + pixels.len());data.extend_from_slice(&0u16.to_be_bytes()); // 0 = uncompressed@@ -44,6 +47,8 @@ fn raw_channel(id: i16, pixels: &[u8]) -> Channel {Channel { id, data }}+/// Encodes constant-color PackBits rows, optionally truncating the middle row.+/// The corrupt variant keeps the row-length table structurally valid.fn rle_channel(id: i16, sample: u8, width: usize, height: usize, corrupt: bool) -> Channel {let mut rows: Vec<Vec<u8>> = Vec::with_capacity(height);for y in 0..height {@@ -75,6 +80,7 @@ fn rle_channel(id: i16, sample: u8, width: usize, height: usize, corrupt: bool)Channel { id, data }}+/// Serializes a PSD layer record and its channel payloads separately, in file order.fn layer(name: &str, rect: (i32, i32, i32, i32), channels: Vec<Channel>) -> Layer {let (left, top, right, bottom) = rect;let name_bytes = name.as_bytes();@@ -110,6 +116,8 @@ fn layer(name: &str, rect: (i32, i32, i32, i32), channels: Vec<Channel>) -> LayeLayer { record, pixels }}+/// Composites the orange rectangle over the checkerboard as an uncompressed+/// merged RGB image, independent of the deliberately damaged layer channel.fn merged_rgb(background: &[Vec<u8>; 3]) -> Vec<u8> {let mut planes = background.clone();for y in PANEL.1..PANEL.3 {diff --git a/crates/ui-egui/src/open_prompt.rs b/crates/ui-egui/src/open_prompt.rsindex 39f4dee8a..ce5364ec5 100644--- a/crates/ui-egui/src/open_prompt.rs+++ b/crates/ui-egui/src/open_prompt.rs@@ -180,6 +180,8 @@ pub(crate) fn owns_damage(fields: &serde_json::Map<String, Value>) -> bool {fields.contains_key(DAMAGE_FIELD)}+/// Shows the standard agent-visible confirmation for the first damaged PSD+/// waiting in the open queue, including its decoding warnings.fn show_damage(app: &mut PhotocraftApp) {let Some(front) = app.held_opens.front().filter(|h| h.damage_pending) else { return };let message = format!(diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rsindex 4a5149de4..da188be36 100644--- a/crates/ui-egui/src/psd_open_tests.rs+++ b/crates/ui-egui/src/psd_open_tests.rs@@ -10,6 +10,7 @@ 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(),@@ -29,6 +30,7 @@ fn app() -> PhotocraftApp {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) {@@ -37,6 +39,7 @@ fn call(app: &mut PhotocraftApp, method: &str, params: Value) -> Value {}}+/// 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);@@ -47,6 +50,7 @@ fn damage_dialog(app: &mut PhotocraftApp) -> u64 {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();@@ -56,6 +60,7 @@ fn healthy_psd_opens_without_a_damage_prompt() {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();@@ -75,6 +80,7 @@ fn damaged_psd_can_be_cancelled_or_accepted_through_agent_dialog_commands() {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();@@ -105,6 +111,7 @@ fn accepted_psd_keeps_its_source_path_and_uses_the_normal_save_writer() {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();@@ -118,6 +125,7 @@ fn accepted_psd_uses_web_download_semantics_without_a_special_writer() {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();@@ -128,6 +136,7 @@ fn damaged_psd_automation_import_does_not_require_interactive_confirmation() {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();@@ -146,6 +155,8 @@ fn cancelling_one_damaged_open_does_not_open_the_next_damaged_file_without_conseassert_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();@@ -167,6 +178,7 @@ fn damage_confirmation_precedes_the_profile_question() {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() {