PhotoCraft: An open-source, photo editor written by scratch in pure Rust
PSD: keep guide resources 1092/1097 only while they match the guides (#5966)
Bram Heerinkf49564d281bf
diff --git a/crates/io/src/guides_map.rs b/crates/io/src/guides_map.rsnew file mode 100644index 000000000..6137011e2--- /dev/null+++ b/crates/io/src/guides_map.rs@@ -0,0 +1,157 @@+//! Guides ⇄ PSD beyond image resource 1032.+//!+//! Photoshop writes two undocumented resources next to 1032 (Grid and Guides), layout+//! inferred from the psd-tools, ag-psd and Photoshop-authored corpora (#5965):+//!+//! * 1092, Grid and Guides version 2: `u32` version 2, `u32` horizontal and vertical grid+//! cycle (576 = 18 px in 1/32 px, as in 1032), `u32` count, then per guide 9 bytes: `i32`+//! position in 1/32 px, `u8` direction (0 vertical, 1 horizontal), one `u8` that is always 0+//! in the corpora, and the guide's colour as `u8` R, G, B. In every corpus file its guides+//! equal 1032's, in the same order.+//! * 1097: `u32` count (1092's), then per guide a length-prefixed ASCII GUID, a `u32` 0 and a+//! second length-prefixed GUID, always all zeros.+//!+//! Import takes the guides' own colours from 1092 (a guide in Photoshop's default colour keeps+//! following the preference colour). Export keeps both resources only while 1092 still+//! describes the document's guides and colours; otherwise it leaves both out, so the file+//! carries 1032 alone, as Photoshop files before version 2 did (#5966).++use photocraft_doc::{Document, Guides};++/// Grid and Guides, version 2 (positions, directions and colours).+pub const GUIDES_V2: u16 = 1092;+/// One GUID per guide, in 1092's order.+pub const GUIDE_IDS: u16 = 1097;+/// Photoshop's default guide colour (Cyan, `#4affff`), which 1092 also stores for guides+/// that use the preference colour.+pub const DEFAULT_GUIDE_RGB: [u8; 3] = [0x4a, 0xff, 0xff];++/// One guide of a 1092 resource.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub struct GuideV2 {+ /// Position in 1/32 px.+ pub location: i32,+ pub vertical: bool,+ pub rgb: [u8; 3],+}++fn be_u32(data: &[u8], at: usize) -> Option<u32> {+ let b = data.get(at..at.checked_add(4)?)?;+ Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))+}++/// The guides of a 1092 resource, or `None` when it is not version 2 or is cut short.+pub fn parse_v2(data: &[u8]) -> Option<Vec<GuideV2>> {+ if be_u32(data, 0)? != 2 {+ return None;+ }+ let count = usize::try_from(be_u32(data, 12)?).ok()?;+ // Each guide takes 9 bytes: a count the data can't hold is not a 1092 we understand.+ if count > data.len().saturating_sub(16) / 9 {+ return None;+ }+ (0..count)+ .map(|i| {+ let at = 16 + i * 9;+ let g = data.get(at..at + 9)?;+ Some(GuideV2 { location: i32::from_be_bytes([g[0], g[1], g[2], g[3]]), vertical: g[4] != 1, rgb: [g[6], g[7], g[8]] })+ })+ .collect()+}++/// The number of entries a 1097 resource declares.+pub fn ids_count(data: &[u8]) -> Option<u32> {+ be_u32(data, 0)+}++/// The document's guides as 1092 would store them, sorted.+fn expected(guides: &Guides) -> Vec<GuideV2> {+ let mut v: Vec<GuideV2> = [(&guides.vertical, true), (&guides.horizontal, false)]+ .into_iter()+ .flat_map(|(list, vertical)| {+ list.iter().map(move |&p| GuideV2 { location: (p * 32.0).round() as i32, vertical, rgb: guides.color(vertical, p).unwrap_or(DEFAULT_GUIDE_RGB) })+ })+ .collect();+ v.sort();+ v+}++/// Whether an imported 1092 still describes the document's guides: the same positions,+/// directions and colours, in any order.+pub fn describes(doc: &Document, data: &[u8]) -> bool {+ let Some(mut stored) = parse_v2(data) else { return false };+ stored.sort();+ stored == expected(&doc.guides)+}++/// Whether to write back an imported 1092 or 1097: only while 1092 describes the guides+/// (and, for 1097, holds as many entries as 1092).+pub fn keep_resource(doc: &Document, id: u16, data: &[u8]) -> bool {+ match id {+ GUIDES_V2 => describes(doc, data),+ GUIDE_IDS => {+ let v2 = doc.metadata.psd_resources.iter().find(|(rid, _, _)| *rid == GUIDES_V2);+ v2.is_some_and(|(_, _, d)| describes(doc, d) && parse_v2(d).map(|g| g.len()).and_then(|n| u32::try_from(n).ok()) == ids_count(data))+ }+ _ => true,+ }+}++/// Gives the document's guides the colours an imported 1092 stores. Only guides that 1032+/// also has are coloured, and Photoshop's default colour is left to the preference.+pub fn apply_colors(doc: &mut Document) {+ let Some(stored) = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == GUIDES_V2).and_then(|(_, _, d)| parse_v2(d)) else {+ return;+ };+ for g in stored {+ if g.rgb == DEFAULT_GUIDE_RGB {+ continue;+ }+ let pos = f64::from(g.location) / 32.0;+ let list = if g.vertical { &doc.guides.vertical } else { &doc.guides.horizontal };+ if list.contains(&pos) {+ doc.guides.set_color(g.vertical, pos, Some(g.rgb));+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn v2(guides: &[(i32, u8, [u8; 3])]) -> Vec<u8> {+ let mut v = Vec::new();+ for n in [2u32, 576, 576, guides.len() as u32] {+ v.extend_from_slice(&n.to_be_bytes());+ }+ for (loc, dir, rgb) in guides {+ v.extend_from_slice(&loc.to_be_bytes());+ v.extend_from_slice(&[*dir, 0]);+ v.extend_from_slice(rgb);+ }+ v+ }++ #[test]+ fn parses_corpus_layout() {+ // clipping-mask4.psd (psd-tools): one vertical and one horizontal guide at 16 px.+ let d = v2(&[(512, 0, DEFAULT_GUIDE_RGB), (512, 1, DEFAULT_GUIDE_RGB)]);+ let g = parse_v2(&d).unwrap();+ assert_eq!(g.len(), 2);+ assert!(g[0].vertical && !g[1].vertical);+ assert_eq!(g[1].location, 512);+ }++ #[test]+ fn rejects_other_versions_and_short_or_hostile_data() {+ let mut d = v2(&[(512, 0, DEFAULT_GUIDE_RGB)]);+ assert!(parse_v2(&d[..d.len() - 1]).is_none());+ d[3] = 1;+ assert!(parse_v2(&d).is_none());+ let mut huge = v2(&[]);+ huge[12..16].copy_from_slice(&u32::MAX.to_be_bytes());+ assert!(parse_v2(&huge).is_none());+ assert!(parse_v2(&[]).is_none());+ assert!(ids_count(&[0, 0]).is_none());+ }+}diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex 378122986..646a82436 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -44,6 +44,7 @@ pub mod effects_map;pub mod exr_parts;mod flat;mod gradient_bake;+pub mod guides_map;pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient};mod kra;pub mod linked;diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 8ba30d83c..8d99a9d89 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -1253,6 +1253,10 @@ pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> boif !crate::annotations_map::keep_resource(doc, id) {return false;}+ // Guides v2 and guide GUIDs: only while they still describe the document's guides.+ if !crate::guides_map::keep_resource(doc, id, data) {+ return false;+ }// A preserved clipping-path resource is only valid while it names the current one.if id == crate::vector_map::CLIPPING_PATH {let n = usize::from(data.first().copied().unwrap_or(0));diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex c20c1b7fe..ae4e15d9b 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -830,6 +830,7 @@ pub(crate) fn psd_to_document_decoded(id => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone()))),}}+ crate::guides_map::apply_colors(&mut doc);for b in &file.global_blocks {doc.metadata.psd_global_blocks.push((b.signature, b.key, Arc::new(b.data.clone())));}diff --git a/crates/io/tests/guides_v2.rs b/crates/io/tests/guides_v2.rsnew file mode 100644index 000000000..73884f00f--- /dev/null+++ b/crates/io/tests/guides_v2.rs@@ -0,0 +1,128 @@+//! Image resources 1092 (guides with colours) and 1097 (guide GUIDs) next to 1032 (#5966).++use photocraft_io::guides_map::{DEFAULT_GUIDE_RGB, GUIDE_IDS, GUIDES_V2};+use photocraft_io::*;+use photocraft_psd::testgen;+use photocraft_psd::{Compression, ImageResource, PsdFile, Version};++const RED: [u8; 3] = [0xff, 0x00, 0x00];++type Edit = fn(&mut photocraft_doc::Document);++fn guides_v1(guides: &[(i32, u8)]) -> Vec<u8> {+ let mut v = Vec::new();+ for n in [1u32, 576, 576, guides.len() as u32] {+ v.extend_from_slice(&n.to_be_bytes());+ }+ for (loc, dir) in guides {+ v.extend_from_slice(&loc.to_be_bytes());+ v.push(*dir);+ }+ v+}++fn guides_v2(guides: &[(i32, u8, [u8; 3])]) -> Vec<u8> {+ let mut v = Vec::new();+ for n in [2u32, 576, 576, guides.len() as u32] {+ v.extend_from_slice(&n.to_be_bytes());+ }+ for (loc, dir, rgb) in guides {+ v.extend_from_slice(&loc.to_be_bytes());+ v.extend_from_slice(&[*dir, 0]);+ v.extend_from_slice(rgb);+ }+ v+}++fn guide_ids(n: u32) -> Vec<u8> {+ let mut v = n.to_be_bytes().to_vec();+ for i in 0..n {+ let id = format!("0000000{i}-1111-2222-3333-444444444444");+ let zero = "00000000-0000-0000-0000-000000000000";+ v.extend_from_slice(&36u32.to_be_bytes());+ v.extend_from_slice(id.as_bytes());+ v.extend_from_slice(&0u32.to_be_bytes());+ v.extend_from_slice(&36u32.to_be_bytes());+ v.extend_from_slice(zero.as_bytes());+ }+ v+}++/// A file as Photoshop writes it: a vertical guide at 16 px in the default colour and a red+/// horizontal one at 10 px, in 1032, 1092 and 1097.+fn photoshop_file() -> PsdFile {+ let mut f = testgen::small(Version::Psd, Compression::Raw);+ f.resources.push(ImageResource::new(1032, guides_v1(&[(512, 0), (320, 1)])));+ f.resources.push(ImageResource::new(GUIDES_V2, guides_v2(&[(512, 0, DEFAULT_GUIDE_RGB), (320, 1, RED)])));+ f.resources.push(ImageResource::new(GUIDE_IDS, guide_ids(2)));+ f+}++fn resource(f: &PsdFile, id: u16) -> Option<&[u8]> {+ f.resources.iter().find(|r| r.id == id).map(|r| r.data.as_slice())+}++#[test]+fn colours_come_from_guides_v2() {+ let (d, _) = psd_to_document(&photoshop_file());+ assert_eq!(d.guides.vertical, [16.0]);+ assert_eq!(d.guides.horizontal, [10.0]);+ assert_eq!(d.guides.color(false, 10.0), Some(RED));+ // The default colour stays with the preference.+ assert_eq!(d.guides.color(true, 16.0), None);+}++#[test]+fn unchanged_guides_keep_both_resources_byte_exact() {+ let f = photoshop_file();+ let (d, _) = psd_to_document(&f);+ let out = document_to_psd(&d);+ assert_eq!(resource(&out, GUIDES_V2), resource(&f, GUIDES_V2));+ assert_eq!(resource(&out, GUIDE_IDS), resource(&f, GUIDE_IDS));+}++#[test]+fn edited_guides_drop_both_resources() {+ let (base, _) = psd_to_document(&photoshop_file());+ let edits: [(&str, Edit); 4] = [+ ("clear", |d| d.guides = Default::default()),+ ("add", |d| d.guides.horizontal.push(40.0)),+ ("move", |d| {+ d.guides.vertical[0] = 20.0;+ }),+ ("recolour", |d| d.guides.set_color(true, 16.0, Some(RED))),+ ];+ for (name, edit) in edits {+ let mut d = base.clone();+ edit(&mut d);+ let out = document_to_psd(&d);+ assert!(resource(&out, GUIDES_V2).is_none(), "{name}: stale 1092 written");+ assert!(resource(&out, GUIDE_IDS).is_none(), "{name}: stale 1097 written");+ let (back, _) = psd_to_document(&out);+ assert_eq!(back.guides.vertical, d.guides.vertical, "{name}");+ assert_eq!(back.guides.horizontal, d.guides.horizontal, "{name}");+ }+}++#[test]+fn mismatched_ids_or_malformed_v2_are_not_kept() {+ let mut f = photoshop_file();+ f.resources.retain(|r| r.id != GUIDE_IDS);+ f.resources.push(ImageResource::new(GUIDE_IDS, guide_ids(3)));+ let (d, _) = psd_to_document(&f);+ let out = document_to_psd(&d);+ assert!(resource(&out, GUIDES_V2).is_some());+ assert!(resource(&out, GUIDE_IDS).is_none());++ let mut f = photoshop_file();+ for r in &mut f.resources {+ if r.id == GUIDES_V2 {+ r.data.truncate(20);+ }+ }+ let (d, _) = psd_to_document(&f);+ assert_eq!(d.guides.color(false, 10.0), None);+ let out = document_to_psd(&d);+ assert!(resource(&out, GUIDES_V2).is_none());+ assert!(resource(&out, GUIDE_IDS).is_none());+}diff --git a/docs/file-format-parity.md b/docs/file-format-parity.mdindex b0771c4d6..5c362e922 100644--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.| Date | Change | Summary ||---|---|---|+| 2026-10-15 | minor | PSD guides: image resource 1092 (guides v2) gives guides their own colours on import; 1092 and 1097 (guide GUIDs) are written back only while they still describe the document's guides, so an edit no longer leaves Photoshop a stale second guide list (#5966) || 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 || 2026-10-13 | minor | Lossy DNG (compression 34892) decodes: 8-bit baseline JPEG tiles and strips, CFA and LinearRaw, partial edge tiles; the stored values take the normal levels and LinearizationTable (FILE-215-11, lossy DNG part) || 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 |