diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index 1a6f2000e..a9b0148ec 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -438,7 +438,9 @@ fn read_descriptor(r: &mut Reader<'_>, depth: usize, limits: ParseLimits) -> Res let mut items = vec_for_count(n); for _ in 0..n { let key = Id::read(r)?; - let v = read_value(r, depth + 1, limits)?; + // A descriptor item is not another container; Objc/GlbO/ObAr and lists + // charge their nested containers exactly once below. + let v = read_value(r, depth, limits)?; items.push((key, v)); } Ok(Descriptor { name, class_id, items }) @@ -837,6 +839,30 @@ mod tests { assert!(matches!(Descriptor::from_bytes(&b), Err(PsdError::Unsupported(_)))); } + #[test] + fn container_depth_is_charged_once_and_still_bounded() { + for kind in ["Objc", "GlbO", "ObAr", "VlLs"] { + for count in [33, MAX_DEPTH, MAX_DEPTH + 1] { + let mut value = Value::Integer(1); + for _ in 0..count { + value = match kind { + "GlbO" => Value::GlobalObject(Descriptor::new("null").with("next", value)), + "ObAr" => Value::ObjectArray(ObjectArray { prefix: 16, body: Descriptor::new("null").with("next", value) }), + "VlLs" => Value::List(vec![value]), + _ => Value::Descriptor(Descriptor::new("null").with("next", value)), + }; + } + let bytes = Descriptor::new("null").with("root", value).to_bytes(); + let result = Descriptor::from_bytes(&bytes); + if count <= MAX_DEPTH { + assert!(result.is_ok(), "{kind} depth {count}: {result:?}"); + } else { + assert!(matches!(result, Err(PsdError::LimitExceeded(_))), "{kind} depth {count}"); + } + } + } + } + #[test] fn deep_nesting_is_limited() { let mut d = Descriptor::new("null"); diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index d4d98c695..38f382292 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -8,7 +8,8 @@ //! bicubic Bézier patches. //! //! The custom mesh is evaluated exactly (bicubic Bézier patches over `meshPoints`, split by -//! `quiltSliceX` / `quiltSliceY`). Photoshop does not publish the curves of its named styles; +//! equally spaced `quiltSliceX` / `quiltSliceY`). Unequal divisions are rejected by the +//! fallible placement reader. Photoshop does not publish the curves of its named styles; //! the styles here are clean-room geometric definitions of what each name describes (Arc, //! Arch, Bulge, Shell, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist), matched by //! behaviour, not numerically. @@ -59,9 +60,31 @@ pub struct Warp { /// The eight numbers of a transform entry (`Trnf`, `nonAffineTransform`), when it has exactly eight. fn eight(d: &Descriptor, key: &str) -> Option<[f64; 8]> { - d.get_numbers(key).try_into().ok() + d.get_numbers(key).into_iter().map(finite).collect::>().try_into().ok() } +fn finite(value: f64) -> f64 { + if value.is_finite() { value } else { 0.0 } +} + +/// A usable normalization rectangle needs finite positive extents on both axes. +fn valid_bounds([l, t, r, b]: [f64; 4]) -> bool { + [l, t, r, b].iter().all(|v| v.is_finite()) && (r - l).is_finite() && r > l && (b - t).is_finite() && b > t +} +/// Explicit quilt rectangles must be complete even without subdivision keys. +fn validate_quilt_bounds(d: &Descriptor) -> Result<()> { + if d.get("bounds").is_none() { + return Ok(()); + } + let bounds = d + .get_object("bounds") + .and_then(|b| Some([b.get_number("Left")?, b.get_number("Top ")?, b.get_number("Rght")?, b.get_number("Btom")?])) + .ok_or_else(|| PsdError::Unsupported("incomplete explicit quilt bounds".into()))?; + if !valid_bounds(bounds.map(finite)) { + return Err(PsdError::Unsupported("invalid explicit quilt bounds".into())); + } + Ok(()) +} /// The corner quad (top-left, top-right, bottom-right, bottom-left) from x0 y0 … x3 y3. fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] { [[t[0], t[1]], [t[2], t[3]], [t[4], t[5]], [t[6], t[7]]] @@ -69,24 +92,76 @@ fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] { /// The patch boundaries of a custom envelope: a list of numbers, or (as Photoshop writes a /// `quiltWarp`) an object array whose body holds them under the same key. -fn quilt_slices(env: &Descriptor, key: &str) -> Vec { - match env.get(key) { - Some(Value::ObjectArray(o)) => o.body.get_numbers(key), - _ => env.get_numbers(key), - } +fn quilt_slices(env: &Descriptor, key: &str) -> Result> { + let Some(value) = env.get(key) else { return Ok(vec![]) }; + // Filtering nonnumbers would change the number and positions of patches. + // Only absence, not a malformed or empty present value, means one patch. + let value = if let Value::ObjectArray(o) = value { o.body.get(key) } else { Some(value) }; + let values = match value { + Some(Value::UnitFloats { values, .. }) => Some(values.clone()), + Some(Value::List(values)) => values.iter().map(Value::as_number).collect::>>(), + _ => None, + }; + values.filter(|values| !values.is_empty()).ok_or_else(|| PsdError::Unsupported("invalid quilt slice values".into())) } +/// The public mesh has no slice coordinates, so only uniform divisions can be +/// represented faithfully. Keep the legacy absent-slices single-patch convention. +fn quilt_patches(slices: &[f64]) -> Result { + if slices.is_empty() { + return Ok(1); + } + if slices.len() < 2 || slices.iter().any(|v| !v.is_finite()) { + return Err(PsdError::Unsupported("invalid quilt divisions".into())); + } + let patches = slices.len() - 1; + let extent = slices[patches] - slices[0]; + if !extent.is_finite() || extent <= 0.0 { + return Err(PsdError::Unsupported("invalid quilt divisions".into())); + } + // Compare against the same endpoint interpolation the writer uses. At large + // coordinate offsets a uniform grid can have differently rounded adjacent widths, + // including coincident boundaries. Only canonical rounded positions are accepted; + // the model keeps the patch count and evaluates in its uniform parameter domain. + let tolerance = (extent / patches as f64) * 1e-9; + if slices.windows(2).any(|pair| pair[1] < pair[0]) + || slices.iter().enumerate().take(patches).skip(1).any(|(i, value)| { + let expected = slices[0] + extent * (i as f64 / patches as f64); + !expected.is_finite() || (value - expected).abs() > tolerance + }) + { + return Err(PsdError::Unsupported("unequal quilt divisions".into())); + } + Ok(patches) +} impl Warp { /// Reads a `warp` descriptor; `None` for no warp (the identity, or a custom warp without a - /// usable mesh). + /// usable mesh), or an unsupported quilt. Use [`Self::try_from_descriptor`] to report unsupported geometry. pub fn from_descriptor(d: &Descriptor) -> Option { + Self::try_from_descriptor(d).ok().flatten() + } + + /// Reads a warp, rejecting unequal or invalid quilt divisions rather than + /// interpreting them as equal-sized patches. Canonical uniform boundaries may coincide + /// after floating-point rounding; their patch count is retained. This is the internal + /// uniform-model contract, not a guarantee of other readers' handling of coincident slices. + /// Nonfinite geometry becomes zero. + pub fn try_from_descriptor(d: &Descriptor) -> Result> { + Self::try_from_descriptor_kind(d, d.class_id.is("quiltWarp")) + } + + // The containing SoLd key is authoritative even if an embedded class differs. + fn try_from_descriptor_kind(d: &Descriptor, quilt: bool) -> Result> { + if quilt { + validate_quilt_bounds(d)?; + } let style = d.get_enum("warpStyle").unwrap_or_else(|| "warpNone".to_string()); - let side = |b: &Descriptor, k: &str| b.get_number(k).unwrap_or(0.0); + let side = |b: &Descriptor, k: &str| finite(b.get_number(k).unwrap_or(0.0)); let bounds = d.get_object("bounds").map_or([0.0; 4], |b| [side(b, "Left"), side(b, "Top "), side(b, "Rght"), side(b, "Btom")]); let mut w = Warp { - bend: d.get_number("warpValue").unwrap_or(0.0), - horizontal: d.get_number("warpPerspective").unwrap_or(0.0), - vertical: d.get_number("warpPerspectiveOther").unwrap_or(0.0), + bend: finite(d.get_number("warpValue").unwrap_or(0.0)), + horizontal: finite(d.get_number("warpPerspective").unwrap_or(0.0)), + vertical: finite(d.get_number("warpPerspectiveOther").unwrap_or(0.0)), rotate_vertical: d.get_enum("warpRotate").as_deref() == Some("Vrtc"), bounds, cols: 1, @@ -95,8 +170,41 @@ impl Warp { style, }; if let Some(env) = d.get_object("customEnvelopeWarp") { - let cols = quilt_slices(env, "quiltSliceX").len().saturating_sub(1).max(1); - let rows = quilt_slices(env, "quiltSliceY").len().saturating_sub(1).max(1); + let slice_x = quilt_slices(env, "quiltSliceX")?; + let slice_y = quilt_slices(env, "quiltSliceY")?; + let cols = quilt_patches(&slice_x)?; + let rows = quilt_patches(&slice_y)?; + if !slice_x.is_empty() || !slice_y.is_empty() { + validate_quilt_bounds(d)?; + + // The evaluator normalizes over bounds, not stored slice coordinates. + // Infer an absent rectangle only when both explicit axes define it. + if !valid_bounds(w.bounds) { + if d.get("bounds").is_some() { + return Err(PsdError::Unsupported("invalid explicit quilt bounds".into())); + } + let (Some(&left), Some(&right), Some(&top), Some(&bottom)) = (slice_x.first(), slice_x.last(), slice_y.first(), slice_y.last()) + else { + return Err(PsdError::Unsupported("quilt divisions need bounds or both axes".into())); + }; + w.bounds = [left, top, right, bottom]; + if !valid_bounds(w.bounds) { + return Err(PsdError::Unsupported("invalid inferred quilt bounds".into())); + } + } + for (slices, start, end) in [(&slice_x, w.bounds[0], w.bounds[2]), (&slice_y, w.bounds[1], w.bounds[3])] { + if let (Some(&first), Some(&last)) = (slices.first(), slices.last()) { + let extent = end - start; + if !extent.is_finite() { + return Err(PsdError::Unsupported("quilt bounds overflow".into())); + } + let tolerance = extent.abs() * 1e-9; + if (first - start).abs() > tolerance || (last - end).abs() > tolerance { + return Err(PsdError::Unsupported("quilt divisions do not match warp bounds".into())); + } + } + } + } if let Some(Value::ObjectArray(pts)) = env.get("meshPoints") { let xs = pts.body.get_numbers("Hrzn"); let ys = pts.body.get_numbers("Vrtc"); @@ -104,18 +212,18 @@ impl Warp { if n.is_some_and(|n| xs.len() == n && ys.len() == n) { w.cols = cols; w.rows = rows; - w.mesh = xs.into_iter().zip(ys).map(|(x, y)| [x, y]).collect(); + w.mesh = xs.into_iter().zip(ys).map(|(x, y)| [finite(x), finite(y)]).collect(); } } } let identity = w.style == "warpNone" || (w.style != "warpCustom" && w.bend == 0.0 && w.horizontal == 0.0 && w.vertical == 0.0); let custom_ok = w.style != "warpCustom" || !w.mesh.is_empty(); - (!identity && custom_ok).then_some(w) + Ok((!identity && custom_ok).then_some(w)) } /// The warp of a content point (content pixels → content pixels). pub fn apply(&self, p: [f64; 2], w: f64, h: f64) -> [f64; 2] { - let [l, t, r, b] = if self.bounds[2] > self.bounds[0] && self.bounds[3] > self.bounds[1] { self.bounds } else { [0.0, 0.0, w, h] }; + let [l, t, r, b] = if valid_bounds(self.bounds) { self.bounds } else { [0.0, 0.0, w, h] }; let (bw, bh) = (r - l, b - t); let (u, v) = ((p[0] - l) / bw, (p[1] - t) / bh); if self.style == "warpCustom" { @@ -273,9 +381,12 @@ impl SmartObject { let t = eight(&d, "Trnf").unwrap_or([0.0; 8]); // The non-affine transform when present (perspective), else the transform. let t = eight(&d, "nonAffineTransform").unwrap_or(t); - let size = d.get_object("Sz ").and_then(|s| Some([s.get_number("Wdth")?, s.get_number("Hght")?])); + let size = d.get_object("Sz ").and_then(|s| Some([finite(s.get_number("Wdth")?), finite(s.get_number("Hght")?)])); // A split warp is in `quiltWarp`, with `warp` holding none. - let warp = d.get_object("quiltWarp").and_then(Warp::from_descriptor).or_else(|| d.get_object("warp").and_then(Warp::from_descriptor)); + let mut warp = d.get_object("quiltWarp").map(|q| Warp::try_from_descriptor_kind(q, true)).transpose()?.flatten(); + if warp.is_none() { + warp = d.get_object("warp").map(|w| Warp::try_from_descriptor_kind(w, false)).transpose()?.flatten(); + } Ok(SmartObject { uuid, quad: quad_from(t), size, warp }) } @@ -949,6 +1060,290 @@ mod tests { assert!(select_linked_records(&unicode, &|uuid, _| uuid == "\u{fffd}").unwrap().is_none()); } + #[test] + fn placement_normalizes_nonfinite_geometry_before_classification() { + let data = placed_layer_data("finite", [f64::NAN, 0.0, 20.0, 0.0, 20.0, 10.0, 0.0, 10.0], |d| { + let warp = Descriptor::new("warp") + .with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpArc") }) + .with("warpValue", Value::Double(f64::NAN)) + .with("warpPerspective", Value::Double(f64::INFINITY)) + .with("warpPerspectiveOther", Value::Double(f64::NEG_INFINITY)); + let size = Descriptor::new("Pnt ").with("Wdth", Value::Double(f64::INFINITY)).with("Hght", Value::Double(10.0)); + d.with("warp", Value::Descriptor(warp)).with("Sz ", Value::Descriptor(size)) + }); + let object = SmartObject::from_placed_layer_data(&data).unwrap(); + assert_eq!(object.quad, [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]); + assert_eq!(object.size, Some([0.0, 10.0])); + assert!(!object.needs_bake()); + assert_eq!(object.map([5.0, 5.0], 20.0, 10.0), [5.0, 5.0]); + } + + fn quilt_descriptor(xs: Vec, ys: Vec) -> Descriptor { + let unfl = |values| Value::UnitFloats { unit: *b"#Pxl", values }; + // Identity control points for a 7 x 4 mesh with a split at x=5. + let x = [0.0, 5.0 / 3.0, 10.0 / 3.0, 5.0, 10.0, 15.0, 20.0]; + let body = Descriptor::new("rationalPoint") + .with("Hrzn", unfl((0..4).flat_map(|_| x).collect())) + .with("Vrtc", unfl((0..4).flat_map(|j| [j as f64 * 10.0 / 3.0; 7]).collect())); + let env = Descriptor::new("customEnvelopeWarp") + .with("quiltSliceX", unfl(xs)) + .with("quiltSliceY", unfl(ys)) + .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body })); + Descriptor::new("warp") + .with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpCustom") }) + .with("customEnvelopeWarp", Value::Descriptor(env)) + } + + #[test] + fn unequal_quilts_are_errors_not_uniform_meshes_or_fallback_warps() { + for (xs, ys) in [(vec![0.0, 5.0, 20.0], vec![0.0, 10.0]), (vec![0.0, 10.0, 20.0], vec![0.0, 2.0, 10.0])] { + let warp = quilt_descriptor(xs, ys); + assert!(matches!(Warp::try_from_descriptor(&warp), Err(PsdError::Unsupported(_)))); + for key in ["warp", "quiltWarp"] { + let data = placed_layer_data("quilt", [0.0; 8], |d| { + let d = if key == "quiltWarp" { d.with("warp", Value::Descriptor(Descriptor::new("warp"))) } else { d }; + d.with(key, Value::Descriptor(warp.clone())) + }); + assert!(matches!(SmartObject::from_placed_layer_data(&data), Err(PsdError::Unsupported(_)))); + } + } + for slices in [vec![0.0], vec![0.0, 0.0], vec![10.0, 0.0], vec![0.0, f64::NAN]] { + assert!(quilt_patches(&slices).is_err()); + } + assert_eq!(quilt_patches(&[]).unwrap(), 1); + assert_eq!(quilt_patches(&[0.0, 10.0, 20.0]).unwrap(), 2); + assert_eq!(quilt_patches(&[1e16, 1e16 + 2.0, 1e16 + 6.0, 1e16 + 8.0]).unwrap(), 3); + assert!(quilt_patches(&[1e16, 1e16 + 4.0, 1e16 + 6.0, 1e16 + 8.0]).is_err()); + let lo = 3.0 * 2.0_f64.powi(970); + assert!((f64::MAX - lo).is_finite()); + assert!((lo + (f64::MAX - lo)).is_infinite()); + assert_eq!(quilt_patches(&[lo, f64::MAX]).unwrap(), 1); + assert_eq!(quilt_patches(&[1e16, 1e16, 1e16, 1e16 + 2.0, 1e16 + 2.0]).unwrap(), 4); + for invalid in [vec![0.0, 0.0, 20.0], vec![0.0, 10.0, 10.0, 20.0], vec![1e16, 1e16 + 2.0, 1e16, 1e16 + 2.0]] { + assert!(quilt_patches(&invalid).is_err()); + } + } + + #[test] + fn quilt_slice_values_are_strict_in_lists_and_object_arrays() { + let list = Value::List(vec![Value::Integer(0), Value::Double(10.0), Value::UnitFloat { unit: *b"#Pxl", value: 20.0 }]); + let unfl = Value::UnitFloats { unit: *b"#Pxl", values: vec![0.0, 10.0, 20.0] }; + let bad_list = Value::List(vec![Value::Double(0.0), Value::Text(UnicodeString::new("bad")), Value::Double(10.0), Value::Double(20.0)]); + for wrapped in [false, true] { + for (value, valid) in [ + (list.clone(), true), + (unfl.clone(), true), + (bad_list.clone(), false), + (Value::List(vec![]), false), + (Value::UnitFloats { unit: *b"#Pxl", values: vec![] }, false), + (Value::Integer(1), false), + ] { + let value = if wrapped { + Value::ObjectArray(ObjectArray { prefix: 3, body: Descriptor::new("UntF").with("quiltSliceX", value) }) + } else { + value + }; + let mut d = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); + let Value::Descriptor(env) = &mut d.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else { + panic!("envelope") + }; + env.items.iter_mut().find(|(key, _)| key.is("quiltSliceX")).unwrap().1 = value; + assert_eq!(Warp::try_from_descriptor(&d).is_ok(), valid); + let bytes = placed_layer_data("slices", [0.0; 8], |parent| parent.with("quiltWarp", Value::Descriptor(d))); + assert_eq!(SmartObject::from_placed_layer_data(&bytes).is_ok(), valid); + } + } + let absent = Descriptor::new("customEnvelopeWarp"); + assert!(quilt_slices(&absent, "quiltSliceX").unwrap().is_empty()); + let missing_body = absent.with("quiltSliceX", Value::ObjectArray(ObjectArray { prefix: 0, body: Descriptor::new("UntF") })); + assert!(quilt_slices(&missing_body, "quiltSliceX").is_err()); + } + #[test] + fn quilt_endpoints_define_or_match_the_normalization_bounds() { + let equal = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); + assert_eq!(Warp::try_from_descriptor(&equal).unwrap().unwrap().bounds, [0.0, 0.0, 20.0, 10.0]); + let bounds = Descriptor::new("bounds") + .with("Left", Value::Double(0.0)) + .with("Top ", Value::Double(0.0)) + .with("Rght", Value::Double(40.0)) + .with("Btom", Value::Double(10.0)); + assert!(Warp::try_from_descriptor(&equal.with("bounds", Value::Descriptor(bounds))).is_err()); + let wrong_type = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]).with("bounds", Value::Integer(1)); + assert!(Warp::try_from_descriptor(&wrong_type).is_err()); + let invalid_bounds = Descriptor::new("bounds") + .with("Left", Value::Double(0.0)) + .with("Top ", Value::Double(0.0)) + .with("Rght", Value::Double(40.0)) + .with("Btom", Value::Double(0.0)); + let explicit_invalid = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]).with("bounds", Value::Descriptor(invalid_bounds)); + assert!(Warp::try_from_descriptor(&explicit_invalid).is_err()); + let data = placed_layer_data("invalid bounds", [0.0; 8], |d| d.with("quiltWarp", Value::Descriptor(explicit_invalid))); + assert!(matches!(SmartObject::from_placed_layer_data(&data), Err(PsdError::Unsupported(_)))); + let mut missing = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); + let Value::Descriptor(env) = &mut missing.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else { + panic!("envelope") + }; + env.items.retain(|(key, _)| !key.is("quiltSliceY")); + assert!(Warp::try_from_descriptor(&missing).is_err()); + let bounds = |top, bottom| { + Descriptor::new("bounds") + .with("Left", Value::Double(0.0)) + .with("Top ", Value::Double(top)) + .with("Rght", Value::Double(20.0)) + .with("Btom", Value::Double(bottom)) + }; + let present = missing.clone().with("bounds", Value::Descriptor(bounds(0.0, 10.0))); + let parsed = Warp::try_from_descriptor(&present).unwrap().unwrap(); + assert_eq!((parsed.cols, parsed.rows), (2, 1)); + assert_eq!(parsed.bounds, [0.0, 0.0, 20.0, 10.0]); + // Even the absent slice axis needs a finite normalization extent. + let overflow = missing.with("bounds", Value::Descriptor(bounds(-f64::MAX, f64::MAX))); + assert!(Warp::try_from_descriptor(&overflow).is_err()); + } + #[test] + fn quilt_bounds_policy_covers_every_slice_axis_and_descriptor_context() { + let rect = |l, t, r, b| { + Value::Descriptor( + Descriptor::new("bounds") + .with("Left", Value::Double(l)) + .with("Top ", Value::Double(t)) + .with("Rght", Value::Double(r)) + .with("Btom", Value::Double(b)), + ) + }; + let cases = [ + (None, true), + (Some(rect(0.0, 0.0, 20.0, 10.0)), true), + (Some(Value::Integer(0)), false), + ( + Some(Value::Descriptor( + Descriptor::new("bounds").with("Left", Value::Double(0.0)).with("Rght", Value::Double(20.0)).with("Btom", Value::Double(10.0)), + )), + false, + ), + ( + Some(Value::Descriptor( + Descriptor::new("bounds") + .with("Left", Value::Double(0.0)) + .with("Top ", Value::Text(UnicodeString::new("bad"))) + .with("Rght", Value::Double(20.0)) + .with("Btom", Value::Double(10.0)), + )), + false, + ), + (Some(rect(0.0, 10.0, 20.0, 10.0)), false), + (Some(rect(0.0, -f64::MAX, 20.0, f64::MAX)), false), + (Some(rect(f64::NAN, f64::NEG_INFINITY, 20.0, 10.0)), true), + ]; + for axes in 0..4 { + for class in ["warp", "quiltWarp"] { + for (bounds, valid) in &cases { + let mut d = Warp { + style: "warpCustom".into(), + cols: 1, + rows: 1, + mesh: (0..4).flat_map(|y| (0..4).map(move |x| [x as f64 * 20.0 / 3.0, y as f64 * 10.0 / 3.0])).collect(), + ..Warp::default() + } + .to_descriptor(); + d.class_id = Id::new(class); + d.items.retain(|(key, _)| !key.is("bounds")); + if let Some(bounds) = bounds { + d.items.push((Id::new("bounds"), bounds.clone())); + } + let Value::Descriptor(env) = &mut d.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else { + panic!("envelope") + }; + for (bit, key, end) in [(1, "quiltSliceX", 20.0), (2, "quiltSliceY", 10.0)] { + if axes & bit != 0 { + env.items.push((Id::new(key), Value::UnitFloats { unit: *b"#Pxl", values: vec![0.0, end] })); + } + } + let expected = |quilt: bool| { + if bounds.is_none() { axes == 0 || axes == 3 } else { *valid || (!quilt && axes == 0) } + }; + assert_eq!( + Warp::try_from_descriptor(&d).is_ok(), + expected(class == "quiltWarp"), + "direct {class}, axes={axes}, bounds={bounds:?}" + ); + for field in ["warp", "quiltWarp"] { + let bytes = placed_layer_data("context", [0.0; 8], |parent| parent.with(field, Value::Descriptor(d.clone()))); + assert_eq!( + SmartObject::from_placed_layer_data(&bytes).is_ok(), + expected(field == "quiltWarp"), + "{field}/{class}, axes={axes}, bounds={bounds:?}" + ); + } + } + } + } + // No envelope and identity style must not bypass explicit quilt bounds. + for class in ["warp", "quiltWarp"] { + let d = Descriptor::new(class).with("bounds", rect(0.0, 10.0, 20.0, 10.0)); + assert_eq!(Warp::try_from_descriptor(&d).is_ok(), class == "warp"); + let bytes = placed_layer_data("identity", [0.0; 8], |parent| parent.with("quiltWarp", Value::Descriptor(d))); + assert!(SmartObject::from_placed_layer_data(&bytes).is_err()); + } + } + #[test] + fn explicit_quilt_bounds_require_every_numeric_side() { + let sides = [("Left", 0.0), ("Top ", 0.0), ("Rght", 20.0), ("Btom", 10.0)]; + for omit_y in [false, true] { + let mut quilt = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); + if omit_y { + let Value::Descriptor(env) = &mut quilt.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else { + panic!("envelope") + }; + env.items.retain(|(key, _)| !key.is("quiltSliceY")); + } + let complete = sides.iter().fold(Descriptor::new("bounds"), |d, (key, value)| d.with(key, Value::Double(*value))); + assert!(Warp::try_from_descriptor(&quilt.clone().with("bounds", Value::Descriptor(complete))).unwrap().is_some()); + for (side, _) in sides { + for missing in [true, false] { + let bounds = sides.iter().fold(Descriptor::new("bounds"), |d, (key, value)| { + if *key != side { + d.with(key, Value::Double(*value)) + } else if missing { + d + } else { + d.with(key, Value::Text(UnicodeString::new("not a number"))) + } + }); + let invalid = quilt.clone().with("bounds", Value::Descriptor(bounds)); + assert!( + matches!(Warp::try_from_descriptor(&invalid), Err(PsdError::Unsupported(_))), + "{side}, missing={missing}, omit_y={omit_y}" + ); + let bytes = placed_layer_data("incomplete", [0.0; 8], |d| d.with("quiltWarp", Value::Descriptor(invalid))); + assert!(matches!(SmartObject::from_placed_layer_data(&bytes), Err(PsdError::Unsupported(_)))); + } + } + } + } + #[test] + fn finite_warp_views_preserve_raw_descriptor_values() { + let mut warp = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); + let bounds = Descriptor::new("bounds") + .with("Left", Value::Double(f64::NAN)) + .with("Top ", Value::Double(f64::NEG_INFINITY)) + .with("Rght", Value::Double(20.0)) + .with("Btom", Value::Double(10.0)); + warp = warp.with("bounds", Value::Descriptor(bounds)); + let env = warp.items.iter_mut().find(|(key, _)| key.as_bytes() == b"customEnvelopeWarp").unwrap(); + let Value::Descriptor(env) = &mut env.1 else { panic!("envelope") }; + let points = env.items.iter_mut().find(|(key, _)| key.as_bytes() == b"meshPoints").unwrap(); + let Value::ObjectArray(points) = &mut points.1 else { panic!("mesh") }; + let values = &mut points.body.items[0].1; + let Value::UnitFloats { values, .. } = values else { panic!("coordinates") }; + values[0] = f64::NAN; + let bytes = warp.to_bytes(); + let view = Warp::try_from_descriptor(&warp).unwrap().unwrap(); + assert_eq!(view.bounds, [0.0, 0.0, 20.0, 10.0]); + assert_eq!(view.mesh[0], [0.0, 0.0]); + assert_eq!(warp.to_bytes(), bytes); + } + #[test] fn placed_layer_data_gives_the_id_quad_size_and_warp() { let quad = [20.0, 4.0, 40.0, 4.0, 40.0, 44.0, 20.0, 44.0]; diff --git a/crates/psd/src/smart/write.rs b/crates/psd/src/smart/write.rs index d409d726c..6976417b2 100644 --- a/crates/psd/src/smart/write.rs +++ b/crates/psd/src/smart/write.rs @@ -3,7 +3,7 @@ //! read back. Came from PhotoCraft's `crates/io/src/smart_map/placed.rs`, on this crate's //! placement types: the caller works out the quad and the warp from its own geometry. -use super::{SmartObject, Warp}; +use super::{SmartObject, Warp, valid_bounds}; use crate::descriptor::{Descriptor, Id, ObjectArray, UnicodeString, Value, VersionedDescriptor}; use crate::io::WriteExt; @@ -78,7 +78,10 @@ impl Warp { /// Style, bend, distortions, axis, bounds and order: the keys a `warp` and a `quiltWarp` /// share, in Photoshop's order. fn head(&self, class: &str) -> Descriptor { - let [l, t, r, b] = self.bounds; + self.head_with_bounds(class, self.bounds) + } + + fn head_with_bounds(&self, class: &str, [l, t, r, b]: [f64; 4]) -> Descriptor { let bounds = Descriptor::new("classFloatRect") .with("Top ", Value::Double(t)) .with("Left", Value::Double(l)) @@ -119,15 +122,32 @@ impl Warp { /// The `quiltWarp` descriptor of a split warp, in Photoshop's layout: the control points, /// `deformNumCols` × `deformNumRows` of them, and the patch boundaries (`quiltSliceX` / - /// `quiltSliceY`) evenly across the warp's bounds. `None` for any other warp. + /// `quiltSliceY`) evenly across the warp's bounds. Invalid axes use 0..1 because this standalone + /// method has no content size; the placed-layer writer supplies that size when available. + /// Canonical boundaries may coincide after rounding at large offsets. The shared reader + /// preserves their uniform-model parameterization; external reader interoperability for + /// coincident slices is not guaranteed. `None` for any other warp. pub fn quilt_descriptor(&self) -> Option { if !self.is_split() { return None; } - let [l, t, r, b] = self.bounds; + // The header and the divisions must describe the same rectangle, including + // when a caller leaves bounds at their default or supplies an invalid axis. + let axis = |lo: f64, hi: f64| if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) }; + let (l, r) = axis(self.bounds[0], self.bounds[2]); + let (t, b) = axis(self.bounds[1], self.bounds[3]); let slices = |key: &str, n: usize, lo: f64, hi: f64| { - let (lo, hi) = if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) }; - let values: Vec = (0..=n).map(|i| lo + (hi - lo) * i as f64 / n as f64).collect(); + let values: Vec = (0..=n) + .map(|i| { + if i == 0 { + lo + } else if i == n { + hi + } else { + lo + (hi - lo) * (i as f64 / n as f64) + } + }) + .collect(); let prefix = values.len() as u32; Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(key, Value::UnitFloats { unit: *b"#Pxl", values }) }) }; @@ -137,7 +157,7 @@ impl Warp { .with("meshPoints", self.mesh_points()); let count = |n: usize| Value::Integer(i32::try_from(n.saturating_mul(3).saturating_add(1)).unwrap_or(i32::MAX)); Some( - self.head("quiltWarp") + self.head_with_bounds("quiltWarp", [l, t, r, b]) .with("deformNumRows", count(self.rows)) .with("deformNumCols", count(self.cols)) .with("customEnvelopeWarp", Value::Descriptor(envelope)), @@ -159,7 +179,13 @@ impl SmartObject { /// The warp written, over the content (or `[0, 0, 0, 0]` without a size) when there is none. fn warp_or_none(&self) -> Warp { let [w, h] = self.size.unwrap_or([0.0; 2]); - self.warp.clone().unwrap_or_else(|| Warp::none([0.0, 0.0, w, h])) + let mut warp = self.warp.clone().unwrap_or_else(|| Warp::none([0.0, 0.0, w, h])); + // Match Warp::apply's whole-rectangle fallback before encoding explicit + // quilt slices. Otherwise default bounds would change the mapping on readback. + if warp.is_split() && !valid_bounds(warp.bounds) { + warp.bounds = [0.0, 0.0, w, h]; + } + warp } /// The data of a `SoLd` block (`soLD`, version 4, a version-16 descriptor, padded to 4). @@ -180,7 +206,9 @@ impl SmartObject { } set(&mut d, "warp", Value::Descriptor(warp.to_descriptor())); // The imported `quiltWarp` stays while it still says what the warp is. - let kept = t.get_object("quiltWarp").is_some_and(|q| Warp::from_descriptor(q).as_ref() == self.warp.as_ref()); + let kept = t + .get_object("quiltWarp") + .is_some_and(|q| Warp::try_from_descriptor_kind(q, true).is_ok_and(|parsed| parsed.as_ref() == self.warp.as_ref())); if !kept { match quilt { Some(q) => set_before(&mut d, "quiltWarp", Value::Descriptor(q), "warp"), @@ -289,6 +317,108 @@ mod tests { ] } + #[test] + fn quilt_writer_uses_one_rectangle_for_header_slices_and_roundtrip() { + for (bounds, expected) in [ + ([0.0; 4], [0.0, 0.0, 1.0, 1.0]), + ([2.0, 3.0, 22.0, 13.0], [2.0, 3.0, 22.0, 13.0]), + ([2.0, 3.0, 22.0, 3.0], [2.0, 0.0, 22.0, 1.0]), + ([f64::NAN, 3.0, 22.0, 13.0], [0.0, 3.0, 1.0, 13.0]), + ([-f64::MAX, 0.0, f64::MAX, 1.0], [0.0, 0.0, 1.0, 1.0]), + ([0.0, 0.0, 1e308, 10.0], [0.0, 0.0, 1e308, 10.0]), + ([3.0 * 2.0_f64.powi(970), 0.0, f64::MAX, 10.0], [3.0 * 2.0_f64.powi(970), 0.0, f64::MAX, 10.0]), + ] { + let warp = Warp { style: "warpCustom".into(), bounds, cols: 2, rows: 1, mesh: grid(2, 1, 20.0, 10.0), ..Warp::default() }; + let descriptor = warp.quilt_descriptor().unwrap(); + let back = Warp::try_from_descriptor(&descriptor).unwrap().unwrap(); + assert_eq!(back.bounds, expected); + assert_eq!((back.cols, back.rows, &back.mesh), (2, 1, &warp.mesh)); + assert_eq!(back.quilt_descriptor().unwrap(), descriptor); + } + let high_offset = Warp { + style: "warpCustom".into(), + bounds: [1e16, 0.0, 1e16 + 8.0, 10.0], + cols: 3, + rows: 1, + mesh: grid(3, 1, 20.0, 10.0), + ..Warp::default() + }; + assert_eq!(Warp::try_from_descriptor(&high_offset.quilt_descriptor().unwrap()).unwrap(), Some(high_offset)); + // At the placed-layer boundary content size is available: preserve the + // evaluator's fallback mapping, not merely the ability to parse the output. + for bounds in [[0.0; 4], [2.0, 3.0, 22.0, 3.0], [f64::NAN, 0.0, 20.0, 10.0], [-f64::MAX, 0.0, f64::MAX, 10.0]] { + let warp = Warp { style: "warpCustom".into(), bounds, cols: 2, rows: 1, mesh: grid(2, 1, 20.0, 10.0), ..Warp::default() }; + let so = SmartObject { size: Some([20.0, 10.0]), ..placed(Some(warp.clone())) }; + let bytes = so.to_placed_layer_data(&PlacedLayerOptions::default()); + let back = SmartObject::from_placed_layer_data(&bytes).unwrap(); + let parsed = back.warp.as_ref().unwrap(); + assert_eq!(parsed.bounds, [0.0, 0.0, 20.0, 10.0]); + for p in [[0.0, 0.0], [5.0, 4.0], [10.0, 5.0], [20.0, 10.0]] { + assert_eq!(parsed.apply(p, 20.0, 10.0), warp.apply(p, 20.0, 10.0)); + } + let template = VersionedDescriptor::parse_prefix(&bytes[8..]).unwrap().0.descriptor; + let rewritten = back.to_placed_layer_data(&PlacedLayerOptions { template: Some(&template), ..Default::default() }); + assert_eq!(SmartObject::from_placed_layer_data(&rewritten).unwrap(), back); + } + } + #[test] + fn canonically_collapsed_boundaries_preserve_both_axes_mapping() { + let lo = 1e16; + let hi = lo + 2.0; + for (cols, rows, bounds, axis) in + [(4, 1, [lo, 0.0, hi, 10.0], "quiltSliceX"), (1, 4, [0.0, lo, 20.0, hi], "quiltSliceY"), (4, 4, [lo, lo, hi, hi], "quiltSliceX")] + { + let warp = Warp { style: "warpCustom".into(), bounds, cols, rows, mesh: grid(cols, rows, 20.0, 10.0), ..Warp::default() }; + let descriptor = warp.quilt_descriptor().unwrap(); + let env = descriptor.get_object("customEnvelopeWarp").unwrap(); + let Value::ObjectArray(slices) = env.get(axis).unwrap() else { panic!("slices") }; + let values = slices.body.get_numbers(axis); + assert_eq!(values, vec![lo, lo, lo, hi, hi]); + // The first, middle and last intervals all have rounded coincident endpoints. + assert_eq!(values[0], values[1]); + assert_eq!(values[1], values[2]); + assert_eq!(values[3], values[4]); + let so = placed(Some(warp.clone())); + let bytes = so.to_placed_layer_data(&PlacedLayerOptions::default()); + let back = SmartObject::from_placed_layer_data(&bytes).unwrap(); + assert_eq!(back.warp, Some(warp.clone())); + let parsed = back.warp.as_ref().unwrap(); + for p in [[bounds[0], bounds[1]], [bounds[2], bounds[1]], [bounds[0], bounds[3]], [bounds[2], bounds[3]]] { + assert_eq!(parsed.apply(p, 20.0, 10.0), warp.apply(p, 20.0, 10.0)); + } + let template = VersionedDescriptor::parse_prefix(&bytes[8..]).unwrap().0.descriptor; + let rewritten = back.to_placed_layer_data(&PlacedLayerOptions { template: Some(&template), ..Default::default() }); + assert_eq!(SmartObject::from_placed_layer_data(&rewritten).unwrap(), back); + } + } + #[test] + fn templates_drop_unsupported_quilts_but_retain_valid_none() { + let bounds = [0.0, 0.0, 20.0, 10.0]; + let unfl = |values| Value::UnitFloats { unit: *b"#Pxl", values }; + let unequal = + Descriptor::new("warp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpCustom") }).with( + "customEnvelopeWarp", + Value::Descriptor( + Descriptor::new("customEnvelopeWarp").with("quiltSliceX", unfl(vec![0.0, 5.0, 20.0])).with("quiltSliceY", unfl(vec![0.0, 10.0])), + ), + ); + assert!(Warp::try_from_descriptor(&unequal).is_err()); + let valid_none = Warp::none(bounds).to_descriptor(); + assert!(matches!(Warp::try_from_descriptor(&valid_none), Ok(None))); + let invalid_none = Warp::none([0.0, 10.0, 20.0, 10.0]).to_descriptor(); + for (quilt, keep) in [(unequal, false), (valid_none, true), (invalid_none, false)] { + let template = Descriptor::new("null").with("quiltWarp", Value::Descriptor(quilt.clone())); + let bytes = placed(None).to_placed_layer_data(&PlacedLayerOptions { + placed: "layer", + resolution: 72.0, + filter_fx: None, + template: Some(&template), + }); + let written = VersionedDescriptor::parse_prefix(&bytes[8..]).unwrap().0.descriptor; + assert_eq!(written.get_object("quiltWarp"), keep.then_some(&quilt)); + assert!(SmartObject::from_placed_layer_data(&bytes).unwrap().warp.is_none()); + } + } #[test] fn placed_layer_data_reads_back_and_passes_the_strict_check() { let filter = Descriptor::new("filterFX")