From 568f0f21685b7900cf6d1653ab9cbedac0bea08c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 20:44:36 -0800 Subject: [PATCH 1/8] Links: Relink, Embed and Unembed keep a distorted image's corners An image changed by Perspective Distort or Free Distort was refused by Relink, Embed and Unembed. Each now keeps the image's corners in one undo step: - Relink puts the new file's pixels between the corners, as Update Links does, whatever `preserve` or the image's Placement Options say. - Embed keeps the file's pixels in the document between the corners, reading the file first when the image shows its saved preview. - Unembed writes the pixels to the file and links the image to it with the same corners. Unembed into a folder keeps the corners too. Relink and Update Links also follow the clipping path a PSD, PSB or DCS file names for a distorted image: the path is drawn through the corners, a clip group of the old file's path takes the new file's, and it becomes a plain group when the new file names none. Unembed of an image from a PSD or PSB file took away the clip group of the file's clipping path, plain images included: the PNG or TIFF it writes keeps the path, but the file was read without it. A PNG or TIFF that keeps the path now comes with it when it is read, so Unembed, and a later Place, Relink or Update Links of the written file, keep the clip group. The params text of Relink, Embed and Unembed, docs/mcp.md and the progress-doc line describe the new behavior. --- crates/engine/src/cmd/fileio/load.rs | 9 +- crates/engine/src/cmd/fileio/tests_psdread.rs | 95 ++++++++++ crates/engine/src/cmd/links.rs | 121 +++++++++---- crates/engine/src/tests/links.rs | 170 ++++++++++++++++++ crates/engine/src/tests/xform.rs | 3 - docs/mcp.md | 18 +- docs/target-app-parity.md | 2 +- 7 files changed, 369 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 4e59e378a5..9de13076ae 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -962,7 +962,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// 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. A PSD/PSB composite's stored image keeps its imported -/// clipping path ([`image_clip`]). +/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes +/// it) comes with it. pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -1139,13 +1140,15 @@ pub fn texture_image(bytes: &[u8]) -> Result { texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture")) } -/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed. +/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed, with the clipping path a +/// PNG or TIFF made from a PSD or PSB file keeps ([`image_clip`]). fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result { if width == 0 || height == 0 { return Err(err("the image is empty")); } let blob = ImageBlob::new(mime, bytes); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) + let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd)); + Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip }) } /// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 249a3f320c..ad17346d19 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -602,6 +602,101 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); } +/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective +/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners, +/// a clip group of the old file's clipping path loses it when the new file names none, and a later +/// file's clipping path clips it again. +#[test] +fn relink_follows_the_clipping_path_of_a_distorted_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-distorted"); + 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 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()), NodeId(r["image"].as_u64().unwrap())); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone(); + assert!(node(&s).is_distorted_image()); + let corners = node(&s).image_corners().unwrap(); + // A path's anchors (in the image's pixels) where the image's corners put them. + let mapped = |s: &Session, pixels: &[[f64; 2]]| -> Vec<[f64; 2]> { + let map = node(s).image_map().unwrap(); + pixels.iter().map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()).map(|p| [p.x, p.y]).collect() + }; + let near = + |a: &[[f64; 2]], b: &[[f64; 2]]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group); + let triangle = mapped(&s, &[[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); + assert!(near(&anchors, &triangle) && even_odd && held == image, "{anchors:?} vs {triangle:?}"); + s.execute("links.relink", &json!({"ids": [image.0], "path": square})).unwrap(); + let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group); + let squared = mapped(&s, &[[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]); + assert!(near(&anchors, &squared) && even_odd && held == image, "the new file's clipping path: {anchors:?} vs {squared:?}"); + assert_eq!(node(&s).image_corners().unwrap(), corners); + s.execute("links.relink", &json!({"ids": [image.0], "path": plain})).unwrap(); + match s.doc().unwrap().doc.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let (anchors, _, held) = clip_group(&s.doc().unwrap().doc, group); + assert!(near(&anchors, &triangle) && held == image, "clipped again: {anchors:?} vs {triangle:?}"); + assert!(node(&s).is_distorted_image()); + assert_eq!(node(&s).image_corners().unwrap(), corners); +} + +/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, for a +/// plain image and for one changed by Perspective Distort or Free Distort, and so do reading the +/// written file again and placing it. +#[test] +fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip"); + // An RGB file is kept as a PNG, a CMYK one as a TIFF. + let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); + let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)]; + for ((kind, file), distort) in files.iter().flat_map(|f| [(f, false), (f, true)]) { + let data = vectorcraft_format::base64_encode(file); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + if distort { + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + } + let before = clip_group(&s.doc().unwrap().doc, group); + // Without an extension the image is written in the format it is stored in. + let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}-{distort}"))})).unwrap(); + let path = r["path"].as_str().unwrap().to_string(); + let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; + assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); + for step in ["unembed", "relink"] { + if step == "relink" { + s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; + assert!(im.link.is_some(), "linked to the file written"); + assert_eq!(d.node(image).unwrap().is_distorted_image(), distort); + // A distorted image's clipping path is drawn through its corners again, within rounding. + let (anchors, even_odd, held) = clip_group(d, group); + let near = anchors.len() == before.0.len() + && anchors.iter().zip(&before.0).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, distorted: {distort}: {anchors:?} vs {:?}", before.0); + } + // Placing the written file gives the same clip group as placing the PSD file did. + if !distort { + let r = s.execute("file.place", &json!({"path": path, "at": [50, 25]})).unwrap(); + let placed = NodeId(r["ids"][0].as_u64().unwrap()); + let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed); + assert!(even_odd && anchors.len() == before.0.len(), "{kind}, place: {anchors:?} vs {:?}", before.0); + } + } +} + /// 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] diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 8fcd589c52..233994d655 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -33,7 +33,7 @@ use vectorcraft_doc::{ Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions, StoredPlace, StoredRoot, }; -use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; +use vectorcraft_geom::{Affine, FillRule, Homography, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param}; @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say; the clipping path its file names is drawn through the corners. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", has_doc, relink ), @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Embed Image", [], None, - "{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). One undo step → {embedded: [ids], missing: [ids]}", + "{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). An image changed by Perspective Distort or Free Distort keeps its corners. One undo step → {embedded: [ids], missing: [ids]}", has_doc, embed ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners); written as stored, an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path for later reads. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -634,7 +634,8 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> /// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a /// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels -/// can't be read ([`readable`]). +/// can't be read ([`readable`]). A PNG or TIFF written from a PSD or PSB file's image (by Unembed) +/// comes with the clipping path it keeps ([`fileio::raster_image`]). fn linked_image(bytes: &[u8], path: Option<&str>) -> Result { let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; @@ -791,13 +792,20 @@ fn clip_to( new_xf: Affine, held: Option<(&PathData, FillRule)>, ) -> ClipTo { + let old = old_clip.filter(|_| held.is_some()).map(|(path, rule)| (path.transformed(old_xf), *rule)); + let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule)); + placed_clip_to(old.as_ref(), clip, file, held) +} + +/// [`clip_to`] with the clipping paths of the old file (`old`) and of the new file (`file`) already +/// on the page. +fn placed_clip_to(old: Option<&FileClip>, clip: Option, file: Option, held: Option<(&PathData, FillRule)>) -> ClipTo { // 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, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held), + let file_held = match (old, held) { + (Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(old, held), _ => false, }; - 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 { @@ -1210,14 +1218,43 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ install(d, &[id], read, Some(Preserve::Bounds), None) } -/// Distorted image `im` shows the file read for `link` (`img`) and keeps its corners and its -/// clipping: the new pixels fill them. Its transform is scaled to the new pixel size, so a reader -/// that places it by the transform still gives it its old size. -fn refill_distorted(im: &mut ImageObject, link: &LinkInfo, img: &RasterImage) { - if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 { - im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height)); +/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels +/// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the +/// transform still gives it its old size. Its Placement Options do not apply. The result is what +/// happens to its clip, as [`clip_to`] decides from the clipping path of the clip group holding +/// just it (`held`): the clipping paths of its old file (`old_clip`, in its old pixels) and of the +/// new file are mapped to the page through its corners, anchors and handles alike, as a distort +/// maps a path's. +fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo { + let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); + if let NodeKind::Image(im) = &mut n.kind { + if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 { + im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height)); + } + (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); } - (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); + let file = img.clip.as_ref().and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); + placed_clip_to(old.as_ref(), None, file, held) +} + +/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points +/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front +/// of it, and one past it to the far side. `None` when a point maps to no finite page point. +fn warped(path: &PathData, map: &Homography) -> Option { + let [[a, b, c], [d, e, f], [g, h, i]] = map.0; + let apply = |p: vectorcraft_geom::Point| { + let w = g * p.x + h * p.y + i; + let w = if w.abs() < 1e-9 { 1e-9_f64.copysign(w) } else { w }; + let q = vectorcraft_geom::Point::new((a * p.x + b * p.y + c) / w, (d * p.x + e * p.y + f) / w); + q.is_finite().then_some(q) + }; + let mut out = path.clone(); + for sp in &mut out.subpaths { + for anchor in &mut sp.anchors { + (anchor.p, anchor.h_in, anchor.h_out) = (apply(anchor.p)?, apply(anchor.h_in)?, apply(anchor.h_out)?); + } + } + Some(out) } /// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each @@ -1244,12 +1281,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { let mut n = n.clone(); let mut clip = ClipTo::Keep; - let distorted = n.is_distorted_image(); + if n.is_distorted_image() { + let old_clip = match &n.kind { + NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()), + _ => None, + }; + let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held); + return (n, clip); + } if let NodeKind::Image(im) = &mut n.kind { - if distorted { - refill_distorted(im, &link, &img); - return (n, clip); - } 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 (old_pt, old_clip) = match old.get(&im.key) { @@ -1266,10 +1306,13 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio } for id in ids { if d.node(*id).is_some_and(Node::is_distorted_image) { - if let Some(n) = d.node_mut(*id) - && let NodeKind::Image(im) = &mut n.kind - { - refill_distorted(im, &link, &img); + let old_clip = match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::Image(im)) => d.images.get(&im.key).and_then(file_clip), + _ => None, + }; + let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule)); + if let Some(n) = d.node_mut(*id) { + clips.push((*id, refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))))); } continue; } @@ -2153,11 +2196,6 @@ fn relink(s: &mut Session, p: &Value) -> Result { } (None, None, None) => return Err(bad(C, "give path (a file) or folder")), } - // A new file's placement options place a plain image: a distorted one is left as it is. - let distorted = files.iter().flat_map(|(ids, _)| ids).find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)); - if let Some(id) = distorted { - return Err(super::xform::distorted_image_error(C, *id)); - } // Every file is read and checked before any is copied. let mut checked = vec![]; for (ids, path) in files { @@ -2620,9 +2658,6 @@ fn embed(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select the linked images or placed documents, or pass ids")); } - if let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) { - return Err(super::xform::distorted_image_error(C, *id)); - } // A DCS file's plates print from its file. let separated = |id: &NodeId| match kind(id) { Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated), @@ -2751,9 +2786,6 @@ fn unembed(s: &mut Session, p: &Value) -> Result { if im.link.is_some() { return Err(bad(C, format!("image {} is linked already", id.0))); } - if n.is_distorted_image() { - return Err(super::xform::distorted_image_error(C, id)); - } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. let stored = stored_extension(blob); @@ -3124,4 +3156,23 @@ mod tests { let long = unembed_stem(&"é".repeat(200)); assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len()); } + + /// A clipping path mapped through a distorted image's corners keeps the points that lie on or + /// past the map's horizon, each mapped as a distort maps a path's point. + #[test] + fn points_past_the_horizon_are_mapped_as_a_distort_maps_them() { + use vectorcraft_geom::{Anchor, Point, SubPath}; + // w = 1 + x / 100: the horizon is the line x = -100. + let map = Homography([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.01, 0.0, 1.0]]); + let (at, handle, on) = (Point::new(0.0, 0.0), Point::new(-200.0, 0.0), Point::new(-100.0, 5.0)); + assert!(map.apply(handle).is_none() && map.apply(on).is_none()); + let path = PathData::new(vec![SubPath::new(vec![Anchor::smooth(at, handle), Anchor::corner(on)], false)]); + let out = warped(&path, &map).expect("a path"); + let (first, second) = (out.subpaths[0].anchors[0], out.subpaths[0].anchors[1]); + assert_eq!((first.p, first.h_in), (at, Point::new(200.0 / 3.0, 0.0))); + // w = -1: the handle maps to the far side. + assert_eq!(first.h_out, Point::new(200.0, 0.0)); + // w = 0 is taken as a billionth. + assert!(second.p.is_finite() && (second.p.x.abs() - 1e11).abs() < 1.0 && (second.p.y.abs() - 5e9).abs() < 1.0, "{:?}", second.p); + } } diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 6386716232..efaf396a4e 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -655,6 +655,176 @@ fn update_links_keeps_a_distorted_images_corners() { scale_matches_ppi(&mut s); } +/// Relink with scope `all` puts the new file's pixels between the corners of the distorted images +/// in symbols too, and scales each one's transform to the new pixel size, so a placement by the +/// transform keeps the old size. +#[test] +fn relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols() { + let dir = Folder::new("distorted-relink-all"); + let (photo, other) = (dir.file("photo.png"), dir.file("other.png")); + write(&photo, &png(20, 10, RED)); + write(&other, &png(60, 20, BLUE)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let before = s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap(); + // The far corner of the pixels as the transform alone places them. + let far = |s: &Session| { + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") }; + im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height)) + }; + let far_before = far(&s); + // A distorted copy in a symbol shows the same file. + let copy = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [copy.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[10, 10], [60, 15], [58, 50], [5, 45]]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap(); + let in_symbol = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| { + if let NodeKind::Image(im) = &n.kind { + out.push((n.image_quad(), (im.width, im.height))); + } + }); + out + }; + let [(Some(symbol_quad), (20, 10))] = in_symbol(&s)[..] else { panic!("one distorted image in the symbol: {:?}", in_symbol(&s)) }; + let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap(); + let relinked = r["relinked"].as_array().unwrap(); + assert!(relinked.len() == 2 && relinked.contains(&json!(id.0)), "the image and the symbol's: {r}"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert_eq!((n.is_distorted_image(), n.image_corners().unwrap()), (true, before)); + assert_eq!((image(&s, id).width, image(&s, id).height), (60, 20)); + assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s)); + assert_eq!(in_symbol(&s), [(Some(symbol_quad), (60, 20))], "the symbol's image keeps its corners"); +} + +/// Relink, Embed and Unembed keep a distorted image's corners, each in one undo step: Relink puts +/// the new file's pixels between them whatever `preserve` and the Placement Options say, Embed +/// keeps the pixels in the document, and Unembed links the image to the file it writes. +#[test] +fn relink_embed_and_unembed_keep_a_distorted_images_corners() { + let dir = Folder::new("distorted-relink"); + let (photo, other, written) = (dir.file("photo.png"), dir.file("other.png"), dir.file("written.png")); + write(&photo, &png(20, 10, RED)); + write(&other, &png(60, 20, BLUE)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // Around the artboard's center, where `centre_colour` looks. + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap(); + let before = corners(&s); + let distorted = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().is_distorted_image(); + let clipped = |s: &Session| { + let d = &s.doc().unwrap().doc; + matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. })) + }; + let undo_len = |s: &Session| s.doc().unwrap().history.undo.len(); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); + + let undo = undo_len(&s); + let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "preserve": "fileDimensions"})).unwrap(); + assert_eq!(r["relinked"], json!([id.0]), "{r}"); + assert_eq!(undo_len(&s), undo + 1); + assert!(distorted(&s)); + assert_eq!(corners(&s), before); + assert!(!clipped(&s), "not clipped by its Placement Options"); + let im = image(&s, id); + assert_eq!((im.width, im.height), (60, 20)); + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str())); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + + let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(r["embedded"], json!([id.0]), "{r}"); + assert_eq!(undo_len(&s), undo + 2); + assert!(distorted(&s)); + assert_eq!(corners(&s), before); + assert!(image(&s, id).link.is_none()); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + + let r = s.execute("links.unembed", &json!({"id": id.0, "path": written})).unwrap(); + assert_eq!(r["id"], json!(id.0), "{r}"); + assert_eq!(undo_len(&s), undo + 3); + assert!(distorted(&s)); + assert_eq!(corners(&s), before); + assert!(!clipped(&s)); + let im = image(&s, id); + assert_eq!((im.width, im.height), (60, 20)); + assert!(im.link.is_some()); + assert!(Path::new(&written).exists()); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + + // Undo takes each back to the same corners, and the first file's pixels in the end. + for _ in 0..3 { + s.execute("edit.undo", &json!({})).unwrap(); + assert!(distorted(&s)); + assert_eq!(corners(&s), before); + } + assert_eq!((image(&s, id).width, image(&s, id).height), (20, 10)); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); +} + +/// Unembed into a folder keeps a distorted image's corners, in one undo step. +#[test] +fn unembed_to_a_folder_keeps_a_distorted_images_corners() { + let dir = Folder::new("distorted-unembed-folder"); + let (photo, out) = (dir.file("photo.png"), dir.file("out")); + std::fs::create_dir_all(&out).unwrap(); + write(&photo, &png(20, 10, RED)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap(); + let before = corners(&s); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("links.unembed", &json!({"ids": [id.0], "folder": out})).unwrap(); + assert_eq!(r["unembedded"][0]["id"], json!(id.0), "{r}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image()); + assert_eq!(corners(&s), before); + assert!(image(&s, id).link.is_some()); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); +} + +/// Embed reads the file of a distorted image that shows its saved preview and keeps the file's +/// pixels in the document between the image's corners, in one undo step. +#[test] +fn embed_reads_a_distorted_images_file_between_its_corners() { + let dir = Folder::new("distorted-embed-preview"); + let photo = dir.file("photo.png"); + // Large enough that the document saves a smaller preview of it. + write(&photo, &png(600, 300, RED)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap(); + let before = corners(&s); + let doc_path = dir.file("poster.vectorcraft"); + save(&mut s, &doc_path); + std::fs::remove_file(&photo).unwrap(); + open(&mut s, &doc_path); + assert!(s.doc().unwrap().doc.images[&image(&s, id).key].is_proxy(), "the preview stands in"); + assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image()); + write(&photo, &png(400, 200, BLUE)); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(r, json!({"embedded": [id.0], "missing": []})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(n.is_distorted_image()); + assert_eq!(n.image_corners().unwrap(), before); + let im = image(&s, id); + assert_eq!((im.width, im.height, im.link.is_none()), (400, 200, true)); + assert!(!s.doc().unwrap().doc.images[&im.key].is_proxy(), "the file's pixels are in the document"); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); +} + /// Update Links reads a changed file again for the images inside symbols, patterns and opacity /// masks too: those showing the same content as an image in the layers, and those no object in the /// layers shows. Each takes the file's place as its own Placement Options say, in one undo step, diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index ccc735440e..ac73b66727 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -723,9 +723,6 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() { for (cmd, params) in [ ("object.cropImage", json!({})), ("imageTrace.make", json!({})), - ("links.relink", json!({"path": "/nowhere/pic.png"})), - ("links.embed", json!({"ids": [img.0]})), - ("links.unembed", json!({})), ("object.createObjectMosaic", json!({})), ("object.mesh.create", json!({})), ( diff --git a/docs/mcp.md b/docs/mcp.md index 729d5523cc..4a56181924 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6662,12 +6662,14 @@ rules opens with the image placed by its transform. A drag is one undo step, and where they are records none. Image info (`image.info`) gives a distorted image's resolution at its middle, and Link Info (`links.info`) gives its scale and rotation there. -Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`), Relink (`links.relink`), -Embed (`links.embed`), Unembed (`links.unembed`), Create Object Mosaic (`object.createObjectMosaic`), Create -Gradient Mesh (`object.mesh.create`) and Place with Replace (`file.place` with `replace`) refuse a distorted image with -an error that names the distortion. Update Links (`links.update`) puts a changed file's pixels between a distorted -image's corners, without applying its Placement Options. Mask (`object.maskImage`) draws its clipping path through the -image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the +Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`), Create Object Mosaic +(`object.createObjectMosaic`), Create Gradient Mesh (`object.mesh.create`) and Place with Replace (`file.place` with +`replace`) refuse a distorted image with an error that names the distortion. Update Links (`links.update`) and Relink +(`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or +Relink's `preserve`. The clipping path a PSD, PSB or DCS file names is drawn through the corners: a clip group of the +old file's clipping path takes the new file's, or becomes a plain group when the new file names none. Embed +(`links.embed`) and Unembed (`links.unembed`) keep the corners, each in one undo step. Mask (`object.maskImage`) draws +its clipping path through the image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the result. These rules are VectorCraft's own. ```json @@ -8773,7 +8775,9 @@ every object in the layers each time the list is read. A `dcsTransparency` that `links.goTo {id}` selects an image (`onCanvas: true`); for an object outside the layer tree it clears the selection and returns `{id, onCanvas: false, owner}`, and the panel says the link has no place on the canvas. `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file -(another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. +(another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. An image from a PSD +or PSB file written as stored (PNG, or TIFF for a CMYK file) keeps the clip group of the clipping path that file +names, and the file written keeps the path for Place, Relink and Update Links. `ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of `id`; default: the selected embedded images) to a new file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ec79a36837..f8e37693f4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1069,7 +1069,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`) (`bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`). - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles, alone or with other objects, and draw its pixels in perspective between them on the canvas, in print and in every export, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Relink, Embed, Unembed, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image; Update Links puts a changed file's pixels between its corners; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). + - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles, alone or with other objects, and draw its pixels in perspective between them on the canvas, in print and in every export, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image; Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_an_embedded_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - Help › Search Commands… is the first item of the Help menu in the window, with its shortcut and a separator after it; in the native macOS menu bar it is the first item below the system's search field. This is VectorCraft's own order and does not raise a score (`menus::tests::help_starts_with_search_commands`, `tests::nativemenu::the_mac_help_menu_starts_with_search_commands`). From ea7731f6c2421aac785e420e129599f4749770d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:12:45 -0800 Subject: [PATCH 2/8] Links: Relink warns when preserve is not applied to a distorted image Relink with `preserve` on an image changed by Perspective Distort or Free Distort keeps the image's corners and now adds a `warnings` entry naming the images the value was not applied to. The params text of Update Links now says how it handles a distorted image's corners and clipping path, and the docs/mcp.md paragraph is rewrapped. docs/mcp.md says that Open also reads a PNG or TIFF written by Unembed with its clip group. New tests cover Update Links and Relink of a distorted image with a PSD or DCS clipping path, Relink with scope all of a distorted image in an opacity mask, and Open of a file written by Unembed. --- crates/engine/src/cmd/fileio/load.rs | 2 +- crates/engine/src/cmd/fileio/tests_psdread.rs | 44 ++++++++++++++++- crates/engine/src/cmd/links.rs | 29 ++++++++++-- crates/engine/src/tests/dcs.rs | 47 +++++++++++++++++++ crates/engine/src/tests/links.rs | 39 ++++++++++++++- docs/mcp.md | 13 ++--- 6 files changed, 160 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 9de13076ae..8249fe6b71 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -963,7 +963,7 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// 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. A PSD/PSB composite's stored image keeps its imported /// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes -/// it) comes with it. +/// it) is read with that path. pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index ad17346d19..2eb7f74d81 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -648,9 +648,45 @@ fn relink_follows_the_clipping_path_of_a_distorted_psd() { assert_eq!(node(&s).image_corners().unwrap(), corners); } +/// Update Links follows the clipping path of a linked PSD file for an image changed by Perspective +/// Distort or Free Distort: the file's new clipping path is drawn through the image's corners, and +/// a file without one leaves a plain group. +#[test] +fn update_links_follows_the_clipping_path_of_a_distorted_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-update-distorted"); + 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": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone(); + let corners = node(&s).image_corners().unwrap(); + let map = node(&s).image_map().unwrap(); + let squared: Vec<[f64; 2]> = [[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]] + .iter() + .map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()) + .map(|p| [p.x, p.y]) + .collect(); + std::fs::write(&cut, red_psd(&square_resources())).unwrap(); + s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); + let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group); + let near = anchors.len() == squared.len() && anchors.iter().zip(&squared).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + assert!(near && even_odd && held == image, "the file's new clipping path: {anchors:?} vs {squared:?}"); + assert_eq!(node(&s).image_corners().unwrap(), corners); + std::fs::write(&cut, red_psd(&[])).unwrap(); + s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); + match s.doc().unwrap().doc.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + assert_eq!(node(&s).image_corners().unwrap(), corners); +} + /// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, for a /// plain image and for one changed by Perspective Distort or Free Distort, and so do reading the -/// written file again and placing it. +/// written file again, placing it and opening it. #[test] fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip"); @@ -693,6 +729,12 @@ fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { let placed = NodeId(r["ids"][0].as_u64().unwrap()); let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed); assert!(even_odd && anchors.len() == before.0.len(), "{kind}, place: {anchors:?} vs {:?}", before.0); + // Opening it gives a document of the image in that clip group. + s.execute("document.open", &json!({"path": path})).unwrap(); + let d = &s.doc().unwrap().doc; + let top = d.layers[0].children().and_then(|c| c.first()).map(|c| c.id).expect("an object"); + let (anchors, even_odd, _) = clip_group(d, top); + assert!(even_odd && anchors.len() == before.0.len(), "{kind}, open: {anchors:?} vs {:?}", before.0); } } } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 233994d655..45bbc4e5e6 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", has_doc, update ), @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say; the clipping path its file names is drawn through the corners. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say, and its clipping is handled as links.update handles it. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's, and one naming the distorted images that preserve was not applied to)}", has_doc, relink ), @@ -634,8 +634,8 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> /// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a /// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels -/// can't be read ([`readable`]). A PNG or TIFF written from a PSD or PSB file's image (by Unembed) -/// comes with the clipping path it keeps ([`fileio::raster_image`]). +/// can't be read ([`readable`]). A PNG or TIFF that Unembed wrote from a PSD or PSB file's image +/// is read with the clipping path it keeps ([`fileio::raster_image`]). fn linked_image(bytes: &[u8], path: Option<&str>) -> Result { let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; @@ -2255,8 +2255,10 @@ fn relink(s: &mut Session, p: &Value) -> Result { } } let relinked: Vec = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect(); + let unpreserved = preserve.and_then(|_| unpreserved_note(&doc, &reads)); drop(doc); - let warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read)); + let mut warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read)); + warnings.extend(unpreserved); if !reads.is_empty() { s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?; } @@ -2279,6 +2281,23 @@ fn relink(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The warning that Relink's `preserve` was not applied to the images of `reads` changed by +/// Perspective Distort or Free Distort, which keep their corners, naming them; `None` when there +/// are none. +fn unpreserved_note(doc: &Document, reads: &[(Vec, Read)]) -> Option { + let ids: Vec = reads + .iter() + .filter(|(_, read)| matches!(read, Read::Image(_))) + .flat_map(|(ids, _)| ids) + .filter(|id| stored(doc, **id).is_some_and(Node::is_distorted_image)) + .map(|id| id.0.to_string()) + .collect(); + let images = if ids.len() == 1 { "image" } else { "images" }; + (!ids.is_empty()).then(|| { + format!("preserve was not applied to {images} {}: an image changed by Perspective Distort or Free Distort keeps its corners", ids.join(", ")) + }) +} + /// `links.relink {scope: "missingInFolder"}`: the other missing links of `st` (not `given`; only /// images when `images_only`, as copy takes), each added to `files` with the file of its name in /// the folder of the first file there; names not there go to `not_found`. diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index 43bdf180a7..6d23bd23d0 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -220,6 +220,53 @@ fn update_link_takes_the_files_new_clipping_path() { assert!((after - before / 2.0).abs() < 1e-6, "the clipping path follows the file: {before} → {after}"); } +/// For an image changed by Perspective Distort or Free Distort, Update Links and Relink draw the +/// DCS file's new clipping path through the image's corners, and a file without one leaves a plain +/// group. +#[test] +fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_corners() { + let dir = temp_dir("distorted-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + s.execute("select.set", &json!({ "ids": [group.0] })).unwrap(); + s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap(); + let node = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(node(&s).is_distorted_image()); + let corners = node(&s).image_corners().unwrap(); + // The clip group's path anchors, and points of the 2 × 2 pixels where the corners put them. + let anchors = |s: &Session| { + let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") }; + let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") }; + path.anchors().map(|(_, _, a)| a.p).collect::>() + }; + let on_page = |s: &Session, x: f64| { + let map = node(s).image_map().unwrap(); + [(0.0, 0.0), (x, 0.0), (x, 2.0), (0.0, 2.0)].map(|(px, py)| map.apply(vectorcraft_geom::Point::new(px, py)).unwrap()) + }; + let matches = |found: &[vectorcraft_geom::Point], want: &[vectorcraft_geom::Point]| { + found.len() == want.len() && want.iter().all(|w| found.iter().any(|f| f.distance(*w) < 1e-6)) + }; + assert!(matches(&anchors(&s), &on_page(&s, 1.0)), "the left half: {:?} vs {:?}", anchors(&s), on_page(&s, 1.0)); + // The same file, its composite drawn through the left quarter of the page (same length). + let quarter = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1); + std::fs::write(&path, quarter.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert!(matches(&anchors(&s), &on_page(&s, 0.5)), "the left quarter: {:?} vs {:?}", anchors(&s), on_page(&s, 0.5)); + assert_eq!(node(&s).image_corners().unwrap(), corners); + // Relink to a file whose composite has no clipping path. + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + let other = write(&dir, "other.eps", unclipped.as_bytes()); + s.execute("links.relink", &json!({ "ids": [id.0], "path": other })).unwrap(); + match &s.doc().unwrap().doc.node(group).unwrap().kind { + NodeKind::Group { children, clip: false } => assert_eq!(children.iter().map(|c| c.id).collect::>(), [id]), + other => panic!("a plain group of the image: {other:?}"), + } + assert_eq!(node(&s).image_corners().unwrap(), corners); +} + #[test] fn update_link_clips_an_image_whose_file_gained_a_clipping_path() { let dir = temp_dir("update-gained-clip"); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index efaf396a4e..e045ea62fd 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -693,6 +693,7 @@ fn relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols() { let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap(); let relinked = r["relinked"].as_array().unwrap(); assert!(relinked.len() == 2 && relinked.contains(&json!(id.0)), "the image and the symbol's: {r}"); + assert!(r.get("warnings").is_none(), "no preserve was given: {r}"); let n = s.doc().unwrap().doc.node(id).unwrap().clone(); assert_eq!((n.is_distorted_image(), n.image_corners().unwrap()), (true, before)); assert_eq!((image(&s, id).width, image(&s, id).height), (60, 20)); @@ -700,6 +701,40 @@ fn relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols() { assert_eq!(in_symbol(&s), [(Some(symbol_quad), (60, 20))], "the symbol's image keeps its corners"); } +/// Relink with scope `all` puts the new file's pixels between the corners of a distorted image in +/// an opacity mask's art. +#[test] +fn relink_of_all_instances_keeps_the_corners_of_a_distorted_image_in_an_opacity_mask() { + let dir = Folder::new("distorted-relink-mask"); + let (photo, other) = (dir.file("photo.png"), dir.file("other.png")); + write(&photo, &png(20, 10, RED)); + write(&other, &png(60, 20, BLUE)); + let mut s = session(); + let id = place(&mut s, &photo); + let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0); + let mask = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [mask.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[10, 10], [60, 15], [58, 50], [5, 45]]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap(); + // The image in the art of `masked`'s opacity mask: (id, corners, pixel size). + let in_mask = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.visit_stored(|n, place| { + if let NodeKind::Image(im) = &n.kind + && place.mask_of == Some(masked) + { + out.push((n.id, n.image_quad(), (im.width, im.height))); + } + }); + out + }; + let [(mask_id, Some(quad), (20, 10))] = in_mask(&s)[..] else { panic!("one distorted image in the mask: {:?}", in_mask(&s)) }; + let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap(); + let relinked = r["relinked"].as_array().unwrap(); + assert!(relinked.len() == 2 && relinked.contains(&json!(mask_id.0)), "the image and the mask's: {r}"); + assert_eq!(in_mask(&s), [(mask_id, Some(quad), (60, 20))], "the mask's image keeps its corners"); +} + /// Relink, Embed and Unembed keep a distorted image's corners, each in one undo step: Relink puts /// the new file's pixels between them whatever `preserve` and the Placement Options say, Embed /// keeps the pixels in the document, and Unembed links the image to the file it writes. @@ -727,7 +762,9 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() { let undo = undo_len(&s); let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "preserve": "fileDimensions"})).unwrap(); - assert_eq!(r["relinked"], json!([id.0]), "{r}"); + // The given preserve is reported as not applied. + let warning = format!("preserve was not applied to image {}: an image changed by Perspective Distort or Free Distort keeps its corners", id.0); + assert_eq!(r, json!({"relinked": [id.0], "notFound": [], "warnings": [warning]})); assert_eq!(undo_len(&s), undo + 1); assert!(distorted(&s)); assert_eq!(corners(&s), before); diff --git a/docs/mcp.md b/docs/mcp.md index 4a56181924..cb77529181 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6666,11 +6666,12 @@ Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.mak (`object.createObjectMosaic`), Create Gradient Mesh (`object.mesh.create`) and Place with Replace (`file.place` with `replace`) refuse a distorted image with an error that names the distortion. Update Links (`links.update`) and Relink (`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or -Relink's `preserve`. The clipping path a PSD, PSB or DCS file names is drawn through the corners: a clip group of the -old file's clipping path takes the new file's, or becomes a plain group when the new file names none. Embed -(`links.embed`) and Unembed (`links.unembed`) keep the corners, each in one undo step. Mask (`object.maskImage`) draws -its clipping path through the image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the -result. These rules are VectorCraft's own. +Relink's `preserve`; Relink then adds a `warnings` entry naming those images. The clipping path a PSD, PSB or DCS +file names is drawn through the corners: the clip group of the old file's clipping path gets the new file's clipping +path, or becomes a plain group when the new file names none. Embed (`links.embed`) and Unembed (`links.unembed`) keep +the corners, each in one undo step. Mask (`object.maskImage`) draws its clipping path through the image's corners. +Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the result. These rules +are VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}} @@ -8777,7 +8778,7 @@ returns `{id, onCanvas: false, owner}`, and the panel says the link has no place file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. An image from a PSD or PSB file written as stored (PNG, or TIFF for a CMYK file) keeps the clip group of the clipping path that file -names, and the file written keeps the path for Place, Relink and Update Links. +names, and the file written keeps the path: Open, Place, Relink and Update Links read the file with its clip group. `ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of `id`; default: the selected embedded images) to a new file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo From eb349d534d4a766cfb9b04f341259512ce281660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 06:17:24 -0800 Subject: [PATCH 3/8] Links: leave reading a PNG's kept clipping path to its own fix The loader change that read the clipping path a PNG or TIFF keeps also changed File > Open and File > Place of plain images. It is now #8561, with its tests, params text and docs, and this branch reads files as main does. For a distorted image, Relink and Update Links now read the new file's clipping path from the PNG or TIFF it is stored as when the reader gives none, as they already do for the old file. Unembed of a distorted image from a PSD or PSB file, with or without a folder, therefore keeps the clip group of that file's clipping path, and so does a later Relink to the written file. - Test: tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd (RGB file kept as PNG, CMYK file kept as TIFF, path and folder). - Docs: docs/mcp.md, links.unembed params text, the progress-doc line. --- crates/engine/src/cmd/fileio/load.rs | 9 ++-- crates/engine/src/cmd/fileio/tests_psdread.rs | 48 ++++++++----------- crates/engine/src/cmd/links.rs | 12 ++--- docs/mcp.md | 11 ++--- docs/target-app-parity.md | 2 +- 5 files changed, 35 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 8249fe6b71..4e59e378a5 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -962,8 +962,7 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// 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. A PSD/PSB composite's stored image keeps its imported -/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes -/// it) is read with that path. +/// clipping path ([`image_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) { @@ -1140,15 +1139,13 @@ pub fn texture_image(bytes: &[u8]) -> Result { texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture")) } -/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed, with the clipping path a -/// PNG or TIFF made from a PSD or PSB file keeps ([`image_clip`]). +/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed. fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result { if width == 0 || height == 0 { return Err(err("the image is empty")); } let blob = ImageBlob::new(mime, bytes); - let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd)); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip }) + 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 diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 2eb7f74d81..4e43565b56 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -684,29 +684,34 @@ fn update_links_follows_the_clipping_path_of_a_distorted_psd() { assert_eq!(node(&s).image_corners().unwrap(), corners); } -/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, for a -/// plain image and for one changed by Perspective Distort or Free Distort, and so do reading the -/// written file again, placing it and opening it. +/// Unembed of a distorted image from a PSD file, with a path and with a folder, keeps the clip +/// group of the clipping path that file names, drawn through its corners, and so does relinking it +/// to the file written. #[test] -fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { - let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip"); +fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-unembed-distorted-clip"); // An RGB file is kept as a PNG, a CMYK one as a TIFF. let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)]; - for ((kind, file), distort) in files.iter().flat_map(|f| [(f, false), (f, true)]) { + for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) { let data = vectorcraft_format::base64_encode(file); let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); - if distort { - s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); - s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); - } + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); let before = clip_group(&s.doc().unwrap().doc, group); // Without an extension the image is written in the format it is stored in. - let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}-{distort}"))})).unwrap(); - let path = r["path"].as_str().unwrap().to_string(); + let path = if folder { + let out = dir.join(format!("folder-{kind}")); + std::fs::create_dir_all(&out).unwrap(); + let r = s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap(); + r["unembedded"][0]["path"].as_str().unwrap().to_string() + } else { + let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}"))})).unwrap(); + r["path"].as_str().unwrap().to_string() + }; let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); for step in ["unembed", "relink"] { @@ -716,25 +721,12 @@ fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; assert!(im.link.is_some(), "linked to the file written"); - assert_eq!(d.node(image).unwrap().is_distorted_image(), distort); - // A distorted image's clipping path is drawn through its corners again, within rounding. + assert!(d.node(image).unwrap().is_distorted_image()); + // The clipping path is drawn through the corners again, within rounding. let (anchors, even_odd, held) = clip_group(d, group); let near = anchors.len() == before.0.len() && anchors.iter().zip(&before.0).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); - assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, distorted: {distort}: {anchors:?} vs {:?}", before.0); - } - // Placing the written file gives the same clip group as placing the PSD file did. - if !distort { - let r = s.execute("file.place", &json!({"path": path, "at": [50, 25]})).unwrap(); - let placed = NodeId(r["ids"][0].as_u64().unwrap()); - let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed); - assert!(even_odd && anchors.len() == before.0.len(), "{kind}, place: {anchors:?} vs {:?}", before.0); - // Opening it gives a document of the image in that clip group. - s.execute("document.open", &json!({"path": path})).unwrap(); - let d = &s.doc().unwrap().doc; - let top = d.layers[0].children().and_then(|c| c.first()).map(|c| c.id).expect("an object"); - let (anchors, even_odd, _) = clip_group(d, top); - assert!(even_odd && anchors.len() == before.0.len(), "{kind}, open: {anchors:?} vs {:?}", before.0); + assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {:?}", before.0); } } } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 45bbc4e5e6..5ebe9c5f54 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners); written as stored, an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path for later reads. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners and, when it came from a PSD or PSB file, the clip group of that file's clipping path, with or without folder). One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -634,8 +634,7 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> /// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a /// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels -/// can't be read ([`readable`]). A PNG or TIFF that Unembed wrote from a PSD or PSB file's image -/// is read with the clipping path it keeps ([`fileio::raster_image`]). +/// can't be read ([`readable`]). fn linked_image(bytes: &[u8], path: Option<&str>) -> Result { let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; @@ -1223,8 +1222,9 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ /// transform still gives it its old size. Its Placement Options do not apply. The result is what /// happens to its clip, as [`clip_to`] decides from the clipping path of the clip group holding /// just it (`held`): the clipping paths of its old file (`old_clip`, in its old pixels) and of the -/// new file are mapped to the page through its corners, anchors and handles alike, as a distort -/// maps a path's. +/// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it: +/// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a +/// distort maps a path's. fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo { let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); if let NodeKind::Image(im) = &mut n.kind { @@ -1233,7 +1233,7 @@ fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, } (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); } - let file = img.clip.as_ref().and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); + let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule))); placed_clip_to(old.as_ref(), None, file, held) } diff --git a/docs/mcp.md b/docs/mcp.md index cb77529181..f80563dc27 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6669,9 +6669,10 @@ Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.mak Relink's `preserve`; Relink then adds a `warnings` entry naming those images. The clipping path a PSD, PSB or DCS file names is drawn through the corners: the clip group of the old file's clipping path gets the new file's clipping path, or becomes a plain group when the new file names none. Embed (`links.embed`) and Unembed (`links.unembed`) keep -the corners, each in one undo step. Mask (`object.maskImage`) draws its clipping path through the image's corners. -Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the result. These rules -are VectorCraft's own. +the corners, each in one undo step. Unembed of a distorted image from a PSD or PSB file keeps the clip group of that +file's clipping path, and so does Relink to the PNG or TIFF it wrote. Mask (`object.maskImage`) draws its clipping +path through the image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a +plain image of the result. These rules are VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}} @@ -8776,9 +8777,7 @@ every object in the layers each time the list is read. A `dcsTransparency` that `links.goTo {id}` selects an image (`onCanvas: true`); for an object outside the layer tree it clears the selection and returns `{id, onCanvas: false, owner}`, and the panel says the link has no place on the canvas. `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file -(another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. An image from a PSD -or PSB file written as stored (PNG, or TIFF for a CMYK file) keeps the clip group of the clipping path that file -names, and the file written keeps the path: Open, Place, Relink and Update Links read the file with its clip group. +(another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. `ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of `id`; default: the selected embedded images) to a new file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8e37693f4..0cb9fc915b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1069,7 +1069,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`) (`bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`). - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles, alone or with other objects, and draw its pixels in perspective between them on the canvas, in print and in every export, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image; Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_an_embedded_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). + - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles, alone or with other objects, and draw its pixels in perspective between them on the canvas, in print and in every export, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image; Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - Help › Search Commands… is the first item of the Help menu in the window, with its shortcut and a separator after it; in the native macOS menu bar it is the first item below the system's search field. This is VectorCraft's own order and does not raise a score (`menus::tests::help_starts_with_search_commands`, `tests::nativemenu::the_mac_help_menu_starts_with_search_commands`). From ef2dcb9df1ff85af13e1fbe735be6af068ee7c09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 07:14:51 -0800 Subject: [PATCH 4/8] Links: Unembed keeps a distorted image's clip group only when written as stored The links.unembed params text and docs/mcp.md now say that a distorted image from a PSD or PSB file keeps its clip group when Unembed writes it in the format it is stored in (PNG, or TIFF for a CMYK file), and that Relink and Update Links to the written file keep it too. A path that converts the image writes no clipping path, and the clip group becomes a plain group. - Test: tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd adds an Update Links step on the written file and an Unembed to a .jpg path. --- crates/engine/src/cmd/fileio/tests_psdread.rs | 21 ++++++++++++++++++- crates/engine/src/cmd/links.rs | 2 +- docs/mcp.md | 9 ++++---- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 4e43565b56..a1c376e938 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -714,10 +714,14 @@ fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { }; let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); - for step in ["unembed", "relink"] { + for step in ["unembed", "relink", "update"] { if step == "relink" { s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap(); } + if step == "update" { + let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); + assert_eq!(r["updated"], json!([image.0]), "{kind}: {r}"); + } let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; assert!(im.link.is_some(), "linked to the file written"); @@ -729,6 +733,21 @@ fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {:?}", before.0); } } + // A path that converts the image writes a file without the clipping path: the clip group + // becomes a plain group of the image, as Relink to any file without one leaves it. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources())); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + s.execute("links.unembed", &json!({"id": image.0, "path": dir.join("converted.jpg")})).unwrap(); + match s.doc().unwrap().doc.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image()); } /// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 5ebe9c5f54..d83e1178fd 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners and, when it came from a PSD or PSB file, the clip group of that file's clipping path, with or without folder). One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners; written as stored (here and with folder), such an image from a PSD or PSB file also keeps the clip group of the clipping path that file names, and the file written keeps the path, so Relink and Update Links to it keep the clip group; a path that converts the image writes no clipping path, and the clip group becomes a plain group). One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), diff --git a/docs/mcp.md b/docs/mcp.md index f80563dc27..5144c4698c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6669,10 +6669,11 @@ Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.mak Relink's `preserve`; Relink then adds a `warnings` entry naming those images. The clipping path a PSD, PSB or DCS file names is drawn through the corners: the clip group of the old file's clipping path gets the new file's clipping path, or becomes a plain group when the new file names none. Embed (`links.embed`) and Unembed (`links.unembed`) keep -the corners, each in one undo step. Unembed of a distorted image from a PSD or PSB file keeps the clip group of that -file's clipping path, and so does Relink to the PNG or TIFF it wrote. Mask (`object.maskImage`) draws its clipping -path through the image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a -plain image of the result. These rules are VectorCraft's own. +the corners, each in one undo step. Unembed of a distorted image from a PSD or PSB file, written as stored (PNG, or +TIFF for a CMYK file), keeps the clip group of that file's clipping path, and so do Relink and Update Links to the +file it wrote; a path that converts the image writes no clipping path, and the clip group becomes a plain group. Mask +(`object.maskImage`) draws its clipping path through the image's corners. Rasterize (`object.rasterize`) draws the +image between its corners and makes a plain image of the result. These rules are VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}} From fb0a82b09579ba48cfef2bf214eaeb605ce8380f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:44:10 -0800 Subject: [PATCH 5/8] Distort: keep blend steps, saved corners, previews and deep masks right - A blend step whose interpolated corners and nearer key's corners both fail the check is placed as the nearer key is. - Corners an image can't take are dropped when a file is read, so a later transform does not make them its distortion. - The .ai editing data writes a distorted image at any nesting depth, as it does a gradient mesh, so an opacity mask at the limit keeps it. - A linked image's preview keeps the clipping path its file keeps, so a document reopened from its preview still knows the file's clip group and Update Links replaces it instead of nesting a new one. - Docs: `corners` in the plugin API covers only corners that are not a parallelogram; Relink's warning for distorted images needs `preserve`. --- crates/doc/src/blend.rs | 23 +++++- crates/doc/src/image_quad.rs | 5 ++ crates/doc/src/node/wire.rs | 4 +- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/load.rs | 14 ++++ crates/engine/src/cmd/fileio/tests_psdread.rs | 79 +++++++++++++++++-- crates/engine/src/cmd/links.rs | 14 ++-- crates/eps/src/ai_editing/tests.rs | 51 ++++++++++++ crates/eps/src/ai_editing/writer.rs | 5 +- crates/pdf/src/tests/compression.rs | 26 ++++++ docs/mcp.md | 3 +- docs/plugins.md | 7 +- 12 files changed, 208 insertions(+), 25 deletions(-) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 17b13b139e..45610c6983 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -1161,9 +1161,15 @@ impl Lerp { && let (Some(qa), Some(qb)) = (a.image_corners(), b.image_corners()) { let near = if t < 0.5 { qa } else { qb }; - if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() { - // The nearer key's corners passed the same check when it was distorted. - let _ = n.set_image_corners(near); + if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() && n.set_image_corners(near).is_err() { + // Corners from a transform that collapses the image fail the check too: the + // step is then placed as the nearer key is. + if let (NodeKind::Image(o), NodeKind::Image(k)) = (&mut n.kind, &base.kind) { + o.xf = k.xf; + } + if n.extras().image_quad != base.extras().image_quad { + n.extras_mut().image_quad = base.extras().image_quad.clone(); + } } } n.extras_mut().mask = None; @@ -2342,6 +2348,17 @@ mod tests { let near = (if t < 0.5 { &a } else { b }).image_corners().unwrap(); assert!(got.iter().zip(near).all(|(g, w)| g.distance(w) < 1e-9), "{t}: {got:?} against {near:?}"); } + // Toward an image whose transform has no height, neither the step's corners nor the + // nearer key's pass the check: the step is placed as that key is. + let mut flat = image([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let collapsed = Affine::new([-3.0, 0.0, 0.0, 0.0, 100.0, 0.0]); + if let NodeKind::Image(im) = &mut flat.kind { + im.xf = collapsed; + } + let step = Lerp::new(&a, &flat, (None, None)).at(0.5); + let NodeKind::Image(im) = &step.kind else { panic!("an image") }; + assert_eq!(im.xf, collapsed); + assert!(!step.is_distorted_image() && step.extras().image_quad.is_none()); } fn key(x: f64) -> Arc { diff --git a/crates/doc/src/image_quad.rs b/crates/doc/src/image_quad.rs index 9d374ff664..613bc2e750 100644 --- a/crates/doc/src/image_quad.rs +++ b/crates/doc/src/image_quad.rs @@ -367,6 +367,11 @@ mod tests { assert_eq!(n.image_quad(), None); assert!(distorted_art(&n).is_none()); assert_eq!(n.image_corners(), Some(rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)))); + // Reading the file drops it, so a later transform can't make it a distortion. + let mut back: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap(); + assert!(back.extras().image_quad.is_none()); + back.transform(Affine::scale_non_uniform(1e6, 1.0), false); + assert!(!back.is_distorted_image()); } #[test] diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 932b9563f7..bb8850a230 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -293,7 +293,9 @@ impl From for Node { color_mask: w.color_mask, warp_piece: w.warp_piece, clip_pieces: w.clip_pieces, - image_quad: w.image_quad, + // Corners the image can't take are dropped as they are read: it is placed by its + // transform, and no later transform makes them its distortion. + image_quad: w.image_quad.filter(|q| matches!(&w.kind, NodeKind::Image(im) if crate::image_quad::check_for(im, q).is_ok())), }; Node { id: w.id, diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index cd6ec30f0d..fb1200cf04 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, image_clip, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, preview_with_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 8249fe6b71..9150039596 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1214,6 +1214,20 @@ pub(crate) fn image_clip(blob: &ImageBlob) -> Option vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) } +/// `blob` with its preview keeping the clipping path its PNG or TIFF keeps ([`image_clip`]), in a +/// text chunk of the preview PNG as [`png_with_clip`] writes it: a document saved without its +/// linked files holds the preview alone, and the Links commands then still know a clip group of +/// that path as the file's. Unchanged without a preview or a clipping path. +pub(crate) fn preview_with_clip(mut blob: ImageBlob) -> ImageBlob { + let Some(proxy) = blob.proxy.clone().filter(|p| !std::sync::Arc::ptr_eq(p, &blob.bytes) && png_clip(p).is_none()) else { return blob }; + let Some(json) = image_clip(&blob).and_then(|clip| serde_json::to_string(&clip).ok()).filter(|j| j.len() <= MAX_PNG_CLIP) else { + return blob; + }; + let png = vectorcraft_render::encode::png::with_text(proxy.to_vec(), &[(CLIP_KEYWORD, json.into())]); + blob.proxy = Some(std::sync::Arc::new(png)); + blob +} + /// 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 { diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 0bd5058a7b..7a56932aed 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -684,15 +684,68 @@ fn update_links_follows_the_clipping_path_of_a_distorted_psd() { assert_eq!(node(&s).image_corners().unwrap(), corners); } +/// A document saved without its linked files keeps a linked PSD file's image as a preview, smaller +/// than the file. Reopened after the file's clipping path changed, Update Links still knows the +/// clip group of the old clipping path as the file's and gives it the new one, for an image changed +/// by Perspective Distort or Free Distort and for one that is not. +#[test] +fn update_links_after_reopening_from_the_preview_replaces_the_files_clipping_path() { + let big = |resources: &[u8]| psd(1, 3, (400, 200), 8, 3, &[], resources, &[], &raw(&[&[255; 80000], &[0; 80000], &[0; 80000]])); + for distorted in [false, true] { + let dir = vectorcraft_testkit::TempDir::new(if distorted { "psd-preview-distorted" } else { "psd-preview" }); + let cut = write_file(&dir, "cut.psd", &big(&triangle_resources())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [200, 100]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + if distorted { + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [400, 30], [360, 200], [20, 180]]})).unwrap(); + } + let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone(); + let corners = node(&s).image_corners().unwrap(); + let doc_path = dir.join("poster.vectorcraft").to_string_lossy().into_owned(); + s.execute("document.save", &json!({"path": doc_path})).unwrap(); + std::fs::write(&cut, big(&square_resources())).unwrap(); + s.execute("document.open", &json!({"path": doc_path})).unwrap(); + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; + assert!(d.images[&im.key].is_proxy(), "the saved preview shows"); + let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); + assert_eq!(r["updated"], json!([image.0]), "{r}"); + let map = node(&s).image_map().unwrap(); + let squared: Vec<[f64; 2]> = [[100.0, 50.0], [300.0, 50.0], [300.0, 150.0], [100.0, 150.0]] + .iter() + .map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()) + .map(|p| [p.x, p.y]) + .collect(); + let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group); + let near = + anchors.len() == squared.len() && anchors.iter().zip(&squared).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + assert!(near && even_odd && held == image, "distorted: {distorted}: {anchors:?} vs {squared:?}"); + assert_eq!(node(&s).image_corners().unwrap(), corners); + } +} + /// Unembed of a distorted image from a PSD file, with a path and with a folder, keeps the clip /// group of the clipping path that file names, drawn through its corners, and so does relinking it -/// to the file written. +/// to the file written. Update Links reads the clipping path the file on disk keeps then, and all +/// four corners stay where they were. #[test] fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { let dir = vectorcraft_testkit::TempDir::new("psd-unembed-distorted-clip"); // An RGB file is kept as a PNG, a CMYK one as a TIFF. - let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); - let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)]; + let cmyk = |resources: &[u8]| psd(1, 4, (100, 50), 8, 4, &[], resources, &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); + let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk(&triangle_resources()))]; + // The file Unembed writes, as stored, for the same kind of file clipped to the square. + let squared_file = |kind: &str| { + let file = if kind == "rgb" { red_psd(&square_resources()) } else { cmyk(&square_resources()) }; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "square.psd", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + let r = s.execute("links.unembed", &json!({"id": r["image"]})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() + }; for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) { let data = vectorcraft_format::base64_encode(file); let mut s = Session::new(); @@ -702,6 +755,7 @@ fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); let before = clip_group(&s.doc().unwrap().doc, group); + let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap(); // Without an extension the image is written in the format it is stored in. let path = if folder { let out = dir.join(format!("folder-{kind}")); @@ -715,22 +769,31 @@ fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); for step in ["unembed", "relink", "update"] { + let mut want = before.0.clone(); if step == "relink" { s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap(); } if step == "update" { + // The file on disk now keeps the square: Update Links reads it from there. + std::fs::write(&path, squared_file(kind)).unwrap(); let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); assert_eq!(r["updated"], json!([image.0]), "{kind}: {r}"); + let map = s.doc().unwrap().doc.node(image).unwrap().image_map().unwrap(); + want = [[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]] + .iter() + .map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()) + .map(|p| [p.x, p.y]) + .collect(); } let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; assert!(im.link.is_some(), "linked to the file written"); - assert!(d.node(image).unwrap().is_distorted_image()); - // The clipping path is drawn through the corners again, within rounding. + assert_eq!(d.node(image).unwrap().image_corners().unwrap(), corners, "{kind}, {step}, folder: {folder}"); + // The clipping path is drawn through the corners, within rounding. let (anchors, even_odd, held) = clip_group(d, group); - let near = anchors.len() == before.0.len() - && anchors.iter().zip(&before.0).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); - assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {:?}", before.0); + let near = + anchors.len() == want.len() && anchors.iter().zip(&want).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {want:?}"); } } // A path that converts the image writes a file without the clipping path: the clip group diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9c4f9ea6a5..9d0a0bbcb3 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say, and its clipping is handled as links.update handles it. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's, and one naming the distorted images that preserve was not applied to)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say, and its clipping is handled as links.update handles it. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's, and, when preserve is given, one naming the distorted images it was not applied to)}", has_doc, relink ), @@ -609,13 +609,14 @@ pub(crate) fn kept_unread(bytes: &[u8]) -> bool { /// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the /// file is one [`kept_unread`] names), its pixels are decoded once to check that they can be read, /// and a `linked` image's preview is made from that decode ([`ImageBlob::checked_with_proxy`]); -/// otherwise a `linked` image gets its preview ([`ImageBlob::with_proxy`]). An error when the -/// pixels can't be read. +/// otherwise a `linked` image gets its preview ([`ImageBlob::with_proxy`]). The preview keeps the +/// clipping path the image keeps ([`fileio::preview_with_clip`]). An error when the pixels can't +/// be read. pub(crate) fn readable(blob: ImageBlob, unread: bool, linked: bool) -> Result { if !unread { - return Ok(if linked { blob.with_proxy() } else { blob }); + return Ok(if linked { fileio::preview_with_clip(blob.with_proxy()) } else { blob }); } - blob.checked_with_proxy(linked).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into())) + blob.checked_with_proxy(linked).map(fileio::preview_with_clip).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into())) } /// [`readable`], and the pixels it decoded are kept in the image store the renderers share @@ -626,6 +627,7 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> return readable(blob, unread, linked); } let (blob, pixels) = blob.checked_with_pixels(linked).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into()))?; + let blob = fileio::preview_with_clip(blob); if let Some(pixels) = pixels { vectorcraft_render::keep_decoded_image(&blob, pixels); } @@ -1668,7 +1670,7 @@ fn resolve_links(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_e store_image(d, &g.key, blob, true); } else if let Some(b) = d.images.get(&g.key).filter(|b| b.proxy.is_none()) { // Linked before links kept a preview. - let b = b.clone().with_proxy(); + let b = fileio::preview_with_clip(b.clone().with_proxy()); d.images.insert(g.key.clone(), b); } // Found away from its path, or read again: the link follows. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 3c2b229e1f..42c5dacb44 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -9288,6 +9288,57 @@ fn a_masked_copy_nested_too_deep_for_its_mask_keeps_all_of_its_pixels() { assert!(whole >= 2, "the first copy and a copy whose mask is left out: {sizes:?}"); } +/// A distorted image in the art of an opacity mask written at the deepest level a mask takes is +/// written as its pieces, as an undistorted image there is written whole: the mask keeps its art. +#[test] +fn a_distorted_image_in_a_mask_at_the_nesting_limit_keeps_its_pixels() { + // GUARDS: the distorted image was written there as an empty group, so the mask hid the object. + let masks = |distorted: bool| { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut masked = speckled_photo(&mut doc); + let mut art = speckled_photo(&mut doc); + if distorted { + let q = [(40.0, 10.0), (100.0, 10.0), (148.0, 138.0), (20.0, 138.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y)); + art.set_image_corners(q).unwrap(); + } + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true })); + doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(masked) }); + // Each isolated instance is written as its art, a level deeper: the masked object's mask + // art is at the limit. + for i in 1..writer::MAX_NEST - 1 { + let mut inner = instance(&mut doc, &format!("S{}", i - 1), Affine::IDENTITY); + inner.isolate = true; + doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(inner) }); + } + let mut outer = instance(&mut doc, &format!("S{}", writer::MAX_NEST - 2), Affine::IDENTITY); + outer.isolate = true; + doc.insert(Some(layer), usize::MAX, outer).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::DEEP_MASKS), "{:?}", out.warnings); + // Each mask read back, by whether its art holds an image. + let back = read_back(&doc); + let mut found = vec![]; + let mut look = |n: &Node| { + if let Some(m) = n.extras().mask.as_ref() { + let mut image = false; + m.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_))); + found.push(image); + } + }; + for l in &back.layers { + l.walk(&mut look); + } + for s in &back.symbols { + s.art.walk(&mut look); + } + found + }; + let (plain, distorted) = (masks(false), masks(true)); + assert!(!plain.is_empty() && plain.iter().all(|i| *i), "{plain:?}"); + assert_eq!(distorted, plain); +} + /// [`warped_photo`] linked to `/Users/someone/Job/art/photo.png`, in folder `art` next to the /// document's. fn linked_warped_photo(doc: &mut Document, effects: Vec) -> Node { diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index d80c77c122..511f19a308 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -958,8 +958,9 @@ impl<'a> Writer<'a> { self.warn(w); } let moved = bounds && self.wrap_on_bounds(n, state); - // A gradient mesh's drawn look is paths, which hold nothing: it is written at any depth. - if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) { + // A gradient mesh's drawn look is paths, and a distorted image's is clipped copies of its + // image, which hold nothing: they are written at any depth. + if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) || n.is_distorted_image() { let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); self.nest += 1; self.drawn += 1; diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 74ca9191cc..8c0be940a7 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -182,6 +182,32 @@ fn a_distorted_image_is_written_with_its_corners_on_its_quad() { assert_eq!(seen, [true; 4]); } +/// A distorted image's own fill that Convert to Shape gives a shape is written with it. +#[test] +fn a_distorted_image_keeps_its_own_shaped_fill() { + use vectorcraft_doc::{AppearanceItem, Effect, FillLayer, color::Color, color::Paint}; + let mut d = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let id = d.layers[0].children().unwrap()[0].id; + let q = [(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| Point::new(x, y)); + let n = d.node_mut(id).unwrap(); + n.set_image_corners(q).unwrap(); + let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + fill.effects = vec![Effect { id: "convertToShape.rectangle".into(), params: json!({"relative": true, "extraW": 0, "extraH": 0}), visible: true }]; + n.appearance.items.push(AppearanceItem::Fill(fill)); + let bytes = export_with_report(&d, &PdfOptions::default()).unwrap().bytes; + let back = crate::import(&bytes).unwrap(); + let (mut green, mut pieces) = (false, 0); + back.walk(|n| match &n.kind { + NodeKind::Image(_) => pieces += 1, + NodeKind::Path { .. } => { + green |= n.appearance.fill().and_then(|f| f.paint.color()).is_some_and(|c| c.to_rgb()[1] > 0.9 && c.to_rgb()[0] < 0.1) + } + _ => {} + }); + assert!(pieces > 2, "{pieces}"); + assert!(green, "the fill is written"); +} + #[test] fn jpeg_zip_and_automatic_compression() { let png = doc(encoded(colour(), ImageFormat::Png), "image/png"); diff --git a/docs/mcp.md b/docs/mcp.md index b72d8f660a..2a177704cc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6951,7 +6951,8 @@ Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.mak (`object.createObjectMosaic`), Create Gradient Mesh (`object.mesh.create`) and Place with Replace (`file.place` with `replace`) refuse a distorted image with an error that names the distortion. Update Links (`links.update`) and Relink (`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or -Relink's `preserve`; Relink then adds a `warnings` entry naming those images. The clipping path a PSD, PSB or DCS +Relink's `preserve`. When `preserve` is given, Relink adds a `warnings` entry naming those images; without it, Relink +adds none for them. The clipping path a PSD, PSB or DCS file names is drawn through the corners: the clip group of the old file's clipping path gets the new file's clipping path, or becomes a plain group when the new file names none. Embed (`links.embed`) and Unembed (`links.unembed`) keep the corners, each in one undo step. Unembed of a distorted image from a PSD or PSB file, written as stored (PNG, or diff --git a/docs/plugins.md b/docs/plugins.md index 92e5ae47db..5f7eb3338a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -678,9 +678,10 @@ every attribute: of JSON: type whose runs and paragraphs don't fit what the type before it in paint order left comes with `truncated: true` too. - An image (`"image"`): `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or - `"unknown"`, read from the image itself. An image changed by Perspective Distort or Free Distort also has `corners`, - its pixel rectangle's corners on the page (top left, top right, bottom right, bottom left), and its `transform` is the - affine placement that matches it at its middle. An embedded image whose pixels take at most 1 MiB in base64 (443 × 443 + `"unknown"`, read from the image itself. An image whose corners Perspective Distort or Free Distort moved to a shape + other than a parallelogram also has `corners`, its pixel rectangle's corners on the page (top left, top right, bottom + right, bottom left), and its `transform` is the affine placement that matches it at its middle. Corners that make a + parallelogram are described by `transform` alone. An embedded image whose pixels take at most 1 MiB in base64 (443 × 443 pixels fit) has them in `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top, and `pixelsOmitted: false`. A CMYK image's pixels are its inks through the working CMYK profile, as sRGB. The pixels of all the images in one input take at most 16 MiB in base64, and an image the host starts to decode takes its size From ac8cdf071defffff436b5c04bbc5778dfbe5e584 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:00:12 -0800 Subject: [PATCH 6/8] Preflight: measure a distorted image's resolution as Image Info does Production Preflight measured a distorted image's effective resolution from its transform alone, so an image enlarged by Perspective Distort or Free Distort could pass the minimum. It now measures it at its middle, with the placement Image Info reports. --- crates/engine/src/cmd/preflight.rs | 4 +++- crates/engine/tests/preflight.rs | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index ebfaf5deeb..a564b29335 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -89,11 +89,13 @@ fn check(s: &mut Session, p: &Value) -> Result { continue; }; let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n)); + // A distorted image is measured at its middle, as Link Info measures it. + let xf = doc.node(source).and_then(vectorcraft_doc::image_quad::nearest_affine).unwrap_or(im.xf); let ppi = context .pages .iter() .filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0)) - .map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf)) + .map(|(_, to_page)| super::place::effective_ppi(*to_page * xf)) .reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]); let Some(ppi) = ppi else { resolution_unchecked += 1; diff --git a/crates/engine/tests/preflight.rs b/crates/engine/tests/preflight.rs index 08b7cf153b..e656596d71 100644 --- a/crates/engine/tests/preflight.rs +++ b/crates/engine/tests/preflight.rs @@ -112,6 +112,26 @@ fn preflight_resolution_follows_placed_size_and_both_axes() { assert!(codes(&screen).is_empty(), "{screen}"); } +/// A distorted image's resolution is measured at its middle, as Image Info measures it. +#[test] +fn preflight_resolution_of_a_distorted_image_is_image_infos() { + let dir = Folder::new("preflight-resolution-distorted"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap(); + let mut s = new(); + let id = s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap()["ids"][0].clone(); + s.execute("select.set", &json!({ "ids": [id] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 24, "height": 24 })).unwrap(); + assert!(codes(&s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap()).is_empty()); + // The top stays 24 pt wide; the bottom is 120 pt wide. + s.execute("object.distort", &json!({ "corners": [[188, 188], [212, 188], [260, 212], [140, 212]] })).unwrap(); + assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().is_distorted_image()); + let info = s.execute("image.info", &json!({ "id": id })).unwrap(); + let r = s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap(); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").expect("a low resolution finding"); + assert_eq!(f["effectivePpi"], info["ppi"], "{info}"); +} + #[test] fn preflight_resolution_accepts_the_exact_threshold_but_rejects_a_real_shortfall() { let dir = Folder::new("preflight-resolution-boundary"); From 99781bb329ae8661cf4dcc028b0a9c29ac93e133 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:10:00 -0800 Subject: [PATCH 7/8] Links: Relink and folder Unembed no longer refuse a distorted image The refusals that ran before the files were read and before a folder was written stopped Relink and the folder form of Unembed on an image changed by Perspective Distort or Free Distort, which now keep their corners. --- crates/engine/src/cmd/links.rs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 2af260011a..9d0a0bbcb3 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -2136,9 +2136,6 @@ fn relink(s: &mut Session, p: &Value) -> Result { _ => None, }) }; - // Whether the images were found as the missing links (nothing selected, a folder given) rather - // than named or selected. - let mut found_missing = false; let mut ids: Vec = match (&each, ids_param(p, "ids", C)?) { (Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(), (None, Some(ids)) => ids, @@ -2146,7 +2143,6 @@ fn relink(s: &mut Session, p: &Value) -> Result { let selected: Vec = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect(); match folder_param { Some(_) if selected.is_empty() => { - found_missing = true; groups(&st.doc, None).into_iter().filter(|g| probe(g, LinkBase::of(st)).0 == Status::Missing).flat_map(|g| g.ids).collect() } _ => selected, @@ -2159,11 +2155,6 @@ fn relink(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select the images to relink, or pass ids")); } - // A named or selected distorted image is refused before a folder is searched, whether or not - // its file is found there. - if !found_missing && let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) { - return Err(super::xform::distorted_image_error(C, *id)); - } // All Instances: the other stored objects linked to the same files, each once. if scope == Scope::All { let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect(); @@ -2868,9 +2859,6 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re skipped.push(id); continue; } - if n.is_distorted_image() { - return Err(super::xform::distorted_image_error(C, id)); - } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; embedded.push((id, n.display_name(), blob)); } From 0a337811582b86ad409321d78ceed6488c10e1a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:02:06 -0800 Subject: [PATCH 8/8] Links: the Unembed code comment names TIFF among the stored formats An image that keeps CMYK inks is stored as TIFF, and Unembed writes it as a .tif file when the path has no extension. The comment above the format choice now lists TIFF with PNG, JPEG, GIF and WebP. --- crates/engine/src/cmd/links.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9d0a0bbcb3..fccff66c0c 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -2809,7 +2809,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("image {} is linked already", id.0))); } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; - // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. + // As stored (PNG, JPEG, GIF, WebP, or TIFF for an image that keeps CMYK inks), unless the path names another format. let stored = stored_extension(blob); let path = str_param(p, "path"); let ext = match path.map(fileio::extension) {