From fb0a82b09579ba48cfef2bf214eaeb605ce8380f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:44:10 -0800 Subject: [PATCH] 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