PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(io): read CS2 placed layers that carry only a PlLd block (#2465) (#4268)
Kartik Dwivedi0002d861eea5
diff --git a/crates/engine/tests/smart_psd.rs b/crates/engine/tests/smart_psd.rsindex 5f4c7bf6e..f7b86048b 100644--- a/crates/engine/tests/smart_psd.rs+++ b/crates/engine/tests/smart_psd.rs@@ -468,3 +468,150 @@ fn displace_psd_filter_renders_with_its_embedded_map() {}}}++/// A version-2 `liFD` item, as in Photoshop CS2's `lnkD` block: the fields every version has, and+/// none of the version 5–7 fields after the file data.+fn lifd_v2(f: &photocraft_io::linked::LinkedFile) -> Vec<u8> {+ let mut item = b"liFD".to_vec();+ item.extend_from_slice(&2u32.to_be_bytes());+ item.push(f.uuid.len() as u8);+ item.extend_from_slice(f.uuid.as_bytes());+ let name: Vec<u16> = f.file_name.encode_utf16().collect();+ item.extend_from_slice(&(name.len() as u32).to_be_bytes());+ item.extend(name.iter().flat_map(|u| u.to_be_bytes()));+ item.extend_from_slice(&photocraft_io::linked::file_type(&f.bytes));+ item.extend_from_slice(b"8BIM");+ item.extend_from_slice(&(f.bytes.len() as u64).to_be_bytes());+ item.push(0); // no open-file descriptor+ item.extend_from_slice(&f.bytes);+ let mut out = (item.len() as u64).to_be_bytes().to_vec();+ out.extend(item);+ out.resize(out.len().next_multiple_of(4), 0);+ out+}++/// `doc` saved as PSD, then rewritten into Photoshop CS2's layout: no `SoLd`, and `lnkD` with+/// version-2 items.+fn cs2_layout(doc: &Document) -> Vec<u8> {+ let out = photocraft_io::export(doc, "psd", &Default::default()).unwrap();+ let mut file = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap();+ for rec in file.layers_mut() {+ rec.blocks.retain(|b| !matches!(&b.key, b"SoLd" | b"SoLE"));+ }+ assert!(file.layers().iter().any(|l| l.block(b"PlLd").is_some()));+ let links = file.global_blocks.iter_mut().find(|b| &b.key == b"lnk2").unwrap();+ let files = photocraft_io::linked::parse_linked_files(&links.data);+ assert_eq!(files.len(), 1);+ links.key = *b"lnkD";+ links.data = files.iter().flat_map(lifd_v2).collect();+ file.to_bytes().unwrap()+}++/// Photoshop CS2 predates `SoLd`: its placed layers carry a `PlLd` block alone, and the embedded+/// file sits in a global `lnkD` block of older `liFD` items. Such a smart object's contents open+/// (they were "unavailable") and it re-renders in place from them (#2465).+#[test]+fn cs2_plld_only_smart_object_opens_its_contents() {+ let mut s = session(8);+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ let id = s.active().unwrap().active_layer.unwrap().0;+ s.execute("edit.transform", json!({"layer": id, "matrix": [0.75, 0, 0, 0.75, 10, 4]})).unwrap();+ let doc = s.active().unwrap().doc.clone();+ let (_, before) = smart(&doc);+ let SmartSource::Embedded { bytes: pcraft, .. } = &before.source else { panic!("embedded") };+ let nested = decode_source("x.pcraft", pcraft).unwrap();++ let back = photocraft_io::import("cs2.psd", &cs2_layout(&doc)).unwrap().document;+ let (bid, after) = smart(&back);+ for (a, b) in after.transform.m.iter().zip(before.transform.m) {+ assert!((a - b).abs() < 1e-9, "transform {:?} vs {:?}", after.transform, before.transform);+ }+ let (name, src) = photocraft_engine::smart_cmds::contents_of(&back, photocraft_doc::LayerId(bid)).expect("the contents are available");+ let inner = decode_source(&name, &src).unwrap();+ assert_eq!((inner.size, inner.layers.len()), (nested.size, nested.layers.len()));+ // It re-renders where it was placed.+ let mut l = back.layer(photocraft_doc::LayerId(bid)).unwrap().clone();+ assert!(refresh_layer(&back, &mut l).unwrap());+ let mut rerendered = back.clone();+ *rerendered.layer_mut(photocraft_doc::LayerId(bid)).unwrap() = l;+ let d = max_diff(&photocraft_compose::flatten(&rerendered).px, &photocraft_compose::flatten(&doc).px);+ assert!(d <= 2.0 / 255.0, "re-render differs by {d}");+ // And Edit Contents (the double-click) opens the nested document.+ let mut s2 = Session::new();+ s2.add_document(back, None);+ s2.select_layer(photocraft_doc::LayerId(bid)).unwrap();+ s2.execute("layer.smartObjects.editContents", json!({})).unwrap();+ assert_eq!(s2.active().unwrap().doc.size, nested.size);+}++/// CS2 can warp a smart object, and `PlLd` keeps the warp after the corners. Now that a+/// `PlLd`-only layer's contents are available, Free Transform, Image Size and mode changes+/// re-render it from them: it must come back warped, not silently unwarped (#2465).+#[test]+fn cs2_plld_only_warped_smart_object_stays_warped() {+ let mut s = session(8);+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ let id = s.active().unwrap().active_layer.unwrap().0;+ s.execute("edit.transform", json!({"layer": id, "matrix": [0.75, 0, 0, 0.75, 10, 4]})).unwrap();+ s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap();+ let doc = s.active().unwrap().doc.clone();+ let (_, before) = smart(&doc);+ assert!(before.warp.is_some());++ let back = photocraft_io::import("cs2.psd", &cs2_layout(&doc)).unwrap().document;+ let (bid, after) = smart(&back);+ assert_eq!(after.warp, before.warp);+ assert!(photocraft_engine::smart_cmds::contents_of(&back, photocraft_doc::LayerId(bid)).is_ok(), "the contents are available");+ // Re-rendered from its source, it is still warped where it was placed.+ let rerender = |warp| {+ let mut l = back.layer(photocraft_doc::LayerId(bid)).unwrap().clone();+ let LayerContent::Smart(sm) = &mut l.content else { panic!() };+ sm.warp = warp;+ assert!(refresh_layer(&back, &mut l).unwrap());+ let mut d = back.clone();+ *d.layer_mut(photocraft_doc::LayerId(bid)).unwrap() = l;+ max_diff(&photocraft_compose::flatten(&d).px, &photocraft_compose::flatten(&doc).px)+ };+ let d = rerender(after.warp.clone());+ assert!(d <= 2.0 / 255.0, "re-render differs by {d}");+ assert!(rerender(None) > 0.1, "an unwarped re-render would differ visibly");+}++/// A CS2 `PlLd`-only smart object is saved as it was while nothing changed it, and with its+/// current placement once it is moved: the old record was written back unchanged, so the save+/// reopened at the old place (#2465).+#[test]+fn cs2_plld_only_smart_object_saves_its_new_transform() {+ let mut s = session(8);+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ let id = s.active().unwrap().active_layer.unwrap().0;+ s.execute("edit.transform", json!({"layer": id, "matrix": [0.75, 0, 0, 0.75, 10, 4]})).unwrap();+ let cs2 = cs2_layout(&s.active().unwrap().doc);+ let plld = |bytes: &[u8]| {+ let f = photocraft_psd::PsdFile::from_bytes(bytes).unwrap();+ let rec = f.layers().iter().find(|l| l.block(b"PlLd").is_some()).cloned().expect("a placed layer");+ (rec.block(b"PlLd").unwrap().data.clone(), rec.block(b"SoLd").is_some())+ };+ let back = photocraft_io::import("cs2.psd", &cs2).unwrap().document;+ let (bid, _) = smart(&back);++ // Unedited: the CS2 record is written back as it was.+ let same = photocraft_io::export(&back, "psd", &Default::default()).unwrap().bytes;+ assert_eq!(plld(&same), (plld(&cs2).0, false));++ // Moved and scaled: written with the new placement, and it reopens there.+ let mut s2 = Session::new();+ s2.add_document(back, None);+ s2.execute("edit.transform", json!({"layer": bid, "matrix": [0.5, 0, 0, 0.5, 20, 12]})).unwrap();+ let edited = s2.active().unwrap().doc.clone();+ let (_, want) = smart(&edited);+ let saved = photocraft_io::export(&edited, "psd", &Default::default()).unwrap().bytes;+ assert!(structure_errors(&saved).is_empty(), "{:?}", structure_errors(&saved));+ assert_ne!(plld(&saved).0, plld(&cs2).0, "the old PlLd record was written back");+ let again = photocraft_io::import("again.psd", &saved).unwrap().document;+ let (aid, got) = smart(&again);+ for (a, b) in got.transform.m.iter().zip(want.transform.m) {+ assert!((a - b).abs() < 1e-9, "transform {:?} vs {:?}", got.transform, want.transform);+ }+ assert!(photocraft_engine::smart_cmds::contents_of(&again, photocraft_doc::LayerId(aid)).is_ok(), "the contents are available");+}diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rsindex 3a6b220d1..87fda102f 100644--- a/crates/io/src/blocks.rs+++ b/crates/io/src/blocks.rs@@ -527,15 +527,25 @@ pub(crate) fn with_pattern_placement(mut d: Descriptor, angle: f32, link: bool,/// The warp of a placed layer (`SoLd`/`SoLE` `warp` descriptor): style, bend, distortions,/// axis, bounds and, for `warpCustom`, the 4 × 4 `customEnvelopeWarp` mesh. Read-only: the raw-/// block is what gets written back. `None` when absent or `warpNone` with no mesh.+/// block is what gets written back. `None` when absent or `warpNone` with no mesh. A `PlLd`+/// record keeps its warp elsewhere: see [`parse_plld_warp`].pub fn parse_placed_warp(key: &[u8; 4], data: &[u8]) -> Option<photocraft_geom::warp::Warp> {- use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};if key != b"SoLd" && key != b"SoLE" {return None;}let d = data.get(8..).and_then(parse_prefix_versioned)?;- let w = get_desc(&d, "warp")?;+ warp_of(get_desc(&d, "warp")?).flatten()+}++/// A `warp` descriptor (the `SoLd` key, or the whole descriptor after a `PlLd` record's corners)+/// as a warp: `Some(None)` for no warp (`warpNone`, or a warp that moves nothing), `None` when it+/// can't be read (an unknown style, missing bounds, a mesh that isn't 4 × 4).+fn warp_of(w: &Descriptor) -> Option<Option<photocraft_geom::warp::Warp>> {+ use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};let style = enum_of(w, "warpStyle").and_then(|v| WarpStyle::parse(&String::from_utf8_lossy(v)))?;+ if style == WarpStyle::None {+ return Some(None);+ }let b = get_desc(w, "bounds")?;let g = |k: &str| num(b.get(k));let bounds = [g("Left")?, g("Top ")?, g("Rght")?, g("Btom")?];@@ -558,7 +568,7 @@ pub fn parse_placed_warp(key: &[u8; 4], data: &[u8]) -> Option<photocraft_geom::warp.mesh = mesh.is_valid().then_some(mesh);warp.mesh.as_ref()?;}- (!warp.is_identity()).then_some(warp)+ Some((!warp.is_identity()).then_some(warp))}/// Text content and transform from a `TySh` block (best effort).@@ -598,7 +608,8 @@ pub(crate) fn placed_frame(warp: Option<&photocraft_geom::warp::Warp>, w: f64, hif ok { b } else { rect }}-/// Smart object identifier and transform from `SoLd`/`PlLd` (best effort).+/// Smart object identifier and transform from `SoLd`/`SoLE` (best effort). A `PlLd` block+/// stores no source size, so its transform needs the embedded file: see [`parse_plld`].pub fn parse_smart(key: &[u8; 4], data: &[u8]) -> (String, Affine) {// SoLd: 'soLD' + version(4) + versioned descriptor.let desc = if key == b"SoLd" || key == b"SoLE" { data.get(8..).and_then(parse_prefix_versioned) } else { None };@@ -611,16 +622,97 @@ pub fn parse_smart(key: &[u8; 4], data: &[u8]) -> (String, Affine) {if let (Some(Value::List(pts)), Some(sz)) = (d.get("Trnf"), get_desc(&d, "Sz ")) {let p: Vec<f64> = pts.iter().filter_map(|v| num(Some(v))).collect();let (w, h) = (num(sz.get("Wdth")).unwrap_or(0.0), num(sz.get("Hght")).unwrap_or(0.0));- if p.len() == 8 && w > 0.0 && h > 0.0 {- let [x0, y0, x1, y1] = placed_frame(parse_placed_warp(key, data).as_ref(), w, h);- let (bw, bh) = (x1 - x0, y1 - y0);- let (a, b, c, d) = ((p[2] - p[0]) / bw, (p[3] - p[1]) / bw, (p[6] - p[0]) / bh, (p[7] - p[1]) / bh);- affine = Affine { m: [a, b, c, d, p[0] - a * x0 - c * y0, p[1] - b * x0 - d * y0] };+ if let (Ok(p), true) = (<[f64; 8]>::try_from(p), w > 0.0 && h > 0.0) {+ affine = corners_affine(&p, placed_frame(parse_placed_warp(key, data).as_ref(), w, h)).unwrap_or(Affine::IDENTITY);}}(id, affine)}+/// The affine that takes the source-space box `frame` (left, top, right, bottom; see+/// [`placed_frame`]) onto placed corners `p` (top-left, top-right, bottom-right, bottom-left as+/// x, y pairs). `None` for an empty or non-finite frame, or non-finite corners.+pub fn corners_affine(p: &[f64; 8], frame: [f64; 4]) -> Option<Affine> {+ let [x0, y0, x1, y1] = frame;+ let (bw, bh) = (x1 - x0, y1 - y0);+ if !(frame.iter().chain(p).all(|v| v.is_finite()) && bw > 0.0 && bh > 0.0) {+ return None;+ }+ let (a, b, c, d) = ((p[2] - p[0]) / bw, (p[3] - p[1]) / bw, (p[6] - p[0]) / bh, (p[7] - p[1]) / bh);+ let m = [a, b, c, d, p[0] - a * x0 - c * y0, p[1] - b * x0 - d * y0];+ m.iter().all(|v| v.is_finite()).then_some(Affine { m })+}++/// The transform and (Distort/Perspective) projective placement of a `PlLd` record's corners `p`+/// for a source of `size` warped by `warp`: the inverse of [`crate::smart_map::plld_bytes`]'s+/// quad. As for `SoLd`'s `Trnf` (#3677), affine corners frame a single-patch custom warp's+/// control-point box (which may spill past the source), else the source rect; projective corners+/// frame the source rect, as `parse_smart_perspective` reads them. `PlLd` stores no source size:+/// without the source file (`None`) the layer is taken as placed at 100 %, the edge lengths being+/// its size (a custom warp's box needs no size); position and rotation stay right, only Replace+/// Contents and re-renders depend on the scale. Import and export (which keeps an unedited record+/// verbatim) both place a `PlLd` layer with this.+pub fn plld_transform(p: &[f64; 8], size: Option<(f64, f64)>, warp: Option<&photocraft_geom::warp::Warp>) -> (Affine, Option<[f64; 9]>) {+ let (w, h) = size.unwrap_or_else(|| ((p[2] - p[0]).hypot(p[3] - p[1]), (p[6] - p[0]).hypot(p[7] - p[1])));+ let perspective = corners_perspective([[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]], (w, h));+ let frame = if perspective.is_some() { [0.0, 0.0, w, h] } else { placed_frame(warp, w, h) };+ (corners_affine(p, frame).unwrap_or(Affine::IDENTITY), perspective)+}++/// The source identifier and placed corners of a `PlLd` block, the placed-layer record Photoshop+/// CS2 and older write with no `SoLd` next to it (#2465). Adobe PSD spec, "Placed Layer": `plcL`,+/// version, Pascal unique id (unpadded), page, total pages, anti-alias policy, layer type, then+/// 8 doubles: the x, y of each corner (top-left, top-right, bottom-right, bottom-left). The warp+/// that follows is read by [`parse_plld_warp`]. `None` for anything else or a truncated record.+pub fn parse_plld(data: &[u8]) -> Option<(String, [f64; 8])> {+ plld_record(data).map(|(id, corners, _)| (id, corners))+}++/// [`parse_plld`] and the offset just past the corners, where the warp starts.+fn plld_record(data: &[u8]) -> Option<(String, [f64; 8], usize)> {+ if data.get(..4)? != b"plcL" {+ return None;+ }+ let n = usize::from(*data.get(8)?);+ let id = String::from_utf8_lossy(data.get(9..9 + n)?).into_owned();+ // Page number, total pages, anti-alias policy and layer type (4 × u32).+ let at = 9 + n + 16;+ let mut corners = [0.0; 8];+ for (i, c) in corners.iter_mut().enumerate() {+ let b = data.get(at + i * 8..at + i * 8 + 8)?;+ *c = f64::from_be_bytes(b.try_into().ok()?);+ }+ corners.iter().all(|v| v.is_finite()).then_some((id, corners, at + 64))+}++/// The warp of a placed layer's `PlLd` record (Photoshop CS2 can warp a smart object).+#[derive(Debug, Clone, PartialEq)]+pub enum PlldWarp {+ /// No warp: `warpNone`, a warp that moves nothing, or a record that ends at its corners.+ None,+ /// The warp, in source pixels like the `SoLd` one.+ Warp(photocraft_geom::warp::Warp),+ /// A warp is stored but can't be read (or the record itself can't be): re-rendering the+ /// layer from its source would drop it.+ Unreadable,+}++/// The warp after a `PlLd` record's corners: a u32 warp version, then a versioned `warp`+/// descriptor (Adobe PSD spec, "Placed Layer"; the layout [`crate::smart_map::plld_bytes`]+/// writes).+pub fn parse_plld_warp(data: &[u8]) -> PlldWarp {+ let Some(rest) = plld_record(data).and_then(|(_, _, end)| data.get(end..)) else { return PlldWarp::Unreadable };+ // Only padding after the corners: no warp stored.+ if rest.iter().all(|b| *b == 0) {+ return PlldWarp::None;+ }+ match rest.get(4..).and_then(parse_prefix_versioned).as_ref().and_then(warp_of) {+ Some(Some(w)) => PlldWarp::Warp(w),+ Some(None) => PlldWarp::None,+ None => PlldWarp::Unreadable,+ }+}+/// The projective placement of a `SoLd` / `SoLE` block whose corners aren't a parallelogram/// (Distort, Perspective): source pixels → document pixels, row-major 3×3. Read from/// `nonAffineTransform` (the placed corners), else `Trnf`. `None` for affine placements, which@@ -638,6 +730,12 @@ pub fn parse_smart_perspective(key: &[u8; 4], data: &[u8]) -> Option<[f64; 9]> {(p.len() == 8 && p.iter().all(|v| v.is_finite())).then(|| [[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]])};let q = quad("nonAffineTransform").or_else(|| quad("Trnf"))?;+ corners_perspective(q, (w, h))+}++/// The projective placement of a `w` × `h` source onto corners `q` that aren't a parallelogram;+/// `None` for affine corners (see [`corners_affine`]) or an empty size.+pub fn corners_perspective(q: [[f64; 2]; 4], (w, h): (f64, f64)) -> Option<[f64; 9]> {// A parallelogram (top-left + bottom-right = top-right + bottom-left) is affine.let tol = 1e-6 * (1.0 + q.iter().flatten().fold(0.0f64, |m, v| m.max(v.abs())));if (0..2).all(|i| (q[0][i] + q[2][i] - q[1][i] - q[3][i]).abs() <= tol) || w <= 0.0 || h <= 0.0 {@@ -916,6 +1014,172 @@ mod more_tests {assert_eq!(id, "uuid-1");assert_eq!(a.m, [2.0, 0.0, 0.0, 2.0, 10.0, 20.0]);assert_eq!(parse_smart(b"PlLd", &data).0, "");+ assert_eq!(parse_plld(&data), None, "soLD data is not a plcL record");+ }++ /// A `PlLd` record (as Photoshop CS2 writes it, with no `SoLd`, #2465) gives its source id and+ /// placed corners; with the source size those are the same transform `SoLd` gives.+ #[test]+ fn plld_id_and_corners() {+ use crate::smart_map::{PlacedSpec, plld_bytes};+ let t = Affine { m: [1.5, 0.25, -0.5, 2.0, 10.0, 20.0] };+ let spec = PlacedSpec { idnt: "uuid-cs2", placed: "", transform: t, perspective: None, size: (40.0, 30.0), dpi: 72.0, warp: None, filter_fx: None };+ let data = plld_bytes(&spec, &mut Vec::new());+ let (id, p) = parse_plld(&data).expect("a plcL record");+ assert_eq!(id, "uuid-cs2");+ assert_eq!(p, [10.0, 20.0, 70.0, 30.0, 55.0, 90.0, -5.0, 80.0]);+ let back = corners_affine(&p, [0.0, 0.0, 40.0, 30.0]).unwrap();+ for (a, b) in back.m.iter().zip(t.m) {+ assert!((a - b).abs() < 1e-12, "{back:?} vs {t:?}");+ }+ assert_eq!(corners_perspective([[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]], (40.0, 30.0)), None, "affine corners");+ assert_eq!(corners_affine(&p, [0.0, 0.0, 0.0, 30.0]), None);+ assert_eq!(corners_affine(&p, [0.0, 0.0, f64::NAN, 30.0]), None);+ assert_eq!(corners_affine(&p, [5.0, 0.0, 5.0, 30.0]), None, "an empty frame");+ let mut nan = p;+ nan[3] = f64::INFINITY;+ assert_eq!(corners_affine(&nan, [0.0, 0.0, 40.0, 30.0]), None);+ // The placed-layer record is the one block that can be the principal one: PlLd-only+ // layers have no smart transform from `parse_smart`.+ assert_eq!(parse_smart(b"PlLd", &data), (String::new(), Affine::IDENTITY));+ }++ /// A `PlLd` record's corners frame the same box as `SoLd`'s `Trnf` (#3677): with a custom+ /// warp whose control points spill past the source, the control-point box, not the source+ /// rect. The CS2 record then places the layer exactly as the equivalent `SoLd` does, with or+ /// without the source size (the box needs none).+ #[test]+ fn plld_corners_frame_a_spilled_custom_warp_like_sold() {+ use crate::smart_map::{PlacedSpec, parse_sold, plld_bytes, sold_bytes};+ use photocraft_geom::warp::{BezierMesh, Warp};+ let bounds = [0.0, 0.0, 50.0, 25.0];+ let mut mesh = BezierMesh::identity(bounds, 1, 1);+ mesh.points[0] = [-10.0, -5.0];+ mesh.points[15] = [60.0, 25.0];+ let warp = Warp::custom(mesh, bounds);+ let t = Affine { m: [2.0, 0.5, -0.25, 2.0, 120.0, 210.0] };+ let spec = PlacedSpec { idnt: "cs2", placed: "p", transform: t, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp: Some(&warp), filter_fx: None };+ let plld = plld_bytes(&spec, &mut Vec::new());+ let sold = sold_bytes(None, &spec, &mut Vec::new());+ let (_, p) = parse_plld(&plld).expect("a plcL record");+ assert_eq!(parse_plld_warp(&plld), PlldWarp::Warp(warp.clone()));+ let from_sold = parse_smart(b"SoLd", &sold).1;+ assert_eq!(parse_sold(&sold).map(|s| s.transform), Some(from_sold));+ let close = |a: Affine, b: Affine| a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() < 1e-9);+ assert!(close(from_sold, t), "{from_sold:?} vs {t:?}");+ for size in [Some((50.0, 25.0)), None] {+ let (got, perspective) = plld_transform(&p, size, Some(&warp));+ assert!(close(got, from_sold), "size {size:?}: {got:?} vs SoLd {from_sold:?}");+ assert_eq!(perspective, None);+ }+ // Framing the source rect instead would stretch it (the bug #3677 fixed for SoLd).+ let rect = corners_affine(&p, [0.0, 0.0, 50.0, 25.0]).unwrap();+ assert!(!close(rect, t), "the test needs a mesh that spills: {rect:?}");+ // With no warp, or a preset one, the frame is the source rect, as before.+ let plain = PlacedSpec { warp: None, ..spec };+ let (_, q) = parse_plld(&plld_bytes(&plain, &mut Vec::new())).unwrap();+ assert!(close(plld_transform(&q, Some((50.0, 25.0)), None).0, t));+ }++ /// Malformed `PlLd` data (wrong magic, truncated anywhere, a Pascal length past the end,+ /// non-finite corners) reads as `None`, never a panic.+ #[test]+ fn plld_malformed_is_none() {+ use crate::smart_map::{PlacedSpec, plld_bytes};+ let spec =+ PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None };+ let data = plld_bytes(&spec, &mut Vec::new());+ // Magic + version + Pascal "id" + 4 × u32 + 8 × f64: everything after is the warp.+ let end = 4 + 4 + 1 + 2 + 16 + 64;+ assert!(parse_plld(&data[..end]).is_some());+ for n in 0..end {+ assert_eq!(parse_plld(&data[..n]), None, "truncated to {n} bytes");+ }+ let mut bad = data.clone();+ bad[..4].copy_from_slice(b"soLD");+ assert_eq!(parse_plld(&bad), None);+ let mut long = data.clone();+ long[8] = 255; // a Pascal id longer than the record+ assert_eq!(parse_plld(&long[..200.min(long.len())]), None);+ let mut nan = data.clone();+ nan[end - 8..end].copy_from_slice(&f64::NAN.to_be_bytes());+ assert_eq!(parse_plld(&nan), None);+ assert_eq!(parse_plld(&[]), None);+ }++ /// Photoshop CS2 can warp a smart object; `PlLd` keeps that warp after the corners (a u32+ /// warp version, then the versioned `warp` descriptor). It reads back as written, and+ /// `warpNone`, an identity warp or a record that stops at its corners mean no warp.+ #[test]+ fn plld_warps_round_trip() {+ use crate::smart_map::{PlacedSpec, plld_bytes};+ use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};+ let bounds = [0.0, 0.0, 60.0, 30.0];+ let mut arc = Warp::preset(WarpStyle::Arc, 40.0, bounds);+ arc.vertical = true;+ arc.h_distort = 10.0;+ let mut mesh = BezierMesh::identity(bounds, 1, 1);+ mesh.points[15] = [67.0, 30.0];+ let custom = Warp::custom(mesh, bounds);+ let flat = Warp::preset(WarpStyle::Flag, 0.0, bounds);+ for (w, back) in+ [(Some(&arc), PlldWarp::Warp(arc.clone())), (Some(&custom), PlldWarp::Warp(custom.clone())), (Some(&flat), PlldWarp::None), (None, PlldWarp::None)]+ {+ let t = Affine { m: [0.5, 0.0, 0.0, 0.5, 3.0, 4.0] };+ let spec = PlacedSpec { idnt: "w", placed: "", transform: t, perspective: None, size: (60.0, 30.0), dpi: 72.0, warp: w, filter_fx: None };+ let data = plld_bytes(&spec, &mut Vec::new());+ assert_eq!(parse_plld_warp(&data), back, "{w:?}");+ // The corners are unchanged by the warp that follows them.+ assert_eq!(parse_plld(&data).map(|(_, p)| p[..2].to_vec()), Some(vec![3.0, 4.0]));+ }+ let spec =+ PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None };+ let end = 4 + 4 + 1 + 2 + 16 + 64;+ let data = plld_bytes(&spec, &mut Vec::new());+ assert_eq!(parse_plld_warp(&data[..end]), PlldWarp::None, "no warp stored");+ assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0; 3]].concat()), PlldWarp::None, "padding");+ }++ /// A `PlLd` warp that is stored but can't be read (truncated, an unknown style, a missing+ /// bounds rectangle or mesh) is `Unreadable`, so the import keeps the warped pixels.+ #[test]+ fn plld_unreadable_warps() {+ use crate::smart_map::{PlacedSpec, plld_bytes};+ use photocraft_geom::warp::{Warp, WarpStyle};+ let arc = Warp::preset(WarpStyle::Arc, 40.0, [0.0, 0.0, 4.0, 4.0]);+ let spec = PlacedSpec {+ idnt: "id",+ placed: "",+ transform: Affine::IDENTITY,+ perspective: None,+ size: (4.0, 4.0),+ dpi: 72.0,+ warp: Some(&arc),+ filter_fx: None,+ };+ let data = plld_bytes(&spec, &mut Vec::new());+ let end = 4 + 4 + 1 + 2 + 16 + 64;+ assert!(matches!(parse_plld_warp(&data), PlldWarp::Warp(_)));+ for n in end + 1..data.len() - 4 {+ if data[end..n].iter().any(|b| *b != 0) {+ assert_eq!(parse_plld_warp(&data[..n]), PlldWarp::Unreadable, "truncated to {n} bytes");+ }+ }+ let with = |d: Descriptor| [data[..end].to_vec(), vec![0; 4], VersionedDescriptor::new(d).to_bytes()].concat();+ let style = |s: &str| Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new(s) };+ assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpSomethingNew")))), PlldWarp::Unreadable);+ assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpArc")))), PlldWarp::Unreadable, "no bounds");+ assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpNone")))), PlldWarp::None);+ let bounds = Descriptor::new("classFloatRect")+ .with("Top ", Value::Double(0.0))+ .with("Left", Value::Double(0.0))+ .with("Btom", Value::Double(4.0))+ .with("Rght", Value::Double(4.0));+ let custom = Descriptor::new("warp").with("warpStyle", style("warpCustom")).with("bounds", Value::Descriptor(bounds));+ assert_eq!(parse_plld_warp(&with(custom)), PlldWarp::Unreadable, "custom with no mesh");+ assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0, 0, 0, 0, 0, 0, 0, 16, 1, 2]].concat()), PlldWarp::Unreadable);+ assert_eq!(parse_plld_warp(&data[..end - 1]), PlldWarp::Unreadable, "the record itself");+ assert_eq!(parse_plld_warp(&[]), PlldWarp::Unreadable);}/// `SoLd` data with a 50 × 25 source, the quad `trnf` and, when given, a custom warp whosediff --git a/crates/io/src/linked.rs b/crates/io/src/linked.rsindex b1b7286d2..636b6a126 100644--- a/crates/io/src/linked.rs+++ b/crates/io/src/linked.rs@@ -84,14 +84,101 @@ pub fn parse_linked_files(data: &[u8]) -> Vec<LinkedFile> {/// The embedded file for smart-object `uuid` among the document's preserved PSD global blocks.pub fn find_linked_file(meta: &Metadata, uuid: &str) -> Option<LinkedFile> {+ find_in_blocks(meta.psd_global_blocks.iter().map(|(_, k, d)| (k, d.as_slice())), uuid)+}++/// The embedded file for smart-object `uuid` among PSD global blocks given as (key, data).+pub fn find_in_blocks<'a>(blocks: impl IntoIterator<Item = (&'a [u8; 4], &'a [u8])>, uuid: &str) -> Option<LinkedFile> {if uuid.is_empty() {return None;}- meta.psd_global_blocks- .iter()- .filter(|(_, k, _)| matches!(k, b"lnk2" | b"lnk3" | b"lnkD"))- .flat_map(|(_, _, d)| parse_linked_files(d))- .find(|f| f.uuid == uuid)+ blocks.into_iter().filter(|(k, _)| matches!(*k, b"lnk2" | b"lnk3" | b"lnkD")).flat_map(|(_, d)| parse_linked_files(d)).find(|f| f.uuid == uuid)+}++/// The size of embedded file `uuid` among PSD global blocks given as (key, data), when it is there+/// and readable with a non-empty size (the source size a `PlLd` record leaves out).+pub(crate) fn source_size_in_blocks<'a>(+ blocks: impl IntoIterator<Item = (&'a [u8; 4], &'a [u8])>,+ uuid: &str,+ ctl: &photocraft_raster::Interrupt,+) -> Option<(f64, f64)> {+ let f = find_in_blocks(blocks, uuid)?;+ if ctl.cancelled() {+ return None;+ }+ source_size_probe(&f.bytes).filter(|(w, h)| *w > 0.0 && *h > 0.0)+}++/// Pixel size of an embedded source file from its header: PSD/PSB, TIFF (the default page's+/// directory), PNG (`IHDR`) and JPEG (the frame header); any other image is decoded flat by+/// `photocraft-codecs`. It never imports a document: a layered TIFF can carry PSD layer data+/// whose `lnkD` holds another file, so a full import here would nest without bound (#2465).+pub(crate) fn source_size_probe(bytes: &[u8]) -> Option<(f64, f64)> {+ let be32 = |at: usize| bytes.get(at..at + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));+ let size = |w: u32, h: u32| (f64::from(w), f64::from(h));+ match bytes {+ _ if crate::is_psd(bytes) => be32(18).zip(be32(14)).map(|(w, h)| size(w, h)),+ [b'I', b'I', 42, 0, ..] | [b'M', b'M', 0, 42, ..] | [b'I', b'I', 43, 0, ..] | [b'M', b'M', 0, 43, ..] => {+ let info = photocraft_codecs::tiff_info(bytes).ok()?;+ let page = info.pages.get(info.default_page()?)?;+ Some(size(page.width, page.height))+ }+ [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, ..] => be32(16).zip(be32(20)).map(|(w, h)| size(w, h)),+ [0xFF, 0xD8, ..] => jpeg_size(bytes),+ _ => photocraft_codecs::decode(bytes).ok().map(|img| {+ let (w, h) = img.dimensions();+ size(w, h)+ }),+ }+}++/// A JPEG's size from its first start-of-frame marker (ITU-T T.81 B.2.2), walking the marker+/// segments without decoding. Each step moves forward, so a malformed file ends the walk.+fn jpeg_size(bytes: &[u8]) -> Option<(f64, f64)> {+ let mut at = 2usize;+ loop {+ // Markers are 0xFF then a code; extra 0xFF fill bytes may come first.+ while bytes.get(at) == Some(&0xFF) && bytes.get(at + 1) == Some(&0xFF) {+ at += 1;+ }+ if *bytes.get(at)? != 0xFF {+ return None;+ }+ let code = *bytes.get(at + 1)?;+ match code {+ // SOF0..SOF15, except DHT (C4), JPG (C8) and DAC (CC).+ 0xC0..=0xCF if !matches!(code, 0xC4 | 0xC8 | 0xCC) => {+ let h = bytes.get(at + 5..at + 7)?;+ let w = bytes.get(at + 7..at + 9)?;+ return Some((f64::from(u16::from_be_bytes([w[0], w[1]])), f64::from(u16::from_be_bytes([h[0], h[1]]))));+ }+ // Standalone markers have no length.+ 0x01 | 0xD0..=0xD7 => at = at.checked_add(2)?,+ // Start of scan or end of image before any frame header.+ 0xDA | 0xD9 => return None,+ _ => {+ let len = bytes.get(at + 2..at + 4).map(|b| usize::from(u16::from_be_bytes([b[0], b[1]])))?;+ if len < 2 {+ return None;+ }+ at = at.checked_add(2 + len)?;+ }+ }+ }+}++/// Size and resolution of a smart-object source file (PSD/PSB header, `.pcraft`, or any image).+/// Other formats are decoded in full, which `ctl` can cancel (its progress is left alone: this is+/// a step of a larger operation).+pub(crate) fn source_geometry(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -> Result<((f64, f64), f64), String> {+ if crate::is_psd(bytes) {+ let rd = |at: usize| bytes.get(at..at + 4).map(|b| f64::from(u32::from_be_bytes([b[0], b[1], b[2], b[3]])));+ let (h, w) = rd(14).zip(rd(18)).ok_or("truncated PSD header")?;+ return Ok(((w, h), 72.0));+ }+ let cancel = || ctl.cancelled();+ let doc = crate::import_with(name, bytes, &photocraft_raster::Interrupt::cancel_only(&cancel)).map_err(|e| e.to_string())?.document;+ Ok(((f64::from(doc.size.width), f64::from(doc.size.height)), f64::from(doc.resolution_dpi)))}/// The four-character file type Photoshop records for an embedded file, from its contents.@@ -210,6 +297,45 @@ mod tests {use super::*;use std::sync::Arc;+ /// #2465: a placed source's size comes from its header, for every format a CS2 file embeds,+ /// and never by importing it as a document.+ #[test]+ fn source_size_probe_reads_headers() {+ use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};+ let img = Image::new(7, 5, ChannelLayout::Rgb, SampleType::U8).unwrap();+ for format in [Format::Png, Format::Jpeg, Format::Tiff, Format::Bmp] {+ let bytes = photocraft_codecs::encode(&img, format, &EncodeOptions::default()).unwrap();+ assert_eq!(source_size_probe(&bytes), Some((7.0, 5.0)), "{format:?}");+ }+ let mut psd = b"8BPS\0\x01".to_vec();+ psd.extend([0; 6]);+ psd.extend(3u16.to_be_bytes());+ psd.extend(40u32.to_be_bytes()); // height+ psd.extend(30u32.to_be_bytes()); // width+ assert_eq!(source_size_probe(&psd), Some((30.0, 40.0)));+ assert_eq!(source_size_probe(b"not an image"), None);+ assert_eq!(source_size_probe(&[]), None);+ }++ /// Malformed JPEG marker walks end without a size and without panicking or looping.+ #[test]+ fn jpeg_size_rejects_malformed_marker_walks() {+ let sof = [0xFF, 0xC0, 0, 17, 8, 0, 5, 0, 7];+ let ok: Vec<u8> = [&[0xFF, 0xD8][..], &[0xFF, 0xE0, 0, 4, 1, 2], &[0xFF, 0xFF, 0xD0], &sof].concat();+ assert_eq!(jpeg_size(&ok), Some((7.0, 5.0)), "APP0, a fill byte and a standalone marker are skipped");+ for bad in [+ vec![0xFF, 0xD8],+ vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 1], // length below 2+ vec![0xFF, 0xD8, 0xFF, 0xE0, 0xFF, 0xFF], // length past the end+ vec![0xFF, 0xD8, 0x00, 0x00], // not a marker+ vec![0xFF, 0xD8, 0xFF, 0xDA, 0, 2], // scan before any frame header+ vec![0xFF, 0xD8, 0xFF, 0xC0, 0, 17, 8], // truncated frame header+ [&[0xFF, 0xD8][..], &[0xFF; 64]].concat(),+ ] {+ assert_eq!(jpeg_size(&bad), None, "{bad:?}");+ }+ }+#[test]fn round_trips_and_finds_by_uuid() {let a = LinkedFile { uuid: "abc-1".into(), file_name: "a.png".into(), bytes: vec![1, 2, 3] };diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex a17e78336..822364bb8 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -244,17 +244,6 @@ impl SmartOut {}}-/// Size and resolution of a smart-object source file (PSD/PSB header, `.pcraft`, or any image).-fn source_geometry(name: &str, bytes: &[u8]) -> Result<((f64, f64), f64), String> {- if crate::is_psd(bytes) {- let rd = |at: usize| bytes.get(at..at + 4).map(|b| f64::from(u32::from_be_bytes([b[0], b[1], b[2], b[3]])));- let (h, w) = rd(14).zip(rd(18)).ok_or("truncated PSD header")?;- return Ok(((w, h), 72.0));- }- let doc = crate::import(name, bytes).map_err(|e| e.to_string())?.document;- Ok(((f64::from(doc.size.width), f64::from(doc.size.height)), f64::from(doc.resolution_dpi)))-}-/// The source size of a smart object whose file we can't decode: its rendered bounds taken back/// through the inverse transform (the source's top-left is the origin).fn size_from_layer(sm: &photocraft_doc::SmartObject) -> (f64, f64) {@@ -593,11 +582,14 @@ impl Ex {}LayerContent::Smart(sm) => {let parsed = sm.psd_raw.as_deref().and_then(|d| crate::smart_map::parse_sold(d));- if sm.psd_raw.is_some() && parsed.is_none() {- // Placed-layer data we don't parse (`PlLd` only): kept verbatim.+ if sm.psd_raw.is_some() && parsed.is_none() && !self.plld_edited(sm) {+ // Placed-layer data that isn't `SoLd` (a CS2 `PlLd` record, or one we can't+ // read) and still says what the layer is: kept verbatim.self.smart.prune_ok = false;set_principal(&mut raw, smart_keys(sm.psd_raw.as_deref().map(Vec::as_slice)), sm.psd_raw.as_ref());} else {+ // An edited CS2 `PlLd`-only layer is written like any other smart object+ // (`SoLd` and a regenerated `PlLd`), with its current placement (#2465).self.smart_blocks(l, sm, parsed, &mut raw);}}@@ -767,6 +759,36 @@ impl Ex {self.warnings.extend(warnings.into_iter().map(|w| if w.starts_with("layer ") { w } else { format!("layer \"{}\": {w}", l.name) }));}+ /// Whether a CS2 placed layer (`PlLd` with no `SoLd`, #2465) no longer matches its record:+ /// moved, transformed, warped, filtered or given other contents. `false` for a record that+ /// can't be read (or whose warp can't), or whose file isn't embedded: its contents were never+ /// available, so it is kept.+ fn plld_edited(&self, sm: &photocraft_doc::SmartObject) -> bool {+ let Some(data) = sm.psd_raw.as_deref() else { return false };+ let Some((id, corners)) = blocks::parse_plld(data) else { return false };+ // Without its embedded file the contents were never available: keep the record as it+ // is, rather than resolve the id (bytes from the file) as a path on disk.+ if !self.smart.known.contains(&id) {+ return false;+ }+ let warp = match blocks::parse_plld_warp(data) {+ blocks::PlldWarp::Unreadable => return false,+ blocks::PlldWarp::None => None,+ blocks::PlldWarp::Warp(w) => Some(w),+ };+ if sm.source != (photocraft_doc::SmartSource::Linked { path: id.clone() })+ || sm.warp != warp+ || !sm.smart_filters.is_empty()+ || sm.filter_mask.is_some()+ {+ return true;+ }+ // Placed as the importer places it (the same source size, from the same file, and the+ // same frame: a custom warp's control-point box, #3677).+ let size = crate::linked::source_size_in_blocks(self.smart.globals.iter().map(|(_, k, d)| (k, d.as_slice())), &id, &photocraft_raster::Interrupt::NONE);+ blocks::plld_transform(&corners, size, warp.as_ref()) != (sm.transform, sm.perspective)+ }+/// Whether an imported placed layer still says what the smart object is: transform, warp,/// filter stack and filter mask as stored.fn placed_unchanged(&self, t: &crate::smart_map::Placed, data: &[u8], sm: &photocraft_doc::SmartObject, stack: &crate::smart_map::FilterStack) -> bool {@@ -798,7 +820,7 @@ impl Ex {let geometry = stored.map(|size| (size, f64::from(self.dpi))).or_else(|| {let meta = photocraft_doc::Metadata { psd_global_blocks: self.smart.globals.clone(), ..Default::default() };let f = crate::linked::find_linked_file(&meta, path)?;- source_geometry(&f.file_name, &f.bytes).ok()+ crate::linked::source_geometry(&f.file_name, &f.bytes, &photocraft_raster::Interrupt::NONE).ok()});let (size, dpi) = geometry.unwrap_or((size_from_layer(sm), f64::from(self.dpi)));let original = self.smart.linked_contents.entry(path.clone()).or_insert(sm.contents_id);@@ -908,7 +930,8 @@ impl Ex {(format!("{stem}.psb"), data, size, f64::from(doc.resolution_dpi), Some(doc))} else {// Formats we can't decode (vector PDF/AI…) are still embedded; their size comes from the layer.- let (size, dpi) = source_geometry(file_name, bytes).unwrap_or(((0.0, 0.0), f64::from(self.dpi)));+ let (size, dpi) =+ crate::linked::source_geometry(file_name, bytes, &photocraft_raster::Interrupt::NONE).unwrap_or(((0.0, 0.0), f64::from(self.dpi)));(file_name.to_string(), bytes.to_vec(), size, dpi, None)};let uuid = contents_uuid(contents_id, &data);diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex af19a0d76..1e77cdaa6 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -59,6 +59,8 @@ pub(crate) struct Ctx<'a> {pub filter_effects: Vec<photocraft_psd::filter_effects::FilterEffectsItem>,/// Placed layers naming the same source share editable contents, not their placement.pub smart_contents: std::collections::HashMap<String, SmartContentsId>,+ /// Source sizes of `PlLd`-only placed layers, by source id (read once per embedded file).+ pub plld_sizes: std::collections::HashMap<String, Option<(f64, f64)>>,/// Cancellation and progress for background opens (checked per layer record).pub ctl: photocraft_raster::Interrupt<'a>,/// Layer records decoded so far, out of `total` (progress).@@ -105,11 +107,51 @@ fn soft_shape_fill(rec: &LayerRecord, has_vector: bool, fill_key: Option<&[u8; 4(soft || pattern).then_some((fill, soft))}+/// Where a placed layer's source goes: read from `SoLd`/`SoLE`, or from a CS2 `PlLd` record.+/// An empty `id` leaves the contents unavailable (the stored pixels stay the rendering).+#[derive(Default)]+struct Placement {+ id: String,+ transform: photocraft_geom::Affine,+ perspective: Option<[f64; 9]>,+ warp: Option<photocraft_geom::warp::Warp>,+}+impl Ctx<'_> {fn warn(&mut self, s: impl Into<String>) {self.warnings.push(s.into());}+ /// Source id, transform, (Distort/Perspective) projective placement and warp of a placed+ /// layer that has only a `PlLd` block, as Photoshop CS2 and older write it (#2465). `PlLd`+ /// stores the placed corners but not the source size, which comes from the embedded file.+ fn plld_placement(&mut self, data: &[u8], name: &str) -> Placement {+ let Some((id, p)) = blocks::parse_plld(data) else {+ self.warn(format!("layer \"{name}\": its placed-layer data (PlLd) could not be read; the smart object's contents are unavailable"));+ return Placement::default();+ };+ let warp = match blocks::parse_plld_warp(data) {+ blocks::PlldWarp::None => None,+ blocks::PlldWarp::Warp(w) => Some(w),+ blocks::PlldWarp::Unreadable => {+ // Re-rendering from the source would unwarp the layer: keep it as saved (its+ // warped pixels), as before PlLd was read.+ self.warn(format!(+ "layer \"{name}\": its smart object warp (PlLd) could not be read; the layer keeps its warped pixels but its contents are unavailable"+ ));+ return Placement::default();+ }+ };+ let (file, ctl) = (self.file, self.ctl);+ let size = *self+ .plld_sizes+ .entry(id.clone())+ .or_insert_with(|| crate::linked::source_size_in_blocks(file.global_blocks.iter().map(|b| (&b.key, b.data.as_slice())), &id, &ctl));+ // Without the source (missing or unreadable), it is taken as placed at 100 %.+ let (transform, perspective) = blocks::plld_transform(&p, size, warp.as_ref());+ Placement { id, transform, perspective, warp }+ }+fn channel_plane(&mut self, rec: &LayerRecord, id: i16, name: &str) -> Option<Vec<u8>> {rec.channel(id)?;match rec.decode_channel(id, self.file.header.depth, self.file.header.version) {@@ -267,7 +309,8 @@ impl Ctx<'_> {let fill_key = [b"SoCo", b"GdFl", b"PtFl"].into_iter().find(|k| rec.block(k).is_some());let vector_key = [b"vsms", b"vmsk"].into_iter().find(|k| rec.block(k).is_some());let adj_key = ADJUSTMENT_KEYS.into_iter().find(|k| rec.block(k).is_some());- let smart_key = [b"SoLd", b"PlLd", b"SoLE"].into_iter().find(|k| rec.block(k).is_some());+ // `SoLE` (a linked smart object) before `PlLd`: a `PlLd` alone is Photoshop CS2's record.+ let smart_key = [b"SoLd", b"SoLE", b"PlLd"].into_iter().find(|k| rec.block(k).is_some());let blocks = preserved_blocks(rec);// `psd_raw` shares the Arc of the matching `psd_blocks` entry.let principal = |k: &[u8; 4]| blocks.iter().find(|(bk, _)| bk == k).map(|(_, d)| d.clone());@@ -321,7 +364,16 @@ impl Ctx<'_> {t.psd_raw = principal(b"TySh");LayerContent::Text(t)} else if let Some(k) = smart_key {- let (id, transform) = rec.block(k).map(|b| blocks::parse_smart(k, &b.data)).unwrap_or_default();+ let Placement { id, transform, perspective, warp } = match rec.block(k) {+ Some(b) if k == b"PlLd" => self.plld_placement(&b.data, &name),+ Some(b) => {+ let (id, transform) = blocks::parse_smart(k, &b.data);+ // Distort / Perspective: the fourth corner (the affine `transform` drops it).+ let perspective = blocks::parse_smart_perspective(k, &b.data);+ Placement { id, transform, perspective, warp: blocks::parse_placed_warp(k, &b.data) }+ }+ None => Placement::default(),+ };let contents_id =if id.is_empty() { SmartContentsId::fresh() } else { *self.smart_contents.entry(id.clone()).or_insert_with(SmartContentsId::fresh) };// Smart filters (`filterFX` in the placed-layer data) and their mask (`FEid`).@@ -340,10 +392,9 @@ impl Ctx<'_> {psd_raw: principal(k),filters_enabled: stack.enabled,filter_mask,- warp: rec.block(k).and_then(|b| blocks::parse_placed_warp(k, &b.data)),+ warp,stack_mode: None,- // Distort / Perspective: the fourth corner (the affine `transform` drops it).- perspective: rec.block(k).and_then(|b| blocks::parse_smart_perspective(k, &b.data)),+ perspective,})} else if let Some((f, soft)) = soft_shape_fill(rec, vector_key.is_some(), fill_key) {// A shape whose vector mask has a density or feather is a fill layer seen through a@@ -650,6 +701,7 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)txt2: file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)),filter_effects: Vec::new(),smart_contents: Default::default(),+ plld_sizes: Default::default(),ctl: *ctl,done: 0,total: file.layers().len(),diff --git a/crates/io/tests/smart_contents_identity.rs b/crates/io/tests/smart_contents_identity.rsindex 632547b0d..5a0714b3d 100644--- a/crates/io/tests/smart_contents_identity.rs+++ b/crates/io/tests/smart_contents_identity.rs@@ -199,3 +199,153 @@ fn independent_unavailable_link_retains_separate_preserved_record() {let (again, _) = round_trip(&doc, "psd");assert_eq!(after.to_bytes().unwrap(), again.to_bytes().unwrap());}++/// A `PlLd`-only placed layer (Photoshop CS2, #2465) whose embedded file is missing still gets its+/// source id and placement (at an assumed 100 % scale); an unreadable `PlLd` is reported.+#[test]+fn plld_only_layers_without_their_file_or_with_a_broken_record() {+ let (mut file, _) = round_trip(&fixture(), "psd");+ file.global_blocks.retain(|b| !matches!(&b.key, b"lnk2" | b"lnk3" | b"lnkD"));+ let rotated = Affine { m: [0.0, 1.0, -1.0, 0.0, 6.0, 1.0] };+ let spec =+ smart_map::PlacedSpec { idnt: "missing", placed: "", transform: rotated, perspective: None, size: (3.0, 2.0), dpi: 72.0, warp: None, filter_fx: None };+ let mut record = file.layers()[0].clone();+ record.blocks.retain(|b| !matches!(&b.key, b"SoLd" | b"SoLE" | b"PlLd"));+ let mut broken = record.clone();+ record.blocks.push(TaggedBlock::new(*b"PlLd", smart_map::plld_bytes(&spec, &mut Vec::new())));+ broken.blocks.push(TaggedBlock::new(*b"PlLd", b"plcL\0\0\0\x03\x05ab\0\0".to_vec()));+ *file.layers_mut() = vec![record, broken];+ let (doc, warnings) = photocraft_io::psd_to_document(&file);+ let LayerContent::Smart(a) = &doc.layers[0].content else { panic!("PlLd layer is not a smart object") };+ assert_eq!(a.source, SmartSource::Linked { path: "missing".into() });+ for (x, y) in a.transform.m.iter().zip(rotated.m) {+ assert!((x - y).abs() < 1e-12, "{:?} vs {rotated:?}", a.transform);+ }+ let LayerContent::Smart(b) = &doc.layers[1].content else { panic!("broken PlLd layer is not a smart object") };+ assert_eq!(b.source, SmartSource::Linked { path: String::new() });+ assert_eq!(warnings.iter().filter(|w| w.contains("(PlLd) could not be read")).count(), 1, "{warnings:?}");+}++/// Photoshop CS2 can warp a smart object and keeps the warp in `PlLd`, after the corners. A+/// `PlLd`-only layer imports with that warp, so re-rendering it from its now-available source+/// (Free Transform, Image Size, mode changes) keeps it warped. A warp that can't be read leaves+/// the contents unavailable, so the warped pixels stay the rendering (#2465).+#[test]+fn plld_only_layers_keep_their_warp() {+ use photocraft_geom::warp::{Warp, WarpStyle};+ let (mut file, _) = round_trip(&fixture(), "psd");+ let bulge = Warp::preset(WarpStyle::Bulge, 35.0, [0.0, 0.0, 2.0, 2.0]);+ let spec = |warp| smart_map::PlacedSpec {+ idnt: "missing",+ placed: "",+ transform: Affine { m: [2.0, 0.0, 0.0, 2.0, 1.0, 0.0] },+ perspective: None,+ size: (2.0, 2.0),+ dpi: 72.0,+ warp,+ filter_fx: None,+ };+ let mut record = file.layers()[0].clone();+ record.blocks.retain(|b| !matches!(&b.key, b"SoLd" | b"SoLE" | b"PlLd"));+ let (mut warped, mut flat, mut broken) = (record.clone(), record.clone(), record);+ warped.blocks.push(TaggedBlock::new(*b"PlLd", smart_map::plld_bytes(&spec(Some(&bulge)), &mut Vec::new())));+ flat.blocks.push(TaggedBlock::new(*b"PlLd", smart_map::plld_bytes(&spec(None), &mut Vec::new())));+ // The warp descriptor cut short: a warp is stored but can't be read.+ let mut cut = smart_map::plld_bytes(&spec(Some(&bulge)), &mut Vec::new());+ cut.truncate(cut.len() - 40);+ broken.blocks.push(TaggedBlock::new(*b"PlLd", cut));+ *file.layers_mut() = vec![warped, flat, broken];+ let (doc, warnings) = photocraft_io::psd_to_document(&file);+ let sm = |i: usize| match &doc.layers[i].content {+ LayerContent::Smart(s) => s,+ _ => panic!("layer {i} is not a smart object"),+ };+ assert_eq!(sm(0).warp, Some(bulge));+ assert_eq!(sm(0).source, SmartSource::Linked { path: "missing".into() });+ assert_eq!((sm(1).warp.as_ref(), &sm(1).source), (None, &SmartSource::Linked { path: "missing".into() }));+ assert_eq!(sm(2).source, SmartSource::Linked { path: String::new() }, "unreadable warp: contents unavailable");+ assert!(sm(2).cache.is_some());+ assert_eq!(warnings.iter().filter(|w| w.contains("warp (PlLd) could not be read")).count(), 1, "{warnings:?}");+}++/// A linked smart object with both `SoLE` and `PlLd` is read from `SoLE`: `PlLd` alone is+/// Photoshop CS2's record (#2465).+#[test]+fn sole_wins_over_plld() {+ let (mut file, _) = round_trip(&fixture(), "psd");+ let spec = smart_map::PlacedSpec {+ idnt: "plld-only",+ placed: "",+ transform: Affine::IDENTITY,+ perspective: None,+ size: (2.0, 2.0),+ dpi: 72.0,+ warp: None,+ filter_fx: None,+ };+ let mut record = file.layers()[0].clone();+ let sold = record.block(b"SoLd").expect("the fixture has SoLd").data.clone();+ let (id, _) = photocraft_io::blocks::parse_smart(b"SoLd", &sold);+ assert!(!id.is_empty() && id != "plld-only");+ record.blocks.retain(|b| !matches!(&b.key, b"SoLd" | b"SoLE" | b"PlLd"));+ record.blocks.push(TaggedBlock::new(*b"PlLd", smart_map::plld_bytes(&spec, &mut Vec::new())));+ record.blocks.push(TaggedBlock::new(*b"SoLE", sold.clone()));+ *file.layers_mut() = vec![record];+ let (doc, _) = photocraft_io::psd_to_document(&file);+ let LayerContent::Smart(sm) = &doc.layers[0].content else { panic!("not a smart object") };+ assert_eq!(sm.source, SmartSource::Linked { path: id });+ assert_eq!(sm.psd_raw.as_deref(), Some(&sold));+}++/// A CS2 `PlLd`-only layer with a custom warp whose control points spill past its source frames+/// that control-point box with its corners, as `SoLd`'s `Trnf` does (#3677): it imports with the+/// same placement as the equivalent `SoLd` layer. Unedited, it saves its `PlLd` record verbatim+/// (no `SoLd` added) and reopens in the same place (#2465).+#[test]+fn plld_only_spilled_custom_warp_places_like_sold_and_round_trips_verbatim() {+ use photocraft_geom::warp::{BezierMesh, Warp};+ let (mut file, _) = round_trip(&fixture(), "psd");+ let mut record = file.layers()[0].clone();+ let (id, _) = photocraft_io::blocks::parse_smart(b"SoLd", &record.block(b"SoLd").expect("the fixture has SoLd").data);+ assert!(!id.is_empty());+ // The embedded source is 2 × 2; the mesh reaches from (-1, -0.5) to (3, 2.5).+ let bounds = [0.0, 0.0, 2.0, 2.0];+ let mut mesh = BezierMesh::identity(bounds, 1, 1);+ mesh.points[0] = [-1.0, -0.5];+ mesh.points[15] = [3.0, 2.5];+ let warp = Warp::custom(mesh, bounds);+ let t = Affine { m: [1.5, 0.0, 0.0, 1.5, 4.0, 1.0] };+ let spec =+ smart_map::PlacedSpec { idnt: &id, placed: "p", transform: t, perspective: None, size: (2.0, 2.0), dpi: 72.0, warp: Some(&warp), filter_fx: None };+ record.blocks.retain(|b| !matches!(&b.key, b"SoLd" | b"SoLE" | b"PlLd"));+ let (mut with_sold, mut cs2) = (record.clone(), record);+ with_sold.blocks.push(TaggedBlock::new(*b"SoLd", smart_map::sold_bytes(None, &spec, &mut Vec::new())));+ let plld = smart_map::plld_bytes(&spec, &mut Vec::new());+ cs2.blocks.push(TaggedBlock::new(*b"PlLd", plld.clone()));+ *file.layers_mut() = vec![with_sold, cs2];++ let (doc, warnings) = photocraft_io::psd_to_document(&file);+ assert!(!warnings.iter().any(|w| w.contains("PlLd")), "{warnings:?}");+ let sm = |d: &Document, i: usize| match &d.layers[i].content {+ LayerContent::Smart(s) => s.clone(),+ _ => panic!("layer {i} is not a smart object"),+ };+ let close = |a: Affine, b: Affine| a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() < 1e-9);+ let (a, b) = (sm(&doc, 0), sm(&doc, 1));+ assert!(close(a.transform, t), "SoLd: {:?} vs {t:?}", a.transform);+ assert!(close(b.transform, a.transform), "PlLd {:?} vs SoLd {:?}", b.transform, a.transform);+ assert_eq!((&b.source, &b.warp, b.perspective), (&a.source, &a.warp, a.perspective));+ assert_eq!(b.warp.as_ref(), Some(&warp));+ assert_eq!(b.source, SmartSource::Linked { path: id.clone() });++ // Unedited: the CS2 record is written back as it was, with no SoLd, and reopens in place.+ let out = export(&doc, "psd", &ExportOptions::default()).unwrap();+ let saved = PsdFile::from_bytes(&out.bytes).unwrap();+ let rec = &saved.layers()[1];+ assert_eq!(rec.block(b"PlLd").map(|b| &b.data), Some(&plld));+ assert!(rec.block(b"SoLd").is_none(), "an unedited PlLd-only layer gained a SoLd");+ let again = import("psd", &out.bytes).unwrap().document;+ let c = sm(&again, 1);+ assert!(close(c.transform, t), "{:?} vs {t:?}", c.transform);+ assert_eq!(c.warp.as_ref(), Some(&warp));+}diff --git a/docs/file-format-parity.md b/docs/file-format-parity.mdindex 12c6dc9d1..39f7ece88 100644--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@ -1,6 +1,6 @@# File-format parity-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (DPX read and write, #1049; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity andtests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write@@ -21,7 +21,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity.| Format | Photoshop | PhotoCraft read | PhotoCraft write | Fidelity and tests ||---|---|---|---|---|-| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2), smart filters (14 mapped, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 133/256, io 146/170, psd-tools 236/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469, #2465 (#2374, text layers, closed 2026-10-10) |+| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (14 mapped, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 133/256, io 146/170, psd-tools 236/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) || PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); 4–5 GB fixtures generated (FILE-216-2); > 4 GB fails on Windows (#375) || Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) || TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders (FILE-215-7: extra alpha channels not written) |@@ -141,6 +141,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.| Date | Change | Summary ||---|---|---|+| 2026-10-12 | minor | #2465 fixed: Photoshop CS2 placed layers (`PlLd` only, file in `lnkD`) open as editable smart objects and save their edits || 2026-10-12 | minor | DPX read and write (#1049); Cineon still missing || 2026-10-12 | minor | Photoshop Actions `.atn`: read and write, 90 events mapped, the rest kept verbatim (AUTO-219-2) || 2026-10-12 | minor | Presets table: Contours `.shc` read and write through the Contour Editor (FILE-215-15); `.csh` and `.tpl` stay missing |diff --git a/docs/gaps.md b/docs/gaps.mdindex 5a5068536..8e7516781 100644--- a/docs/gaps.md+++ b/docs/gaps.md@@ -1,6 +1,6 @@# Where PhotoCraft falls short of Photoshop-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impacton the way to beta. This is the work list agents pick from: take the highest-ranked entry that@@ -46,7 +46,7 @@ what an agent can't finish alone.oracles 133/256 (52%), io corpus 146/170 (86%), psd-tools 236/309 (76%); round trips ~100%within the corpus. Smart-filter re-render matches 5/30. User reports: a PSD with text layersre-saved unmodified would not reopen (#2374, closed 2026-10-10), Photoshop 26.6 cannot reopen our files (#1281), "PSD not- opening in Photoshop" (#2469), a CS2-era smart object unavailable (#2465), PSB smart object+ opening in Photoshop" (#2469), a CS2-era smart object unavailable (#2465, fixed 2026-10-12), PSB smart objectblank (#1764), perspective placed layers flattened (#579), PSB > 4 GB fails on Windows (#375).No test opens our exports in a third-party editor (FILE-216-4).- **Impact:** PSD is the format professionals exchange. Beta requires it to be reliable.@@ -240,6 +240,7 @@ what an agent can't finish alone.| Date | Change | Summary ||---|---|---|+| 2026-10-12 | minor | G1: #2465 (CS2 `PlLd`-only smart objects) marked fixed || 2026-10-12 | minor | G5: spring-loaded tool letters done (#2672) || 2026-10-12 | minor | G10: DPX read and write (#1049); Cineon remains open || 2026-10-12 | minor | G4: checkbox-only Brush Settings rows preserve the open controls and Smoothing settings (#4283); no readiness percentage or estimate changed |