From 0f48dfacc8df498e0deed7b36035186a7281ab4d Mon Sep 17 00:00:00 2001 From: Hasan-Zayni Date: Sun, 25 Oct 2026 15:37:14 +0300 Subject: [PATCH 1/2] fix(io): import a Displace smart filter that names its map file without embedding it (#9162) Photoshop can save a Displace smart filter with only DspF, a path to the map file, and no embedded DspD map. Import required the embedded map, so such a filter became psd.unsupportedFilter and Replace Contents skipped it. It now imports as filter.distort.displace with the path as mapPath (read on re-render through the document path policy) and writes back unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/it/smart_psd.rs | 68 ++++++++++++++++++++++++ crates/io/src/displace_map.rs | 82 +++++++++++++++++++++++++---- 2 files changed, 141 insertions(+), 9 deletions(-) diff --git a/crates/engine/tests/it/smart_psd.rs b/crates/engine/tests/it/smart_psd.rs index 4aeda1519b3..542220f34b2 100644 --- a/crates/engine/tests/it/smart_psd.rs +++ b/crates/engine/tests/it/smart_psd.rs @@ -469,6 +469,74 @@ fn displace_psd_filter_renders_with_its_embedded_map() { } } +/// #9162: a Photoshop Displace smart filter that names its map file (`DspF`, a `Pth `) without +/// embedding it was skipped as "not supported" on Replace Contents. Opened from PSD, it now reads +/// that file and the replaced contents come out displaced. +#[test] +fn displace_psd_filter_with_only_a_map_path_renders_after_replace_contents() { + use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value}; + let dir = std::env::temp_dir().join(format!("pcraft-9162-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let png = |name: &str, size: (u32, u32), c: [f32; 4]| { + let d = Document::with_background( + "m", + photocraft_geom::Size::new(size.0, size.1), + photocraft_color::ColorMode::Rgb, + photocraft_color::SampleType::U8, + photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]), + ); + let path = dir.join(name); + std::fs::write(&path, photocraft_io::export(&d, "png", &Default::default()).unwrap().bytes).unwrap(); + path.to_str().unwrap().to_string() + }; + // Red is the horizontal map (full right), green the vertical one (about neutral), as in the + // issue's map. + let map = png("map.png", (12, 8), [1.0, 0.5, 0.5, 1.0]); + let design = png("design.png", (72, 52), [1.0, 0.0, 0.0, 1.0]); + // `DspF` as Photoshop writes a path: `txtu`, sizes (LE), UTF-16LE with a trailing NUL. + let units: Vec = map.encode_utf16().chain([0]).collect(); + let mut pth = b"txtu".to_vec(); + pth.extend((12 + 2 * units.len() as u32).to_le_bytes()); + pth.extend((units.len() as u32).to_le_bytes()); + pth.extend(units.iter().flat_map(|u| u.to_le_bytes())); + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let fltr = Descriptor::new("Dspl") + .with("HrzS", Value::Integer(10)) + .with("VrtS", Value::Integer(10)) + .with("DspM", e("DspM", "StrF")) + .with("UndA", e("UndA", "RptE")) + .with("DspF", Value::Path(pth)); + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Displace..."))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(1148416108)); + for depth in [8, 16, 32] { + let mut s = session(depth); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let id = photocraft_doc::LayerId(s.active().unwrap().active_layer.unwrap().0); + s.edit("displace", |doc, _| { + let LayerContent::Smart(sm) = &mut doc.layer_mut(id).unwrap().content else { panic!("smart") }; + sm.smart_filters.push(photocraft_io::smart_map::filter_from_item(&item)); + Ok(()) + }) + .unwrap(); + let psd = photocraft_io::export(&s.active().unwrap().doc, "psd", &Default::default()).unwrap().bytes; + // The issue's flow: open the PSD, Replace Contents of the smart object. + let mut s2 = Session::new(); + s2.add_document(photocraft_io::import("pc-displace-repro.psd", &psd).unwrap().document, None); + let (sid, _) = smart(&s2.active().unwrap().doc); + let out = s2.execute("layer.smartObjects.replaceContents", json!({"layer": sid, "path": design})).unwrap(); + assert_eq!(out["warnings"], json!([]), "depth {depth}"); + let cache = smart(&s2.active().unwrap().doc).1.cache.unwrap(); + // 10 % of 128 px at full map contrast: the design (x 8..80) moves 12.8 px left. + let alpha = |x: i32| cache.pixel(x, 30)[3]; + assert!(alpha(2) > 0.99 && alpha(75) < 0.01, "depth {depth}: {} {}", alpha(2), alpha(75)); + } + std::fs::remove_dir_all(&dir).ok(); +} + /// A Perspective Warp smart filter as Photoshop writes it (`perspectiveWarpTransform`: vertices, /// warped vertices and quads of vertex indices, document pixels) opens as /// `layer.smartObjects.perspectiveWarp` and re-renders warped instead of flat (#6268), and keeps diff --git a/crates/io/src/displace_map.rs b/crates/io/src/displace_map.rs index 48b34c4b010..b6253d0463a 100644 --- a/crates/io/src/displace_map.rs +++ b/crates/io/src/displace_map.rs @@ -10,10 +10,14 @@ //! width * height bytes (horizontal map, vertical map), then padding //! ``` //! +//! Photoshop does not always embed the map: a Displace can carry only `DspF`, a `Pth ` to the map +//! file (ag-psd models the filter with no `DspD` at all), and Photoshop reads that file again. Such +//! a filter imports with the path as its `mapPath`, read on re-render like any stored path (#9162). +//! //! The whole `filterFX` item (with the map) is kept verbatim in the params as a template //! ([`TEMPLATE_KEY`]), so the filter re-renders, survives `.pcraft` and is written back to PSD -//! with only the editable settings replaced. Anything else (another mode, a missing or truncated -//! map, unknown enum values) stays an opaque [`super::UNSUPPORTED_FILTER`]. +//! with only the editable settings replaced. Anything else (another mode, a truncated map, no map +//! and no readable path, unknown enum values) stays an opaque [`super::UNSUPPORTED_FILTER`]. use std::sync::Arc; @@ -80,6 +84,21 @@ fn fltr_map(item: &Descriptor) -> Option> { } } +/// The map file `DspF` names, when it is a `Pth `: `txtu`, u32 LE size, u32 LE count of UTF-16 +/// units, then the UTF-16LE path ending in NUL (ag-psd's layout). A Mac alias (`alis`) is not +/// decoded. +fn fltr_path(item: &Descriptor) -> Option { + let Value::Path(b) = get_desc(item, "Fltr")?.get("DspF")? else { return None }; + if b.get(..4)? != b"txtu" { + return None; + } + let units = usize::try_from(u32::from_le_bytes(b.get(8..12)?.try_into().ok()?)).ok()?; + let text = b.get(12..12usize.checked_add(units.checked_mul(2)?)?)?; + let path = String::from_utf16(&text.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect::>()).ok()?; + let path = path.trim_end_matches('\0'); + (!path.is_empty()).then(|| path.to_string()) +} + fn lookup<'a>(table: &[(&[u8], &'a str)], v: &[u8]) -> Option<&'a str> { table.iter().find(|(k, _)| *k == v).map(|(_, s)| *s) } @@ -95,14 +114,17 @@ fn settings(f: &Descriptor) -> Option { })) } -/// `filter.distort.displace` params for a Displace item with an embedded map. +/// `filter.distort.displace` params for a Displace item with an embedded map, or else a map file +/// path (then `mapPath`). pub(super) fn import_params(item: &Descriptor) -> Option { let f = get_desc(item, "Fltr")?; if !f.class_id.is(CLASS) { return None; } let mut params = settings(f)?; - fltr_map(item)?; + if fltr_map(item).is_none() { + params.as_object_mut()?.insert("mapPath".into(), json!(fltr_path(item)?)); + } // Neutral blending in the template: the model's own fields replace it on export. let mut template = item.clone(); let neutral = SmartFilter { command: String::new(), params: J::Null, blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true }; @@ -112,7 +134,7 @@ pub(super) fn import_params(item: &Descriptor) -> Option { Some(params) } -/// The template item of `params`, checked to be a Displace filter with a readable map. +/// The template item of `params`, checked to be a Displace filter with a readable map or map path. fn template(params: &J) -> Result { let raw = params.get(TEMPLATE_KEY).ok_or("a Displace map from a file or document is not written to PSD")?; let raw = raw.as_str().ok_or("the Displace PSD data must be hex text")?; @@ -121,8 +143,8 @@ fn template(params: &J) -> Result { } let bytes = from_hex(raw).ok_or("the Displace PSD data is not valid hex")?; let item = Descriptor::from_bytes(&bytes).map_err(|e| format!("the Displace PSD data is unreadable ({e})"))?; - if !item.class_id.is("filterFX") || int(&item, "filterID") != Some(FILTER_ID) || fltr_map(&item).is_none() { - return Err("the Displace PSD data is not a Displace filter with an embedded map".into()); + if !item.class_id.is("filterFX") || int(&item, "filterID") != Some(FILTER_ID) || (fltr_map(&item).is_none() && fltr_path(&item).is_none()) { + return Err("the Displace PSD data is not a Displace filter with an embedded map or map file".into()); } Ok(item) } @@ -130,10 +152,12 @@ fn template(params: &J) -> Result { /// The `filterFXList` item: the template with the current scales, fit and undefined areas. pub(super) fn export_item(params: &J) -> Result { let object = params.as_object().ok_or("Displace parameters must be an object")?; - if let Some(k) = object.keys().find(|k| !super::is_meta(k) && !["horizontal", "vertical", "fit", "undefinedAreas"].contains(&k.as_str())) { + let mut item = template(params)?; + // The `mapPath` imported from the template's own `DspF` is already in it; another one isn't. + let own_path = |k: &str| k == "mapPath" && params.get(k).and_then(J::as_str) == fltr_path(&item).as_deref(); + if let Some(k) = object.keys().find(|k| !super::is_meta(k) && !own_path(k) && !["horizontal", "vertical", "fit", "undefinedAreas"].contains(&k.as_str())) { return Err(format!("Displace setting `{k}` has no PSD equivalent next to its embedded map")); } - let mut item = template(params)?; let mut f = get_desc(&item, "Fltr").ok_or("the Displace PSD data has no filter")?.clone(); let scale = |k: &str, d: f64| -> Result { let v = params.get(k).map_or(Some(d), J::as_f64).filter(|v| v.is_finite()).ok_or(format!("Displace `{k}` must be a number"))?; @@ -385,6 +409,46 @@ mod tests { } } + /// A `Pth ` value as ag-psd reads it: `txtu`, sizes (LE), UTF-16LE path with a trailing NUL. + fn pth(path: &str) -> Value { + let units: Vec = path.encode_utf16().chain([0]).collect(); + let mut b = b"txtu".to_vec(); + b.extend((12 + 2 * units.len() as u32).to_le_bytes()); + b.extend((units.len() as u32).to_le_bytes()); + b.extend(units.iter().flat_map(|u| u.to_le_bytes())); + Value::Path(b) + } + + /// #9162: Photoshop can save a Displace with only `DspF`, the map file's path, and no + /// embedded map. It imports as Displace reading that file, and writes back unchanged. + #[test] + fn a_map_named_only_by_its_path_imports_as_map_path() { + let with_file = |file: Value| { + let mut i = item(Vec::new()); + let mut f = get_desc(&i, "Fltr").unwrap().clone(); + f.items.retain(|(k, _)| !k.is(MAP_KEY)); + set(&mut f, "DspF", file); + set(&mut i, "Fltr", Value::Descriptor(f)); + i + }; + let src = with_file(pth("C:\\maps\\repro-map.psd")); + let f = filter_from_item(&src); + assert_eq!(f.command, COMMAND); + assert_eq!(f.params["mapPath"], json!("C:\\maps\\repro-map.psd")); + assert!(embedded_map(&f.params).is_none()); + assert_eq!(item_for_filter(&f).unwrap(), src, "written back as it was"); + let mut moved = f.clone(); + moved.params["mapPath"] = json!("/elsewhere/map.png"); + assert!(item_for_filter(&moved).is_err(), "another map path has no place in the template"); + // Not a path we can read: kept opaque, as before. + for bad in + [Value::Path(b"txtu".to_vec()), Value::Path(b"abcd\0\0\0\0\x02\0\0\0a\0\0\0".to_vec()), Value::Path(b"txtu\0\0\0\0\x09\0\0\0a\0".to_vec()), pth("")] + { + let src = with_file(bad); + assert_eq!(filter_from_item(&src).command, UNSUPPORTED_FILTER); + } + } + #[test] fn bad_exports_report_errors() { let ok = filter_from_item(&item(tdta(2, 2, |_| 0, |_| 0, 0))).params; From 4bab657cd4fb4a91ced44d3721e63a002ca5068c Mon Sep 17 00:00:00 2001 From: Hasan-Zayni Date: Sun, 25 Oct 2026 21:41:51 +0300 Subject: [PATCH 2/2] fix(io): trust a Displace map path only when it is well formed and nothing is embedded Review follow-ups on #9162: - a `txtu` path record must have a size of 12 + 2 * units matching its length and end in one NUL; otherwise the filter stays opaque. - the DspF path is used only when no DspD is embedded, so a damaged embedded map stays opaque instead of falling back to the path. - a path-only template writes to PSD only with its own mapPath, so the exported PSD never names a map the render did not read. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/displace_map.rs | 71 ++++++++++++++++++++++++++++------- 1 file changed, 57 insertions(+), 14 deletions(-) diff --git a/crates/io/src/displace_map.rs b/crates/io/src/displace_map.rs index b6253d0463a..792c8e72df1 100644 --- a/crates/io/src/displace_map.rs +++ b/crates/io/src/displace_map.rs @@ -84,19 +84,33 @@ fn fltr_map(item: &Descriptor) -> Option> { } } -/// The map file `DspF` names, when it is a `Pth `: `txtu`, u32 LE size, u32 LE count of UTF-16 -/// units, then the UTF-16LE path ending in NUL (ag-psd's layout). A Mac alias (`alis`) is not -/// decoded. +/// The map file `DspF` names, when it is a `Pth `: `txtu`, u32 LE total size (`12 + 2 * units`), +/// u32 LE count of UTF-16 units, then the UTF-16LE path ending in one NUL (ag-psd's layout). A +/// record whose size disagrees with its units, or that lacks the NUL, is not trusted as a path. A +/// Mac alias (`alis`) is not decoded. fn fltr_path(item: &Descriptor) -> Option { let Value::Path(b) = get_desc(item, "Fltr")?.get("DspF")? else { return None }; + let u32_at = |i: usize| usize::try_from(u32::from_le_bytes(b.get(i..i.checked_add(4)?)?.try_into().ok()?)).ok(); if b.get(..4)? != b"txtu" { return None; } - let units = usize::try_from(u32::from_le_bytes(b.get(8..12)?.try_into().ok()?)).ok()?; - let text = b.get(12..12usize.checked_add(units.checked_mul(2)?)?)?; - let path = String::from_utf16(&text.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect::>()).ok()?; - let path = path.trim_end_matches('\0'); - (!path.is_empty()).then(|| path.to_string()) + let (size, units) = (u32_at(4)?, u32_at(8)?); + if size != 12usize.checked_add(units.checked_mul(2)?)? || b.len() != size { + return None; + } + let text: Vec = b.get(12..)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let (&0, path) = text.split_last()? else { return None }; + let path = String::from_utf16(path).ok()?; + (!path.is_empty() && !path.contains('\0')).then_some(path) +} + +/// The `DspF` path a Displace reads its map from, only when no `DspD` is embedded at all: a +/// damaged embedded map keeps the filter opaque rather than falling back to the path. +fn path_only(item: &Descriptor) -> Option { + if get_desc(item, "Fltr")?.get(MAP_KEY).is_some() { + return None; + } + fltr_path(item) } fn lookup<'a>(table: &[(&[u8], &'a str)], v: &[u8]) -> Option<&'a str> { @@ -123,7 +137,7 @@ pub(super) fn import_params(item: &Descriptor) -> Option { } let mut params = settings(f)?; if fltr_map(item).is_none() { - params.as_object_mut()?.insert("mapPath".into(), json!(fltr_path(item)?)); + params.as_object_mut()?.insert("mapPath".into(), json!(path_only(item)?)); } // Neutral blending in the template: the model's own fields replace it on export. let mut template = item.clone(); @@ -143,7 +157,7 @@ fn template(params: &J) -> Result { } let bytes = from_hex(raw).ok_or("the Displace PSD data is not valid hex")?; let item = Descriptor::from_bytes(&bytes).map_err(|e| format!("the Displace PSD data is unreadable ({e})"))?; - if !item.class_id.is("filterFX") || int(&item, "filterID") != Some(FILTER_ID) || (fltr_map(&item).is_none() && fltr_path(&item).is_none()) { + if !item.class_id.is("filterFX") || int(&item, "filterID") != Some(FILTER_ID) || (fltr_map(&item).is_none() && path_only(&item).is_none()) { return Err("the Displace PSD data is not a Displace filter with an embedded map or map file".into()); } Ok(item) @@ -154,7 +168,13 @@ pub(super) fn export_item(params: &J) -> Result { let object = params.as_object().ok_or("Displace parameters must be an object")?; let mut item = template(params)?; // The `mapPath` imported from the template's own `DspF` is already in it; another one isn't. - let own_path = |k: &str| k == "mapPath" && params.get(k).and_then(J::as_str) == fltr_path(&item).as_deref(); + // A path-only template also needs that `mapPath`: without it the filter renders no map while + // the PSD would still name one. + let template_path = path_only(&item); + if template_path.is_some() && params.get("mapPath").and_then(J::as_str) != template_path.as_deref() { + return Err("a Displace that reads its map from a file needs that file as `mapPath` to be written to PSD".into()); + } + let own_path = |k: &str| k == "mapPath" && template_path.is_some(); if let Some(k) = object.keys().find(|k| !super::is_meta(k) && !own_path(k) && !["horizontal", "vertical", "fit", "undefinedAreas"].contains(&k.as_str())) { return Err(format!("Displace setting `{k}` has no PSD equivalent next to its embedded map")); } @@ -440,13 +460,36 @@ mod tests { let mut moved = f.clone(); moved.params["mapPath"] = json!("/elsewhere/map.png"); assert!(item_for_filter(&moved).is_err(), "another map path has no place in the template"); + let mut no_path = f.clone(); + no_path.params.as_object_mut().unwrap().remove("mapPath"); + assert!(item_for_filter(&no_path).is_err(), "a path-only template needs its mapPath, or the PSD names a map the render never read"); + // A record whose size field disagrees with its units, or without the final NUL. + let mut wrong_size = pth("map.psd"); + if let Value::Path(b) = &mut wrong_size { + b[4] = b[4].wrapping_add(2); + } + let mut no_nul = b"txtu".to_vec(); + no_nul.extend(16u32.to_le_bytes()); + no_nul.extend(2u32.to_le_bytes()); + no_nul.extend([b'a', 0, b'b', 0]); // Not a path we can read: kept opaque, as before. - for bad in - [Value::Path(b"txtu".to_vec()), Value::Path(b"abcd\0\0\0\0\x02\0\0\0a\0\0\0".to_vec()), Value::Path(b"txtu\0\0\0\0\x09\0\0\0a\0".to_vec()), pth("")] - { + for bad in [ + Value::Path(b"txtu".to_vec()), + Value::Path(b"abcd\0\0\0\0\x02\0\0\0a\0\0\0".to_vec()), + Value::Path(b"txtu\0\0\0\0\x09\0\0\0a\0".to_vec()), + pth(""), + wrong_size, + Value::Path(no_nul), + ] { let src = with_file(bad); assert_eq!(filter_from_item(&src).command, UNSUPPORTED_FILTER); } + // A damaged embedded map is never replaced by a readable path. + let mut damaged = item(vec![0; 4]); + let mut fltr = get_desc(&damaged, "Fltr").unwrap().clone(); + set(&mut fltr, "DspF", pth("C:\\maps\\repro-map.psd")); + set(&mut damaged, "Fltr", Value::Descriptor(fltr)); + assert_eq!(filter_from_item(&damaged).command, UNSUPPORTED_FILTER); } #[test]