PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Add native layered Paint.NET (.pdn) import (#1998)
SilentYetidb0fb0786282
diff --git a/README.md b/README.mdindex 7c42d8bc7..eba47a916 100644--- a/README.md+++ b/README.md@@ -187,7 +187,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off</td><td width="33%" valign="top"><h4>🗃️ Layers, done properly</h4>- Groups, clipping masks, pixel and vector masks, fill layers (solid, gradient and pattern), adjustment layers, live smart objects with smart filters and lossless transforms and warps, multi-layer selection with align, distribute and link, alpha channels and Quick Mask, 27 blend modes, opacity and fill, locks, colour labels, layer filters, merge, flatten, rasterize, Layer via Copy/Cut, Paste Into.+ Groups, clipping masks, pixel and vector masks, fill layers (solid, gradient and pattern), adjustment layers, live smart objects with smart filters and lossless transforms and warps, multi-layer selection with align, distribute and link, alpha channels and Quick Mask, 27 Photoshop blend modes plus six Paint.NET variants, opacity and fill, locks, colour labels, layer filters, merge, flatten, rasterize, Layer via Copy/Cut, Paste Into.</td></tr><tr>@@ -199,7 +199,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off</td><td width="33%" valign="top"><h4>🗂️ Formats</h4>- PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR and Radiance HDR, and the native <code>.pcraft</code> format. Flat formats retain the depths they support: PNG keeps 8/16-bit samples, TIFF keeps 8/16-bit and 32-bit float samples, and OpenEXR keeps half/float samples; JPEG, WebP and the other 8-bit formats reduce higher-depth samples with an export warning. See the <a href="crates/codecs/README.md#capability-matrix-default-build">codec capability matrix</a> for each format. HEIC photos from iPhone and Mac are read-only (included in official builds; optional <code>--features heif</code> for source builds). AVIF is write-only with the optional <code>avif</code> build feature; AVIF decoding and JPEG XL are unavailable. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.+ PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), <a href="docs/pdn.md">Paint.NET PDN3 (read, with editable layers and all 14 blend modes)</a>, SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR and Radiance HDR, and the native <code>.pcraft</code> format. Flat formats retain the depths they support: PNG keeps 8/16-bit samples, TIFF keeps 8/16-bit and 32-bit float samples, and OpenEXR keeps half/float samples; JPEG, WebP and the other 8-bit formats reduce higher-depth samples with an export warning. See the <a href="crates/codecs/README.md#capability-matrix-default-build">codec capability matrix</a> for each format. HEIC photos from iPhone and Mac are read-only (included in official builds; optional <code>--features heif</code> for source builds). AVIF is write-only with the optional <code>avif</code> build feature; AVIF decoding and JPEG XL are unavailable. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.</td><td width="33%" valign="top"><h4>🪄 The everyday essentials</h4>diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rsindex fcccb2b38..202458469 100644--- a/apps/photocraft-cli/src/lib.rs+++ b/apps/photocraft-cli/src/lib.rs@@ -341,7 +341,7 @@ fn same_dir(a: &Path, b: &Path) -> bool {fn is_input(p: &Path) -> bool {let known = |e: &str| {- matches!(e, "pcraft" | "psd" | "psb" | "af" | "afdesign" | "afphoto" | "afpub")+ matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "af" | "afdesign" | "afphoto" | "afpub")|| photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read)};p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rsindex 83fa57e66..fa7872242 100644--- a/apps/photocraft-web/src/web.rs+++ b/apps/photocraft-web/src/web.rs@@ -17,8 +17,8 @@ type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.const OPEN_EXTS: &[&str] = &[- "pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",- "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",+ "pcraft", "pdn", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm",+ "pam", "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af","afdesign", "afphoto", "afpub",];const CANVAS_ID: &str = "photocraft_canvas";diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rsindex 3c85eebb8..af599fa2a 100644--- a/apps/photocraft/src/services.rs+++ b/apps/photocraft/src/services.rs@@ -19,8 +19,8 @@ mod recovery_tests;/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.const OPEN_EXTS: &[&str] = &[- "pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",- "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",+ "pcraft", "pdn", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm",+ "pam", "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af","afdesign", "afphoto", "afpub",];@@ -87,7 +87,10 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>,let dialog = if let Some(exts) = extensions {dialog.add_filter("Supported Files", &open_filter_extensions(&exts.iter().map(String::as_str).collect::<Vec<_>>()))} else {- dialog.add_filter("All Formats", &open_filter_extensions(OPEN_EXTS)).add_filter("PhotoCraft", &open_filter_extensions(&["pcraft"]))+ dialog+ .add_filter("All Formats", &open_filter_extensions(OPEN_EXTS))+ .add_filter("PhotoCraft", &open_filter_extensions(&["pcraft"]))+ .add_filter("Paint.NET", &open_filter_extensions(&["pdn"]))};if multiple {let picked = dialog.pick_files();diff --git a/contributors/people.toml b/contributors/people.tomlindex 6fa921c60..140a9acb6 100644--- a/contributors/people.toml+++ b/contributors/people.toml@@ -48,6 +48,9 @@ real_name = "Willy Foo"display_name = "Willy Foo"sync_github_name = false+[people.SilentYeti]+sync_github_name = true+[people.Elvis33LE]sync_github_name = truediff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rsindex 02fdadef1..05ab00f16 100644--- a/crates/color/src/blend.rs+++ b/crates/color/src/blend.rs@@ -1,4 +1,4 @@-//! Photoshop blend modes (scalar reference implementation).+//! Photoshop and Paint.NET blend modes (scalar reference implementation).//!//! Formulas follow the public PDF / ISO 32000-2 and W3C Compositing definitions,//! with Photoshop's variants where they differ (Soft Light, Hard Mix, Darker/Lighter Color,@@ -38,10 +38,27 @@ pub enum BlendMode {Saturation,Color,Luminosity,+ Reflect,+ Glow,+ Negation,+ Xor,+ PaintNetColorBurn,+ PaintNetColorDodge,}impl BlendMode {- /// All modes except PassThrough, in Photoshop menu order.+ /// Paint.NET modes without an exact Photoshop equivalent.+ pub const PAINT_NET_MODES: [BlendMode; 6] = [Self::Reflect, Self::Glow, Self::Negation, Self::Xor, Self::PaintNetColorBurn, Self::PaintNetColorDodge];++ /// All editable layer modes, with Paint.NET modes after Photoshop's menu order.+ pub fn layer_modes() -> impl Iterator<Item = Self> {+ Self::LAYER_MODES.into_iter().chain(Self::PAINT_NET_MODES)+ }++ pub fn has_psd_equivalent(self) -> bool {+ !Self::PAINT_NET_MODES.contains(&self)+ }+ /// Photoshop modes except PassThrough, in Photoshop menu order.pub const LAYER_MODES: [BlendMode; 27] = [BlendMode::Normal,BlendMode::Dissolve,@@ -102,10 +119,17 @@ impl BlendMode {BlendMode::Saturation => "Saturation",BlendMode::Color => "Color",BlendMode::Luminosity => "Luminosity",+ BlendMode::Reflect => "Reflect",+ BlendMode::Glow => "Glow",+ BlendMode::Negation => "Negation",+ BlendMode::Xor => "XOR",+ BlendMode::PaintNetColorBurn => "Color Burn (Paint.NET)",+ BlendMode::PaintNetColorDodge => "Color Dodge (Paint.NET)",}}- /// PSD 4-character blend key.+ /// PSD 4-character blend key. Modes without an equivalent fall back to Normal;+ /// exporters must report that loss using [`Self::has_psd_equivalent`].pub fn psd_key(self) -> [u8; 4] {*match self {BlendMode::PassThrough => b"pass",@@ -136,6 +160,9 @@ impl BlendMode {BlendMode::Saturation => b"sat ",BlendMode::Color => b"colr",BlendMode::Luminosity => b"lum ",+ BlendMode::Reflect | BlendMode::Glow | BlendMode::Negation | BlendMode::Xor | BlendMode::PaintNetColorBurn | BlendMode::PaintNetColorDodge => {+ b"norm"+ }}}@@ -212,11 +239,38 @@ fn channel(mode: BlendMode, cb: f32, cs: f32, hi: f32) -> f32 {(cb / cs).min(hi)}}+ BlendMode::Reflect => reflect(cb, cs),+ BlendMode::Glow => reflect(cs, cb),+ BlendMode::Negation => 1.0 - (1.0 - cb - cs).abs(),+ BlendMode::Xor => {+ // Paint.NET's XOR is defined on 8-bit channels even in a floating-point compositor.+ let b = (cb.clamp(0.0, 1.0) * 255.0).round() as u8;+ let s = (cs.clamp(0.0, 1.0) * 255.0).round() as u8;+ f32::from(b ^ s) / 255.0+ }+ BlendMode::PaintNetColorBurn => {+ if cs <= 0.0 {+ 0.0+ } else {+ (1.0 - (1.0 - cb) / cs).max(0.0)+ }+ }+ BlendMode::PaintNetColorDodge => {+ if cs >= 1.0 {+ 1.0+ } else {+ (cb / (1.0 - cs)).min(1.0)+ }+ }// Non-separable modes are handled by `blend_rgb`; fall back to source.BlendMode::DarkerColor | BlendMode::LighterColor | BlendMode::Hue | BlendMode::Saturation | BlendMode::Color | BlendMode::Luminosity => cs,}}+fn reflect(cb: f32, cs: f32) -> f32 {+ if cs >= 1.0 { 1.0 } else { (cb * cb / (1.0 - cs)).min(1.0) }+}+#[inline]fn vivid_light_hard_mix(cb: f32, cs: f32) -> f32 {const EDGE: f32 = 1e-4;@@ -405,6 +459,34 @@ mod tests {assert_eq!(seen.len(), 28);}+ #[test]+ fn paint_net_modes_keep_their_math_and_distinct_psd_status() {+ assert!(close(blend_channel(BlendMode::Reflect, 0.5, 0.5), 0.5));+ assert!(close(blend_channel(BlendMode::Reflect, 0.2, 0.0), 0.04));+ assert!(close(blend_channel(BlendMode::Glow, 0.5, 0.2), 0.08));+ assert!(close(blend_channel(BlendMode::Negation, 0.2, 0.7), 0.9));+ assert_eq!(blend_channel(BlendMode::Reflect, 0.0, 1.0), 1.0);+ assert_eq!(blend_channel(BlendMode::Glow, 1.0, 0.0), 1.0);+ assert_eq!(blend_channel(BlendMode::PaintNetColorBurn, 1.0, 0.0), 0.0);+ assert_eq!(blend_channel(BlendMode::PaintNetColorDodge, 0.0, 1.0), 1.0);+ for b in 0..=255u8 {+ for s in 0..=255u8 {+ assert!(close(blend_channel(BlendMode::Xor, f32::from(b) / 255.0, f32::from(s) / 255.0), f32::from(b ^ s) / 255.0));+ }+ }+ for mode in BlendMode::PAINT_NET_MODES {+ assert!(!mode.has_psd_equivalent());+ assert_eq!(mode.psd_key(), *b"norm");+ for b in [0.0, 0.1, 0.5, 1.0] {+ for s in [0.0, 0.1, 0.5, 1.0] {+ let v = blend_channel(mode, b, s);+ assert!(v.is_finite() && (0.0..=1.0).contains(&v), "{mode:?}");+ }+ }+ }+ assert_eq!(BlendMode::layer_modes().count(), 33);+ }+#[test]fn normal_is_source() {for &(cb, cs) in &[(0.2, 0.7), (1.0, 0.0), (0.0, 1.0)] {diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 69930266c..d82eb8ef4 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -235,7 +235,7 @@ pub(crate) fn layer_param(s: &Session, p: &Value) -> Result<LayerId> {pub fn blend_from_str(s: &str) -> Option<BlendMode> {let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "");let want = norm(s);- std::iter::once(BlendMode::PassThrough).chain(BlendMode::LAYER_MODES).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want)+ std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want)}/// The active selection as the mask of a layer being created, or None without a selection.diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex 657eb02e4..3883e2510 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -116,8 +116,8 @@ pub(crate) fn list_images(dir: &str) -> Result<Vec<String>> {/// Extensions the batch commands pick up from a folder.const OPENABLE: &[&str] = &[- "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", "pnm", "ppm", "pgm", "heic", "heif",- "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", "afphoto", "afpub",+ "pdn", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", "pnm", "ppm", "pgm", "heic",+ "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", "afphoto", "afpub",];/// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lonediff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rsindex 47a0749b2..ad776e7df 100644--- a/crates/engine/src/file_cmds/tests.rs+++ b/crates/engine/src/file_cmds/tests.rs@@ -480,7 +480,7 @@ fn only_layered_files_save_in_place() {assert!(saves_in_place(path), "{path}");}// Flat formats, no extension, a dotted folder with an extensionless file, a dot file.- for path in ["a.png", "a.jpg", "a", "my.psd/a", ".psd", "a.", ""] {+ for path in ["a.png", "a.jpg", "a.pdn", "a.PDN", "a", "my.psd/a", ".psd", "a.", ""] {assert!(!saves_in_place(path), "{path}");}assert_eq!(extension("dir/Photo.JPEG").as_deref(), Some("jpeg"));diff --git a/crates/engine/tests/pdn.rs b/crates/engine/tests/pdn.rsnew file mode 100644index 000000000..75c3f18c5--- /dev/null+++ b/crates/engine/tests/pdn.rs@@ -0,0 +1,43 @@+//! Actual imported PDN layers exercise the same commands/history as other pixel layers.+use photocraft_engine::Session;+use serde_json::json;++#[test]+#[ignore = "requires PDN_TEST_FILE pointing to a real Paint.NET document"]+fn imported_layers_remain_editable_with_history_and_native_persistence() {+ let path = std::env::var("PDN_TEST_FILE").expect("set PDN_TEST_FILE");+ let mut session = Session::new();+ photocraft_engine::file_cmds::open_bytes_as(&mut session, &path, &std::fs::read(&path).unwrap(), None, Some(path.clone())).unwrap();+ assert!(session.active().unwrap().source_read_only);+ assert!(session.active().unwrap().path.is_none());+ assert!(session.execute("file.save", json!({})).is_err());+ let before = session.active().unwrap().doc.clone();+ let id = before.layers[0].id;+ session.execute("layer.setProps", json!({"layer":id.0,"name":"Edited PDN layer","visible":true,"opacity":0.4,"blend":"Reflect"})).unwrap();+ let edited = session.active().unwrap().doc.layer(id).unwrap();+ assert_eq!(edited.name, "Edited PDN layer");+ assert_eq!(edited.blend, photocraft_color::BlendMode::Reflect);+ assert_eq!(edited.opacity, 0.4);+ assert!(session.undo());+ assert_eq!(session.active().unwrap().doc.layers, before.layers);+ assert!(session.redo());+ let copy = session.execute("layer.duplicate", json!({"layer":id.0})).unwrap()["layer"].as_u64().unwrap();+ session.execute("layer.translate", json!({"layer":copy,"dx":1,"dy":1})).unwrap();+ session.execute("layer.moveTo", json!({"layer":copy,"target":id.0,"position":"below"})).unwrap();+ session.execute("layer.select", json!({"layer":copy})).unwrap();+ let pixels_before = session.active().unwrap().doc.layer(photocraft_doc::LayerId(copy)).unwrap().surface().unwrap().clone();+ session.execute("paint.stroke", json!({"points":[[2,2],[10,10]],"size":4,"hardness":1.0,"color":"#ff0000"})).unwrap();+ assert_ne!(session.active().unwrap().doc.layer(photocraft_doc::LayerId(copy)).unwrap().surface().unwrap(), &pixels_before);+ assert_eq!(session.active().unwrap().doc.layer(id).unwrap().surface(), before.layer(id).unwrap().surface());+ assert!(session.undo());+ assert_eq!(session.active().unwrap().doc.layer(photocraft_doc::LayerId(copy)).unwrap().surface().unwrap(), &pixels_before);+ assert!(session.redo());+ session.execute("layer.layerMask.revealAll", json!({"layer":copy})).unwrap();+ assert!(session.active().unwrap().doc.layer(photocraft_doc::LayerId(copy)).unwrap().mask.is_some());+ session.execute("layer.delete", json!({"layer":copy})).unwrap();+ assert!(session.undo());+ let doc = &session.active().unwrap().doc;+ let native = photocraft_io::export(doc, "edited.pcraft", &Default::default()).unwrap();+ let reopened = photocraft_io::import("edited.pcraft", &native.bytes).unwrap().document;+ assert_eq!(doc.layers, reopened.layers);+}diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgslindex 91b36920f..c06b4a865 100644--- a/crates/gpu/src/compose.wgsl+++ b/crates/gpu/src/compose.wgsl@@ -188,6 +188,28 @@ fn blend_channel(mode: i32, cb: f32, cs: f32) -> f32 {if (cs <= 0.0) { return select(1.0, 0.0, cb <= 0.0); }return min(cb / cs, hi);}+ case 28: { // Reflect+ if (cs >= 1.0) { return 1.0; }+ return min(cb * cb / (1.0 - cs), 1.0);+ }+ case 29: { // Glow+ if (cb >= 1.0) { return 1.0; }+ return min(cs * cs / (1.0 - cb), 1.0);+ }+ case 30: { return 1.0 - abs(1.0 - cb - cs); } // Negation+ case 31: { // XOR (8-bit channel operation)+ let b = u32(floor(clamp(cb, 0.0, 1.0) * 255.0 + 0.5));+ let s = u32(floor(clamp(cs, 0.0, 1.0) * 255.0 + 0.5));+ return f32(b ^ s) / 255.0;+ }+ case 32: { // Paint.NET Color Burn+ if (cs <= 0.0) { return 0.0; }+ return max(1.0 - (1.0 - cb) / cs, 0.0);+ }+ case 33: { // Paint.NET Color Dodge+ if (cs >= 1.0) { return 1.0; }+ return min(cb / (1.0 - cs), 1.0);+ }default: { return cs; } // Normal, Dissolve, PassThrough}}diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rsindex e42b7dd89..340a77f1a 100644--- a/crates/gpu/src/plan.rs+++ b/crates/gpu/src/plan.rs@@ -1666,6 +1666,12 @@ pub fn mode_index(m: BlendMode) -> i32 {BlendMode::Saturation => 25,BlendMode::Color => 26,BlendMode::Luminosity => 27,+ BlendMode::Reflect => 28,+ BlendMode::Glow => 29,+ BlendMode::Negation => 30,+ BlendMode::Xor => 31,+ BlendMode::PaintNetColorBurn => 32,+ BlendMode::PaintNetColorDodge => 33,}}diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rsindex aab24bef5..342e901b7 100644--- a/crates/gpu/tests/parity.rs+++ b/crates/gpu/tests/parity.rs@@ -156,7 +156,7 @@ fn first_frame_renders() {#[test]fn blend_modes() {let Some(mut g) = gpu() else { return };- for mode in BlendMode::LAYER_MODES {+ for mode in BlendMode::layer_modes() {let mut d = base_doc(64, 48);let mut l = noise_layer("top", PixelFormat::RGBA8, Rect::new(4, 3, 60, 45), 2, 0.0);l.blend = mode;@@ -170,6 +170,25 @@ fn blend_modes() {}}+#[test]+fn xor_rounding_on_half_float_targets() {+ let Some((_adapter, device, queue, _lock)) = any_device() else { return };+ let Ok(mut comp) = Compositor::try_new_with_format(&device, wgpu::TextureFormat::Rgba16Float) else { return };+ let mut doc = Document::new("XOR rounding", Size::new(2, 2), ColorMode::Rgb, SampleType::U8);+ for (value, opacity, blend) in [(127, 1.0, BlendMode::Normal), (128, 127.0 / 255.0, BlendMode::Normal), (64, 1.0, BlendMode::Xor)] {+ let mut layer = Layer::raster("pixel", PixelFormat::RGBA8);+ let channel = value as f32 / 255.0;+ layer.surface_mut().unwrap().fill_rect(doc.bounds(), &[channel, channel, channel, 1.0]);+ layer.opacity = opacity;+ layer.blend = blend;+ doc.layers.push(layer);+ }+ let cpu = photocraft_compose::flatten(&doc);+ assert!((cpu.px[0][0] - 63.0 / 255.0).abs() < 1e-6);+ let gpu = render_to_vec(&mut comp, &device, &queue, &doc, doc.bounds()).unwrap();+ assert!(worst_diff(&cpu.px, &gpu).0 <= TOL, "CPU {:?}, GPU {:?}", cpu.px[0], gpu[0]);+}+fn hue_ranges() -> [HueRange; 6] {let mut r = HueRange::defaults();r[0] = HueRange { hue: 20.0, saturation: -50.0, lightness: 10.0, ..HueRange::neutral(0) };@@ -648,7 +667,7 @@ fn small_layers_composite_over_their_bounds() {l};let mut d = base_doc(200, 150);- for (i, mode) in BlendMode::LAYER_MODES.into_iter().enumerate() {+ for (i, mode) in BlendMode::layer_modes().enumerate() {let i = i as i32;d.layers.push(small(100 + i as u32, (i * 29) % 190 - 8, (i * 37) % 140 - 5, mode));}@@ -682,7 +701,7 @@ fn small_layers_composite_over_their_bounds() {check(&mut g, &d, "small layers");// The same over several compositor chunks.let mut big = base_doc(1500, 1200);- for (i, mode) in BlendMode::LAYER_MODES.into_iter().enumerate() {+ for (i, mode) in BlendMode::layer_modes().enumerate() {let i = i as i32;big.layers.push(small(400 + i as u32, 1010 + (i % 4) * 5, 1010 + (i / 4) * 5, mode));}@@ -1385,7 +1404,7 @@ fn blend_mode_extremes() {let Some(mut g) = gpu() else { return };let vals = [0.0f32, 1.0, 0.5];for depth in [SampleType::U8, SampleType::U16] {- for mode in BlendMode::LAYER_MODES {+ for mode in BlendMode::layer_modes() {let mut d = Document::new("x", Size::new(9, 9), ColorMode::Rgb, depth);let fmt = d.pixel_format();let mut bg = Layer::raster("bg", fmt);diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.tomlindex ffe99e4db..60063e72c 100644--- a/crates/io/Cargo.toml+++ b/crates/io/Cargo.toml@@ -34,7 +34,8 @@ photocraft-format = { path = "../format" }thiserror = { workspace = true }serde_json = { workspace = true }blake3 = { version = "1.8", default-features = false, features = ["pure"] }-# svg.rs inflates `.svgz` itself (with a size cap) so the XML can be checked before it is parsed.+# svg.rs inflates `.svgz` itself (with a size cap) so the XML can be checked before it is parsed;+# pdn.rs inflates Paint.NET's gzip pixel chunks.flate2 = { workspace = true }# SVG import (svg.rs): usvg parses, resvg rasterises what the shape model can't hold. Both are# already in the tree through the UI's icon loader; text shaping needs the fonts feature set.diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex b3fbf48c5..7d108c08a 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -15,6 +15,7 @@//! layer; unsupported raw variants fall back to the embedded JPEG preview.//! * Layered TIFFs (Photoshop layer data in tags 37724 and 34377) open with their//! layers through the PSD path and are written back the same way; see `tiff_layers`.+//! * Paint.NET PDN3 documents open as editable bitmap layers (import only).//! * Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`) open natively//! with no source save path, what isn't imported listed in the warnings; a file//! whose native data can't be read opens as its embedded preview; see `affinity`.@@ -40,6 +41,7 @@ mod gradient_bake;pub mod linked;mod multichannel_map;pub mod pattern_map;+mod pdn;pub mod pixels;mod psd_export;mod psd_import;@@ -64,6 +66,9 @@ pub use psd_import::{psd_to_document, psd_to_document_with};/// Errors from import/export.#[derive(Debug, thiserror::Error)]pub enum IoError {+ /// Paint.NET document decode failure.+ #[error("PDN: {0}")]+ Pdn(String),/// PSD parse/write failure.#[error("PSD: {0}")]Psd(#[from] PsdError),@@ -97,7 +102,7 @@ pub struct ImportResult {pub document: Document,/// Human-readable notes about anything approximated or dropped.pub warnings: Vec<String>,- /// Save must not write back to the source (an Affinity document: PhotoCraft can't write it).+ /// Save must not write back to an import-only source, such as Affinity or Paint.NET.pub source_read_only: bool,/// Only a stand-in picture of the file (an Affinity document whose native data couldn't be/// read): Open shows it with its warning; Place and other auxiliary imports refuse it.@@ -201,6 +206,9 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -if affinity::is_affinity(bytes) || affinity::has_extension(name) {return affinity::import(name, bytes);}+ if has_extension(name, "pdn") || bytes.starts_with(b"PDN3") {+ return pdn::import(name, bytes, ctl);+ }if raw::is_raw(bytes) {return raw::import_raw(name, bytes);}@@ -222,6 +230,9 @@ fn has_extension(name: &str, expected: &str) -> bool {/// bare extension).pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result<ExportResult, IoError> {let ext = extension(name_or_ext);+ if ext == "pdn" {+ return Err(IoError::Unsupported("PDN is import-only; save as .pcraft to preserve all layers and blend modes".into()));+ }if affinity::EXTENSIONS.contains(&ext.as_str()) {return Err(IoError::Unsupported("Affinity export is not implemented; save a new PSD, PNG or .pcraft copy".into()));}diff --git a/crates/io/src/pdn.rs b/crates/io/src/pdn.rsnew file mode 100644index 000000000..08e294b7b--- /dev/null+++ b/crates/io/src/pdn.rs@@ -0,0 +1,241 @@+//! Native, import-only PDN3 reader. Layout reference: addisonElliott/pypdn's reader;+//! NRBF records follow Microsoft's public MS-NRBF specification (see `nrbf`).++mod nrbf;+#[cfg(test)]+mod tests;++use std::collections::HashMap;+use std::io::Read;++use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};+use photocraft_doc::{Document, Layer, LayerContent};+use photocraft_geom::{Rect, Size};+use photocraft_raster::{Interrupt, Surface};++use crate::{ImportResult, IoError};+use nrbf::{Graph, Reader, Value};++type Result<T> = std::result::Result<T, IoError>;++// shortcut: imports cap decoded pixels at 1 GiB, use streamed tile decoding for larger PDNs.+const MAX_PIXEL_BYTES: usize = 1 << 30;+const MAX_LAYERS: usize = 1024;+const MODES: [BlendMode; 14] = [+ BlendMode::Normal,+ BlendMode::Multiply,+ BlendMode::LinearDodge,+ BlendMode::PaintNetColorBurn,+ BlendMode::PaintNetColorDodge,+ BlendMode::Reflect,+ BlendMode::Glow,+ BlendMode::Overlay,+ BlendMode::Difference,+ BlendMode::Negation,+ BlendMode::Lighten,+ BlendMode::Darken,+ BlendMode::Screen,+ BlendMode::Xor,+];+const OLD_MODES: [&str; 14] =+ ["Normal", "Multiply", "Additive", "ColorBurn", "ColorDodge", "Reflect", "Glow", "Overlay", "Difference", "Negation", "Lighten", "Darken", "Screen", "Xor"];++fn invalid(message: impl Into<String>) -> IoError {+ IoError::Pdn(message.into())+}++fn count(graph: &Graph, object: &Value, field: &str) -> Result<usize> {+ usize::try_from(graph.integer(graph.field(object, field)?)?).map_err(|_| invalid(format!("invalid {field}")))+}++fn blend(graph: &Graph, layer: &Value, props: &Value) -> Result<BlendMode> {+ if let Some(mode) = graph.optional_field(props, "blendMode")? {+ let mode = match graph.resolve(mode)? {+ Value::Int(n) => *n,+ _ => graph.integer(graph.field(mode, "value__")?)?,+ };+ let mode = usize::try_from(mode).map_err(|_| invalid("invalid blend mode"))?;+ return MODES.get(mode).copied().ok_or_else(|| invalid(format!("unsupported blend mode {mode}")));+ }+ let props = graph.field(layer, "properties")?;+ let mode = graph.class_name(graph.field(props, "blendOp")?)?;+ let mode = mode+ .strip_prefix("PaintDotNet.UserBlendOps+")+ .and_then(|s| s.strip_suffix("BlendOp"))+ .ok_or_else(|| invalid(format!("unsupported blend operation {mode}")))?;+ OLD_MODES.iter().position(|m| *m == mode).and_then(|i| MODES.get(i)).copied().ok_or_else(|| invalid(format!("unsupported blend operation {mode}")))+}++/// Reads a memory block's numbered chunks in their on-disk order; each chunk has its own gzip+/// stream and checksum. Inflate directly into the bounded destination, checking its exact size.+fn pixels(reader: &mut Reader<'_>, length: usize, ctl: &Interrupt<'_>) -> Result<Vec<u8>> {+ let version = reader.byte()?;+ if version > 1 {+ return Err(invalid(format!("unsupported pixel compression {version}")));+ }+ let chunk_size = reader.be_u32()?;+ if chunk_size == 0 {+ return Err(invalid("zero pixel chunk size"));+ }+ let chunks = length.div_ceil(chunk_size);+ if chunks > 1_000_000 {+ return Err(invalid("too many pixel chunks"));+ }+ // Uncompressed chunks hold every pixel byte: a file shorter than that is truncated, and is+ // rejected before the buffer is allocated.+ if version == 1 && reader.bytes.len().saturating_sub(reader.pos) < length {+ return Err(invalid("uncompressed pixel data is truncated"));+ }+ let mut seen = vec![false; chunks];+ let mut data = vec![0; length];+ for _ in 0..chunks {+ ctl.check().map_err(|_| IoError::Cancelled)?;+ let index = reader.be_u32()?;+ let found = seen.get_mut(index).ok_or_else(|| invalid("pixel chunk index out of bounds"))?;+ if *found {+ return Err(invalid("duplicate pixel chunk"));+ }+ *found = true;+ let size = reader.be_u32()?;+ let raw = reader.take(size)?;+ let start = index.checked_mul(chunk_size).ok_or_else(|| invalid("pixel offset overflow"))?;+ let end = start.checked_add(chunk_size.min(length.saturating_sub(start))).ok_or_else(|| invalid("pixel offset overflow"))?;+ let dst = data.get_mut(start..end).ok_or_else(|| invalid("invalid pixel chunk range"))?;+ if version == 0 {+ let mut decoder = flate2::bufread::GzDecoder::new(raw);+ for band in dst.chunks_mut(1 << 20) {+ ctl.check().map_err(|_| IoError::Cancelled)?;+ decoder.read_exact(band).map_err(|e| invalid(format!("invalid gzip pixel chunk: {e}")))?;+ }+ let mut extra = [0];+ if decoder.read(&mut extra).map_err(|e| invalid(format!("invalid gzip pixel checksum: {e}")))? != 0 || !decoder.into_inner().is_empty() {+ return Err(invalid("pixel chunk has excess data"));+ }+ } else {+ if raw.len() != dst.len() {+ return Err(invalid("incorrect uncompressed pixel chunk size"));+ }+ dst.copy_from_slice(raw);+ }+ }+ Ok(data)+}++pub(super) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result<ImportResult> {+ let mut reader = Reader { bytes, pos: 0 };+ if reader.take(4)? != b"PDN3" {+ return Err(invalid("unsupported document signature (expected PDN3)"));+ }+ let mut header_size = [0; 4];+ header_size.get_mut(..3).ok_or_else(|| invalid("invalid header"))?.copy_from_slice(reader.take(3)?);+ reader.take(u32::from_le_bytes(header_size) as usize)?;+ if reader.take(2)? != [0, 1] {+ return Err(invalid("unsupported PDN3 serialization version"));+ }+ let graph = nrbf::parse(&mut reader, ctl)?;+ let root = &graph.root;+ if graph.class_name(root)? != "PaintDotNet.Document" {+ return Err(invalid("root object is not a Paint.NET document"));+ }+ let width = count(&graph, root, "width")?;+ let height = count(&graph, root, "height")?;+ let row_bytes = width.checked_mul(4).ok_or_else(|| invalid("canvas size overflow"))?;+ let canvas_bytes = row_bytes.checked_mul(height).ok_or_else(|| invalid("canvas size overflow"))?;+ if width == 0 || height == 0 || width > i32::MAX as usize || height > i32::MAX as usize || canvas_bytes > MAX_PIXEL_BYTES {+ return Err(invalid("canvas is empty or exceeds the 1 GiB pixel limit"));+ }+ let list = graph.field(root, "layers")?;+ let layers = graph.array(graph.field(list, "ArrayList+_items")?)?;+ let len = count(&graph, list, "ArrayList+_size")?;+ if len == 0 || len > MAX_LAYERS {+ return Err(invalid("document must have 1..1024 bitmap layers"));+ }+ let layers = layers.get(..len).ok_or_else(|| invalid("layer list count exceeds its array"))?;+ let bounds = Rect::from_xywh(0, 0, width as u32, height as u32);+ let mut layouts = HashMap::new();+ let mut output = Vec::with_capacity(len);+ for layer in layers {+ ctl.check().map_err(|_| IoError::Cancelled)?;+ if graph.class_name(layer)? != "PaintDotNet.BitmapLayer" {+ return Err(invalid("only PDN3 bitmap layers are supported"));+ }+ if count(&graph, layer, "Layer+width")? != width || count(&graph, layer, "Layer+height")? != height {+ return Err(invalid("layer dimensions do not match the canvas"));+ }+ let surface = graph.field(layer, "surface")?;+ if graph.class_name(surface)? != "PaintDotNet.Surface" || count(&graph, surface, "width")? != width || count(&graph, surface, "height")? != height {+ return Err(invalid("invalid bitmap surface"));+ }+ let stride = count(&graph, surface, "stride")?;+ if stride < row_bytes {+ return Err(invalid("surface stride is too short for BGRA32 pixels"));+ }+ let memory = graph.field(surface, "scan0")?;+ let Value::Ref(id) = memory else { return Err(invalid("missing pixel memory reference")) };+ if let Some(old) = layouts.insert(*id, stride)+ && old != stride+ {+ return Err(invalid("shared pixel memory has inconsistent strides"));+ }+ let props = graph.field(layer, "Layer+properties")?;+ let opacity = count(&graph, props, "opacity")?;+ if opacity > 255 {+ return Err(invalid("opacity exceeds 255"));+ }+ let mut l = Layer::raster(graph.string(graph.field(props, "name")?)?, PixelFormat::RGBA8);+ l.visible = graph.boolean(graph.field(props, "visible")?)?;+ l.opacity = opacity as f32 / 255.0;+ l.blend = blend(&graph, layer, props)?;+ output.push((*id, l));+ }+ let blocks: Vec<_> = graph.objects_of_class("PaintDotNet.MemoryBlock").collect();+ let mut total = 0usize;+ // Validate every allocation before decoding any block.+ for (id, block) in &blocks {+ let length = count(&graph, block, "length64")?;+ let stride = *layouts.get(id).ok_or_else(|| invalid("unreferenced pixel memory block"))?;+ if length != stride.checked_mul(height).ok_or_else(|| invalid("pixel length overflow"))? {+ return Err(invalid("pixel memory length does not match the surface"));+ }+ if graph.boolean(graph.field(block, "hasParent")?)? || !graph.boolean(graph.field(block, "deferred")?)? {+ return Err(invalid("unsupported non-deferred or parented pixel memory"));+ }+ total = total.checked_add(length).ok_or_else(|| invalid("pixel length overflow"))?;+ if total > MAX_PIXEL_BYTES {+ return Err(invalid("decoded pixels exceed the 1 GiB limit"));+ }+ }+ let mut surfaces = HashMap::new();+ for (i, (id, block)) in blocks.iter().enumerate() {+ let length = count(&graph, block, "length64")?;+ let mut data = pixels(&mut reader, length, ctl)?;+ let stride = *layouts.get(id).ok_or_else(|| invalid("missing surface layout"))?;+ let mut surface = Surface::new(PixelFormat::RGBA8);+ for (y, row) in data.chunks_exact_mut(stride).enumerate() {+ ctl.check().map_err(|_| IoError::Cancelled)?;+ let row = row.get_mut(..row_bytes).ok_or_else(|| invalid("invalid pixel row"))?;+ for pixel in row.as_chunks_mut::<4>().0 {+ pixel.swap(0, 2);+ }+ surface.write_interleaved(Rect::from_xywh(0, y as i32, bounds.width(), 1), row);+ }+ surfaces.insert(*id, surface);+ ctl.progress(0.05 + 0.95 * (i + 1) as f32 / blocks.len() as f32);+ }+ if reader.pos != bytes.len() {+ return Err(invalid("unexpected trailing data"));+ }+ let mut document = Document::new(name, Size::new(width as u32, height as u32), ColorMode::Rgb, SampleType::U8);+ for (id, mut layer) in output {+ layer.content = LayerContent::Raster(surfaces.get(&id).cloned().ok_or_else(|| invalid("missing pixel memory block"))?);+ document.layers.push(layer);+ }+ let mut warnings = Vec::new();+ if let Some(meta) = graph.optional_field(root, "userMetadataItems")?+ && !matches!(graph.resolve(meta)?, Value::Null)+ && !graph.array(meta)?.is_empty()+ {+ warnings.push("Paint.NET document metadata was not imported".into());+ }+ Ok(ImportResult { document, warnings, source_read_only: true, preview_only: false })+}diff --git a/crates/io/src/pdn/nrbf.rs b/crates/io/src/pdn/nrbf.rsnew file mode 100644index 000000000..065bf7a7a--- /dev/null+++ b/crates/io/src/pdn/nrbf.rs@@ -0,0 +1,420 @@+//! Data-only subset of MS-NRBF used by PDN3. References stay as ids; no .NET types are executed.+//! https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nrbf/++use std::collections::HashMap;+use std::sync::Arc;++use photocraft_raster::Interrupt;++use super::{Result, invalid};++const MAX_ITEMS: usize = 1_000_000;+const MAX_STRINGS: usize = 64 << 20;+const MAX_DEPTH: usize = 64;++pub(super) struct Reader<'a> {+ pub bytes: &'a [u8],+ pub pos: usize,+}++impl<'a> Reader<'a> {+ pub fn take(&mut self, len: usize) -> Result<&'a [u8]> {+ let end = self.pos.checked_add(len).ok_or_else(|| invalid("length overflow"))?;+ let b = self.bytes.get(self.pos..end).ok_or_else(|| invalid("truncated document"))?;+ self.pos = end;+ Ok(b)+ }++ pub fn byte(&mut self) -> Result<u8> {+ Ok(self.take(1)?.first().copied().unwrap_or_default())+ }++ pub fn le_i32(&mut self) -> Result<i32> {+ Ok(i32::from_le_bytes(self.take(4)?.try_into().map_err(|_| invalid("invalid integer"))?))+ }++ pub fn be_u32(&mut self) -> Result<usize> {+ usize::try_from(u32::from_be_bytes(self.take(4)?.try_into().map_err(|_| invalid("invalid integer"))?)).map_err(|_| invalid("length overflow"))+ }++ fn count(&mut self) -> Result<usize> {+ let n = usize::try_from(self.le_i32()?).map_err(|_| invalid("negative count"))?;+ if n > MAX_ITEMS {+ return Err(invalid("serialized array or class is too large"));+ }+ Ok(n)+ }+}++#[derive(Debug)]+pub(super) struct Class {+ name: String,+ names: Vec<String>,+ primitives: Vec<Option<u8>>,+}++#[derive(Debug)]+pub(super) enum Value {+ Null,+ Bool(bool),+ Int(i64),+ String(String),+ Ref(i32),+ Array(Vec<Value>),+ Object { class: Arc<Class>, members: Vec<Value> },+}++pub(super) struct Graph {+ pub root: Value,+ objects: HashMap<i32, Value>,+ order: Vec<i32>,+}++impl Graph {+ pub fn objects_of_class<'a>(&'a self, name: &'a str) -> impl Iterator<Item = (i32, &'a Value)> {+ self.order+ .iter()+ .filter_map(|id| self.objects.get(id).map(|v| (*id, v)))+ .filter(move |(_, v)| matches!(v, Value::Object { class, .. } if class.name == name))+ }+ pub fn resolve<'a>(&'a self, mut value: &'a Value) -> Result<&'a Value> {+ for _ in 0..MAX_DEPTH {+ match value {+ Value::Ref(id) => value = self.objects.get(id).ok_or_else(|| invalid("missing object reference"))?,+ _ => return Ok(value),+ }+ }+ Err(invalid("cyclic or excessively deep object reference"))+ }++ pub fn class_name<'a>(&'a self, value: &'a Value) -> Result<&'a str> {+ match self.resolve(value)? {+ Value::Object { class, .. } => Ok(&class.name),+ _ => Err(invalid("expected a serialized object")),+ }+ }++ pub fn field<'a>(&'a self, value: &'a Value, name: &str) -> Result<&'a Value> {+ self.optional_field(value, name)?.ok_or_else(|| invalid(format!("missing field {name}")))+ }++ pub fn optional_field<'a>(&'a self, value: &'a Value, name: &str) -> Result<Option<&'a Value>> {+ match self.resolve(value)? {+ Value::Object { class, members } => Ok(class.names.iter().position(|n| n == name).and_then(|i| members.get(i))),+ _ => Err(invalid("expected a serialized object")),+ }+ }++ pub fn integer(&self, value: &Value) -> Result<i64> {+ match self.resolve(value)? {+ Value::Int(n) => Ok(*n),+ _ => Err(invalid("expected an integer")),+ }+ }++ pub fn boolean(&self, value: &Value) -> Result<bool> {+ match self.resolve(value)? {+ Value::Bool(b) => Ok(*b),+ _ => Err(invalid("expected a boolean")),+ }+ }++ pub fn string<'a>(&'a self, value: &'a Value) -> Result<&'a str> {+ match self.resolve(value)? {+ Value::String(s) => Ok(s),+ _ => Err(invalid("expected a string")),+ }+ }++ pub fn array<'a>(&'a self, value: &'a Value) -> Result<&'a [Value]> {+ match self.resolve(value)? {+ Value::Array(a) => Ok(a),+ _ => Err(invalid("expected an array")),+ }+ }+}++struct Parser<'a, 'b> {+ reader: &'b mut Reader<'a>,+ ctl: &'b Interrupt<'b>,+ graph: Graph,+ classes: HashMap<i32, Arc<Class>>,+ items: usize,+ strings: usize,+}++pub(super) fn parse(reader: &mut Reader<'_>, ctl: &Interrupt<'_>) -> Result<Graph> {+ if reader.byte()? != 0 {+ return Err(invalid("missing NRBF stream header"));+ }+ let root = reader.le_i32()?;+ let _header = reader.le_i32()?;+ if root == 0 || reader.le_i32()? != 1 || reader.le_i32()? != 0 {+ return Err(invalid("unsupported NRBF stream version"));+ }+ let mut parser = Parser {+ reader,+ ctl,+ graph: Graph { root: Value::Ref(root), objects: HashMap::new(), order: Vec::new() },+ classes: HashMap::new(),+ items: 0,+ strings: 0,+ };+ loop {+ let tag = parser.reader.byte()?;+ if tag == 11 {+ break;+ }+ parser.record(tag, 0)?;+ }+ parser.graph.resolve(&parser.graph.root)?;+ Ok(parser.graph)+}++impl Parser<'_, '_> {+ fn budget(&mut self, n: usize) -> Result<()> {+ self.items = self.items.checked_add(n).ok_or_else(|| invalid("object count overflow"))?;+ if self.items > MAX_ITEMS {+ return Err(invalid("too many serialized objects or members"));+ }+ Ok(())+ }++ fn string(&mut self) -> Result<String> {+ let mut len = 0usize;+ for shift in (0..35).step_by(7) {+ let b = self.reader.byte()?;+ if shift == 28 && b > 7 {+ return Err(invalid("invalid string length"));+ }+ len |= usize::from(b & 127) << shift;+ if b & 128 == 0 {+ self.strings = self.strings.checked_add(len).ok_or_else(|| invalid("string length overflow"))?;+ if self.strings > MAX_STRINGS {+ return Err(invalid("serialized strings are too large"));+ }+ return String::from_utf8(self.reader.take(len)?.to_vec()).map_err(|_| invalid("invalid UTF-8 string"));+ }+ }+ Err(invalid("invalid string length"))+ }++ fn primitive(&mut self, tag: u8) -> Result<Value> {+ macro_rules! number {+ ($ty:ty, $variant:ident) => {+ Value::$variant(<$ty>::from_le_bytes(self.reader.take(size_of::<$ty>())?.try_into().map_err(|_| invalid("invalid primitive"))?).into())+ };+ }+ Ok(match tag {+ 1 => match self.reader.byte()? {+ 0 => Value::Bool(false),+ 1 => Value::Bool(true),+ _ => return Err(invalid("invalid boolean")),+ },+ 2 => Value::Int(i64::from(self.reader.byte()?)),+ 3 => {+ let first = self.reader.byte()?;+ let len = match first {+ 0..=0x7f => 1,+ 0xc2..=0xdf => 2,+ 0xe0..=0xef => 3,+ _ => return Err(invalid("invalid character")),+ };+ let mut b = vec![first];+ b.extend_from_slice(self.reader.take(len - 1)?);+ Value::String(String::from_utf8(b).map_err(|_| invalid("invalid character"))?)+ }+ 5 | 18 => Value::String(self.string()?),+ 6 => {+ self.reader.take(8)?;+ Value::Null+ }+ 7 => number!(i16, Int),+ 8 => number!(i32, Int),+ 9 | 12 => number!(i64, Int),+ 10 => Value::Int(i64::from(self.reader.byte()? as i8)),+ 11 => {+ self.reader.take(4)?;+ Value::Null+ }+ 13 | 16 => {+ let n = u64::from_le_bytes(self.reader.take(8)?.try_into().map_err(|_| invalid("invalid integer"))?);+ // Metadata dates may use the high bits; their bit pattern stays intact.+ Value::Int(n as i64)+ }+ 14 => number!(u16, Int),+ 15 => number!(u32, Int),+ 17 => Value::Null,+ _ => return Err(invalid(format!("unsupported primitive type {tag}"))),+ })+ }++ fn type_info(&mut self, tag: u8) -> Result<Option<u8>> {+ match tag {+ 0 => Ok(Some(self.reader.byte()?)),+ 1 | 2 | 5 | 6 => Ok(None),+ 3 => {+ self.string()?;+ Ok(None)+ }+ 4 => {+ self.string()?;+ self.reader.le_i32()?;+ Ok(None)+ }+ 7 => {+ self.reader.byte()?;+ Ok(None)+ }+ _ => Err(invalid(format!("unsupported binary type {tag}"))),+ }+ }++ fn reserve(&mut self, id: i32) -> Result<()> {+ if id == 0 || self.graph.objects.insert(id, Value::Null).is_some() {+ return Err(invalid("duplicate or zero object id"));+ }+ self.graph.order.push(id);+ Ok(())+ }++ fn value(&mut self, depth: usize) -> Result<Value> {+ loop {+ let tag = self.reader.byte()?;+ if tag == 12 {+ self.record(tag, depth)?;+ } else {+ return self.record(tag, depth);+ }+ }+ }++ fn object(&mut self, id: i32, class: Arc<Class>, depth: usize) -> Result<Value> {+ self.reserve(id)?;+ self.budget(class.names.len())?;+ let mut members = Vec::with_capacity(class.names.len());+ for primitive in &class.primitives {+ members.push(match primitive {+ Some(p) => self.primitive(*p)?,+ None => self.value(depth + 1)?,+ });+ }+ self.graph.objects.insert(id, Value::Object { class, members });+ Ok(Value::Ref(id))+ }++ fn array(&mut self, id: i32, len: usize, primitive: Option<u8>, depth: usize) -> Result<Value> {+ self.reserve(id)?;+ self.budget(len)?;+ if primitive == Some(2) {+ self.reader.take(len)?;+ return Ok(Value::Ref(id));+ }+ let mut values = Vec::with_capacity(len);+ while values.len() < len {+ self.ctl.check().map_err(|_| crate::IoError::Cancelled)?;+ if let Some(p) = primitive {+ values.push(self.primitive(p)?);+ continue;+ }+ let tag = self.reader.byte()?;+ if matches!(tag, 13 | 14) {+ let count = if tag == 13 { usize::from(self.reader.byte()?) } else { self.reader.count()? };+ if count == 0 || count > len - values.len() {+ return Err(invalid("invalid array null run"));+ }+ values.resize_with(values.len() + count, || Value::Null);+ } else if tag == 12 {+ self.record(tag, depth + 1)?;+ } else {+ values.push(self.record(tag, depth + 1)?);+ }+ }+ self.graph.objects.insert(id, Value::Array(values));+ Ok(Value::Ref(id))+ }++ fn record(&mut self, tag: u8, depth: usize) -> Result<Value> {+ self.ctl.check().map_err(|_| crate::IoError::Cancelled)?;+ self.budget(1)?;+ if depth > MAX_DEPTH {+ return Err(invalid("serialized objects nested too deeply"));+ }+ match tag {+ 1 => {+ let id = self.reader.le_i32()?;+ let metadata = self.reader.le_i32()?;+ let class = self.classes.get(&metadata).cloned().ok_or_else(|| invalid("missing class metadata"))?;+ self.object(id, class, depth)+ }+ 2..=5 => {+ let id = self.reader.le_i32()?;+ let name = self.string()?;+ let count = self.reader.count()?;+ self.budget(count)?;+ let names = (0..count).map(|_| self.string()).collect::<Result<Vec<_>>>()?;+ let primitives = if tag >= 4 {+ let types = self.reader.take(count)?.to_vec();+ types.into_iter().map(|t| self.type_info(t)).collect::<Result<Vec<_>>>()?+ } else {+ vec![None; count]+ };+ if matches!(tag, 3 | 5) {+ self.reader.le_i32()?;+ }+ let class = Arc::new(Class { name, names, primitives });+ if self.classes.insert(id, class.clone()).is_some() {+ return Err(invalid("duplicate class metadata"));+ }+ self.object(id, class, depth)+ }+ 6 => {+ let id = self.reader.le_i32()?;+ self.reserve(id)?;+ let value = Value::String(self.string()?);+ self.graph.objects.insert(id, value);+ Ok(Value::Ref(id))+ }+ 7 => {+ let id = self.reader.le_i32()?;+ let kind = self.reader.byte()?;+ let rank = self.reader.count()?;+ if kind > 5 || rank == 0 || rank > 32 {+ return Err(invalid("invalid array dimensions"));+ }+ let mut len = 1usize;+ for _ in 0..rank {+ len = len.checked_mul(self.reader.count()?).ok_or_else(|| invalid("array size overflow"))?;+ }+ if kind >= 3 {+ for _ in 0..rank {+ if self.reader.le_i32()? != 0 {+ return Err(invalid("nonzero array lower bounds are unsupported"));+ }+ }+ }+ let tag = self.reader.byte()?;+ let primitive = self.type_info(tag)?;+ self.array(id, len, primitive, depth)+ }+ 8 => {+ let primitive = self.reader.byte()?;+ self.primitive(primitive)+ }+ 9 => Ok(Value::Ref(self.reader.le_i32()?)),+ 10 => Ok(Value::Null),+ 12 => {+ self.reader.le_i32()?;+ self.string()?;+ Ok(Value::Null)+ }+ 15..=17 => {+ let id = self.reader.le_i32()?;+ let len = self.reader.count()?;+ let primitive = if tag == 15 { Some(self.reader.byte()?) } else { None };+ self.array(id, len, primitive, depth)+ }+ _ => Err(invalid(format!("unsupported NRBF record {tag}"))),+ }+ }+}diff --git a/crates/io/src/pdn/tests.rs b/crates/io/src/pdn/tests.rsnew file mode 100644index 000000000..139c87d6a--- /dev/null+++ b/crates/io/src/pdn/tests.rs@@ -0,0 +1,299 @@+use super::*;+use std::io::Write;++enum Field {+ Int(i32),+ Long(i64),+ Byte(u8),+ Bool(bool),+ Ref(i32),+}++struct Writer(Vec<u8>);++impl Writer {+ fn int(&mut self, n: i32) {+ self.0.extend(n.to_le_bytes());+ }+ fn string(&mut self, s: &str) {+ let mut len = s.len();+ while len >= 128 {+ self.0.push((len as u8 & 127) | 128);+ len >>= 7;+ }+ self.0.push(len as u8);+ self.0.extend(s.as_bytes());+ }+ fn object(&mut self, id: i32, class: &str, fields: &[(&str, Field)]) {+ self.0.push(5);+ self.int(id);+ self.string(class);+ self.int(fields.len() as i32);+ for (name, _) in fields {+ self.string(name);+ }+ for (_, f) in fields {+ self.0.push(if matches!(f, Field::Ref(_)) { 2 } else { 0 });+ }+ for (_, f) in fields {+ match f {+ Field::Int(_) => self.0.push(8),+ Field::Long(_) => self.0.push(9),+ Field::Byte(_) => self.0.push(2),+ Field::Bool(_) => self.0.push(1),+ Field::Ref(_) => {}+ }+ }+ self.int(1);+ for (_, f) in fields {+ match f {+ Field::Int(n) => self.int(*n),+ Field::Long(n) => self.0.extend(n.to_le_bytes()),+ Field::Byte(n) => self.0.push(*n),+ Field::Bool(b) => self.0.push(u8::from(*b)),+ Field::Ref(id) => {+ self.0.push(9);+ self.int(*id);+ }+ }+ }+ }+}++/// Independent synthetic PDN writer: padded rows, forward references, a root cycle,+/// spare ArrayList capacity, and reversed gzip/raw chunks. There is no production PDN writer.+fn fixture(modes: &[i32], legacy: bool, compressed: bool) -> Vec<u8> {+ use Field::*;+ let mut w = Writer(b"PDN3\0\0\0\0\x01".to_vec());+ w.0.push(0);+ for n in [1, -1, 1, 0] {+ w.int(n);+ }+ w.0.push(12);+ w.int(1);+ w.string("PaintDotNet.Data");+ w.object(1, "PaintDotNet.Document", &[("width", Int(2)), ("height", Int(2)), ("layers", Ref(2))]);+ w.object(2, "PaintDotNet.LayerList", &[("parent", Ref(1)), ("ArrayList+_size", Int(modes.len() as i32)), ("ArrayList+_items", Ref(3))]);+ w.0.push(16);+ w.int(3);+ w.int(modes.len() as i32 + 2);+ for i in 0..modes.len() {+ w.0.push(9);+ w.int(16 + i as i32 * 10);+ }+ w.0.extend([13, 2]);+ for (i, mode) in modes.iter().enumerate() {+ let id = 16 + i as i32 * 10;+ w.object(+ id,+ "PaintDotNet.BitmapLayer",+ &[("Layer+width", Int(2)), ("Layer+height", Int(2)), ("surface", Ref(id + 1)), ("Layer+properties", Ref(id + 2)), ("properties", Ref(id + 3))],+ );+ w.object(id + 1, "PaintDotNet.Surface", &[("width", Int(2)), ("height", Int(2)), ("stride", Int(12)), ("scan0", Ref(id + 7))]);+ let mut fields =+ vec![("name", Ref(id + 4)), ("opacity", Byte(if i == 0 { 255 } else { 128 })), ("visible", Bool(i != 1)), ("isBackground", Bool(i == 0))];+ if !legacy {+ fields.push(("blendMode", Ref(id + 5)));+ }+ w.object(id + 2, "PaintDotNet.Layer+LayerProperties", &fields);+ w.object(id + 3, "PaintDotNet.BitmapLayer+BitmapLayerProperties", &[("blendOp", Ref(id + 6))]);+ w.0.push(6);+ w.int(id + 4);+ w.string(&format!("Läyer {i}"));+ w.object(id + 5, "PaintDotNet.LayerBlendMode", &[("value__", Int(*mode))]);+ w.object(id + 6, &format!("PaintDotNet.UserBlendOps+{}BlendOp", OLD_MODES.get(*mode as usize).unwrap_or(&"Unknown")), &[]);+ w.object(id + 7, "PaintDotNet.MemoryBlock", &[("length64", Long(24)), ("hasParent", Bool(false)), ("deferred", Bool(true))]);+ }+ w.0.push(11);+ for _ in modes {+ w.0.push(if compressed { 0 } else { 1 });+ w.0.extend(12u32.to_be_bytes());+ for index in [1u32, 0] {+ let raw = if index == 0 { vec![30, 20, 10, 255, 60, 50, 40, 128, 99, 99, 99, 99] } else { vec![90, 80, 70, 64, 120, 110, 100, 0, 99, 99, 99, 99] };+ let data = if compressed {+ let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());+ enc.write_all(&raw).unwrap();+ enc.finish().unwrap()+ } else {+ raw+ };+ w.0.extend(index.to_be_bytes());+ w.0.extend((data.len() as u32).to_be_bytes());+ w.0.extend(data);+ }+ }+ w.0+}++#[test]+fn all_pdn_blend_modes_and_layer_properties_import_and_save_natively() {+ let modes: Vec<_> = (0..14).collect();+ for legacy in [false, true] {+ for compressed in [false, true] {+ let bytes = fixture(&modes, legacy, compressed);+ // Detection must work without an extension too.+ let imported = crate::import("sample", &bytes).unwrap();+ assert!(imported.source_read_only);+ assert!(!imported.preview_only);+ let doc = imported.document;+ assert_eq!(doc.layers.len(), 14);+ assert_eq!((doc.size.width, doc.size.height), (2, 2));+ for (i, layer) in doc.layers.iter().enumerate() {+ assert_eq!(layer.name, format!("Läyer {i}"));+ assert_eq!(layer.blend, MODES[i]);+ assert_eq!(layer.visible, i != 1);+ assert_eq!(layer.opacity, if i == 0 { 1.0 } else { 128.0 / 255.0 });+ assert!(!layer.locks.all && !layer.locks.pixels && !layer.locks.position);+ let surface = layer.surface().unwrap();+ for (x, y, expected) in [(0, 0, [10, 20, 30, 255]), (1, 0, [40, 50, 60, 128]), (0, 1, [70, 80, 90, 64]), (1, 1, [100, 110, 120, 0])] {+ let pixel = surface.pixel(x, y);+ assert_eq!(pixel.iter().map(|v| (v * 255.0).round() as u8).collect::<Vec<_>>(), expected);+ }+ }+ let saved = crate::export(&doc, "sample.pcraft", &Default::default()).unwrap();+ assert!(saved.warnings.is_empty());+ let back = crate::import("sample.pcraft", &saved.bytes).unwrap().document;+ assert_eq!(doc.layers, back.layers);+ assert_eq!(photocraft_compose::flatten(&doc).px, photocraft_compose::flatten(&back).px);+ }+ }+}++#[test]+fn truncation_unknown_modes_and_corrupt_chunks_fail_without_panicking() {+ let raw = fixture(&[0], false, false);+ for len in 0..raw.len() {+ assert!(crate::import("truncated.pdn", &raw[..len]).is_err(), "length {len}");+ }+ assert!(crate::import("unknown.pdn", &fixture(&[999], false, false)).is_err());+ let mut corrupt = raw.clone();+ let block = corrupt.len() - 45;+ // Zero chunk size.+ corrupt[block + 1..block + 5].fill(0);+ assert!(crate::import("corrupt.pdn", &corrupt).is_err());+ let mut duplicate = raw.clone();+ // Both row chunks claim index 1.+ duplicate[block + 25..block + 29].copy_from_slice(&1u32.to_be_bytes());+ assert!(crate::import("duplicate.pdn", &duplicate).is_err());+ let mut zipped = fixture(&[0], false, true);+ let last = zipped.len() - 1;+ zipped[last] ^= 1;+ assert!(crate::import("checksum.pdn", &zipped).is_err());+}++#[test]+fn pdn_import_can_be_cancelled_during_parsing_and_pixel_decode() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ let bytes = fixture(&[0, 1], false, true);+ for limit in [0, 10] {+ let checks = AtomicUsize::new(0);+ let cancel = || checks.fetch_add(1, Ordering::Relaxed) >= limit;+ let result = crate::import_with("cancel.pdn", &bytes, &Interrupt::cancel_only(&cancel));+ assert!(matches!(result, Err(IoError::Cancelled)));+ }+ let cancel = AtomicUsize::new(0);+ let no = || cancel.load(Ordering::Relaxed) != 0;+ let progress = |_| {+ cancel.store(1, Ordering::Relaxed);+ };+ let result = crate::import_with("cancel.pdn", &bytes, &Interrupt::new(&no, &progress));+ assert!(matches!(result, Err(IoError::Cancelled)));+}++proptest::proptest! {+ #[test]+ fn arbitrary_serialized_data_returns_an_error_without_panicking(data in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..4096)) {+ let mut bytes = b"PDN3\0\0\0\0\x01".to_vec();+ bytes.extend(data);+ let _ = crate::import("fuzz.pdn", &bytes);+ }++ #[test]+ fn mutated_layered_documents_never_panic(edits in proptest::collection::vec((proptest::prelude::any::<usize>(), proptest::prelude::any::<u8>()), 1..8)) {+ let mut bytes = fixture(&[0, 5, 13], false, true);+ for (offset, value) in edits {+ let index = offset % bytes.len();+ bytes[index] = value;+ }+ let _ = crate::import("mutated.pdn", &bytes);+ }+}++#[test]+fn psd_export_reports_paint_net_blend_loss() {+ let mut doc = crate::import("sample.pdn", &fixture(&[5], false, false)).unwrap().document;+ doc.layers[0].effects.items.push(photocraft_doc::effects::Effect::ColorOverlay {+ common: photocraft_doc::effects::FxCommon::new(BlendMode::Glow, 1.0),+ color: photocraft_color::Color::BLACK,+ });+ let result = crate::export(&doc, "sample.psd", &Default::default()).unwrap();+ assert!(result.warnings.iter().any(|s| s.contains("Reflect") && s.contains("no PSD equivalent")));+ assert!(result.warnings.iter().any(|s| s.contains("Color Overlay") && s.contains("Glow") && s.contains("no PSD equivalent")));+ let native = crate::export(&doc, "sample.pcraft", &Default::default()).unwrap();+ assert_eq!(crate::import("sample.pcraft", &native.bytes).unwrap().document.layers, doc.layers);+}++#[test]+fn malformed_pdn_reports_a_format_error() {+ for bytes in [b"".as_slice(), b"PDN3", b"PDN3\xff\xff\xff", b"PDN4\0\0\0"] {+ assert!(matches!(crate::import("bad.pdn", bytes), Err(IoError::Pdn(_))));+ }+}++#[test]+fn serialized_counts_depth_and_references_are_bounded() {+ let header = || {+ let mut w = Writer(vec![0]);+ for n in [1, -1, 1, 0] {+ w.int(n);+ }+ w+ };+ let mut oversized = header();+ oversized.0.push(16);+ oversized.int(1);+ oversized.int(1_000_001);+ let mut nested = header();+ for id in 1..=66 {+ nested.0.push(16);+ nested.int(id);+ nested.int(1);+ }+ nested.0.extend([10, 11]);+ let mut duplicate = header();+ for _ in 0..2 {+ duplicate.0.push(6);+ duplicate.int(1);+ duplicate.string("duplicate");+ }+ duplicate.0.push(11);+ let mut null_run = header();+ null_run.0.push(16);+ null_run.int(1);+ null_run.int(1);+ null_run.0.extend([13, 2, 11]);+ let mut missing_class = header();+ missing_class.0.push(1);+ missing_class.int(1);+ missing_class.int(999);+ let mut missing_root = header();+ missing_root.0.push(11);+ for w in [oversized, nested, duplicate, null_run, missing_class, missing_root] {+ let mut reader = Reader { bytes: &w.0, pos: 0 };+ assert!(nrbf::parse(&mut reader, &Interrupt::NONE).is_err());+ }+}++#[test]+fn pdn_export_is_explicitly_unsupported() {+ let doc = Document::new("x", Size::new(1, 1), ColorMode::Rgb, SampleType::U8);+ assert!(matches!(crate::export(&doc, "x.pdn", &Default::default()), Err(IoError::Unsupported(_))));+}++#[test]+fn truncated_uncompressed_pixels_are_rejected_before_allocating() {+ // A raw (version 1) block of 256 MiB chunks that declares 1 GiB of pixels but holds a few bytes.+ let mut reader = Reader { bytes: &[1, 0x10, 0, 0, 0, 0, 0, 0, 0], pos: 0 };+ let e = pixels(&mut reader, 1 << 30, &Interrupt::NONE).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(e.contains("uncompressed pixel data is truncated"), "{e}");+}diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 8cdb79a74..f58f73280 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -372,6 +372,29 @@ impl Ex {// Effects: the original lfx2 while the effects are unchanged (or// could not be decoded at all); otherwise regenerated.let fx = &l.effects;+ for effect in &fx.items {+ use photocraft_doc::effects::Effect;+ let modes = match effect {+ Effect::DropShadow(s) | Effect::InnerShadow(s) => [Some(s.common.blend), None],+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => [Some(g.common.blend), None],+ Effect::Stroke(s) => [Some(s.common.blend), None],+ Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => {+ [Some(common.blend), None]+ }+ Effect::Satin(s) => [Some(s.common.blend), None],+ Effect::BevelEmboss(b) => [Some(b.highlight.blend), Some(b.shadow.blend)],+ };+ for mode in modes.into_iter().flatten() {+ if !mode.has_psd_equivalent() {+ self.warnings.push(format!(+ "layer \"{}\", {}: {} has no PSD equivalent and was written as Normal; save as .pcraft to preserve it",+ l.name,+ effect.label(),+ mode.label()+ ));+ }+ }+ }let lfx2 = match effects_unchanged(l) {Some(true) | None if fx.psd_raw.is_some() => fx.psd_raw.as_ref().map(|r| r.to_vec()),_ => (!fx.items.is_empty()).then(|| crate::effects_map::write_lfx2(fx.enabled, &fx.items)),@@ -389,6 +412,13 @@ impl Ex {b.data.push(0);}}+ if !l.blend.has_psd_equivalent() {+ self.warnings.push(format!(+ "layer \"{}\": {} has no PSD equivalent and was written as Normal; save as .pcraft to preserve it",+ l.name,+ l.blend.label()+ ));+ }LayerRecord {rect,channels,diff --git a/crates/io/tests/pdn_corpus.rs b/crates/io/tests/pdn_corpus.rsnew file mode 100644index 000000000..1e67b3d22--- /dev/null+++ b/crates/io/tests/pdn_corpus.rs@@ -0,0 +1,49 @@+//! Local PDN oracles are not bundled. Set PDN_TEST_DIR to a directory containing PDNs and their+//! exported PNGs, then run `cargo test -p photocraft-io --test pdn_corpus -- --ignored --nocapture`.++use std::path::{Path, PathBuf};++fn files(dir: &Path, out: &mut Vec<PathBuf>) {+ for entry in std::fs::read_dir(dir).unwrap() {+ let path = entry.unwrap().path();+ if path.is_dir() {+ files(&path, out);+ } else if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("pdn")) {+ out.push(path);+ }+ }+}++#[test]+#[ignore = "requires PDN_TEST_DIR with real Paint.NET files and matching PNG exports"]+fn real_pdn_layers_and_native_saves() {+ let root = std::env::var_os("PDN_TEST_DIR").expect("set PDN_TEST_DIR");+ let mut paths = Vec::new();+ files(Path::new(&root), &mut paths);+ paths.sort();+ assert!(!paths.is_empty(), "no PDN files found");+ let mut worst = 0.0f32;+ for path in &paths {+ let doc = photocraft_io::import(&path.to_string_lossy(), &std::fs::read(path).unwrap()).unwrap_or_else(|e| panic!("{}: {e}", path.display())).document;+ let flat = photocraft_compose::flatten(&doc);+ let native = photocraft_io::export(&doc, "copy.pcraft", &Default::default()).unwrap();+ let back = photocraft_io::import("copy.pcraft", &native.bytes).unwrap().document;+ assert_eq!(doc.layers, back.layers, "{}", path.display());+ assert_eq!(flat.px, photocraft_compose::flatten(&back).px);+ let png = path.with_extension("png");+ let oracle = photocraft_io::import("oracle.png", &std::fs::read(&png).expect("matching PNG export")).unwrap().document;+ assert_eq!(doc.size, oracle.size);+ let expected = photocraft_compose::flatten(&oracle);+ let error = flat+ .px+ .iter()+ .zip(&expected.px)+ .flat_map(|(a, b)| (0..4).map(move |c| if c == 3 { (a[3] - b[3]).abs() } else { (a[c] * a[3] - b[c] * b[3]).abs() }))+ .fold(0.0f32, f32::max);+ eprintln!("{}: {} layers, max PNG error {:.3}/255", path.display(), doc.layers.len(), error * 255.0);+ worst = worst.max(error);+ }+ // Paint.NET 4.x quantized intermediate layers to 8 bits; our compositor keeps floats.+ assert!(worst <= 3.0 / 255.0, "max error {worst}");+ eprintln!("{} real PDNs passed", paths.len());+}diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rsindex 3363b3a5a..7f2d976de 100644--- a/crates/ui-egui/src/file_dialog/tests.rs+++ b/crates/ui-egui/src/file_dialog/tests.rs@@ -25,6 +25,21 @@ fn app() -> (PhotocraftApp, Open, Rc<RefCell<Vec<String>>>) {(app, open, written)}+#[test]+fn pdn_save_requests_a_native_copy_without_overwriting_the_source() {+ let (mut app, open, written) = app();+ let st = app.session.active_mut().unwrap();+ st.path = Some("/pics/layers.PDN".into());+ let ctx = egui::Context::default();+ menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ assert!(matches!(open.borrow().as_slice(), [(FileDialogRequest::Save { suggested }, _)] if suggested == "/pics/layers.pcraft"));+ answer(&open, Some(FileDialogAnswer::SaveTo("/pics/layers.pcraft".into())));+ app.poll_file_dialog(&ctx, None);+ assert_eq!(*written.borrow(), ["/pics/layers.pcraft"]);+ assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/pics/layers.pcraft"));+}+/// The user answers the open dialog, from the dialog's own thread.fn answer(open: &Open, answer: Option<FileDialogAnswer>) {let (_, reply) = open.borrow_mut().pop().expect("a dialog is open");diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 503044b6f..02c29b169 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2327,3 +2327,9 @@ fontWeight Italic KurzívaKeep this tab open to retain your brushes. Nechte tuto kartu otevřenou, abyste si štětce zachovali.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. Úložiště prohlížeče není k dispozici; štětce platí jen pro tuto relaci. Nechte tuto kartu otevřenou, abyste si je zachovali.Saving brush presets… Keep this tab open until saving finishes. Ukládání předvoleb štětců… Nechte tuto kartu otevřenou, dokud ukládání neskončí.+ Reflect Odraz+ Glow Záře+ Negation Negace+ XOR XOR+ Color Burn (Paint.NET) Ztmavit barvy (Paint.NET)+ Color Dodge (Paint.NET) Zesvětlit barvy (Paint.NET)diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 8d5fe0020..b2030d621 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2366,3 +2366,9 @@ fontWeight Italic KursivKeep this tab open to retain your brushes. Lass diesen Tab geöffnet, um deine Pinsel zu behalten.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. Der Browserspeicher ist nicht verfügbar; Pinsel gelten nur für diese Sitzung. Lass diesen Tab geöffnet, um sie zu behalten.Saving brush presets… Keep this tab open until saving finishes. Pinselvorgaben werden gespeichert… Lass diesen Tab geöffnet, bis das Speichern abgeschlossen ist.+ Reflect Reflektieren+ Glow Glühen+ Negation Negation+ XOR XOR+ Color Burn (Paint.NET) Farbig nachbelichten (Paint.NET)+ Color Dodge (Paint.NET) Farbig abwedeln (Paint.NET)diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 59eef60d1..857a19618 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3437,3 +3437,9 @@ fontWeight Thin Πολύ λεπτάKeep this tab open to retain your brushes. Κρατήστε αυτή την καρτέλα ανοιχτή για να διατηρήσετε τα πινέλα σας.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. Ο χώρος αποθήκευσης του προγράμματος περιήγησης δεν είναι διαθέσιμος· τα πινέλα ισχύουν μόνο για αυτή την περίοδο λειτουργίας. Κρατήστε αυτή την καρτέλα ανοιχτή για να τα διατηρήσετε.Saving brush presets… Keep this tab open until saving finishes. Αποθήκευση προεπιλογών πινέλων… Κρατήστε αυτή την καρτέλα ανοιχτή μέχρι να ολοκληρωθεί η αποθήκευση.+ Reflect Αντανάκλαση+ Glow Λάμψη+ Negation Άρνηση+ XOR XOR+ Color Burn (Paint.NET) Κάψιμο χρώματος (Paint.NET)+ Color Dodge (Paint.NET) Φωτισμός χρώματος (Paint.NET)diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 5edafc789..73a682fec 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2395,3 +2395,9 @@ fontWeight Italic CursivaKeep this tab open to retain your brushes. Mantén esta pestaña abierta para conservar tus pinceles.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. El almacenamiento del navegador no está disponible; los pinceles solo duran esta sesión. Mantén esta pestaña abierta para conservarlos.Saving brush presets… Keep this tab open until saving finishes. Guardando ajustes preestablecidos de pincel… Mantén esta pestaña abierta hasta que termine.+ Reflect Reflejar+ Glow Resplandor+ Negation Negación+ XOR XOR+ Color Burn (Paint.NET) Sobreexponer color (Paint.NET)+ Color Dodge (Paint.NET) Aclarar color (Paint.NET)diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 098b9e24d..8f51a2bfc 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2748,3 +2748,9 @@ fontWeight Italic ItaliqueKeep this tab open to retain your brushes. Gardez cet onglet ouvert pour conserver vos formes.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. Le stockage du navigateur n'est pas disponible ; les formes ne durent que le temps de la session. Gardez cet onglet ouvert pour les conserver.Saving brush presets… Keep this tab open until saving finishes. Enregistrement des paramètres prédéfinis de forme… Gardez cet onglet ouvert jusqu'à la fin de l'enregistrement.+ Reflect Réflexion+ Glow Lueur+ Negation Négation+ XOR XOR+ Color Burn (Paint.NET) Densité couleur + (Paint.NET)+ Color Dodge (Paint.NET) Densité couleur − (Paint.NET)diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 17af80d7e..2f3fe0e48 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2735,3 +2735,9 @@ fontWeight Italic MiringKeep this tab open to retain your brushes. Biarkan tab ini terbuka untuk mempertahankan kuas Anda.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. Penyimpanan browser tidak tersedia; kuas hanya berlaku untuk sesi ini. Biarkan tab ini terbuka untuk mempertahankannya.Saving brush presets… Keep this tab open until saving finishes. Menyimpan preset kuas… Biarkan tab ini terbuka sampai penyimpanan selesai.+ Reflect Pantul+ Glow Pendar+ Negation Negasi+ XOR XOR+ Color Burn (Paint.NET) Color Burn (Paint.NET)+ Color Dodge (Paint.NET) Color Dodge (Paint.NET)diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 2e8f4a07b..57eb646ad 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2397,3 +2397,9 @@ fontWeight Italic CorsivoKeep this tab open to retain your brushes. Tieni aperta questa scheda per conservare i tuoi pennelli.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. L'archiviazione del browser non è disponibile; i pennelli valgono solo per questa sessione. Tieni aperta questa scheda per conservarli.Saving brush presets… Keep this tab open until saving finishes. Salvataggio dei predefiniti pennello… Tieni aperta questa scheda finché il salvataggio non è completato.+ Reflect Riflesso+ Glow Bagliore+ Negation Negazione+ XOR XOR+ Color Burn (Paint.NET) Colore brucia (Paint.NET)+ Color Dodge (Paint.NET) Colore scherma (Paint.NET)diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex ddb8bdae3..70983cde9 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3351,3 +3351,9 @@ fontWeight Italic 斜体Keep this tab open to retain your brushes. ブラシを保持するには、このタブを開いたままにしてください。Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. ブラウザーのストレージを利用できないため、ブラシはこのセッション中のみ有効です。保持するには、このタブを開いたままにしてください。Saving brush presets… Keep this tab open until saving finishes. ブラシプリセットを保存中… 保存が完了するまでこのタブを開いたままにしてください。+ Reflect 反射+ Glow グロー+ Negation 否定+ XOR XOR+ Color Burn (Paint.NET) 焼き込みカラー (Paint.NET)+ Color Dodge (Paint.NET) 覆い焼きカラー (Paint.NET)diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 9e72bf14d..6c063308a 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2906,3 +2906,9 @@ fontWeight Italic 기울임Keep this tab open to retain your brushes. 브러시를 유지하려면 이 탭을 열어 두세요.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. 브라우저 저장소를 사용할 수 없어 브러시는 이 세션에서만 유지됩니다. 유지하려면 이 탭을 열어 두세요.Saving brush presets… Keep this tab open until saving finishes. 브러시 사전 설정 저장 중… 저장이 끝날 때까지 이 탭을 열어 두세요.+ Reflect 반사+ Glow 광선+ Negation 부정+ XOR XOR+ Color Burn (Paint.NET) 색상 번 (Paint.NET)+ Color Dodge (Paint.NET) 색상 닷지 (Paint.NET)diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rsindex bd40695c1..2f5af1a7f 100644--- a/crates/ui-egui/src/i18n/mod.rs+++ b/crates/ui-egui/src/i18n/mod.rs@@ -771,7 +771,7 @@ mod tests {#[test]fn blend_mode_names_are_translated() {for l in LANGUAGES.iter().filter(|l| l.complete_menus) {- for m in std::iter::once(photocraft_color::BlendMode::PassThrough).chain(photocraft_color::BlendMode::LAYER_MODES) {+ for m in std::iter::once(photocraft_color::BlendMode::PassThrough).chain(photocraft_color::BlendMode::layer_modes()) {assert!(l.catalog().plain(m.label()).is_some(), "{}: blend mode {:?}", l.code, m.label());}}diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex f41711d97..811278053 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -3512,3 +3512,9 @@ cameraRaw Whites WittenKeep this tab open to retain your brushes. Houd dit tabblad open om je penselen te behouden.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. Browseropslag is niet beschikbaar; penselen gelden alleen voor deze sessie. Houd dit tabblad open om ze te behouden.Saving brush presets… Keep this tab open until saving finishes. Penseelvoorinstellingen opslaan… Houd dit tabblad open tot het opslaan klaar is.+ Reflect Reflecteren+ Glow Gloed+ Negation Negatie+ XOR XOR+ Color Burn (Paint.NET) Kleur doordrukken (Paint.NET)+ Color Dodge (Paint.NET) Kleur tegenhouden (Paint.NET)diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 482de22ee..fe38be900 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3350,3 +3350,9 @@ cameraRaw Roughness ChropowatośćKeep this tab open to retain your brushes. Nie zamykaj tej karty, aby zachować pędzle.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. Pamięć przeglądarki jest niedostępna; pędzle działają tylko w tej sesji. Nie zamykaj tej karty, aby je zachować.Saving brush presets… Keep this tab open until saving finishes. Zapisywanie ustawień predefiniowanych pędzli… Nie zamykaj tej karty, dopóki zapis się nie zakończy.+ Reflect Odbicie+ Glow Poświata+ Negation Negacja+ XOR XOR+ Color Burn (Paint.NET) Wypalanie koloru (Paint.NET)+ Color Dodge (Paint.NET) Rozjaśnianie koloru (Paint.NET)diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex c042c24b6..573f1b2b1 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2756,3 +2756,9 @@ fontWeight Italic ItálicoKeep this tab open to retain your brushes. Mantenha esta aba aberta para manter seus pincéis.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. O armazenamento do navegador não está disponível; os pincéis valem apenas para esta sessão. Mantenha esta aba aberta para mantê-los.Saving brush presets… Keep this tab open until saving finishes. Salvando predefinições de pincel… Mantenha esta aba aberta até o salvamento terminar.+ Reflect Refletir+ Glow Brilho+ Negation Negação+ XOR XOR+ Color Burn (Paint.NET) Superexposição de cores (Paint.NET)+ Color Dodge (Paint.NET) Subexposição de cores (Paint.NET)diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex f40a222a7..401b10bb5 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2602,3 +2602,9 @@ fontWeight Italic КурсивKeep this tab open to retain your brushes. Не закрывайте эту вкладку, чтобы сохранить кисти.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. Хранилище браузера недоступно; кисти действуют только в этом сеансе. Не закрывайте эту вкладку, чтобы сохранить их.Saving brush presets… Keep this tab open until saving finishes. Сохранение наборов кистей… Не закрывайте эту вкладку, пока сохранение не завершится.+ Reflect Отражение+ Glow Свечение+ Negation Отрицание+ XOR XOR+ Color Burn (Paint.NET) Затемнение основы (Paint.NET)+ Color Dodge (Paint.NET) Осветление основы (Paint.NET)diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 7b9195547..15bd21062 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3437,3 +3437,9 @@ cameraRaw Masking МаскуванняKeep this tab open to retain your brushes. Не закривайте цю вкладку, щоб зберегти пензлі.Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. Сховище браузера недоступне; пензлі діють лише в цьому сеансі. Не закривайте цю вкладку, щоб зберегти їх.Saving brush presets… Keep this tab open until saving finishes. Збереження наборів пензлів… Не закривайте цю вкладку, доки збереження не завершиться.+ Reflect Відбиття+ Glow Світіння+ Negation Заперечення+ XOR XOR+ Color Burn (Paint.NET) Затемнення основи (Paint.NET)+ Color Dodge (Paint.NET) Освітлення основи (Paint.NET)diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex b5e373e2e..a1bd15e96 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2335,3 +2335,9 @@ fontWeight Italic 斜体Keep this tab open to retain your brushes. 请保持此标签页打开以保留您的画笔。Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. 浏览器存储不可用;画笔仅在本次会话中有效。请保持此标签页打开以保留它们。Saving brush presets… Keep this tab open until saving finishes. 正在保存画笔预设… 请保持此标签页打开,直到保存完成。+ Reflect 反射+ Glow 发光+ Negation 否定+ XOR XOR+ Color Burn (Paint.NET) 颜色加深 (Paint.NET)+ Color Dodge (Paint.NET) 颜色减淡 (Paint.NET)diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 326f95b59..424d6b544 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2304,3 +2304,9 @@ fontWeight Italic 斜體Keep this tab open to retain your brushes. 請保持此分頁開啟以保留您的筆刷。Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them. 瀏覽器儲存空間無法使用;筆刷僅在本次工作階段有效。請保持此分頁開啟以保留它們。Saving brush presets… Keep this tab open until saving finishes. 正在儲存筆刷預設集… 請保持此分頁開啟,直到儲存完成。+ Reflect 反射+ Glow 光暈+ Negation 否定+ XOR XOR+ Color Burn (Paint.NET) 加深顏色 (Paint.NET)+ Color Dodge (Paint.NET) 加亮顏色 (Paint.NET)diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rsindex 67b41f284..7ba7a7f71 100644--- a/crates/ui-egui/src/layer_style.rs+++ b/crates/ui-egui/src/layer_style.rs@@ -1082,7 +1082,9 @@ fn blending_page(ui: &mut egui::Ui, p: &mut Value, names: &[String]) {ui.horizontal(|ui| {ui.label(RichText::new(tl!("Blend Mode")).color(t.text_dim));let mut cur = p.get("blend").and_then(Value::as_str).unwrap_or("Normal").to_string();- let opts: Vec<(String, &str)> = photocraft_color::BlendMode::LAYER_MODES.iter().map(|m| (m.label().to_string(), m.label())).collect();+ // Photoshop's modes, plus the layer's own Paint.NET mode when it has one (an imported .pdn).+ let own = photocraft_color::BlendMode::PAINT_NET_MODES.into_iter().find(|m| m.label() == cur);+ let opts: Vec<(String, &str)> = photocraft_color::BlendMode::LAYER_MODES.into_iter().chain(own).map(|m| (m.label().to_string(), m.label())).collect();if widgets::dropdown(ui, "fx-blend-blendingOptions", &mut cur, &opts, 150.0) {p["blend"] = json!(cur);}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 41634b0ad..47d4b137e 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -963,14 +963,19 @@ impl PhotocraftApp {return self.save_to(path);}let st = self.session.active().ok_or("no document")?;- // Suggest the file's own name if Save As can write its format, otherwise switch to .psd.+ // PDN imports default to our native format, which preserves Paint.NET's blend modes.+ // Other files keep their format when writable, otherwise switch to .psd.let ext = st.path.as_deref().and_then(|p| std::path::Path::new(p).extension()).map(|e| e.to_string_lossy().to_ascii_lowercase());let writable = ext.is_some_and(|e| {matches!(e.as_str(), photocraft_format::EXTENSION | "psd" | "psb") || photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write)});let suggested = match &st.path {Some(p) if writable => p.clone(),- p => std::path::Path::new(p.as_deref().unwrap_or(&st.doc.name)).with_extension("psd").to_string_lossy().into_owned(),+ p => {+ let source = p.as_deref().unwrap_or(&st.doc.name);+ let ext = if photocraft_engine::file_cmds::extension(source).as_deref() == Some("pdn") { "pcraft" } else { "psd" };+ std::path::Path::new(source).with_extension(ext).to_string_lossy().into_owned()+ }};let doc = st.doc.id;self.pick_save(&suggested, move |app, path| app.with_document(doc, |app| app.save_to(path)))diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 8f4eb8d29..c9a4f68c0 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -1572,8 +1572,11 @@ fn simple_lock_toggle(background: bool, l: &Layer) -> (String, Value) {("layer.setProps".into(), json!({"layer": l.id.0, "locks": locks}))}-fn blend_options(groups: bool) -> Vec<(BlendMode, &'static str)> {- std::iter::once(BlendMode::PassThrough).filter(|_| groups).chain(BlendMode::LAYER_MODES).map(|m| (m, m.label())).collect()+/// The Layers panel's blend modes: Photoshop's, plus the layer's own Paint.NET mode when it has one+/// (an imported `.pdn`), so the menu matches Photoshop's for every other layer.+fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static str)> {+ let own = Some(current).filter(|m| !m.has_psd_equivalent());+ std::iter::once(BlendMode::PassThrough).filter(|_| groups).chain(BlendMode::LAYER_MODES).chain(own).map(|m| (m, m.label())).collect()}/// Scroll the Layers panel while holding a layer drag over its top/bottom edge or past them.@@ -1654,7 +1657,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let opacity_label = if t.pro { tl!("Opacity:") } else { tl!("Opacity") };let right = (body_text_width(ui, opacity_label) + LAYER_PCT_W + 2.0 * ui.spacing().item_spacing.x + 16.0).max(150.0);let w = ui.available_width() - right;- let (chosen, hovered) = widgets::dropdown_wheel_hovered(ui, "blend", &mut m, &blend_options(l.is_group()), w.max(100.0));+ let (chosen, hovered) = widgets::dropdown_wheel_hovered(ui, "blend", &mut m, &blend_options(l.is_group(), l.blend), w.max(100.0));// One step per choice: a click, an arrow key or each wheel notch (#1747).for m in &chosen {actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "blend": m.label()})));diff --git a/docs/pdn.md b/docs/pdn.mdnew file mode 100644index 000000000..dea41eb14--- /dev/null+++ b/docs/pdn.md@@ -0,0 +1,54 @@+# Paint.NET documents++PhotoCraft opens PDN3 `.pdn` files natively, without Paint.NET, Python, .NET or an external+converter. File › Open, recent files, drops, the CLI and automation use the shared importer.+The browser file picker also accepts `.pdn`.++Each bitmap layer remains editable. Layer order, Unicode names, visibility, opacity and pixel+alpha are retained. Painting, masks, transforms, reordering, duplication and undo use the same+commands as other pixel layers. All 14 PDN3 blend modes are supported on the CPU and GPU.+Reflect, Glow, Negation and XOR have no Photoshop equivalent, and Color Burn and Color Dodge have+separate Paint.NET variants because their edge cases differ. The blend menus stay Photoshop's: a+layer that uses one of these six modes lists its own mode after Photoshop's, and other layers don't+show them.++PDN support is **import only**. Save opens Save As and suggests `.pcraft`, which preserves the+layers and every blend mode. Exporting as `.pdn` fails with an explanatory error. PSD cannot+represent six Paint.NET variants; exporting those as PSD reports that their blending was+changed to Normal. Use `.pcraft` for continued editing, and PNG for a flattened rendering.++The reader supports PDN3's typed NRBF objects, both numeric and older blend-operation records,+BGRA32 surfaces with padded rows, shared pixel memory, and gzip or raw numbered pixel chunks.+It validates references, dimensions, strides, counts, chunk ranges and gzip checksums. Metadata+object nesting is capped at 64, layers at 1024 and total decoded pixel memory at 1 GiB. Imports+can be cancelled while parsing, decompressing or copying pixels. Unsupported layouts and+versions return errors. Paint.NET document metadata (including print resolution and profiles)+is currently omitted; nonempty user metadata produces an import warning. Layer data is preserved.++## Verification++Synthetic unit tests exercise every blend mode, names, hidden layers, opacity, alpha, row+padding, reversed chunks, old/new mode records, native saves, cancellation and malformed data.+The GPU parity tests include the additional modes. Local real-file checks are opt-in:++```sh+PDN_TEST_DIR=/path/to/pdn-and-png-exports cargo test -p photocraft-io --test pdn_corpus -- --ignored --nocapture+PDN_TEST_FILE=/path/to/layered.pdn cargo test -p photocraft-engine --test pdn -- --ignored+```++Each PDN in `PDN_TEST_DIR` needs a corresponding `.png` export with the same basename. The+test checks pixels against that export and verifies layer preservation through `.pcraft`.+Keep real-file corpora outside the application repository.++The local Paint.NET 4.0.10 corpus (14 small texture documents, 1–8 layers) also matches its+embedded full-size previews within 2.142/255. Older Paint.NET rounded between layers; PhotoCraft+keeps floating-point precision, so layered composites are not necessarily byte-identical.+A supplied 5.x document (1280×720, 11 layers, header version `5.3.8488.42200`) passes editing,+painting, undo/redo and native-save checks. Its embedded 256×144 preview matches a Catmull–Rom+downsample of our rendering with mean error 0.418/255 and maximum error 8/255. Its neighboring+PNG differs from the saved PDN preview, so it is unsuitable as a full-size rendering oracle.+These checks do not establish compatibility with every Paint.NET release.++Format references: [MS-NRBF](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nrbf/)+and the [pypdn reader](https://github.com/addisonElliott/pypdn/blob/master/pypdn/reader.py).+This reader implements the layout independently; it does not run .NET deserialization.diff --git a/docs/roadmap.md b/docs/roadmap.mdindex 2a4307436..de8d08027 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -97,6 +97,7 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either| Menu wiring | 626/626 menu items dispatch a command (`parity.md`) | high but shallow | Says nothing about behaviour. || PSD fidelity (rendering) | Corpus oracle 115/170 (68%): 30 differ, 26 have no usable reference, 1 import error. 2026-10-07: io corpus 146/170, psd-tools corpus 236/309 (was 229: Advanced Blending knockouts), Photoshop oracles 132/258 | medium | Push to 170/170 under way (effects/strokes, multi-instance effects, 16/32-bit and colour modes, references for skipped files). || PSD round trip | 169/169 re-import identically; every adjustment layer and blend mode round-trips | high (within corpus) | Floors in `crates/io/tests/corpus.rs`; raise, never lower. Corpora: `cargo xtask corpus --all` (ours: https://github.com/storytold/photocraft-corpus). |+| Paint.NET import | 2026-10-09: 14/14 local PDN3 textures preserve editable layers exactly through `.pcraft` and render within 2.142/255 of full-size previews; a supplied 5.x document (1280×720, 11 layers) passes editing/history/native saves and matches its thumbnail within 0.418/255 mean; all 14 blend modes exercised synthetically | medium (limited corpus) | Import only; metadata omitted. More current-version files and full-size exports needed. See [PDN support](pdn.md). || Smart filters / text / effect shapes in PSDs | Measured on our Photoshop-authored set (https://github.com/storytold/photocraft-corpus, `corpus/photoshop`, 258 files): see the per-group floors in `crates/io/tests/corpus.rs` and `crates/engine/tests/photoshop_oracles.rs`. Smart objects and smart filters now survive PSD save and open (41 corpus files, 206 smart objects, round trip strict; Photoshop opens our exports with live filters); re-rendering Photoshop's smart filters with ours matches 5/30 (was 1/30) | low–medium | Remaining re-render gaps are filter maths (Gaussian/Motion Blur, Unsharp Mask, Emboss, Add Noise RNG) and bicubic placement. || Core editing (layers, masks, selections, adjustments, filters, transforms) | Broad engine coverage; many interaction bugs fixed after 0.2.0 (adjustment dialogs, Curves, crop, Move/Transform modifiers, gesture origin) | medium | Fixes not yet user-validated. || UI / UX polish | Shortcut audit 214 → 0 failures; dock, Layers rows and menus reworked; first visual-QA sweep found 14 defects (#147–#157). 2026-10-07: the keyboard-only shortcuts with no menu item (⌥[ ⌥] ⌥, ⌥. layer navigation, ⇧⌥[ ⇧⌥] to extend the selection, 1–0 for opacity and ⇧ for flow or fill, ⇧[ ⇧] hardness, ⌥⌘T to transform a copy and ⌥⇧⌘T to step and repeat), ⌥-click colour sampling with painting tools, double-click a Layers row for Layer Style, File › New from Clipboard, a centred main window and remembered Liquify settings (#352, #417, #350, #368, #419, #418). 2026-10-09: canvas zoom is physical at any display scale — 100% is one document pixel per physical display pixel, and every screen-space overlay, cursor, scrollbar, navigator and fit follows it (#1943) | low–medium | Needs recurring visual QA with realistic documents. |diff --git a/packaging/linux/ai.storyteller.photocraft.desktop b/packaging/linux/ai.storyteller.photocraft.desktopindex 10292206b..f491187d7 100644--- a/packaging/linux/ai.storyteller.photocraft.desktop+++ b/packaging/linux/ai.storyteller.photocraft.desktop@@ -12,4 +12,4 @@ StartupNotify=falseStartupWMClass=photocraftCategories=Graphics;2DGraphics;RasterGraphics;Photography;Keywords=photo;image;editor;psd;layers;retouch;paint;-MimeType=application/x-photocraft;image/vnd.adobe.photoshop;image/x-psd;image/x-psb;image/png;image/jpeg;image/tiff;image/webp;image/gif;image/bmp;image/x-tga;image/x-icon;image/vnd.microsoft.icon;image/x-portable-anymap;image/x-portable-bitmap;image/x-portable-graymap;image/x-portable-pixmap;image/x-exr;image/vnd.radiance;image/avif;image/qoi;+MimeType=application/x-photocraft;image/x-paintnet;image/vnd.adobe.photoshop;image/x-psd;image/x-psb;image/png;image/jpeg;image/tiff;image/webp;image/gif;image/bmp;image/x-tga;image/x-icon;image/vnd.microsoft.icon;image/x-portable-anymap;image/x-portable-bitmap;image/x-portable-graymap;image/x-portable-pixmap;image/x-exr;image/vnd.radiance;image/avif;image/qoi;diff --git a/packaging/linux/ai.storyteller.photocraft.metainfo.xml.in b/packaging/linux/ai.storyteller.photocraft.metainfo.xml.inindex 6bb2bfe89..0282e0f39 100644--- a/packaging/linux/ai.storyteller.photocraft.metainfo.xml.in+++ b/packaging/linux/ai.storyteller.photocraft.metainfo.xml.in@@ -62,6 +62,7 @@<provides><binary>photocraft</binary><mediatype>application/x-photocraft</mediatype>+ <mediatype>image/x-paintnet</mediatype><mediatype>image/vnd.adobe.photoshop</mediatype><mediatype>image/x-psb</mediatype></provides>diff --git a/packaging/linux/ai.storyteller.photocraft.mime.xml b/packaging/linux/ai.storyteller.photocraft.mime.xmlindex a31429762..d7c935a87 100644--- a/packaging/linux/ai.storyteller.photocraft.mime.xml+++ b/packaging/linux/ai.storyteller.photocraft.mime.xml@@ -24,4 +24,12 @@</magic><glob pattern="*.qoi"/></mime-type>+ <mime-type type="image/x-paintnet">+ <comment>Paint.NET document</comment>+ <generic-icon name="image-x-generic"/>+ <magic priority="50">+ <match type="string" value="PDN3" offset="0"/>+ </magic>+ <glob pattern="*.pdn"/>+ </mime-type></mime-info>diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.inindex 92e9fc5a3..e927d73e6 100644--- a/packaging/macos/Info.plist.in+++ b/packaging/macos/Info.plist.in@@ -72,6 +72,21 @@<!-- Types macOS may not know; the system's own declaration wins when it has one. --><key>UTImportedTypeDeclarations</key><array>+ <dict>+ <key>UTTypeIdentifier</key>+ <string>ai.storyteller.photocraft.pdn</string>+ <key>UTTypeDescription</key>+ <string>Paint.NET Document</string>+ <key>UTTypeConformsTo</key>+ <array><string>public.data</string><string>public.image</string></array>+ <key>UTTypeTagSpecification</key>+ <dict>+ <key>public.filename-extension</key>+ <array><string>pdn</string></array>+ <key>public.mime-type</key>+ <array><string>image/x-paintnet</string></array>+ </dict>+ </dict><dict><key>UTTypeIdentifier</key><string>com.adobe.photoshop-large-image</string>@@ -155,6 +170,7 @@<string>public.radiance</string><string>public.avif</string><string>ai.storyteller.photocraft.qoi</string>+ <string>ai.storyteller.photocraft.pdn</string></array></dict></array>diff --git a/packaging/windows/photocraft.wxs b/packaging/windows/photocraft.wxsindex 0be10a566..847baf0f7 100644--- a/packaging/windows/photocraft.wxs+++ b/packaging/windows/photocraft.wxs@@ -101,6 +101,7 @@<RegistryValue Root="HKLM" Key="Software\Classes\Photocraft.Image\shell\open\command" Value=""[#PhotocraftExe]" "%1"" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\.psd\OpenWithProgids" Name="Photocraft.PhotoshopDocument" Value="" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\.psb\OpenWithProgids" Name="Photocraft.PhotoshopDocument" Value="" Type="string" />+ <RegistryValue Root="HKLM" Key="Software\Classes\.pdn\OpenWithProgids" Name="Photocraft.Image" Value="" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\.png\OpenWithProgids" Name="Photocraft.Image" Value="" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\.jpg\OpenWithProgids" Name="Photocraft.Image" Value="" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\.jpeg\OpenWithProgids" Name="Photocraft.Image" Value="" Type="string" />@@ -122,6 +123,7 @@<RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".pcraft" Value="" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".psd" Value="" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".psb" Value="" Type="string" />+ <RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".pdn" Value="" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".png" Value="" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".jpg" Value="" Type="string" /><RegistryValue Root="HKLM" Key="Software\Classes\Applications\photocraft.exe\SupportedTypes" Name=".jpeg" Value="" Type="string" />