PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Layer comp offsets out of i32 range are dropped with a warning, not overflowed (#1017) (#1039)
yangcd03d49c34c8
diff --git a/crates/engine/src/comps_cmds.rs b/crates/engine/src/comps_cmds.rsindex 57d8fa010..3857236f6 100644--- a/crates/engine/src/comps_cmds.rs+++ b/crates/engine/src/comps_cmds.rs@@ -78,11 +78,14 @@ pub fn apply_comp(doc: &mut Document, comp: &LayerComp, all: bool) {&& let Some((x, y)) = st.position&& let Some((cx, cy)) = doc.layer(id).and_then(layer_position)&& (x, y) != (cx, cy)+ // Recorded positions can come from files; a move that does not fit an `i32` is+ // skipped rather than wrapped onto some other position (#1017).+ && let (Some(dx), Some(dy)) = (x.checked_sub(cx), y.checked_sub(cy)){let snapshot = doc.clone();if let Some(l) = doc.layer_mut(id) {- crate::commands::translate_layer(&snapshot, l, x - cx, y - cy);- crate::vector_cmds::translate_vectors(&snapshot, l, f64::from(x - cx), f64::from(y - cy));+ crate::commands::translate_layer(&snapshot, l, dx, dy);+ crate::vector_cmds::translate_vectors(&snapshot, l, f64::from(dx), f64::from(dy));}}let Some(l) = doc.layer_mut(id) else { continue };diff --git a/crates/engine/src/comps_cmds/tests.rs b/crates/engine/src/comps_cmds/tests.rsindex fd33b3daa..cf7497279 100644--- a/crates/engine/src/comps_cmds/tests.rs+++ b/crates/engine/src/comps_cmds/tests.rs@@ -225,3 +225,33 @@ fn out_of_range_comp_ids_are_rejected_not_wrapped() {assert!(r.is_err());let _ = std::fs::remove_dir_all(dir);}++#[test]+fn unreachable_comp_positions_leave_the_layer_in_place() {+ // #1017: a recorded position whose distance from the layer's current one leaves i32 range+ // (e.g. from a file) panicked on apply. The move is skipped; visibility still applies.+ for target in [(i32::MIN, 4), (4, i32::MIN)] {+ let (mut s, a, b) = session(8);+ let comp = LayerComp {+ id: 1,+ name: "Far".into(),+ comment: String::new(),+ apply_visibility: true,+ apply_position: true,+ apply_appearance: false,+ states: vec![+ CompLayerState { layer: a, visible: Some(false), position: Some(target), appearance: None },+ // Control: an ordinary position on another layer still moves it.+ CompLayerState { layer: b, visible: None, position: Some((31, 22)), appearance: None },+ ],+ };+ s.edit("far", |d, _| {+ apply_comp(d, &comp, false);+ Ok(())+ })+ .unwrap();+ assert_eq!(pos(&s, a), Some((4, 4)), "{target:?}");+ assert!(!doc(&s).layer(a).unwrap().visible);+ assert_eq!(pos(&s, b), Some((31, 22)));+ }+}diff --git a/crates/io/src/comps_map.rs b/crates/io/src/comps_map.rsindex 65e7205de..57134224d 100644--- a/crates/io/src/comps_map.rs+++ b/crates/io/src/comps_map.rs@@ -134,7 +134,8 @@ pub(crate) fn artboard_block(guides: &Guides, l: &Layer, raw: &mut Vec<([u8; 4],struct Setting {comps: Vec<u32>,visible: Option<bool>,- offset: Option<(i32, i32)>,+ /// Kept at the file's width: whether origin + offset fits an `i32` is decided per layer (#1017).+ offset: Option<(i64, i64)>,}fn parse_cmls(data: &[u8]) -> Option<Vec<Setting>> {@@ -151,7 +152,7 @@ fn parse_cmls(data: &[u8]) -> Option<Vec<Setting>> {Some(Value::Boolean(b)) => Some(*b),_ => None,};- let offset = desc(s, "Ofst").and_then(|o| Some((int(o, "Hrzn")? as i32, int(o, "Vrtc")? as i32)));+ let offset = desc(s, "Ofst").and_then(|o| Some((int(o, "Hrzn")?, int(o, "Vrtc")?)));out.push(Setting { comps, visible, offset });}Some(out)@@ -163,11 +164,25 @@ fn layer_cmls(l: &Layer) -> Option<Vec<u8>> {parse_shmd(shmd).ok()?.into_iter().find(|it| &it.key == b"cmls").map(|it| it.data)}+/// Absolute comp position of a layer at `here` moved by a file offset; None when it does not fit+/// an `i32` (the offsets come from the file, so the sum must not wrap or overflow, #1017).+fn offset_position((x, y): (i32, i32), (dx, dy): (i64, i64)) -> Option<(i32, i32)> {+ let add = |a: i32, d: i64| i64::from(a).checked_add(d).and_then(|v| i32::try_from(v).ok());+ Some((add(x, dx)?, add(y, dy)?))+}+/// Comps, last applied comp and Last Document State described by `resource` (1065 data) and the/// layers' `cmls` metadata.pub fn comps_from_psd(resource: Option<&[u8]>, doc: &Document) -> (Vec<LayerComp>, Option<u32>, Option<LayerComp>) {- let Some(data) = resource else { return (Vec::new(), None, None) };- let Ok((vd, _)) = VersionedDescriptor::parse_prefix(data) else { return (Vec::new(), None, None) };+ let (comps, last_applied, last, _) = decode_comps(resource, doc);+ (comps, last_applied, last)+}++/// [`comps_from_psd`] plus import warnings for comp data that could not be represented.+pub(crate) fn decode_comps(resource: Option<&[u8]>, doc: &Document) -> (Vec<LayerComp>, Option<u32>, Option<LayerComp>, Vec<String>) {+ let mut warnings = Vec::new();+ let Some(data) = resource else { return (Vec::new(), None, None, warnings) };+ let Ok((vd, _)) = VersionedDescriptor::parse_prefix(data) else { return (Vec::new(), None, None, warnings) };let d = &vd.descriptor;let mut comps: Vec<LayerComp> = Vec::new();if let Some(Value::List(items)) = d.get("list") {@@ -208,7 +223,16 @@ pub fn comps_from_psd(resource: Option<&[u8]>, doc: &Document) -> (Vec<LayerComplayer: l.id,visible: s.visible,position: match (here, s.offset) {- (Some((x, y)), Some((dx, dy))) => Some((x + dx, y + dy)),+ (Some(h), Some(o)) => {+ let p = offset_position(h, o);+ if p.is_none() {+ warnings.push(format!(+ "layer \"{}\": layer comp position offset ({}, {}) is out of range; that position was not imported",+ l.name, o.0, o.1+ ));+ }+ p+ }_ => None,},appearance: None,@@ -222,7 +246,7 @@ pub fn comps_from_psd(resource: Option<&[u8]>, doc: &Document) -> (Vec<LayerComp}}let last = (!last.states.is_empty()).then_some(last);- (comps, last_applied, last)+ (comps, last_applied, last, warnings)}/// The 1065 resource data for `doc`'s comps (None when there are none).@@ -254,8 +278,12 @@ fn setting_value(ids: &[u32], st: Option<&CompLayerState>, here: Option<(i32, i3if let Some(v) = st.visible {s = s.with("enab", Value::Boolean(v));}- if let (Some((x, y)), Some((hx, hy))) = (st.position, here) {- s = s.with("Ofst", Value::Descriptor(obj("null").with("Hrzn", Value::Integer(x - hx)).with("Vrtc", Value::Integer(y - hy))));+ // A position whose offset from the layer does not fit an `i32` (e.g. from a `.pcraft`+ // file) is left out rather than wrapped: the comp then records no position (#1017).+ if let (Some((x, y)), Some((hx, hy))) = (st.position, here)+ && let (Some(dx), Some(dy)) = (x.checked_sub(hx), y.checked_sub(hy))+ {+ s = s.with("Ofst", Value::Descriptor(obj("null").with("Hrzn", Value::Integer(dx)).with("Vrtc", Value::Integer(dy))));}}Value::Descriptor(s.with("compList", Value::List(ids.iter().map(|i| Value::Integer(*i as i32)).collect())))@@ -374,4 +402,75 @@ mod tests {set_cmls(&mut only, None);assert!(only.is_empty());}++ /// A layer at origin (4, 4) whose `shmd` carries a `cmls` item with one `layerSettings`+ /// entry for comp 1: visible, offset by `ofst`.+ fn doc_with_cmls_offset(ofst: (Value, Value)) -> (Document, photocraft_doc::LayerId, Vec<u8>) {+ let mut d = Document::with_background("t", Size::new(32, 32), ColorMode::Rgb, SampleType::U8, Color::WHITE);+ let mut l = Layer::raster("A", PixelFormat::RGBA8);+ l.surface_mut().unwrap().fill_rect(Rect::new(4, 4, 8, 8), &[1.0, 0.0, 0.0, 1.0]);+ assert_eq!(layer_position(&l), Some((4, 4)));+ let setting = obj("null")+ .with("enab", Value::Boolean(true))+ .with("compList", Value::List(vec![Value::Integer(1)]))+ .with("Ofst", Value::Descriptor(obj("null").with("Hrzn", ofst.0).with("Vrtc", ofst.1)));+ let cmls = VersionedDescriptor::new(Descriptor::new("null").with("layerSettings", Value::List(vec![Value::Descriptor(setting)]))).to_bytes();+ l.psd_blocks = vec![(*b"shmd", std::sync::Arc::new(write_shmd(&[MetadataItem::new(*b"cmls", cmls)])))];+ let lid = l.id;+ d.layers.push(l);+ let comp = Descriptor::new("Comp").with("Nm ", Value::Text(nul_name())).with("compID", Value::Integer(1)).with("capturedInfo", Value::Integer(3));+ let res = VersionedDescriptor::new(Descriptor::new("CompList").with("list", Value::List(vec![Value::Descriptor(comp)]))).to_bytes();+ (d, lid, res)+ }++ #[test]+ fn unrepresentable_comp_offsets_are_dropped_not_wrapped() {+ // #1017: the layer origin plus a file-supplied offset left i32 range and panicked on+ // import (wrapped in release builds). The position is dropped with a warning; the+ // visibility of the same entry is kept.+ for (h, v) in [(i32::MAX, 0), (0, i32::MAX)] {+ let (d, lid, res) = doc_with_cmls_offset((Value::Integer(h), Value::Integer(v)));+ let (comps, _, _, warnings) = decode_comps(Some(&res), &d);+ let st = comps[0].state(lid).unwrap();+ assert_eq!((st.visible, st.position), (Some(true), None), "({h}, {v})");+ assert_eq!(warnings.len(), 1, "{warnings:?}");+ assert!(warnings[0].contains("layer comp position"), "{warnings:?}");+ assert_eq!(comps_from_psd(Some(&res), &d).0, comps);+ }+ // Offsets wider than i32 (64-bit integers) are dropped too, not truncated.+ let (d, lid, res) = doc_with_cmls_offset((Value::LargeInteger(i64::from(u32::MAX) + 2), Value::Integer(0)));+ let (comps, _, _, warnings) = decode_comps(Some(&res), &d);+ assert_eq!(comps[0].state(lid).unwrap().position, None);+ assert_eq!(warnings.len(), 1, "{warnings:?}");+ // Control: an ordinary offset still decodes to layer origin + offset, without warnings.+ let (d, lid, res) = doc_with_cmls_offset((Value::Integer(6), Value::Integer(-3)));+ let (comps, _, _, warnings) = decode_comps(Some(&res), &d);+ assert_eq!(comps[0].state(lid).unwrap().position, Some((10, 1)));+ assert!(warnings.is_empty(), "{warnings:?}");+ }++ #[test]+ fn unrepresentable_comp_positions_are_written_without_offset() {+ // #1017: a stored position minus the layer origin left i32 range and panicked on export.+ // The offset is omitted (the comp then records no position for that layer).+ let mut l = Layer::raster("A", PixelFormat::RGBA8);+ l.surface_mut().unwrap().fill_rect(Rect::new(4, 4, 8, 8), &[1.0, 0.0, 0.0, 1.0]);+ let comp = |position| LayerComp {+ id: 1,+ name: "One".into(),+ comment: String::new(),+ apply_visibility: true,+ apply_position: true,+ apply_appearance: false,+ states: vec![CompLayerState { layer: l.id, visible: Some(false), position, appearance: None }],+ };+ for p in [(i32::MIN, 0), (0, i32::MIN)] {+ let cm = write_cmls(&[comp(Some(p))], None, &l, 1).unwrap();+ let s = parse_cmls(&cm).unwrap();+ assert_eq!(s[0], Setting { comps: vec![1], visible: Some(false), offset: None }, "{p:?}");+ }+ // Control: an ordinary position is written as its offset from the layer origin.+ let cm = write_cmls(&[comp(Some((10, 1)))], None, &l, 1).unwrap();+ assert_eq!(parse_cmls(&cm).unwrap()[0].offset, Some((6, -3)));+ }}diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex 846f88e04..63d2f25e9 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -774,7 +774,10 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)// Layer comps (resource 1065 + per-layer `cmls`); the raw data stays for verbatim export.let raw_comps = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == crate::comps_map::LAYER_COMPS).map(|(_, _, d)| d.clone());- (doc.layer_comps, doc.last_applied_comp, doc.last_document_state) = crate::comps_map::comps_from_psd(raw_comps.as_deref().map(Vec::as_slice), &doc);+ let comp_warnings;+ (doc.layer_comps, doc.last_applied_comp, doc.last_document_state, comp_warnings) =+ crate::comps_map::decode_comps(raw_comps.as_deref().map(Vec::as_slice), &doc);+ cx.warnings.extend(comp_warnings);// Slices (resource 1050), after layer ids are known; the raw data stays for verbatim export.crate::slices_map::import(&mut doc);// Character and paragraph styles from the type layers' engine data.diff --git a/crates/io/tests/comps_artboards.rs b/crates/io/tests/comps_artboards.rsindex 1028c833d..346d7cc06 100644--- a/crates/io/tests/comps_artboards.rs+++ b/crates/io/tests/comps_artboards.rs@@ -239,3 +239,75 @@ fn synthetic_pcraft_roundtrip_keeps_everything() {assert!(import("pcraft", &png).is_ok());assert!(matches!(import("broken.pcraft", b"not a native bundle"), Err(photocraft_io::IoError::Pcraft(_))));}++/// A layer at (4, 4) whose preserved `shmd` block offsets it by `(dx, 0)` in comp 1, plus the+/// matching resource 1065: what a PSD with that comp data imports to before decoding comps.+fn doc_with_raw_comp_offset(dx: i32) -> Document {+ use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor};+ use photocraft_psd::metadata::{MetadataItem, write_shmd};+ let obj = |class: &str| Descriptor { name: UnicodeString(vec![0]), ..Descriptor::new(class) };+ let mut d = Document::new("s", Size::new(32, 32), ColorMode::Rgb, SampleType::U8);+ let mut l = Layer::raster("A", PixelFormat::RGBA8);+ l.surface_mut().unwrap().fill_rect(Rect::new(4, 4, 8, 8), &[1.0, 0.0, 0.0, 1.0]);+ let setting = obj("null")+ .with("enab", Value::Boolean(false))+ .with("compList", Value::List(vec![Value::Integer(1)]))+ .with("Ofst", Value::Descriptor(obj("null").with("Hrzn", Value::Integer(dx)).with("Vrtc", Value::Integer(0))));+ let cmls = VersionedDescriptor::new(Descriptor::new("null").with("layerSettings", Value::List(vec![Value::Descriptor(setting)]))).to_bytes();+ l.psd_blocks = vec![(*b"shmd", std::sync::Arc::new(write_shmd(&[MetadataItem::new(*b"cmls", cmls)])))];+ d.layers.push(l);+ let comp = Descriptor::new("Comp")+ .with("Nm ", Value::Text(UnicodeString::new_nul("One")))+ .with("compID", Value::Integer(1))+ .with("capturedInfo", Value::Integer(3));+ let res = VersionedDescriptor::new(Descriptor::new("CompList").with("list", Value::List(vec![Value::Descriptor(comp)]))).to_bytes();+ d.metadata.psd_resources.push((LAYER_COMPS, String::new(), std::sync::Arc::new(res)));+ d+}++#[test]+fn out_of_range_comp_offsets_import_and_export_without_panic() {+ // #1017: an `Ofst` that puts the layer past i32 range panicked on import and on export (the+ // unchanged-comps check decodes the preserved data). The position is dropped with a warning,+ // the rest of the comp survives, and the file data is still written back verbatim.+ let mut src = doc_with_raw_comp_offset(i32::MAX);+ (src.layer_comps, src.last_applied_comp, src.last_document_state) =+ photocraft_io::comps_map::comps_from_psd(src.metadata.psd_resources.last().map(|r| r.2.as_slice()), &src);+ let bytes = to_psd(&src);+ let imported = import("x.psd", &bytes).unwrap();+ assert!(imported.warnings.iter().any(|w| w.contains("layer comp position")), "{:?}", imported.warnings);+ let c = &imported.document.layer_comps[0];+ assert_eq!((c.name.as_str(), c.states.len()), ("One", 1));+ assert_eq!((c.states[0].visible, c.states[0].position), (Some(false), None));+ let a = PsdFile::from_bytes(&bytes).unwrap();+ let b = PsdFile::from_bytes(&to_psd(&imported.document)).unwrap();+ assert_eq!(layer_block(&a, "A", b"shmd"), layer_block(&b, "A", b"shmd"));++ // Export of a stored position whose offset from the layer is out of range (no preserved+ // data, so `cmls` is regenerated): the offset is left out and reads back as no position.+ let mut d = Document::new("s", Size::new(32, 32), ColorMode::Rgb, SampleType::U8);+ let mut l = Layer::raster("A", PixelFormat::RGBA8);+ l.surface_mut().unwrap().fill_rect(Rect::new(4, 4, 8, 8), &[1.0, 0.0, 0.0, 1.0]);+ let st = photocraft_doc::CompLayerState { layer: l.id, visible: Some(false), position: Some((i32::MIN, 0)), appearance: None };+ d.layers.push(l);+ d.layer_comps.push(LayerComp {+ id: 1,+ name: "One".into(),+ comment: String::new(),+ apply_visibility: true,+ apply_position: true,+ apply_appearance: false,+ states: vec![st],+ });+ let back = import("x.psd", &to_psd(&d)).unwrap().document;+ let s = &back.layer_comps[0].states[0];+ assert_eq!((s.visible, s.position), (Some(false), None));++ // Control: an ordinary offset imports as layer origin + offset, without a warning.+ let mut ok = doc_with_raw_comp_offset(6);+ (ok.layer_comps, ok.last_applied_comp, ok.last_document_state) =+ photocraft_io::comps_map::comps_from_psd(ok.metadata.psd_resources.last().map(|r| r.2.as_slice()), &ok);+ let imported = import("x.psd", &to_psd(&ok)).unwrap();+ assert!(!imported.warnings.iter().any(|w| w.contains("layer comp")), "{:?}", imported.warnings);+ assert_eq!(imported.document.layer_comps[0].states[0].position, Some((10, 4)));+}