From cbe83c89a784a8e653cabcb58d895d67bcf54fba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:04:20 -0800 Subject: [PATCH] Links: relinking a clipped PSD follows the new file's clipping path links.relink and links.update kept a PSD or PSB file's clip group as it was, so an image relinked to a file with another clipping path, or with none, stayed clipped to the old file's path, and a plain image relinked to a clipped PSD came in unclipped. - The PNG a PSD or PSB file's merged image is kept as now carries the clipping path the file names in a text chunk, and RasterImage.clip holds it with its fill rule (even-odd), as it holds a DCS file's (nonzero). - links.relink and links.update read that path the way they read a DCS file's: the clip group's clipping path becomes the new file's, a file that names none leaves a plain group of the image, and a later file that names one clips it again. A clip group whose path or fill rule was changed in the document stays as a clipping mask around the file's clip group. - docs/mcp.md and the evidence line in docs/target-app-parity.md describe the new behavior. --- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/load.rs | 54 +++++- crates/engine/src/cmd/fileio/tests_psdread.rs | 92 ++++++++++ crates/engine/src/cmd/links.rs | 162 ++++++++++-------- crates/engine/src/cmd/place.rs | 2 +- crates/engine/src/cmd/place/dcs.rs | 1 + docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 8 files changed, 242 insertions(+), 78 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index fc5be365d5..d8c9074001 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -39,7 +39,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note}; mod heifread; mod hpgl; mod jp2read; diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 52ed7f0e7f..1d954ba7cb 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -73,8 +73,10 @@ pub struct RasterImage { pub height: u32, /// The resolution the file declares (see [`super::ppi::resolution`]). pub ppi: Option<(f64, f64)>, - /// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]). - pub clip: Option, + /// The clipping path its file draws it through, in the image's pixel space, with its fill rule: + /// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd, + /// [`psdread::clipping_path`]). + pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>, } pub(super) fn err(e: impl std::fmt::Display) -> EngineError { @@ -942,7 +944,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; -/// other samples become 8-bit RGBA. +/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file +/// names ([`png_with_clip`]). pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -950,7 +953,8 @@ pub fn raster_image(bytes: &[u8]) -> Result { } if psdread::is_psd(bytes) { let cms = vectorcraft_color::cms::active(); - return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi); + let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?; + return Ok(png_with_clip(img, psdread::clipping_path(bytes))); } if jxlread::is_jxl(bytes) { let (img, icc, orientation) = jxlread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?; @@ -1118,10 +1122,48 @@ fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) } +/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from +/// ([`png_with_clip`]). +const CLIP_KEYWORD: &str = "VectorCraft clip"; + +/// Longest clipping path a PNG keeps (bytes of its JSON). +const MAX_PNG_CLIP: usize = 16 << 20; + +/// `img`, a PNG made from a PSD or PSB file, with `clip`, the clipping path that file names in the +/// image's pixel space (even-odd): the image keeps it, and its PNG keeps it in a text chunk, so the +/// Links commands know a clip group of that path as the file's ([`png_clip`]). A path whose JSON is +/// longer than [`MAX_PNG_CLIP`] is left out, and the image comes in unclipped. +fn png_with_clip(mut img: RasterImage, clip: Option) -> RasterImage { + let Some(clip) = clip else { return img }; + let Some(json) = serde_json::to_string(&clip).ok().filter(|j| j.len() <= MAX_PNG_CLIP) else { return img }; + let png = vectorcraft_render::encode::png::with_text(img.blob.bytes.to_vec(), &[(CLIP_KEYWORD, json.into())]); + img.blob = ImageBlob::new("image/png", png); + img.key = img.blob.content_key(); + img.clip = Some((clip, vectorcraft_geom::FillRule::EvenOdd)); + img +} + +/// The clipping path a PNG made from a PSD or PSB file keeps ([`png_with_clip`]), in its pixel +/// space; `None` for other images, and for a text chunk longer than [`MAX_PNG_CLIP`] or a path +/// past [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Reads only the chunks before the image data. +pub(crate) fn png_clip(png: &[u8]) -> Option { + if !png.starts_with(b"\x89PNG\r\n\x1a\n") { + return None; + } + let keyword = [CLIP_KEYWORD.as_bytes(), &[0]].concat(); + let json = super::ppi::png_chunks(png) + .take_while(|(ty, _)| *ty != b"IDAT") + .find_map(|(ty, data)| data.strip_prefix(keyword.as_slice()).filter(|_| ty == b"tEXt"))?; + if json.len() > MAX_PNG_CLIP { + return None; + } + vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) +} + /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { - let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?; + let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?; let (sx, sy) = crate::cmd::place::pt_per_px(ppi); let mut d = Document::new(width as f64 * sx, height as f64 * sy); let layer = d.layers[0].id; @@ -1131,7 +1173,7 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { id, NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })), ); - let mut n = file_clipped(&mut d, n, psdread::clipping_path(bytes)); + let mut n = file_clipped(&mut d, n, clip.map(|(path, _)| path)); n.name = Some(name.to_string()); d.images.insert(key, blob); d.insert(Some(layer), 0, n).map_err(err)?; diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 6d66b8da4e..2a7340a79e 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -414,6 +414,98 @@ fn a_plain_image_replacing_a_clipped_psd_keeps_its_rotation() { assert!(after.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-9), "{after:?} != {before:?}"); } +/// A square saved as "Square" and the clipping path naming it. +fn square_resources() -> Vec { + let square = saved_path(false, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]); + [resource(2000, b"Square", &square), clipping_name(b"Square")].concat() +} + +/// `bytes` written as `name` in `dir`, by its path. +fn write_file(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() +} + +/// links.relink and links.update put a linked PSD file's image in the clip group of the clipping +/// path its new file names, take that clip group's clipping path away when the new file names +/// none, and give it back when a later file names one again. +#[test] +fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-clip"); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let square = write_file(&dir, "square.psd", &red_psd(&square_resources())); + let plain = write_file(&dir, "plain.psd", &red_psd(&[])); + let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]]; + let squared = vec![[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), r["image"].as_u64().unwrap()); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image))); + s.execute("links.relink", &json!({"ids": [image], "path": square})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared.clone(), true, NodeId(image)), "the new file's clipping path"); + s.execute("links.relink", &json!({"ids": [image], "path": plain})).unwrap(); + let d = &s.doc().unwrap().doc; + match d.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id.0).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + s.execute("links.relink", &json!({"ids": [image], "path": cut})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)), "clipped again"); + // The file is saved again with another clipping path. + std::fs::write(&cut, red_psd(&square_resources())).unwrap(); + s.execute("links.update", &json!({"ids": [image]})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); +} + +/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a +/// text chunk within the size limit that reads as a path gives one back. +#[test] +fn the_kept_png_holds_the_clipping_path_within_bounds() { + let img = raster_image(&red_psd(&triangle_resources())).unwrap(); + let (path, rule) = img.clip.clone().expect("the file's clipping path"); + assert_eq!(rule, vectorcraft_geom::FillRule::EvenOdd); + assert_eq!(super::load::png_clip(&img.blob.bytes), Some(path)); + let plain = raster_image(&red_psd(&[])).unwrap(); + assert!(plain.clip.is_none() && super::load::png_clip(&plain.blob.bytes).is_none()); + let with = |text: String| vectorcraft_render::encode::png::with_text(plain.blob.bytes.to_vec(), &[("VectorCraft clip", text.into())]); + assert_eq!(super::load::png_clip(&with("not a path".into())), None); + assert_eq!(super::load::png_clip(&with(" ".repeat((16 << 20) + 1))), None, "a chunk past the limit is not read"); +} + +/// A plain image relinked to a PSD file that names a clipping path goes into a clip group of that +/// path, under the even-odd rule; a clipping mask made in the document stays around it. +#[test] +fn a_plain_image_relinked_to_a_clipped_psd_is_clipped_by_its_path() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-plain"); + let plain = write_file(&dir, "plain.psd", &red_psd(&[])); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": plain, "at": [50, 25]})).unwrap(); + let image = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let group = d.parent_of(image).expect("a clip group"); + assert_eq!(clip_group(d, group), (vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]], true, image)); + // The clipping path's fill rule changed in the document makes it the document's own mask: a + // relink keeps it and puts the file's clip group inside it. + let clip = match d.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, .. }) => children[0].id, + other => panic!("{other:?}"), + }; + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(vectorcraft_doc::Node { kind: NodeKind::Path { rule, .. }, .. }) = doc.node_mut(clip) { + *rule = vectorcraft_geom::FillRule::NonZero; + } + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let inner = d.parent_of(image).unwrap(); + assert_eq!(d.parent_of(inner), Some(group), "the document's mask holds the file's clip group"); + assert!(clip_group(d, inner).1, "the file's clip group is even-odd"); +} + #[test] fn a_fill_that_starts_with_all_pixels_puts_the_image_around_the_path() { let hole = saved_path(true, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index b3fc65e8fc..9abccf1392 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -698,6 +698,20 @@ fn clip_shape((frame, room): Clip) -> PathData { shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame) } +/// The clipping path an image's file draws it through, with the fill rule its clip group takes: +/// a DCS file's (nonzero) or a PSD or PSB file's (even-odd). +type FileClip = (PathData, FillRule); + +/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it +/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB +/// file's ([`fileio::png_clip`]). +fn file_clip(blob: &ImageBlob) -> Option { + if let Some(path) = blob.separated_clip() { + return Some((path, FillRule::NonZero)); + } + (blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd)) +} + /// What happens to the clip of an object a link update remakes. enum ClipTo { /// It stays as it is. @@ -705,25 +719,25 @@ enum ClipTo { /// It is clipped to this path (Placement Options' clip): the clipping path of the clip group /// holding just it changes, else it goes into a new clip group. Path(PathData), - /// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`], - /// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group - /// again. - File(PathData), + /// It is clipped to this path, the clipping path its file draws it through, under its fill + /// rule: as [`ClipTo::Path`], except that a plain group holding just it (as [`ClipTo::Off`] + /// leaves one) becomes a clip group again. + File(FileClip), /// It goes into a new clip group of this path, inside the clip group that holds it. - Nest(PathData), - /// Placement Options clip it to `placement` while its DCS file draws it through `file`: it is + Nest(FileClip), + /// Placement Options clip it to `placement` while its file draws it through `file`: it is /// clipped to `file` as [`ClipTo::File`] clips it, and the clip group holding it is clipped to /// `placement` as [`ClipTo::Path`] clips an object. With no `file` (the new file lacks the /// clipping path of the clip group holding it), that group stays as [`ClipTo::Off`] leaves it, /// clipped to `placement`. - Both { file: Option, placement: PathData }, - /// Placement Options clip it to `placement` while its DCS file draws it through `file`, and the + Both { file: Option, placement: PathData }, + /// Placement Options clip it to `placement` while its file draws it through `file`, and the /// clip group holding just it is not its old file's: that clip group's clipping path becomes /// `placement`, and it goes into a new clip group of `file` inside it. - BothInside { file: PathData, placement: PathData }, - /// The clipping path of the clip group holding just it goes (a DCS file's clipping path that - /// its new file lacks): the group stays as a plain group of it, with its id, name, visibility - /// and transparency. + BothInside { file: FileClip, placement: PathData }, + /// The clipping path of the clip group holding just it goes (its old file's clipping path, + /// which its new file lacks): the group stays as a plain group of it, with its id, name, + /// visibility and transparency. Off, } @@ -756,25 +770,25 @@ fn same_path(a: &PathData, b: &PathData) -> bool { } /// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with -/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path a DCS file -/// draws `img` through, the file's clip group inside the placement's. When neither clips it, a clip -/// group holding just it whose clipping path `held` is its old DCS file's (`old_clip`, in the old -/// pixels, under the nonzero rule its clip groups get) goes. +/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path the file +/// (DCS, PSD or PSB) draws `img` through, the file's clip group inside the placement's. When +/// neither clips it, a clip group holding just it whose clipping path `held` is its old file's +/// (`old_clip`, in the old pixels, under the fill rule its clip groups get) goes. fn clip_to( old_xf: Affine, - old_clip: Option<&PathData>, + old_clip: Option<&FileClip>, clip: Option, img: &RasterImage, new_xf: Affine, held: Option<(&PathData, FillRule)>, ) -> ClipTo { - // Whether the clip group holding just the image is the old DCS file's: a clipping path whose - // fill rule was changed in the document is not. + // Whether the clip group holding just the image is the old file's: a clipping path whose fill + // rule was changed in the document is not. let file_held = match (old_clip, held) { - (Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held), + (Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held), _ => false, }; - let file = img.clip.as_ref().map(|path| path.transformed(new_xf)); + let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule)); if let Some(clip) = clip { let placement = clip_shape(clip); return match file { @@ -831,7 +845,7 @@ impl Nested<'_> { fn root(&mut self, n: &mut Arc) { if !(self.pick)(n) { if let Some(placement) = self.update(n, true) { - *n = Arc::new(self.clip_group(Arc::clone(n), placement)); + *n = Arc::new(self.clip_group(Arc::clone(n), (placement, FillRule::NonZero))); } return; } @@ -839,7 +853,8 @@ impl Nested<'_> { let mut new = Arc::new(new); let _ = self.update(&mut new, true); *n = match clip { - ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)), + ClipTo::Path(path) => Arc::new(self.clip_group(new, (path, FillRule::NonZero))), + ClipTo::File(file) | ClipTo::Nest(file) => Arc::new(self.clip_group(new, file)), ClipTo::Both { file, placement } => self.clip_both(new, file, placement), ClipTo::BothInside { file, placement } => self.clip_both(new, Some(file), placement), ClipTo::Keep | ClipTo::Off => new, @@ -848,8 +863,8 @@ impl Nested<'_> { /// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays /// the same node when none is there, and only the nodes on the way to one are copied. The - /// result is Placement Options' clip that `n` itself, now the clip group of a DCS file's - /// clipping path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes: + /// result is Placement Options' clip that `n` itself, now the clip group of a file's clipping + /// path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes: /// the clipping path of the clip group holding just `n` becomes it, else `n` goes into a new /// clip group of it. #[must_use] @@ -880,8 +895,8 @@ impl Nested<'_> { match (self.update(&mut new, nested), clip_path) { (None, _) if Arc::ptr_eq(&new, c) => {} (None, _) => slots.push((i, new)), - (Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement)), (1, new)]), - (Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, placement)))), + (Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement, None)), (1, new)]), + (Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, (placement, FillRule::NonZero))))), } continue; } @@ -894,17 +909,22 @@ impl Nested<'_> { let _ = self.update(&mut new, true); match (clip, clip_path) { (ClipTo::Keep, _) => slots.push((i, new)), - (ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip)), (1, new)]), + (ClipTo::Path(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, None)), (1, new)]), + (ClipTo::File((clip, rule)), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, Some(rule))), (1, new)]), (ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)), - (ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => { + (ClipTo::Path(clip), _) => { + let group = self.clip_group(new, (clip, FillRule::NonZero)); + slots.push((i, Arc::new(group))); + } + (ClipTo::File(clip) | ClipTo::Nest(clip), _) => { let group = self.clip_group(new, clip); slots.push((i, Arc::new(group))); } (ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new), (ClipTo::Off, _) => slots.push((i, new)), // The file's clip group stays `n`, and the placement's clip goes around it. - (ClipTo::Both { file: Some(file), placement }, Some(path)) if i == 1 => { - slots.extend([(0, with_clip(path, file)), (1, new)]); + (ClipTo::Both { file: Some((file, rule)), placement }, Some(path)) if i == 1 => { + slots.extend([(0, with_clip(path, file, Some(rule))), (1, new)]); around = Some(placement); } (ClipTo::Both { file: Some(file), placement }, None) if plain => { @@ -917,7 +937,7 @@ impl Nested<'_> { } (ClipTo::BothInside { file, placement }, Some(path)) if i == 1 => { let group = self.clip_group(new, file); - slots.extend([(0, with_clip(path, placement)), (1, Arc::new(group))]); + slots.extend([(0, with_clip(path, placement, None)), (1, Arc::new(group))]); } (ClipTo::Both { file, placement }, _) => slots.push((i, self.clip_both(new, file, placement))), (ClipTo::BothInside { file, placement }, _) => slots.push((i, self.clip_both(new, Some(file), placement))), @@ -958,27 +978,28 @@ impl Nested<'_> { /// A clip group of `placement` holding `object`, inside a clip group of `file` when there is a /// `file` ([`ClipTo::Both`] for an object no clip group holds yet). - fn clip_both(&mut self, object: Arc, file: Option, placement: PathData) -> Arc { + fn clip_both(&mut self, object: Arc, file: Option, placement: PathData) -> Arc { let object = match file { Some(file) => Arc::new(self.clip_group(object, file)), None => object, }; - Arc::new(self.clip_group(object, placement)) + Arc::new(self.clip_group(object, (placement, FillRule::NonZero))) } - /// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers. - fn clip_group(&mut self, object: Arc, clip: PathData) -> Node { + /// A clip group of `object` clipped to `clip` under its fill rule, as [`new_clip_group`] makes + /// one in the layers. + fn clip_group(&mut self, object: Arc, clip: FileClip) -> Node { let path = self.clipping_path(clip); let group_id = NodeId(self.next); self.next += 1; Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true }) } - /// A clipping path of `clip`, with the next node id. - fn clipping_path(&mut self, clip: PathData) -> Node { + /// A clipping path of `clip` under its fill rule, with the next node id. + fn clipping_path(&mut self, (clip, rule): FileClip) -> Node { let id = NodeId(self.next); self.next += 1; - clipping_path(id, clip) + clipping_path(id, clip, rule) } } @@ -1082,9 +1103,9 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n (frame * at * Affine::scale_non_uniform(size.0 / nw, size.1 / nh), (o.clip && over).then_some((frame, room))) } -/// The clipping path of the clip group of `d` holding just object `id` becomes `path`; false when -/// no such clip group holds it. -fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { +/// The clipping path of the clip group of `d` holding just object `id` becomes `path`, under fill +/// rule `rule` when one is given; false when no such clip group holds it. +fn set_clip_path(d: &mut Document, id: NodeId, path: PathData, rule: Option) -> bool { let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind { NodeKind::Group { children, clip: true } => match &children[..] { [c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id), @@ -1093,8 +1114,9 @@ fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { _ => None, }); let Some(c) = clip_path else { return false }; - if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) { + if let Some(Node { kind: NodeKind::Path { path: p, rule: r, .. }, .. }) = d.node_mut(c) { *p = path; + *r = rule.unwrap_or(*r); } true } @@ -1108,25 +1130,25 @@ fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { /// Clip object `id` of `d` to `path`: the clipping path of the clip group holding just it changes, /// else it goes into a new clip group. fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { - if set_clip_path(d, id, path.clone()) { + if set_clip_path(d, id, path.clone(), None) { return Ok(()); } - new_clip_group(d, id, path) + new_clip_group(d, id, (path, FillRule::NonZero)) } -/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping -/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`] -/// leaves one) becomes a clip group again, else it goes into a new clip group. -fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { - if set_clip_path(d, id, path.clone()) { +/// Clip object `id` of `d` to `path`, the clipping path its file draws it through, under its fill +/// rule: the clipping path of the clip group holding just it changes, a plain group holding just it +/// (as [`unclip`] leaves one) becomes a clip group again, else it goes into a new clip group. +fn clip_file_to(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> { + if set_clip_path(d, id, path.clone(), Some(rule)) { return Ok(()); } let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) { Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id), _ => false, }); - let Some(g) = plain else { return new_clip_group(d, id, path) }; - let clip = clipping_path(d.alloc_id(), path); + let Some(g) = plain else { return new_clip_group(d, id, (path, rule)) }; + let clip = clipping_path(d.alloc_id(), path, rule); d.insert(Some(g), 0, clip)?; if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) { *clip = true; @@ -1134,30 +1156,33 @@ fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { Ok(()) } -/// Clipping path `path` (a node) with its path changed to `clip`. -fn with_clip(path: &Node, clip: PathData) -> Arc { +/// Clipping path `path` (a node) with its path changed to `clip`, and its fill rule to `rule` when +/// one is given. +fn with_clip(path: &Node, clip: PathData, rule: Option) -> Arc { let mut path = Node::clone(path); - if let NodeKind::Path { path: p, .. } = &mut path.kind { + if let NodeKind::Path { path: p, rule: r, .. } = &mut path.kind { *p = clip; + *r = rule.unwrap_or(*r); } Arc::new(path) } -/// A clipping path `id` of `path`, unpainted. -fn clipping_path(id: NodeId, path: PathData) -> Node { +/// A clipping path `id` of `path` under fill rule `rule`, unpainted. +fn clipping_path(id: NodeId, path: PathData, rule: FillRule) -> Node { let none = vectorcraft_color::Paint::None; let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0)); - if let NodeKind::Path { clipping, .. } = &mut clip.kind { + if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind { *clipping = true; + *r = rule; } clip } -/// Put object `id` of `d` into a new clip group of `path`, where it is. -fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { +/// Put object `id` of `d` into a new clip group of `path`, under its fill rule, where it is. +fn new_clip_group(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> { let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; let image = d.remove(id)?; - let clip = clipping_path(d.alloc_id(), path); + let clip = clipping_path(d.alloc_id(), path, rule); let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true }); d.insert(par, index, group)?; Ok(()) @@ -1186,15 +1211,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let nested = nested_ids(d, ids); if also.is_some() || !nested.is_empty() { let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false))); - // The resolution of each content the images picked show, and the clipping path its DCS file + // The resolution of each content the images picked show, and the clipping path its file // drew it through, looked up once each. - let mut old: BTreeMap)> = BTreeMap::new(); + let mut old: BTreeMap)> = BTreeMap::new(); d.visit_stored(|n, _| { if let NodeKind::Image(im) = &n.kind && pick(n) && !old.contains_key(&im.key) { - old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip))); + old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(file_clip))); } }); let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { @@ -1220,8 +1245,9 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o); - // Placement Options' clip, else a DCS file's clipping path, read again with its plates. - let old_clip = d.images.get(&im.key).and_then(ImageBlob::separated_clip); + // Placement Options' clip, else the clipping path of a DCS file (read again with its + // plates) or of a PSD or PSB file. + let old_clip = d.images.get(&im.key).and_then(file_clip); clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id)))); if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind @@ -1235,8 +1261,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio clips.into_iter().try_for_each(|(id, clip)| match clip { ClipTo::Keep => Ok(()), ClipTo::Path(path) => clip_image_to(d, id, path), - ClipTo::File(path) => clip_file_to(d, id, path), - ClipTo::Nest(path) => new_clip_group(d, id, path), + ClipTo::File(file) => clip_file_to(d, id, file), + ClipTo::Nest(file) => new_clip_group(d, id, file), ClipTo::Off => unclip(d, id), ClipTo::Both { file, placement } => { match file { diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 83216b2f43..1b0ec6b888 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -304,7 +304,7 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes)); let mut warnings: Vec = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect(); *slices_out = psd_slices(slices_from, natural, &mut warnings); - let clip = fileio::psdread::clipping_path(&src.bytes); + let clip = img.clip.clone().map(|(path, _)| path); return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None }); } if pdf { diff --git a/crates/engine/src/cmd/place/dcs.rs b/crates/engine/src/cmd/place/dcs.rs index 69a397c5d1..efa02e06a8 100644 --- a/crates/engine/src/cmd/place/dcs.rs +++ b/crates/engine/src/cmd/place/dcs.rs @@ -104,6 +104,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result { }; let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref()) .ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?; + let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero)); let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip }; let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect(); Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings }) diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..cb6bdad68c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8691,7 +8691,10 @@ path is that path, under the even-odd rule, so the image shows only inside it. T that can be edited or released. `file.place` answers `image`, the id of the image in the clip group. The [import options help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) says that a file imported as one flattened image keeps the document's clipping path when it has one. `links.update` -and `links.relink` read the file's pixels again and leave the clip group and its clipping path as they are. Files that name no clipping path, or name a path +and `links.relink` read the file again: the clip group's clipping path becomes the one the new file names, under the +even-odd rule, and the clip group stays as a plain group of the image when the new file names none. A plain image relinked to such a +file goes into a clip group of its path. A clip group whose clipping path was changed in the document, or whose fill rule was, is kept as a +clipping mask, with the file's clip group inside it. Files that name no clipping path, or name a path they don't have, come in as a plain image. `file.place` with `replace` on such a clip group puts a new image, clipped or not, at the scale and rotation of the image in the group. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..6fade6b57b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1879,7 +1879,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` keep the clip group, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - Pixar picture files (`.pxr`) open, place and paste, from "The Format of Stored Pictures" in the Pixar Image Computer manuals: any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded with all four packet kinds and block ends, in tiles of any size (pixels of border tiles past the picture are dropped). R alone is gray, a missing color channel is 0 and a missing A opaque; 12-bit samples are clamped to 0.0 to 1.0; color matted to black becomes straight color; a null tile is transparent when the picture has A and black otherwise. The offsets aren't read, and the image takes the default resolution. Version 2 headers read like version 0. A file cut short, one with a tile whose writing wasn't finished, one with header values or packets the format doesn't define, and one whose pixels as RGBA pass the pixel allowance are refused with a message. Every reader recognizes a Pixar file by its magic number. Tested on synthetic files only (`crates/engine/src/cmd/fileio/tests_pxrread.rs`).