diff --git a/Cargo.lock b/Cargo.lock index 69ddc08af5..b8995c19ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7056,6 +7056,7 @@ dependencies = [ "craft-image-codecs", "craft-vectorcraft-format", "log", + "rustix 1.1.6", "serde", "serde_json", "sha2", diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 1280e7d998..6d1f33dd5c 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -13,6 +13,8 @@ workspace = true spine-count = [] # `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only). symbol-read-count = [] +# `vectorcraft_doc::locked_artboard_measures` for other crates' tests (dev-dependencies only). +locked-artboard-count = [] [dependencies] vectorcraft-geom = { workspace = true } diff --git a/crates/doc/src/artboard.rs b/crates/doc/src/artboard.rs index fd06ea9093..848cf038fa 100644 --- a/crates/doc/src/artboard.rs +++ b/crates/doc/src/artboard.rs @@ -174,6 +174,21 @@ impl ArtboardSide { } } +#[cfg(any(test, feature = "locked-artboard-count"))] +thread_local! { + /// How many objects [`LockedArtboards::overlaps`] has measured on this thread. + static LOCKED_ARTBOARD_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many objects [`LockedArtboards::overlaps`] has measured on this thread, for other crates' +/// tests that count how often art is measured to find what a locked artboard holds (the +/// `locked-artboard-count` feature, dev-dependencies only). +#[cfg(any(test, feature = "locked-artboard-count"))] +#[doc(hidden)] +pub fn locked_artboard_measures() -> usize { + LOCKED_ARTBOARD_MEASURES.with(std::cell::Cell::get) +} + /// A document's locked artboards ([`Document::locked_artboards`]). pub struct LockedArtboards<'a> { pub(crate) rects: Vec, @@ -210,6 +225,8 @@ impl LockedArtboards<'_> { if let Some(held) = self.held.borrow().get(&n.id) { return *held; } + #[cfg(any(test, feature = "locked-artboard-count"))] + LOCKED_ARTBOARD_MEASURES.with(|c| c.set(c.get() + 1)); let held = n.visual_bounds_with(&self.symbols).is_some_and(|b| self.rects.iter().any(|r| b.x0 < r.x1 && b.x1 > r.x0 && b.y0 < r.y1 && b.y1 > r.y0)); self.held.borrow_mut().insert(n.id, held); diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 02458af8c5..0418477194 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -1162,9 +1162,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; @@ -2343,6 +2349,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 e07fd47760..e6fe10022b 100644 --- a/crates/doc/src/image_quad.rs +++ b/crates/doc/src/image_quad.rs @@ -392,6 +392,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/lib.rs b/crates/doc/src/lib.rs index 0578474c99..5a9b27b304 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -161,6 +161,9 @@ mod records; mod stored_art; mod units; +#[cfg(any(test, feature = "locked-artboard-count"))] +#[doc(hidden)] +pub use artboard::locked_artboard_measures; pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS}; pub use canvas_range::BeyondCanvas; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 4f0c3d6005..4fcb2bf4fc 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -42,7 +42,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; pub mod hpgl; mod jp2read; diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index cedda4844a..1818816842 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1370,6 +1370,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 881519fbda..7a56932aed 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -602,6 +602,217 @@ 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); +} + +/// 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); +} + +/// 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. 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 = |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(); + 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())); + 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}")); + 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", "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_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() == 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 + // 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()); +} + /// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, with a /// path and with a folder, and so do relinking to the written file, placing it and opening it. #[test] diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 13394fc8d0..3b295a1805 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -3455,6 +3455,145 @@ fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() { assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id))); } +/// A column graph whose series 0 group is linked to style "Blue" (as a file can hold it) and whose first path directly +/// inside that group is linked to style "Green" and has its look: the session, the graph, the group, series 0's paths, +/// and the ids of "Blue" and "Green". +fn linked_group_with_a_green_mark() -> (Session, NodeId, NodeId, Vec, u32, u32) { + let (mut s, id, _, marks) = column_marks(); + let (group, _) = series_0_group(&s, id); + let (blue, green) = blue_and_green_styles(&mut s); + link_group_and_member(&mut s, group, &blue, marks[0], &green); + (s, id, group, marks, blue.id, green.id) +} + +/// Graphic styles "Blue" (a blue fill at 50% opacity) and "Green" (a green fill at full opacity), made from one new +/// rectangle that is linked to neither. +fn blue_and_green_styles(s: &mut Session) -> (vectorcraft_doc::GraphicStyle, vectorcraft_doc::GraphicStyle) { + let (rect, _) = blue_style(s, "Blue", false); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap(); + s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Green"})).unwrap(); + let d = &s.doc().unwrap().doc; + (d.graphic_style("Blue").unwrap().clone(), d.graphic_style("Green").unwrap().clone()) +} + +/// Links `group` to `outer` with its look and `member` to `inner` with its look, as a file can hold them. +fn link_group_and_member( + s: &mut Session, + group: NodeId, + outer: &vectorcraft_doc::GraphicStyle, + member: NodeId, + inner: &vectorcraft_doc::GraphicStyle, +) { + s.edit("Link", |d, _| { + let g = d.node_mut(group).unwrap(); + g.appearance = outer.appearance.clone().into(); + g.extras_mut().graphic_style = Some(outer.id); + let m = d.node_mut(member).unwrap(); + m.appearance = inner.appearance.clone().into(); + m.extras_mut().graphic_style = Some(inner.id); + Ok(()) + }) + .unwrap(); +} + +/// Asserts that `d` holds what `was` holds for a redefinition of style "Blue": its definition, the link of `group`, the +/// look and link of each of `members`, and everything graph `id` stores (series paints and label rows included). +fn assert_same_redefine_state( + d: &vectorcraft_doc::Document, + was: &vectorcraft_doc::Document, + id: NodeId, + group: NodeId, + members: &[NodeId], + when: &str, +) { + assert_eq!(d.graphic_style("Blue"), was.graphic_style("Blue"), "{when}: the definition of Blue"); + assert_eq!(d.node(group).unwrap().extras().graphic_style, was.node(group).unwrap().extras().graphic_style, "{when}: the group's link"); + for m in members { + let (a, b) = (d.node(*m).unwrap(), was.node(*m).unwrap()); + assert_eq!((&a.appearance, a.extras().graphic_style), (&b.appearance, b.extras().graphic_style), "{when}: member {m:?}"); + } + assert_eq!(d.node(id).unwrap().extras().graph, was.node(id).unwrap().extras().graph, "{when}: what the graph stores"); +} + +/// Redefine Graphic Style with another style's look (`from`) on a linked series group leaves a path of the group that is +/// linked to that other style linked to it, and restyles and links the group's other paths; one undo takes the +/// redefinition back and redo makes it again. +#[test] +fn redefining_a_graphic_style_from_another_style_keeps_a_mark_linked_to_it() { + let (mut s, id, group, marks, blue, green) = linked_group_with_a_green_mark(); + let own = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone(); + let look = s.doc().unwrap().doc.graphic_style("Green").unwrap().appearance.fill_paint(); + let was = s.doc().unwrap().doc.clone(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "from": "Green"})).unwrap(); + let after = s.doc().unwrap().doc.clone(); + let first = after.node(marks[0]).unwrap(); + assert_eq!((&first.appearance, first.extras().graphic_style), (&own, Some(green)), "the mark keeps its own style"); + assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().appearance.fill_paint() == look)); + assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().extras().graphic_style == Some(blue))); + assert_eq!(after.node(group).unwrap().extras().graphic_style, None); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(look), "the graph stores the new look"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_same_redefine_state(&s.doc().unwrap().doc, &was, id, group, &marks, "after one undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_same_redefine_state(&s.doc().unwrap().doc, &after, id, group, &marks, "after redo"); +} + +/// Redefine Graphic Style from an object on a linked series group leaves a path of the group that is linked to another +/// style as it is, restyles and links the group's other paths; one undo takes the redefinition back and redo makes it +/// again. +#[test] +fn redefining_a_graphic_style_from_an_object_keeps_a_mark_linked_to_another_style() { + let (mut s, id, group, marks, blue, green) = linked_group_with_a_green_mark(); + let own = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone(); + let red = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.setItem", &json!({"ids": [red.0], "index": top_row(&s, red, true), "color": "#ff0000", "opacity": 100})).unwrap(); + let look = s.doc().unwrap().doc.node(red).unwrap().appearance.fill_paint(); + let was = s.doc().unwrap().doc.clone(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": red.0})).unwrap(); + let after = s.doc().unwrap().doc.clone(); + let first = after.node(marks[0]).unwrap(); + assert_eq!((&first.appearance, first.extras().graphic_style), (&own, Some(green)), "the mark keeps its own style"); + assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().appearance.fill_paint() == look)); + assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().extras().graphic_style == Some(blue))); + assert_eq!(after.node(group).unwrap().extras().graphic_style, None); + assert_eq!(spec(&s, id).series_paints[0].fill, Some(look), "the graph stores the new look"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_same_redefine_state(&s.doc().unwrap().doc, &was, id, group, &marks, "after one undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_same_redefine_state(&s.doc().unwrap().doc, &after, id, group, &marks, "after redo"); +} + +/// Redefine Graphic Style on a graph's Legend group linked to the style leaves a label of the group that is linked to +/// another style with its look and its link, restyles and links the group's other label, and clears and unlinks the +/// group; one undo takes the redefinition back and redo makes it again. +#[test] +fn redefining_a_graphic_style_keeps_a_legend_label_linked_to_another_style() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let legend = group(s.doc().unwrap().doc.node(id).unwrap(), "Legend").id; + let labels = [text_id(&s, id, "Legend", "2024"), text_id(&s, id, "Legend", "2025")]; + let (blue, green) = blue_and_green_styles(&mut s); + link_group_and_member(&mut s, legend, &blue, labels[0], &green); + let own = s.doc().unwrap().doc.node(labels[0]).unwrap().appearance.clone(); + let red = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.setItem", &json!({"ids": [red.0], "index": top_row(&s, red, true), "color": "#ff0000", "opacity": 100})).unwrap(); + let look = s.doc().unwrap().doc.node(red).unwrap().appearance.fill_paint(); + let was = s.doc().unwrap().doc.clone(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": red.0})).unwrap(); + let after = s.doc().unwrap().doc.clone(); + let kept = after.node(labels[0]).unwrap(); + assert_eq!((&kept.appearance, kept.extras().graphic_style), (&own, Some(green.id)), "the label keeps its own style"); + let other = after.node(labels[1]).unwrap(); + assert_eq!((other.appearance.fill_paint(), other.extras().graphic_style), (look, Some(blue.id)), "the other label follows"); + let g = after.node(legend).unwrap(); + assert_eq!((g.appearance.items.is_empty(), g.extras().graphic_style), (true, None), "the group is cleared and unlinked"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_same_redefine_state(&s.doc().unwrap().doc, &was, id, legend, &labels, "after one undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_same_redefine_state(&s.doc().unwrap().doc, &after, id, legend, &labels, "after redo"); +} + /// Series `index`'s group: its object opacity and blend mode, and those of each path directly inside it. fn group_transparency(s: &Session, id: NodeId, index: u32) -> ((f32, BlendMode), Vec<(f32, BlendMode)>) { let n = s.doc().unwrap().doc.node(id).unwrap().clone(); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index abb1a2d2aa..fccff66c0c 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}; @@ -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. 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, when preserve is given, one naming the distorted images it was not applied to)}", 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; written as stored (here and with folder), 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, so Open, Place, Relink and Update Links read the file with that clip 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. 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 and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners). The image is written as stored (PNG, JPEG, GIF, WebP or TIFF; as PNG when that format is not one of VectorCraft's raster file formats) when path has no extension or names the stored format, and converted when path ends in another of .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp. Written as stored (here and with folder), 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, so Open, Place, Relink and Update Links read the file with that clip group (drawn through a distorted image's corners); a converted file holds 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 ), @@ -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); } @@ -792,13 +794,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 { @@ -1211,14 +1220,44 @@ 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 (`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 { + 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.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) +} + +/// `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 @@ -1245,12 +1284,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) { @@ -1267,10 +1309,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; } @@ -1625,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. @@ -2091,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, @@ -2101,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, @@ -2114,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(); @@ -2163,11 +2199,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 { @@ -2227,8 +2258,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))))?; } @@ -2251,6 +2284,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`. @@ -2630,9 +2680,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), @@ -2761,11 +2808,8 @@ 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. + // 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) { @@ -2815,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)); } @@ -3137,4 +3178,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/cmd/place.rs b/crates/engine/src/cmd/place.rs index b97109026f..fef99cc9c3 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -1188,8 +1188,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { let doc = super::links::with_brush_art(&st.doc); let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) }; - // Effective resolution, taken at the middle of a distorted image. - let ppi = effective_ppi(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf)); + // Effective resolution at the middle of a distorted image. + let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf); let size = n.geometric_bounds().unwrap_or_default(); // A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info. let doc_path = super::links::LinkBase::of(st).doc; @@ -1201,7 +1201,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { "colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)), "pixelWidth": im.width, "pixelHeight": im.height, - "ppi": ppi, + "ppi": effective_ppi(xf), "width": size.width(), "height": size.height(), })) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 5570dc6a81..2a1b8c8b40 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1044,7 +1044,7 @@ fn load_folder(s: &Session, folder: &str) -> Value { if r.disabled_changed { s.store_disabled_plugins_in(&turn); } - json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::>()}) + json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::>(), "leftOut": r.left_out}) } Err(e) => json!({"folder": folder, "error": e.to_string()}), } @@ -1270,7 +1270,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1333,7 +1333,7 @@ pub fn specs() -> Vec { "Reload Plug-ins", ["Object", "Plug-ins"], None, - "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it (desktop; a bad module, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}]}", + "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}", always, reload ), 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/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 14c6957e23..50f59e77e7 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", + "{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source, paths linked to the style whose look was edited and members linked to another style, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", has_doc, style_redefine ), @@ -554,10 +554,13 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); set_link(d, &edited, None); // A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and - // goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look. + // goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its + // lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps + // its look and its link. let mut follow_marks = super::graph::series_group_marks(d, &follow); let edited: HashSet = edited.into_iter().collect(); - follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid)); + let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id)); + follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid)); super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); let g = d.graphic_styles[i].clone(); let mut shared = None; diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index 6e385cbb7e..a8e37ff812 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 268fa79ad0..6391c4f3db 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -663,6 +663,213 @@ 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}"); + 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)); + 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 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. +#[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(); + // 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); + 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 89c3b28b13..ab823a696e 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -879,13 +879,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"})), - // Refused before the folder is searched, so a file missing there does not hide it. - ("links.relink", json!({"folder": "/nowhere"})), - ("links.embed", json!({"ids": [img.0]})), - ("links.unembed", json!({})), - // Refused before any file is written. - ("links.unembed", json!({"folder": "/nowhere"})), ("object.createObjectMosaic", json!({})), ("object.mesh.create", json!({})), ( 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"); diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 3fc99847d6..ea7d6c5cb3 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -9309,6 +9309,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 263353c675..8065b8cbb5 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -974,8 +974,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/pathops/src/addons/pathtools/tangent_circle/on_segments.rs b/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs index 615c7f1412..82d2f2c7a0 100644 --- a/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs +++ b/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs @@ -7,7 +7,7 @@ //! //! The roots are found by sampling a distance function along one parameter: samples where it is 0, //! bisection where it changes sign, and a golden-section search where it comes down to 0 between -//! samples without changing sign. +//! samples without changing sign. For a radius, each second segment has its own distance function. use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, ParamCurveNearest, Point, Vec2}; @@ -256,7 +256,19 @@ pub fn circles_of_radius(first: CubicBez, second: &[CubicBez], radius: f64) -> V let mut found = vec![]; for side in [1.0, -1.0] { let center = |t: f64| normal(&first, t, own).map(|n| first.eval(t) + n * (side * radius)); - for t in roots(&samples, |t| center(t).and_then(|c| nearest(c, second)).map(|(d, _)| d - radius), CONTACT * radius) { + // Each second segment is searched on its own, so that two segments touching circles close + // together along `first` give both; `touching` then checks each circle against all of them. + let mut ts: Vec = second + .iter() + .flat_map(|seg| { + let dist = |t: f64| center(t).and_then(|c| nearest(c, std::slice::from_ref(seg))).map(|(d, _)| d - radius); + roots(&samples, dist, CONTACT * radius) + }) + .collect(); + // A segment repeated in `second` gives the same places again; each is checked once. + ts.sort_by(f64::total_cmp); + ts.dedup(); + for t in ts { if let Some(c) = center(t) && let Some(touch) = touching(c, radius, second, own) { diff --git a/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs index c130fb5be3..0104672125 100644 --- a/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs +++ b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs @@ -654,6 +654,20 @@ fn two_circles_between_the_same_two_places_tried_are_both_found() { assert!(near(found[0].circle.center, x - dx, 20.0, 1e-6) && near(found[1].circle.center, x + dx, 20.0, 1e-6), "{found:?}"); } +#[test] +fn two_segments_that_touch_circles_close_together_give_both() { + // A peak whose two feet touch circles of radius 20 on y = 0 at both feet, between the same + // places tried along the line; then the same on a line 10,000 pt long, with the feet 10 pt apart. + for (len, a, b) in [(100.0, 50.03, 50.15), (1e4, 5003.0, 5013.0)] { + let top = 0.5 * (a + b); + let second = [line((a, 40.0), (top, 60.0)), line((top, 60.0), (b, 40.0))]; + let found = circles_of_radius(line((0.0, 0.0), (len, 0.0)), &second, 20.0); + assert_eq!(found.len(), 2, "{len}: {found:?}"); + assert!(near(found[0].circle.center, a, 20.0, 1e-6) && near(found[0].second, a, 40.0, 1e-6), "{len}: {found:?}"); + assert!(near(found[1].circle.center, b, 20.0, 1e-6) && near(found[1].second, b, 40.0, 1e-6), "{len}: {found:?}"); + } +} + #[test] fn a_tiny_circle_between_long_lines_close_together_is_found() { let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &[line((0.0, 1e-4), (100.0, 1e-4))]); diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 86bbb69bcb..dcc32b01fe 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -196,6 +196,32 @@ fn a_distorted_image_is_written_with_its_corners_on_its_quad() { assert!(quad_clips >= 1, "no clipping path on the quad"); } +/// 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/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 8cd7ceb62f..0a964167a2 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -28,5 +28,10 @@ wasmparser = { workspace = true } # the build through eframe. web-time = "1" +# Opens a `.wasm` in the plug-ins folder without waiting when it is a named pipe (`registry.rs`). +# Already in Cargo.lock, so this adds no new crate. +[target.'cfg(unix)'.dependencies] +rustix = { workspace = true, features = ["std", "fs"] } + [dev-dependencies] wat = { workspace = true } diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index 1178f7c9ac..6d20452ce6 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -182,20 +182,75 @@ pub fn intern(s: &str) -> &'static str { /// and loads it. #[cfg(not(target_arch = "wasm32"))] pub fn load_file(path: &std::path::Path, limits: Limits) -> Result { - use std::io::Read; - let meta = std::fs::metadata(path).map_err(|e| Error::Io(format!("{}: {e}", path.display())))?; - if !meta.is_file() { - return Err(Error::Io(format!("{} is not a file", path.display()))); - } - if meta.len() > limits.max_module_bytes as u64 { - return Err(Error::Module(format!("{} is {} bytes (limit {})", path.display(), meta.len(), limits.max_module_bytes))); - } - let f = std::fs::File::open(path).map_err(|e| Error::Io(format!("{}: {e}", path.display())))?; - let mut bytes = Vec::new(); - f.take(limits.max_module_bytes as u64 + 1).read_to_end(&mut bytes).map_err(|e| Error::Io(format!("{}: {e}", path.display())))?; + let bytes = read_module(path, &limits, || {})?; Ok(Plugin::load(&bytes, limits)?.with_source(path.display().to_string())) } +/// The bytes of the module file at `path`. A path that doesn't name a regular file is refused +/// before it is opened, and so is one over the module limit. On Unix the file is opened without +/// waiting, so a named pipe put in its place after that check doesn't hold the load until something +/// writes to it; what was opened is checked again and refused the same way. `opening` runs between +/// the first check and the open. +#[cfg(not(target_arch = "wasm32"))] +fn read_module(path: &std::path::Path, limits: &Limits, opening: impl FnOnce()) -> Result> { + use std::io::Read; + let io = |e: std::io::Error| Error::Io(format!("{}: {e}", path.display())); + let regular = |meta: std::fs::Metadata| { + if !meta.is_file() { + return Err(Error::Io(format!("{} is not a file", path.display()))); + } + if meta.len() > limits.max_module_bytes as u64 { + return Err(Error::Module(format!("{} is {} bytes (limit {})", path.display(), meta.len(), limits.max_module_bytes))); + } + Ok(()) + }; + regular(std::fs::metadata(path).map_err(io)?)?; + opening(); + let f = open_module(path).map_err(io)?; + regular(f.metadata().map_err(io)?)?; + let mut bytes = Vec::new(); + f.take(limits.max_module_bytes as u64 + 1).read_to_end(&mut bytes).map_err(io)?; + Ok(bytes) +} + +/// Opens the module file at `path` for reading. On Unix the open doesn't wait for a writer when +/// the path names a named pipe, and doesn't make a terminal device the controlling terminal. +#[cfg(not(target_arch = "wasm32"))] +fn open_module(path: &std::path::Path) -> std::io::Result { + let mut open = std::fs::OpenOptions::new(); + open.read(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::custom_flags(&mut open, (rustix::fs::OFlags::NONBLOCK | rustix::fs::OFlags::NOCTTY).bits() as i32); + open.open(path) +} + +/// The most `.wasm` files one [`load_folder`] reads. +#[cfg(not(target_arch = "wasm32"))] +const MAX_FOLDER_FILES: usize = 1000; + +/// The first [`MAX_FOLDER_FILES`] `*.wasm` paths directly in `dir` by file name, sorted, and how +/// many more there are. Only that many paths are held while the folder is listed. An error while +/// the folder is listed is returned, as one opening it is. +#[cfg(not(target_arch = "wasm32"))] +fn folder_files(dir: &std::path::Path) -> Result<(Vec, usize)> { + let io = |e: std::io::Error| Error::Io(format!("{}: {e}", dir.display())); + let rd = std::fs::read_dir(dir).map_err(io)?; + let mut kept = std::collections::BinaryHeap::new(); + let mut more = 0; + for entry in rd { + let p = entry.map_err(io)?.path(); + if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) { + continue; + } + kept.push(p); + if kept.len() > MAX_FOLDER_FILES { + kept.pop(); + more += 1; + } + } + Ok((kept.into_sorted_vec(), more)) +} + /// What [`load_folder`] reports for a plug-in the user disabled. pub const DISABLED: &str = "disabled: turn it on again in Help › Safe Mode, for the next launch"; @@ -204,18 +259,22 @@ pub const DISABLED: &str = "disabled: turn it on again in Help › Safe Mode, fo pub struct FolderReport { /// Ids of the plug-ins installed. pub loaded: Vec, - /// `(file, error)` for each `.wasm` that failed to load. + /// `(file, error)` for each `.wasm` that failed to load, including one that isn't a regular file. pub failed: Vec<(String, String)>, + /// How many `.wasm` files were not tried because the folder holds more than a load reads. + pub left_out: usize, /// The disabled items saved for the next launch changed: a plug-in disabled by its id alone was /// found in a file, which is now disabled too ([`crate::safe_mode::disable_file_of`]). The app /// saves the list again. pub disabled_changed: bool, } -/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order. A bad module is -/// reported and skipped, the others still load; so is a heavy one ([`crate::Budget::Heavy`]), -/// which installs only once the user agrees, and one that lists permissions the user has not -/// granted this very module ([`approved`]). +/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first +/// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything +/// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it +/// ([`load_file`]). A bad module is reported and skipped, the others still load; so is a heavy one +/// ([`crate::Budget::Heavy`]), which installs only once the user agrees, and one that lists +/// permissions the user has not granted this very module ([`approved`]). #[cfg(not(target_arch = "wasm32"))] pub fn load_folder(dir: &std::path::Path) -> Result { load_folder_where(dir, |_| Ok(()), approved) @@ -237,12 +296,8 @@ pub fn load_folder_where( ) -> Result { use crate::safe_mode::{self, Item}; safe_mode::check()?; - let rd = std::fs::read_dir(dir).map_err(|e| Error::Io(format!("{}: {e}", dir.display())))?; - let mut files: Vec = - rd.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm"))).collect(); - files.sort(); - files.truncate(1000); - let mut report = FolderReport::default(); + let (files, left_out) = folder_files(dir)?; + let mut report = FolderReport { left_out, ..FolderReport::default() }; for f in files { if let Err(why) = allow(&f) { report.failed.push((f.display().to_string(), why)); @@ -453,4 +508,114 @@ mod tests { assert!(granted(id).is_none(), "a module without permissions forgets the grant"); assert!(remove(id)); } + + /// An empty folder for one test, with anything an earlier run left there removed. + #[cfg(not(target_arch = "wasm32"))] + fn test_dir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vc-registry-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// Makes a named pipe at `path`. + #[cfg(unix)] + fn make_pipe(path: &std::path::Path) { + assert!(std::process::Command::new("mkfifo").arg(path).status().unwrap().success(), "mkfifo {}", path.display()); + } + + /// Limits that let a test go past the module size with a few bytes. + #[cfg(not(target_arch = "wasm32"))] + fn small_limits() -> Limits { + Limits { max_module_bytes: 16, ..Limits::default() } + } + + /// A module file is opened so that a named pipe in its place doesn't make the open wait for a + /// writer. The test holds the pipe open for reading and writing itself, so the open returns + /// either way. + #[cfg(unix)] + #[test] + fn a_module_file_is_opened_without_waiting_for_a_writer() { + let dir = test_dir("open"); + let pipe = dir.join("x.wasm"); + make_pipe(&pipe); + let held = std::fs::OpenOptions::new().read(true).write(true).open(&pipe).unwrap(); + let opened = open_module(&pipe).unwrap(); + let flags = rustix::fs::fcntl_getfl(&opened).unwrap(); + drop((opened, held)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(flags.contains(rustix::fs::OFlags::NONBLOCK), "the open would wait for a writer: {flags:?}"); + } + + /// A `.wasm` that a named pipe replaces after it was checked is refused as not a file, even + /// when the pipe holds more bytes than the module limit allows. + #[cfg(unix)] + #[test] + fn a_file_replaced_by_a_pipe_is_refused() { + use std::io::Write; + let dir = test_dir("pipe"); + let path = dir.join("x.wasm"); + let pipe = dir.join("pipe"); + std::fs::write(&path, b"\0asm").unwrap(); + make_pipe(&pipe); + let mut held = std::fs::OpenOptions::new().read(true).write(true).open(&pipe).unwrap(); + held.write_all(&[0; 32]).unwrap(); + let read = read_module(&path, &small_limits(), || std::fs::rename(&pipe, &path).unwrap()); + drop(held); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&read, Err(Error::Io(e)) if e.ends_with("is not a file")), "{read:?}"); + } + + /// A `.wasm` that grows past the module limit after it was checked is refused by its size. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_file_that_grows_after_the_check_is_refused() { + let dir = test_dir("grow"); + let path = dir.join("x.wasm"); + std::fs::write(&path, b"\0asm").unwrap(); + let read = read_module(&path, &small_limits(), || std::fs::write(&path, [0; 32]).unwrap()); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&read, Err(Error::Module(e)) if e.contains("limit 16")), "{read:?}"); + } + + /// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm` + /// names as not files, and goes on. + #[cfg(unix)] + #[test] + fn a_folder_reports_entries_that_are_not_files() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("special"); + std::fs::create_dir(dir.join("a.wasm")).unwrap(); + make_pipe(&dir.join("b.wasm")); + std::os::unix::fs::symlink(dir.join("b.wasm"), dir.join("c.wasm")).unwrap(); + let r = load_folder_where(&dir, |_| Ok(()), |_| false); + std::fs::remove_dir_all(&dir).unwrap(); + let r = r.unwrap(); + let failed: Vec<(String, bool)> = r.failed.iter().map(|(f, e)| (f.clone(), e.ends_with("is not a file"))).collect(); + let expected: Vec<(String, bool)> = ["a", "b", "c"].iter().map(|n| (dir.join(format!("{n}.wasm")).display().to_string(), true)).collect(); + assert_eq!(failed, expected, "{r:?}"); + assert!(r.loaded.is_empty() && r.left_out == 0, "{r:?}"); + } + + /// A folder with more `.wasm` files than a load reads tries the first ones by file name and + /// counts the files it left out. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_over_the_file_limit_reports_the_files_left_out() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("limit"); + // Written last first, so the listing's order is not the file-name order. + for i in (0..MAX_FOLDER_FILES + 2).rev() { + std::fs::write(dir.join(format!("{i:05}.wasm")), b"").unwrap(); + } + let r = load_folder_where(&dir, |_| Ok(()), |_| false).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(r.loaded.is_empty(), "{r:?}"); + assert_eq!(r.left_out, 2, "{r:?}"); + let tried: Vec = r.failed.iter().map(|(f, _)| f.clone()).collect(); + let first: Vec = (0..MAX_FOLDER_FILES).map(|i| dir.join(format!("{i:05}.wasm")).display().to_string()).collect(); + assert_eq!(tried, first, "the first files by name, in that order"); + } } diff --git a/crates/text/src/fontdb/scan.rs b/crates/text/src/fontdb/scan.rs index e25891fb32..f410353573 100644 --- a/crates/text/src/fontdb/scan.rs +++ b/crates/text/src/fontdb/scan.rs @@ -3,6 +3,8 @@ use super::build::{style_italic, style_weight}; use super::dirs::sfnt_of; use super::face::{MAX_AXES, MAX_INSTANCES}; use super::names::{all_names, name, norm}; +#[cfg(not(target_arch = "wasm32"))] +use super::traits::may_set_thai; use super::traits::{FaceKeys, FaceStyle, FontTraits, face_styles}; use super::{FileRef, MetadataProvider, Path, StringId, Tag}; @@ -126,40 +128,51 @@ pub(super) fn font_files(path: &Path) -> Vec> { const OUTLINE_TABLES: [&[u8; 4]; 6] = [b"glyf", b"CFF ", b"CFF2", b"VARC", b"sbix", b"CBDT"]; /// The styles of every face in the font file at `path` ([`face_styles`]), reading only its table -/// directories and `name`, `fvar` and `OS/2` tables: a scan opens hundreds of font files, many of +/// directories and `name`, `fvar` and `OS/2` tables (and the `cmap` table of a face that may set +/// Thai, [`may_set_thai`]): a scan opens hundreds of font files, many of /// them megabytes long. Faces without outlines the font engine draws (no [`OUTLINE_TABLES`] table) /// are left out. #[cfg(not(target_arch = "wasm32"))] pub(super) fn file_face_names(path: &Path) -> Vec { - file_face_names_within(path, MAX_FACES, u64::MAX) + file_face_names_reading(path, MAX_FACES, u64::MAX, true) } -/// [`file_face_names`], reading at most `max_faces` faces and `max_read` bytes of the file in all. -/// A suitcase font's resource fork is read whole when it is at most `max_read` bytes long, and the -/// limits then apply to each of its fonts; a longer fork gives none. +/// [`file_face_names`], reading at most `max_faces` faces and `max_read` bytes of the file in all, +/// and no `cmap` table: a face's [`FontTraits::thai`] is false. A suitcase font's resource fork is +/// read whole when it is at most `max_read` bytes long, and the limits then apply to each of its +/// fonts; a longer fork gives none. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn file_face_names_within(path: &Path, max_faces: u32, max_read: u64) -> Vec { + file_face_names_reading(path, max_faces, max_read, false) +} + +/// [`file_face_names_within`], reading the `cmap` table of a face that may set Thai when +/// `read_cmap` is true. +#[cfg(not(target_arch = "wasm32"))] +fn file_face_names_reading(path: &Path, max_faces: u32, max_read: u64, read_cmap: bool) -> Vec { if crate::suitcase::is_suitcase(path) { if crate::suitcase::fork_len(path) > max_read { return vec![]; } return crate::suitcase::read_fonts(path) .into_iter() - .flat_map(|font| reader_face_names_within(std::io::Cursor::new(font), max_faces, max_read)) + .flat_map(|font| reader_face_names_within(std::io::Cursor::new(font), max_faces, max_read, read_cmap)) .collect(); } match std::fs::File::open(path) { - Ok(file) => reader_face_names_within(file, max_faces, max_read), + Ok(file) => reader_face_names_within(file, max_faces, max_read, read_cmap), Err(_) => vec![], } } -/// [`file_face_names_within`] for the font file `file` reads. +/// [`file_face_names_reading`] for the font file `file` reads. #[cfg(not(target_arch = "wasm32"))] -fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_faces: u32, max_read: u64) -> Vec { +fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_faces: u32, max_read: u64, read_cmap: bool) -> Vec { use std::io::SeekFrom; - /// The largest table read from a (possibly damaged) file. + /// The largest table read from a (possibly damaged) file, other than `cmap`. const MAX_NAME_TABLE: u32 = 1 << 20; + /// The largest `cmap` table read. + const MAX_CMAP_TABLE: u32 = 16 << 20; /// The `post` table's header: version, italic angle, underline and fixed-pitch fields. const POST_HEADER: u32 = 32; let mut read = 0u64; @@ -188,11 +201,12 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) { return None; } - // A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE` gives nothing. + // A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE` + // (`MAX_CMAP_TABLE` for `cmap`) gives nothing. let mut table_within = |tag: &[u8; 4], most: u32| -> Option> { let rec: &[u8] = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?; let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?.min(most)); - if len > MAX_NAME_TABLE { + if len > if tag == b"cmap" { MAX_CMAP_TABLE } else { MAX_NAME_TABLE } { return None; } read_at(offset.into(), len as usize) @@ -217,7 +231,13 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa tables.push((tag, data.as_slice())); } } - let font = sfnt_of(&tables)?; + let mut font = sfnt_of(&tables)?; + // Its character map too when it may set Thai, to tell whether it does. + let cmap = if read_cmap && may_set_thai(&skrifa::FontRef::new(&font).ok()?) { table_within(b"cmap", u32::MAX) } else { None }; + if let Some(cmap) = &cmap { + tables.push((b"cmap", cmap.as_slice())); + font = sfnt_of(&tables)?; + } Some(face_styles(&skrifa::FontRef::new(&font).ok()?)) }) .flatten() diff --git a/crates/text/src/fontdb/traits.rs b/crates/text/src/fontdb/traits.rs index deff6ce054..c25ce20c4f 100644 --- a/crates/text/src/fontdb/traits.rs +++ b/crates/text/src/fontdb/traits.rs @@ -95,7 +95,7 @@ impl FontClass { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct FontTraits { pub japanese: bool, - /// Its character map has Thai (ก and า). + /// Its OS/2 table allows Thai ([`may_set_thai`]) and its character map has Thai (ก and า). pub thai: bool, pub class: FontClass, /// The face has variation axes (an `fvar` table of at most 64 axes); for a family, one of @@ -216,8 +216,21 @@ impl FontLikeness { } } +/// Whether a face may set Thai by its OS/2 table: it has none, or the table's Unicode ranges have +/// Thai (bit 24) or its code pages have Thai (bit 16, code page 874). Only such a face has its +/// character map checked for Thai ([`FontTraits::thai`]); the system font scan reads a face's +/// `cmap` table only then ([`super::scan::file_face_names`]). +pub(super) fn may_set_thai(font: &skrifa::FontRef<'_>) -> bool { + use skrifa::raw::TableProvider; + match font.os2() { + Ok(o) => o.ul_unicode_range_1() & (1 << 24) != 0 || o.ul_code_page_range_1().unwrap_or(0) & (1 << 16) != 0, + Err(_) => true, + } +} + impl FontTraits { - /// From a face's OS/2 and `fvar` tables (when it has them) and names. + /// From a face's OS/2 and `fvar` tables (when it has them), names and, when it may set Thai + /// ([`may_set_thai`]), character map. fn of(font: &skrifa::FontRef<'_>, keys: &FaceKeys) -> Self { use skrifa::raw::TableProvider; let os2 = font.os2().ok(); @@ -230,7 +243,7 @@ impl FontTraits { }; // Hiragana (bit 49) or Katakana (bit 50) in the Unicode ranges, or the JIS code page. let japanese = ranges2 & (0b11 << 17) != 0 || codepages & (1 << 17) != 0 || has_japanese_name; - let thai = ['\u{0E01}', '\u{0E32}'].iter().all(|c| font.charmap().map(*c).is_some()); + let thai = may_set_thai(font) && ['\u{0E01}', '\u{0E32}'].iter().all(|c| font.charmap().map(*c).is_some()); let family_type = panose.first().copied().unwrap_or(0); let serif_style = panose.get(1).copied().unwrap_or(0); let proportion = panose.get(3).copied().unwrap_or(0); diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 29847f9fc8..dd16a004c4 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -705,6 +705,51 @@ fn repeat_font(family: &str, chars: &[(char, char)]) -> Option> { Some(builder.build()) } +/// The families [`thai_font`] can be named, two fonts that set Thai. +pub const THAI_FAMILY: &str = "Thaitest Sans"; +pub const THAI_OTHER_FAMILY: &str = "Thaiothertest Sans"; + +/// Bundled Source Sans 3 Regular as `family`, with a cmap that maps ก and า to the glyphs of A and +/// B beside the Latin letters and the space. With `claimed`, its OS/2 table has the Thai Unicode +/// range (bit 24) set; without, neither that range nor the Thai code page (bit 16). `None` when it +/// can't be built. +pub fn thai_font(family: &str, claimed: bool) -> Option> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let glyph = |c| Some(write_fonts::types::GlyphId::new(charmap.map(c)?.to_u32())); + let mut mappings: Vec<(char, write_fonts::types::GlyphId)> = vec![('\u{0E01}', glyph('A')?), ('\u{0E32}', glyph('B')?)]; + for c in ('A'..='Z').chain('a'..='z').chain([' ']) { + mappings.push((c, glyph(c)?)); + } + let cmap = Cmap::from_mappings(mappings).ok()?; + let full = format!("{family} Regular"); + let postscript = format!("{}-Regular", family.replace(' ', "")); + let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &postscript)])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag == Tag::new(b"GSUB") || builder.contains(tag) { + continue; + } + let mut data = font.table_data(r.tag())?.as_bytes().to_vec(); + if tag == Tag::new(b"OS/2") { + // ulUnicodeRange1 at bytes 42 to 46, ulCodePageRange1 at bytes 78 to 82. + let ranges = u32::from_be_bytes(data.get(42..46)?.try_into().ok()?); + let ranges = if claimed { ranges | 1 << 24 } else { ranges & !(1 << 24) }; + data.get_mut(42..46)?.copy_from_slice(&ranges.to_be_bytes()); + let pages = u32::from_be_bytes(data.get(78..82)?.try_into().ok()?) & !(1 << 16); + data.get_mut(78..82)?.copy_from_slice(&pages.to_be_bytes()); + } + builder.add_raw(tag, data); + } + Some(builder.build()) +} + /// The family of [`half_form_font`]. pub const HALF_FORM_FAMILY: &str = "Halftest Sans"; diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 06c4db899c..08f6584186 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -590,6 +590,39 @@ fn the_scan_reads_a_familys_likeness_without_loading_it() { let _ = std::fs::remove_dir_all(&dir); } +/// Font menus' Thai filter and Show Similar Fonts: the scan tells whether a family sets Thai as +/// loading it does. A face whose OS/2 table names neither the Thai range nor the Thai code page does +/// not set Thai, loaded or scanned, whatever its character map holds. +#[test] +fn the_scan_tells_whether_a_family_sets_thai_without_loading_it() { + use crate::test_fonts::{THAI_FAMILY, THAI_OTHER_FAMILY, thai_font}; + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-thai", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for claimed in [true, false] { + std::fs::write(dir.join("Thaitest-Regular.ttf"), thai_font(THAI_FAMILY, claimed).unwrap()).unwrap(); + let scanned = FontDb::with_font_dirs(vec![dir.clone()]); + let thai = scanned.family_traits(THAI_FAMILY).thai; + assert!(!scanned.is_loaded(THAI_FAMILY), "the scan's traits, nothing loaded"); + let loaded = FontDb::with_font_dirs(vec![]); + assert_eq!(loaded.add_font(thai_font(THAI_FAMILY, claimed).unwrap()), 1); + assert_eq!(thai, loaded.family_traits(THAI_FAMILY).thai, "claimed: {claimed}"); + assert_eq!(thai, claimed); + } + // A loaded Thai family lists a scanned Thai family before a Latin family that looks the same, + // and the order stays when the scanned family is loaded. + std::fs::write(dir.join("Thaitest-Regular.ttf"), thai_font(THAI_FAMILY, true).unwrap()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + assert_eq!(db.add_font(thai_font(THAI_OTHER_FAMILY, true).unwrap()), 1); + let families: Vec = ["Source Sans 3", THAI_FAMILY, THAI_OTHER_FAMILY].map(String::from).to_vec(); + let expected: Vec = [THAI_OTHER_FAMILY, THAI_FAMILY, "Source Sans 3"].map(String::from).to_vec(); + assert_eq!(db.similar_families(THAI_OTHER_FAMILY, &families), expected); + assert!(!db.is_loaded(THAI_FAMILY)); + assert_eq!(db.add_font(thai_font(THAI_FAMILY, true).unwrap()), 1); + assert_eq!(db.similar_families(THAI_OTHER_FAMILY, &families), expected); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn registered_fonts_outside_the_font_folders_are_their_full_paths() { let dir = std::env::temp_dir().join("Fonts"); diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index ed275a0361..96b6a36291 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -24,5 +24,5 @@ serde_json = { workspace = true } craft-image-codecs = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). vectorcraft-text = { workspace = true, features = ["test-fonts", "bundled-fonts"] } -# How many times a path is flattened. -vectorcraft-doc = { workspace = true, features = ["spine-count"] } +# How many times a path is flattened, and how often art is measured for the locked artboards. +vectorcraft-doc = { workspace = true, features = ["spine-count", "locked-artboard-count"] } diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index 1ab964988e..b40cffd8e7 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -170,7 +170,8 @@ fn round_step(least: f64) -> f64 { /// Draw circle `c`: through three points spread around it, with `shape.circleThroughPoints`, which /// leaves it where it is with Align New Objects to Pixel Grid on, so that it stays tangent. None /// when the three points do not give the circle back to within `tol` (a circle too small for its -/// distance from the origin, or too large, in floating point). +/// distance from the origin, or too large, in floating point), or when the circle would reach past +/// the canvas ([`crate::circle::circle_of`]), which the command refuses. fn draw(c: &SegmentCircle, tol: f64) -> Option { let (at, r) = (c.circle.center, c.circle.radius); let points: Vec = [90.0f64, 210.0, 330.0] @@ -180,7 +181,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option { Point::new(at.x + r * k, at.y + r * s) }) .collect(); - let (back, rb) = vectorcraft_geom::shapes::circle_through(points[0], points[1], points[2])?; + let (back, rb) = crate::circle::circle_of(&points)?; if !(back.distance(at) <= tol && (rb - r).abs() <= tol) { return None; } @@ -462,7 +463,7 @@ impl Tool for TangentCircleTool { mod tests { use super::*; use crate::testutil::*; - use vectorcraft_doc::{Appearance, Document, Node, Selection}; + use vectorcraft_doc::{Appearance, Document, MAX_COORD, Node, Selection}; use vectorcraft_geom::{PathData, SubPath}; /// Two open lines, (100, 100)–(300, 100) and (100, 140)–(300, 140), and an L from (100, 300) @@ -810,4 +811,40 @@ mod tests { .collect(); assert!(matches!(segments[..], [n] if n < 100), "{segments:?}"); } + + #[test] + fn a_circle_that_would_reach_past_the_canvas_is_not_offered() { + // Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives + // the circle of radius 20 around (x, 120), whose right side is at x + 20. + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + for y in [100.0, 140.0] { + let id = d.alloc_id(); + let pts = [Point::new(MAX_COORD - 100.0, y), Point::new(MAX_COORD, y)]; + d.insert(Some(l), 0, Node::path(id, PathData::single(SubPath::polyline(&pts, false)), Appearance::default_art())).unwrap(); + } + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + // Past the edge by 5 pt: the note shows, and a click draws nothing. + let x = MAX_COORD - 15.0; + t.pointer(&cx, &ev(PointerKind::Down, x, 100.0)); + t.pointer(&cx, &ev(PointerKind::Up, x, 100.0)); + t.pointer(&cx, &ev(PointerKind::Move, x, 140.0)); + assert!(t.found.is_none() && t.looked, "{:?}", t.found); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == NO_CIRCLE))); + t.pointer(&cx, &ev(PointerKind::Down, x, 140.0)); + assert!(t.pointer(&cx, &ev(PointerKind::Up, x, 140.0)).is_empty(), "nothing drawn"); + assert!(t.first.is_some(), "the first segment stays for another try"); + // Its right side 1 pt inside the edge: drawn. + let x = MAX_COORD - 21.0; + t.key(&cx, ToolKey::Escape, Mods::default()); + t.pointer(&cx, &ev(PointerKind::Down, x, 100.0)); + t.pointer(&cx, &ev(PointerKind::Up, x, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, x, 140.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, x, 140.0)); + let (bx, by, w, h) = drawn(&released); + assert!((bx - (x - 20.0)).abs() < 1e-3 && (by - 100.0).abs() < 1e-3 && (w - 40.0).abs() < 1e-3 && (h - 40.0).abs() < 1e-3, "{released:?}"); + assert!(bx + w <= MAX_COORD, "{released:?}"); + } } diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index ab234cf507..7823c5c602 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -55,9 +55,9 @@ struct PathWidgets { impl PathWidgets { /// The widgets of path `id` at `zoom` (screen px per document point), if it has any: any path - /// with Direct Selection (`any_path`), live rectangles and polygons with Selection. `id` is - /// editable ([`Document::is_editable`]). - fn of(doc: &Document, selection: &Selection, id: NodeId, zoom: f64, any_path: bool) -> Option { + /// with Direct Selection (`any_path`), live rectangles and polygons with Selection, when + /// `editable` ([`Document::editable`]) answers true for `id`. + fn of(doc: &Document, selection: &Selection, id: NodeId, zoom: f64, any_path: bool, editable: &impl Fn(NodeId) -> bool) -> Option { if selection.segments.contains_key(&id) { return None; } @@ -65,6 +65,10 @@ impl PathWidgets { if !any_path && !matches!(live.as_deref(), Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. })) { return None; } + // After the kind: on a locked artboard it measures the art of the layer object holding `id`. + if !editable(id) { + return None; + } let lc = LiveCorners::new(path, live.as_deref())?; let det = lc.xf.determinant().abs(); if det < 1e-12 { @@ -105,9 +109,10 @@ impl CornerWidgets { /// The widgets at `zoom` (screen px per document point), if the selection has them: on any /// path with Direct Selection (`any_path`), on live rectangles and polygons with Selection. pub fn of(doc: &Document, selection: &Selection, zoom: f64, any_path: bool) -> Option { - let editable = doc.editable(); - let paths: Vec<_> = - selection.objects.iter().filter(|id| editable(**id)).filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path)).collect(); + // Made for the first path, then shared: the art on the locked artboards is measured once. + let locks = std::cell::OnceCell::new(); + let editable = |id| locks.get_or_init(|| doc.editable())(id); + let paths: Vec<_> = selection.objects.iter().filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path, &editable)).collect(); (!paths.is_empty()).then_some(Self { paths }) } diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 9fc34597f3..dffe13a378 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -245,10 +245,18 @@ struct PreviewBoxes { revision: Option<(u64, u64)>, geometric: HashMap>, preview: HashMap>, + /// The editable path holding each corner of a measured object's preview bounds, found when + /// the object is measured, so that a pointer move reads no member. + holders: HashMap; 4]>, /// Whether a point at each corner (by object and corner number) can be held against its path. holdable: HashMap<(NodeId, usize), bool>, } +/// How many member paths one pointer move may read to measure objects not yet measured, apart +/// from the objects it visits: an object with more members than are left gives no corner on +/// that move. +const PREVIEW_MEMBER_WORK: usize = 20_000; + /// A corner of an object's preview bounds that a Linear pick can land on. #[derive(Clone, Copy, Debug)] struct PreviewCorner { @@ -264,7 +272,9 @@ struct PreviewCorner { /// strokes and effects included) nearest `p` within reach, on any editable one whose preview /// bounds differ from its geometric bounds. In a compound path, the member whose own box reaches /// nearest to the corner holds it. The work is bounded, and dimension artwork is skipped, as in -/// [`pick`]. `cache` keeps the bounds measured for the document's revision. +/// [`pick`]: the objects visited count against one budget, and the member paths read to measure +/// them against [`PREVIEW_MEMBER_WORK`]. `cache` keeps the bounds and holders measured for the +/// document's revision. fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Option { struct Walk<'a, 'c> { symbols: Option>, @@ -273,8 +283,38 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio p: Point, reach: f64, budget: usize, + /// Member paths left to read for objects not yet measured. + work: usize, best: Option<(f64, PreviewCorner)>, } + /// Takes `count` from the member work left, or nothing when less is left. + fn charge(work: &mut usize, count: usize) -> bool { + let fits = count <= *work; + if fits { + *work -= count; + } + fits + } + fn corners(r: Rect) -> [Point; 4] { + [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] + } + /// For each corner of `preview`, the path whose own box reaches nearest to it: in a compound + /// path, the member that puts that corner where it is. A hidden or locked member, or one made + /// into a guide, gives no corner. One pass reads each member once for all four corners. + fn holders<'n>(members: impl Iterator, preview: Rect) -> [Option; 4] { + let mut best: [Option<(f64, NodeId, bool)>; 4] = [None; 4]; + for m in members { + let Some(b) = m.geometric_bounds() else { continue }; + let editable = m.visible && !m.locked && !m.is_guide(); + for ((holder, c), q) in best.iter_mut().zip(corners(b)).zip(corners(preview)) { + let gap = c.distance(q); + if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) { + *holder = Some((gap, m.id, editable)); + } + } + } + best.map(|h| h.filter(|(.., editable)| *editable).map(|(_, id, _)| id)) + } fn visit(n: &Node, w: &mut Walk) { if w.budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() { return; @@ -284,7 +324,6 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio // its strokes reach. let effects = !n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty()); let reach = n.appearance.outset() + w.reach; - let corners = |r: Rect| [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; // A path is its own member; a compound path's members are its paths. let compound = match &n.kind { NodeKind::Compound { children, .. } => Some(children.as_slice()), @@ -292,25 +331,45 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio }; let members = || compound.into_iter().flatten().map(|c| c.as_ref()).chain(compound.is_none().then_some(n)).filter(|m| m.path_data().is_some()); + // Measuring the object, its bounds or its holders, reads every member once. + let count = compound.map_or(1, <[_]>::len); // A path made into a guide draws as a guide, without its strokes or effects. The pointer // test includes the right and bottom edges, as the distance test below does. let within = |r: Rect| (r.x0..=r.x1).contains(&w.p.x) && (r.y0..=r.y1).contains(&w.p.y); - if !n.is_guide() - && members().next().is_some() - && let Some(geometric) = *w.cache.geometric.entry(n.id).or_insert_with(|| n.geometric_bounds()) + // Set once this move has paid for reading the members: measuring the preview bounds and + // holders on the same move reads them again without a second charge. + let mut paid = false; + let geometric = match w.cache.geometric.get(&n.id) { + _ if n.is_guide() || members().next().is_none() => None, + Some(g) => *g, + None if charge(&mut w.work, count) => { + paid = true; + let g = n.geometric_bounds(); + w.cache.geometric.insert(n.id, g); + g + } + None => None, + }; + if let Some(geometric) = geometric && (effects || within(geometric.inflate(reach, reach))) { let doc = w.doc; let measured = match w.cache.preview.get(&n.id) { - Some(r) => *r, - None => { + Some(r) => Some(*r), + None if paid || charge(&mut w.work, count) => { let symbols = w.symbols.get_or_insert_with(|| doc.symbol_boxes()); let r = vectorcraft_effects::preview::visual_bounds(symbols, n); w.cache.preview.insert(n.id, r); - r + if let Some(r) = r + && r != geometric + { + w.cache.holders.insert(n.id, holders(members(), r)); + } + Some(r) } + None => None, }; - if let Some(r) = measured + if let Some(Some(r)) = measured && r != geometric { for (k, q) in corners(r).into_iter().enumerate() { @@ -318,26 +377,13 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio if d > w.reach || w.best.is_some_and(|(nearest, ..)| d >= nearest) { continue; } - // The path whose own box reaches furthest towards the corner holds it: in a - // compound path, the member that puts that corner where it is. A hidden or - // locked member, or one made into a guide, gives no corner. - let mut holder: Option<(f64, NodeId, bool)> = None; - for m in members() { - let Some(b) = *w.cache.geometric.entry(m.id).or_insert_with(|| m.geometric_bounds()) else { continue }; - let gap = corners(b).get(k).map_or(f64::INFINITY, |c| c.distance(q)); - let editable = m.visible && !m.locked && !m.is_guide(); - if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) { - holder = Some((gap, m.id, editable)); - } - } - let holder = holder.filter(|(.., editable)| *editable).map(|(gap, id, _)| (gap, id)); + let holder = w.cache.holders.get(&n.id).and_then(|h| h.get(k).copied().flatten()); // A path that cannot hold a point at the corner (a stroked dot, whose anchors // all coincide) gives no corner. let holdable = |id: NodeId, cache: &mut PreviewBoxes| { *cache.holdable.entry((n.id, k)).or_insert_with(|| FreePoint::on(doc, id, q).is_some()) }; - let holder = holder.filter(|(_, id)| holdable(*id, w.cache)); - if let Some(((_, holder), stands_for)) = holder.zip(corners(geometric).get(k).copied()) { + if let Some((holder, stands_for)) = holder.filter(|id| holdable(*id, w.cache)).zip(corners(geometric).get(k).copied()) { w.best = Some((d, PreviewCorner { at: q, holder, stands_for })); } } @@ -360,7 +406,7 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio if cache.revision != Some(cx.revision) { *cache = PreviewBoxes { revision: Some(cx.revision), ..Default::default() }; } - let mut w = Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, best: None }; + let mut w = Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, work: PREVIEW_MEMBER_WORK, best: None }; for n in cx.doc.layers.iter().rev() { visit(n, &mut w); } @@ -1671,6 +1717,60 @@ mod tests { assert!(t.points.first().is_some_and(|(q, _)| near(*q, Point::new(80.0, 80.0))), "{:?}", t.points); } + /// A stroked compound path of a small hole and `extra` more tiny squares inside a square from + /// 100 to 200, with the ids of the compound, the hole and the square. + fn stroked_compound(extra: usize) -> (vectorcraft_doc::Document, [NodeId; 3]) { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, hole, part, whole) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id()); + let square = + |id, a: f64, b: f64| std::sync::Arc::new(Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(a, a, b, b)), Default::default())); + let mut children = vec![square(hole, 140.0, 160.0), square(part, 100.0, 200.0)]; + for _ in 0..extra { + children.push(square(d.alloc_id(), 150.0, 151.0)); + } + let mut n = Node::new(whole, NodeKind::Compound { children, rule: Default::default() }); + n.appearance = vectorcraft_doc::Appearance::default_art().into(); + d.insert(Some(l), 0, n).expect("the compound path"); + (d, [whole, hole, part]) + } + + /// The member holding each corner of a compound path is found when the compound is measured, + /// and later pointer moves over the same revision take it from the cache without reading the + /// members. + #[test] + fn a_compound_paths_corner_holders_are_found_once_per_revision() { + let (d, [whole, hole, part]) = stroked_compound(0); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut cache = PreviewBoxes::default(); + let corner = preview_corner(&c, Point::new(99.5, 99.5), &mut cache).expect("the corner of the stroke"); + assert_eq!(corner.holder, part, "the member that reaches the corner holds it"); + assert_eq!(cache.holders.get(&whole), Some(&[Some(part); 4])); + // A move over the same revision reads the holder from the cache: one changed there is the + // one it gives. + cache.holders.insert(whole, [Some(hole); 4]); + let corner = preview_corner(&c, Point::new(200.5, 200.5), &mut cache).expect("the corner of the stroke"); + assert_eq!(corner.holder, hole, "the cached holder is used"); + } + + /// A compound path with more members than one pointer move may read gives no corner, and is + /// neither measured nor cached, so its member work stays bounded. A compound within the limit + /// still gives its corner. + #[test] + fn a_compound_path_past_the_member_work_gives_no_corner() { + let (s, p) = (Selection::default(), paint()); + // Two members plus `extra`: exactly the limit, then one more. + for (extra, within) in [(PREVIEW_MEMBER_WORK - 2, true), (PREVIEW_MEMBER_WORK - 1, false)] { + let (d, [whole, ..]) = stroked_compound(extra); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut cache = PreviewBoxes::default(); + let corner = preview_corner(&c, Point::new(99.5, 99.5), &mut cache); + assert_eq!(corner.is_some(), within, "{} members", extra + 2); + assert_eq!(cache.preview.contains_key(&whole), within, "{} members", extra + 2); + assert_eq!(cache.geometric.contains_key(&whole), within, "{} members", extra + 2); + } + } + /// With Use Preview Bounds on, hovering by a corner of a stroked path's preview bounds, or /// right on it, shows the anchor ring there. #[test] diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 47ab6bd06c..29bfecd4e9 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -738,6 +738,9 @@ pub(crate) mod testutil { } } +#[cfg(test)] +mod widget_order_tests; + #[cfg(test)] mod cursor_tests { use super::testutil::{cx, doc_with_rect, paint}; diff --git a/crates/tools/src/mirror.rs b/crates/tools/src/mirror.rs index feba99f51d..ad9a3ed11a 100644 --- a/crates/tools/src/mirror.rs +++ b/crates/tools/src/mirror.rs @@ -20,13 +20,14 @@ impl MirrorAxis { /// A single editable mirror repeat selected whole. Multi-selection keeps ordinary transforms. pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { let [id] = selection.objects.as_slice() else { return None }; - if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 { + if !selection.anchors.is_empty() || !selection.segments.is_empty() || !zoom.is_finite() || zoom <= 0.0 { return None; } let n = doc.node(*id)?; let NodeKind::Repeat(spec) = &n.kind else { return None }; let RepeatKind::Mirror { angle, center } = spec.kind else { return None }; - if !angle.is_finite() || !finite(center) { + // After the kind: on a locked artboard it measures the art of the layer object holding `id`. + if !angle.is_finite() || !finite(center) || !doc.is_editable(*id) { return None; } let bounds = n.geometric_bounds_with(&doc.symbol_boxes())?; diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index 906600f334..5bf60e36b4 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -104,12 +104,14 @@ fn one_group<'a>(doc: &'a Document, selection: &Selection, zoom: f64) -> Option< return None; } let [group] = selection.objects.as_slice() else { return None }; - if !doc.editable()(*group) { - return None; - } let n = doc.node(*group)?; let rec = n.extras().objects_on_path.as_deref()?; let children = n.children()?; + // After the group is known: on a locked artboard it measures the art of the layer object that + // holds `group`. + if !doc.editable()(*group) { + return None; + } let (path, measured) = attachable(children.iter().find(|c| c.id == rec.path)?)?; Some(Group { id: *group, rec, children: children.as_slice(), path, measured: Arc::new(measured) }) } diff --git a/crates/tools/src/pie.rs b/crates/tools/src/pie.rs index cf1b22bc57..f524fe4920 100644 --- a/crates/tools/src/pie.rs +++ b/crates/tools/src/pie.rs @@ -98,11 +98,15 @@ impl PieWidget { if !selection.anchors.is_empty() || !zoom.is_finite() || zoom <= 0.0 { return vec![]; } - let editable = doc.editable(); - let shown = |id: &&NodeId| editable(**id) && !selection.segments.contains_key(*id); + // Made for the first ellipse, then shared: on a locked artboard it measures the art of the + // layer object that holds each ellipse. + let editable = std::cell::OnceCell::new(); let mut out = vec![]; - for id in selection.objects.iter().filter(shown) { + for id in selection.objects.iter().filter(|id| !selection.segments.contains_key(*id)) { let Some((e, (start, end))) = Ellipse::of(doc, *id) else { continue }; + if !editable.get_or_init(|| doc.editable())(*id) { + continue; + } let c = e.center(); for (which, deg) in [(PieEnd::End, end), (PieEnd::Start, start)] { let on = e.point_at(deg); diff --git a/crates/tools/src/repeat_grid.rs b/crates/tools/src/repeat_grid.rs index 3513e362d1..ce932658d6 100644 --- a/crates/tools/src/repeat_grid.rs +++ b/crates/tools/src/repeat_grid.rs @@ -90,13 +90,14 @@ impl GridHandles { /// bounding box the Selection tool shows; its geometric bounds without one) at `zoom`. pub fn of(doc: &Document, selection: &Selection, frame: Option, zoom: f64) -> Option { let [id] = selection.objects.as_slice() else { return None }; - if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 { + if !selection.anchors.is_empty() || !selection.segments.is_empty() || !zoom.is_finite() || zoom <= 0.0 { return None; } let n = doc.node(*id)?; let NodeKind::Repeat(spec) = &n.kind else { return None }; let RepeatKind::Grid { h_spacing, v_spacing, rows, cols, grid_type, .. } = spec.kind else { return None }; - if !h_spacing.is_finite() || !v_spacing.is_finite() { + // After the kind: on a locked artboard it measures the art of the layer object holding `id`. + if !h_spacing.is_finite() || !v_spacing.is_finite() || !doc.is_editable(*id) { return None; } let source = spec.source_bounds()?; diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs index 986d98bb49..a9c8ebbfc2 100644 --- a/crates/tools/src/repeat_radial.rs +++ b/crates/tools/src/repeat_radial.rs @@ -124,13 +124,14 @@ impl RadialHandles { /// at `zoom`. pub fn of(doc: &Document, selection: &Selection, frame: Option, zoom: f64) -> Option { let [id] = selection.objects.as_slice() else { return None }; - if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 { + if !selection.anchors.is_empty() || !selection.segments.is_empty() || !zoom.is_finite() || zoom <= 0.0 { return None; } let n = doc.node(*id)?; let NodeKind::Repeat(spec) = &n.kind else { return None }; let RepeatKind::Radial { instances, radius, center, start_angle, end_angle, .. } = spec.kind else { return None }; - if ![radius, center.x, center.y, start_angle, end_angle].iter().all(|v| v.is_finite()) { + // After the kind: on a locked artboard it measures the art of the layer object holding `id`. + if ![radius, center.x, center.y, start_angle, end_angle].iter().all(|v| v.is_finite()) || !doc.is_editable(*id) { return None; } let source = spec.source_bounds()?; diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index a562024839..eee6600591 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -608,8 +608,13 @@ pub(crate) fn shown_box(cx: &ToolContext) -> Option { /// Direct Selection's does (#4891). pub(crate) fn hit_center(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Point)> { let (symbols, editable) = (cx.doc.symbol_boxes(), cx.doc.editable()); - cx.selection.objects.iter().copied().filter(|id| editable(*id) && crate::direct::in_scope(cx.doc, cx.isolation, *id)).find_map(|id| { - let c = cx.doc.node(id).filter(|n| n.shows_center())?.geometric_bounds_with(&symbols)?.center(); + cx.selection.objects.iter().copied().find_map(|id| { + let n = cx.doc.node(id).filter(|n| n.shows_center())?; + // After the center: on a locked artboard it measures the art of the layer object holding `id`. + if !crate::direct::in_scope(cx.doc, cx.isolation, id) || !editable(id) { + return None; + } + let c = n.geometric_bounds_with(&symbols)?.center(); (c.distance(p) <= tol).then_some((id, c)) }) } diff --git a/crates/tools/src/sidewidget.rs b/crates/tools/src/sidewidget.rs index f026a41c35..361430dcf5 100644 --- a/crates/tools/src/sidewidget.rs +++ b/crates/tools/src/sidewidget.rs @@ -44,11 +44,15 @@ impl SideWidget { /// segments of it selected. pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option { let [id] = selection.objects[..] else { return None }; - if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !doc.is_editable(id) || !zoom.is_finite() || zoom <= 0.0 { + if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !zoom.is_finite() || zoom <= 0.0 { return None; } let NodeKind::Path { live, .. } = &doc.node(id)?.kind else { return None }; let Some(LiveShape::Polygon { sides, .. }) = live.as_deref() else { return None }; + // After the kind: on a locked artboard it measures the art of the layer object holding `id`. + if !doc.is_editable(id) { + return None; + } let r = bx.rect; let at = bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y); (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides: *sides }) diff --git a/crates/tools/src/trace_split.rs b/crates/tools/src/trace_split.rs index f5949be2a4..0fecb6453e 100644 --- a/crates/tools/src/trace_split.rs +++ b/crates/tools/src/trace_split.rs @@ -32,7 +32,7 @@ impl TraceDivider { /// The divider of the one Image Trace object selected whole, when it shows the Split view. pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { let [id] = selection.objects.as_slice() else { return None }; - if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 { + if !selection.anchors.is_empty() || !selection.segments.is_empty() || !zoom.is_finite() || zoom <= 0.0 { return None; } let n = doc.node(*id)?; @@ -41,6 +41,10 @@ impl TraceDivider { } let NodeKind::Group { children, clip: false } = &n.kind else { return None }; let NodeKind::Image(im) = &children.first()?.kind else { return None }; + // After the kind: on a locked artboard it measures the art of the layer object holding `id`. + if !doc.is_editable(*id) { + return None; + } let (width, height) = (f64::from(im.width), f64::from(im.height)); let det = im.xf.determinant(); if width <= 0.0 || height <= 0.0 || !det.is_finite() || det.abs() < 1e-12 || !im.xf.as_coeffs().iter().all(|c| c.is_finite()) { diff --git a/crates/tools/src/typewidget.rs b/crates/tools/src/typewidget.rs index 13753fb034..0f0ea86ee6 100644 --- a/crates/tools/src/typewidget.rs +++ b/crates/tools/src/typewidget.rs @@ -34,7 +34,7 @@ impl TypeWidget { /// path, nor type in perspective, which transforms whole). pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option { let [id] = selection.objects[..] else { return None }; - if !doc.is_editable(id) || !zoom.is_finite() || zoom <= 0.0 { + if !zoom.is_finite() || zoom <= 0.0 { return None; } let n = doc.node(id).filter(|n| n.extras().perspective.is_none())?; @@ -44,6 +44,10 @@ impl TypeWidget { TextKind::Area { .. } => true, _ => return None, }; + // Last: on a locked artboard it measures the art of the layer object that holds `id`. + if !doc.is_editable(id) { + return None; + } let r = bx.rect; Some(Self { id, at: bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y), area }) } diff --git a/crates/tools/src/widget_order_tests.rs b/crates/tools/src/widget_order_tests.rs new file mode 100644 index 0000000000..545a74e211 --- /dev/null +++ b/crates/tools/src/widget_order_tests.rs @@ -0,0 +1,359 @@ +//! The Selection tool's on-canvas widgets ask whether an object is editable only once its kind +//! can have the widget: on a locked artboard the question measures the art of the layer object +//! that holds the object. + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::objects_on_path::{CENTER, ObjectsOnPath, place}; +use vectorcraft_doc::pattern::RepeatSpec; +use vectorcraft_doc::{ + Appearance, Document, ImageObject, LiveShape, Node, NodeId, NodeKind, OrientedBox, Selection, TextKind, TextObject, locked_artboard_measures, +}; +use vectorcraft_geom::{Affine, Point, Rect, shapes}; + +use crate::corners::CornerWidgets; +use crate::mirror::MirrorAxis; +use crate::objects_on_path::Widgets; +use crate::pie::PieWidget; +use crate::repeat_grid::GridHandles; +use crate::repeat_radial::RadialHandles; +use crate::select::hit_center; +use crate::sidewidget::SideWidget; +use crate::testutil::{cx, paint}; +use crate::trace_split::TraceDivider; +use crate::typewidget::TypeWidget; + +/// The page's left edge of the locked artboard: art placed this far right is on it. +const LOCKED_X: f64 = 2000.0; + +/// A widget constructor: its name, whether it needs exactly one selected object, the name of an +/// object (in [`mixed`]) that has the widget, and what it gives for a selection and a pointer (as +/// text). +type Site = (&'static str, bool, &'static str, fn(&Document, &Selection, Point) -> String); + +/// The center of the first object of `ids`: where the center widget is looked for. +fn pointer(doc: &Document, ids: &[NodeId]) -> Point { + ids.first().and_then(|id| doc.node(*id)?.geometric_bounds_with(&doc.symbol_boxes())).map_or(Point::ZERO, |b| b.center()) +} + +fn center_at(doc: &Document, sel: &Selection, p: Point) -> String { + let paint = paint(); + format!("{:?}", hit_center(&cx(doc, sel, &paint), p, 1.0)) +} + +const SITES: [Site; 11] = [ + ("type", true, "point type", |d, s, _| format!("{:?}", TypeWidget::of(d, s, &OrientedBox::aligned(Rect::new(0.0, 0.0, 10.0, 10.0)), 1.0))), + ("pie", false, "ellipse", |d, s, _| format!("{:?}", PieWidget::of(d, s, 1.0))), + ("objects on path", true, "objects on path", |d, s, _| format!("{:?}", Widgets::of(d, s, 1.0))), + ("mirror", true, "mirror", |d, s, _| format!("{:?}", MirrorAxis::of(d, s, 1.0))), + ("grid", true, "grid", |d, s, _| format!("{:?}", GridHandles::of(d, s, None, 1.0))), + ("radial", true, "radial", |d, s, _| format!("{:?}", RadialHandles::of(d, s, None, 1.0))), + ("sides", true, "polygon", |d, s, _| format!("{:?}", SideWidget::of(d, s, &OrientedBox::aligned(Rect::new(0.0, 0.0, 10.0, 10.0)), 1.0))), + ("trace split", true, "trace", |d, s, _| format!("{:?}", TraceDivider::of(d, s, 1.0))), + ("corners", false, "live rectangle", |d, s, _| format!("{:?}", CornerWidgets::of(d, s, 1.0, false))), + ("corners of any path", false, "rectangle", |d, s, _| format!("{:?}", CornerWidgets::of(d, s, 1.0, true))), + ("center", false, "ellipse", center_at), +]; + +fn with_live(id: NodeId, shape: LiveShape) -> Node { + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + n +} + +fn rect(d: &mut Document, r: Rect) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()) +} + +fn repeat(d: &mut Document, dx: f64, spec: fn(Vec>) -> RepeatSpec) -> Node { + let source = rect(d, Rect::new(dx + 500.0, 500.0, dx + 540.0, 540.0)); + let mut n = rect(d, Rect::new(dx + 500.0, 500.0, dx + 540.0, 540.0)); + n.kind = NodeKind::Repeat(spec(vec![Arc::new(source)])); + n +} + +/// The objects every widget is asked about, by name, placed `dx` right of the page's origin. `big` +/// is a group of that many rectangles. +fn objects(d: &mut Document, dx: f64, big: usize) -> Vec<(&'static str, Node)> { + let mut out = vec![("rectangle", rect(d, Rect::new(dx + 50.0, 50.0, dx + 150.0, 150.0)))]; + let mut centered = rect(d, Rect::new(dx + 50.0, 200.0, dx + 150.0, 260.0)); + centered.edit_attrs(|a| a.show_center = Some(true)); + out.push(("rectangle with its center shown", centered)); + let ellipse = |d: &mut Document, y: f64| { + with_live(d.alloc_id(), LiveShape::Ellipse { w: 120.0, h: 60.0, pie: (0.0, 90.0), xf: Affine::translate((dx + 200.0, y)) }) + }; + out.push(("ellipse", ellipse(d, 50.0))); + let mut hidden_center = ellipse(d, 150.0); + hidden_center.edit_attrs(|a| a.show_center = Some(false)); + out.push(("ellipse with its center hidden", hidden_center)); + let polygon = LiveShape::Polygon { + radius: 50.0, + sides: 6, + xf: Affine::translate((dx + 400.0, 100.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }; + out.push(("polygon", with_live(d.alloc_id(), polygon))); + let live_rect = LiveShape::Rectangle { + w: 100.0, + h: 80.0, + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate((dx + 50.0, 300.0)), + }; + out.push(("live rectangle", with_live(d.alloc_id(), live_rect))); + let point = TextObject::point(Point::new(dx + 300.0, 300.0), "Point", Default::default()); + out.push(("point type", Node::new(d.alloc_id(), NodeKind::Text(Box::new(point))))); + let mut area = TextObject::point(Point::new(dx + 300.0, 400.0), "Area", Default::default()); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 40.0)) }; + out.push(("area type", Node::new(d.alloc_id(), NodeKind::Text(Box::new(area))))); + let line = Node::path(d.alloc_id(), shapes::line(Point::new(dx, 700.0), Point::new(dx + 400.0, 700.0)), Appearance::default_art()); + let (a, b) = (rect(d, Rect::new(dx + 50.0, 600.0, dx + 70.0, 620.0)), rect(d, Rect::new(dx + 100.0, 600.0, dx + 120.0, 620.0))); + let rec = ObjectsOnPath::new(line.id, &[&a, &b], CENTER, 0.0); + let mut on_path = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(line), Arc::new(a), Arc::new(b)], clip: false }); + on_path.extras_mut().objects_on_path = Some(Box::new(rec)); + place(&mut on_path, &Document::new(1.0, 1.0).symbol_boxes()); + out.push(("objects on path", on_path)); + out.push(("mirror", repeat(d, dx, |s| RepeatSpec::mirror(s, 90.0, 10.0)))); + out.push(("grid", repeat(d, dx, |s| RepeatSpec::grid(s, 20.0, 20.0)))); + out.push(("radial", repeat(d, dx, |s| RepeatSpec::radial(s, 8, Some(100.0))))); + let im = ImageObject { + key: "k".into(), + width: 100, + height: 50, + xf: Affine::translate((dx + 600.0, 600.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let source = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + let mut traced = Node::group(d.alloc_id(), vec![Arc::new(source)]); + traced.extras_mut().trace = Some(Box::new(json!({"view": "split", "split": 0.5}))); + out.push(("trace", traced)); + out.push(("big group", grid_of_rects(d, Point::new(dx + 700.0, 50.0), big, 50))); + out +} + +/// A group of `count` 3 × 3 rectangles, `per_row` to a row, 5 apart, from `at`. +fn grid_of_rects(d: &mut Document, at: Point, count: usize, per_row: usize) -> Node { + let members = (0..count) + .map(|i| { + let (x, y) = (at.x + (i % per_row) as f64 * 5.0, at.y + (i / per_row) as f64 * 5.0); + Arc::new(rect(d, Rect::new(x, y, x + 3.0, y + 3.0))) + }) + .collect(); + Node::group(d.alloc_id(), members) +} + +fn is_empty(widget: &str) -> bool { + matches!(widget, "None" | "[]") || widget == format!("{:?}", Widgets::default()) +} + +/// A document with one artboard that is not locked and, at [`LOCKED_X`], one that is, holding +/// [`objects`] on each, plus an ellipse on a locked layer and a polygon on a hidden one. Each +/// object's name, whether it is on the locked artboard, and its id. +fn mixed(big: usize) -> (Document, Vec<(&'static str, bool, NodeId)>) { + let mut d = Document::new(1000.0, 1000.0); + let mut board = d.artboards[0].clone(); + board.rect = Rect::new(LOCKED_X, 0.0, LOCKED_X + 1000.0, 1000.0); + board.locked = true; + d.artboards.push(board); + let l = d.layers[0].id; + let mut ids = vec![]; + for (dx, on) in [(0.0, false), (LOCKED_X, true)] { + for (name, n) in objects(&mut d, dx, big) { + ids.push((name, on, n.id)); + d.insert(Some(l), 0, n).unwrap(); + } + } + for (name, hide) in [("ellipse", false), ("polygon", true)] { + let layer = d.add_layer(None); + let n = objects(&mut d, 0.0, 0).into_iter().find(|(o, _)| *o == name).map(|(_, n)| n).unwrap(); + ids.push((name, false, n.id)); + d.insert(Some(layer), 0, n).unwrap(); + let layer = d.node_mut(layer).unwrap(); + if hide { + layer.visible = false; + } else { + layer.locked = true; + } + } + (d, ids) +} + +fn selection(ids: &[NodeId]) -> Selection { + let mut s = Selection::default(); + s.set(ids.iter().copied()); + s +} + +/// `doc` with every artboard and layer unlocked and every layer shown: everything in it is +/// editable. +fn all_editable(doc: &Document) -> Document { + let mut free = doc.clone(); + for a in &mut free.artboards { + a.locked = false; + } + for l in doc.layers.iter().map(|l| l.id) { + let n = free.node_mut(l).unwrap(); + (n.visible, n.locked) = (true, false); + } + free +} + +/// Every widget gives what it gave when it asked about editability first: for an editable object, +/// what it gives with everything editable, and for one that is not, what it gives without it. +#[test] +fn the_widgets_are_the_same_as_when_editability_came_first() { + let (doc, ids) = mixed(20); + let free = all_editable(&doc); + let all: Vec = ids.iter().map(|o| o.2).collect(); + let mut selections: Vec> = all.iter().map(|id| vec![*id]).collect(); + selections.extend(all.windows(2).map(<[NodeId]>::to_vec)); + selections.extend([all.clone(), all.iter().rev().copied().collect(), vec![], vec![NodeId(u64::MAX)]]); + let editable = doc.editable(); + for ids in &selections { + let sel = selection(ids); + let kept = selection(&ids.iter().copied().filter(|id| editable(*id)).collect::>()); + let p = pointer(&doc, ids); + for (name, single, _, f) in SITES { + // A widget of one object only shows for a selection of one, editable or not. + let old = f(&free, if single && ids.len() != 1 { &sel } else { &kept }, p); + assert_eq!(f(&doc, &sel, p), old, "{name} of {ids:?}"); + } + } + // Each widget shows for an object of its kind off the locked artboard and not on it, so the + // comparison is not of empty results alone. + for (name, _, has, f) in SITES { + for on in [false, true] { + let (_, _, id) = ids.iter().find(|o| o.0 == has && o.1 == on).unwrap(); + let w = f(&doc, &selection(&[*id]), pointer(&doc, &[*id])); + assert_eq!(is_empty(&w), on, "{name} of the {has} (on the locked artboard: {on}): {w}"); + } + } +} + +/// An object of another kind is not measured for the locked artboard, alone or with others; an +/// object of the widget's kind still is, and its widget is left out. +#[test] +fn widgets_measure_no_art_for_objects_of_other_kinds() { + let (doc, ids) = mixed(500); + let id = |name: &str, on: bool| ids.iter().find(|o| o.0 == name && o.1 == on).map(|o| o.2).unwrap(); + let big = id("big group", true); + let others = [big, id("rectangle", true), id("area type", true), id("trace", true)]; + let mut measured = vec![]; + for (name, single, has, f) in SITES { + let several: Vec = others.iter().copied().filter(|o| *o != id(has, true)).collect(); + for ids in [vec![big], several] { + if single && ids.len() != 1 { + continue; + } + let before = locked_artboard_measures(); + std::hint::black_box(f(&doc, &selection(&ids), pointer(&doc, &ids))); + if locked_artboard_measures() != before { + measured.push(format!("{name} of {ids:?}")); + } + } + let before = locked_artboard_measures(); + std::hint::black_box(f(&doc, &selection(&[id(has, true)]), pointer(&doc, &[id(has, true)]))); + assert!(locked_artboard_measures() > before, "{name} of a {has} on the locked artboard"); + } + assert_eq!(measured, Vec::::new()); +} + +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn cpu_time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// Timings of each widget for a group of 5,000 rectangles and for 128 rectangles, selected on a +/// locked artboard and with no artboard locked, 100 calls a run: with the editability check first +/// (the selection's editable objects are kept, then the widget is asked about them in the document +/// with everything editable, as in [`the_widgets_are_the_same_as_when_editability_came_first`]), +/// and as the widgets are now. 7 runs each, in turn. Ignored by default; it prints the median per +/// call and sets no bound on it: +/// `cargo test --release -p vectorcraft-tools --lib widget_order_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn widget_order_perf() { + const RUNS: usize = 7; + const CALLS: usize = 100; + eprintln!("widget_order_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + let (mut locked, _) = mixed(0); + let l = locked.layers[0].id; + let group = grid_of_rects(&mut locked, Point::new(LOCKED_X, 0.0), 5000, 100); + let group_id = group.id; + locked.insert(Some(l), 0, group).unwrap(); + let mut rects = vec![]; + for i in 0..128 { + let (x, y) = (LOCKED_X + (i % 16) as f64 * 60.0, 600.0 + (i / 16) as f64 * 40.0); + let n = rect(&mut locked, Rect::new(x, y, x + 30.0, y + 30.0)); + rects.push(n.id); + locked.insert(Some(l), 0, n).unwrap(); + } + let unlocked = all_editable(&locked); + for (doc, board) in [(&locked, "locked artboard"), (&unlocked, "no artboard locked")] { + for (what, ids) in [("a group of 5,000", vec![group_id]), ("128 rectangles", rects.clone())] { + timings(doc, &selection(&ids), &format!("{what}, {board}")); + } + } + + fn timings(doc: &Document, sel: &Selection, case: &str) { + // The widgets' own editability checks find nothing locked here, so each object's + // editability is measured once, as when it came first. + let free = all_editable(doc); + for (name, single, _, f) in SITES { + if single && sel.objects.len() != 1 { + continue; + } + let p = pointer(doc, &sel.objects); + let before = || { + for _ in 0..CALLS { + let editable = doc.editable(); + let kept = selection(&sel.objects.iter().copied().filter(|id| editable(*id)).collect::>()); + std::hint::black_box(f(std::hint::black_box(&free), &kept, p)); + } + }; + let after = || { + for _ in 0..CALLS { + std::hint::black_box(f(std::hint::black_box(doc), sel, p)); + } + }; + let (mut old, mut new) = (vec![], vec![]); + for run in 0..RUNS { + // The two take turns going first. + if run % 2 == 0 { + old.push(cpu_time(before)); + new.push(cpu_time(after)); + } else { + new.push(cpu_time(after)); + old.push(cpu_time(before)); + } + } + old.sort(); + new.sort(); + let us = |d: std::time::Duration| d.as_secs_f64() * 1e6 / CALLS as f64; + eprintln!("{name}, {case}: {:.2} µs a call with the check first, {:.2} µs without", us(old[RUNS / 2]), us(new[RUNS / 2])); + } + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 8f6deb6172..746d441236 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -957,7 +957,8 @@ link, and `graphicStyle.apply` with `add` unlinks the group. With `appearance.tr target group's paths keeps its look on a move, and a `source` that is the group's only path is an error. `graphicStyle.redefine` gives the style to the paths directly in a series group linked to it, whether or not the group has rows of its own, links them, and clears and unlinks the group; the source and the paths linked to the style whose -look was edited keep their look. Read as a source, by `graphicStyle.new`, `graphicStyle.redefine` or +look was edited keep their look, and a path in the group linked to another style keeps its look and its link. Read as a +source, by `graphicStyle.new`, `graphicStyle.redefine` or `appearance.transfer`, a series group that has no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own gives the look and the style link of the topmost path directly in it, and a move with `appearance.transfer` clears each of those paths; a series group that has one of them is read itself. @@ -7582,16 +7583,22 @@ or breaks these rules, opens with the image placed by its transform. A drag is o the corners 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`) and Place with -Replace (`file.place` with `replace`) of anything but a text file refuse a distorted image with an error that names the -distortion; Place with Replace does not refuse a clipping group that holds a distorted image of a DCS file's plates. Relink and Unembed refuse a named or selected distorted image before they search a folder or write a file. -Create Gradient Mesh (`object.mesh.create`) converts the other objects it is given and lists each distorted image it -leaves as it is in `skipped`, with its `id` and the error as `reason`; with nothing else to convert, it returns that -error. 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 -result. These rules are VectorCraft's own. +Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`), Create Object Mosaic +(`object.createObjectMosaic`) and Place with Replace (`file.place` with `replace`) of anything but a text file refuse a +distorted image with an error that names the distortion; Place with Replace does not refuse a clipping group that holds +a distorted image of a DCS file's plates. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is +given and lists each distorted image it leaves as it is in `skipped`, with its `id` and the error as `reason`; with +nothing else to convert, it returns that error. 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`. 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 +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]]}}} @@ -14560,8 +14567,8 @@ Tools: outside it with a point on it (within a millionth of its radius); it never crosses the first segment, and it touches the two segments at different points. The circle is a new ellipse with the current paint, drawn through three of its points with `shape.circleThroughPoints` so that Align New Objects to Pixel Grid leaves it in place, one - undo step. A circle too small or too large for its three points to give it back in floating point counts as no - circle. Shift pressed or let go during a click counts at the release. With no circle the note shows, a click draws + undo step. A circle too small or too large for its three points to give it back in floating point, or one that + would reach past the canvas (4,000,000 pt from the origin), counts as no circle. Shift pressed or let go during a click counts at the release. With no circle the note shows, a click draws nothing and the first segment stays picked; it also stays when drawing the circle fails or the press on the second segment is canceled (a canceled touch). Escape, an edit, Undo or Redo outside the tool, another document, or a change to the first segment that makes no undo step (a live preview, or one that was canceled) forgets the first diff --git a/docs/plugins.md b/docs/plugins.md index d81eb153e0..7e6dd26185 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -34,7 +34,7 @@ in `crates/engine/src/cmd/plugin.rs`). | `plugin.inspect` | as `plugin.install`: `{"path"}` or `{"dataBase64", "name"?}` | Validates a module without installing it; returns the `plugin.list` entry it would have, plus `needsApproval` (true when installing it needs a person's approval), `needsReplace` (true when `plugin.install` needs `replace: true`), and the `commandAllowlist` ids no command has (`unknownCommands`) and those no plug-in may call (`refusedCommands`). | | `plugin.remove` | `{"id"}` | Uninstalls, and deletes it from the `Plug-ins` folder with its [settings and cache](#settings-and-cache). | | `plugin.clearCache` | `{"id"?}` | Deletes every entry in the [cache](#settings-and-cache) of plug-in `id`, or of every installed plug-in; settings stay. Returns `{"cleared": [id], "bytesFreed"}`. | -| `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` in a folder; a bad module is reported and skipped, and so are a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). | +| `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` in a folder, the first 1,000 by file name; a bad module is reported and skipped, and so are an entry that is not a regular file, a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). Returns `{"folder", "loaded", "failed": [{file, error}], "leftOut"}`; `leftOut` counts the `*.wasm` files past the first 1,000, which were not tried. | Live effects are applied like any effect: `effect.apply {"effect": "plugin.", "params": {…}}`, edited with `effect.setParams`, listed by `effect.list` (menu `Effect › Plug-ins`) and baked by Object › Expand Appearance. @@ -108,7 +108,10 @@ replaced by a module without it. **Preference folder.** Edit › Preferences › Plug-ins & Scratch Disks › *Additional Plug-ins Folder*: when set, every `*.wasm` in that folder (not recursive) is installed at startup and whenever the preference changes (desktop builds; the web build installs from bytes). On the desktop, Choose… beside the field picks the folder; the dialog refuses a -picked or typed folder whose contents can't be listed, and `prefs.set` refuses such a folder too. +picked or typed folder whose contents can't be listed, and `prefs.set` refuses such a folder too. A folder load reads at +most 1,000 `.wasm` files, the first ones by file name (VectorCraft's own limit); its report counts the files left out +(`leftOut`). An entry that is not a regular file, such as a subfolder or a named pipe with a `.wasm` name, is listed in +the report and skipped, and the load does not wait on a named pipe. Plug-ins are installed **per process**, not per document. Documents store a live effect as an ordinary effect record (`{"id": "plugin.", "params": {…}}`): while the plug-in is installed it is drawn, exported and expanded; without it @@ -684,7 +687,8 @@ every attribute: `"unknown"`, read from the image itself. An image whose corners Perspective Distort or Free Distort moved to a shape that is not 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 then the affine placement nearest them, the one that matches the - perspective at the middle of its pixels. An embedded image whose pixels take at most 1 MiB in base64 (443 × 443 + perspective at the middle of its pixels. 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5b85e0c926..f8a3dc84a0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1195,7 +1195,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). - The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`). - 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 when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); 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 (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); 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`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; 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 when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); 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 (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); 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`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; 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`). - With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`). - 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). @@ -2128,7 +2128,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A graphic style dragged onto the Graphic Styles panel's New Graphic Style button is duplicated, as the panel menu's Duplicate Graphic Style does, and both put the copy at the end of the list, as the help page describes ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=391)). VectorCraft's own rules: the button takes the drop with no art selected; a dragged style that is highlighted brings the other highlighted styles, copied in panel order in one undo step, and the copies are highlighted; the copy is named ` copy`, with a number when that is taken, and no art is linked to it (`a_style_dropped_on_new_graphic_style_is_duplicated_at_the_end` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step`). A graphic style dragged onto the Graphic Styles panel's Delete Graphic Style button is deleted, which the help page gives as another way to delete a style besides the panel menu's Delete Graphic Style; art that used the style keeps its look and is no longer linked to it ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=392)). VectorCraft's own rules: the drop asks first as the button does, and with Alt held it deletes without asking; the button takes the drop with no style highlighted; a dragged style that is highlighted brings the other highlighted styles, deleted in one undo step (`a_style_dropped_on_delete_graphic_style_is_deleted_as_the_button_deletes` in `crates/ui-egui/src/panels/graphic_styles.rs`). The Appearance panel's thumbnail dropped on a graphic style with Alt held replaces that style with the look of the object the panel shows; the style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: art dragged off the canvas does the same with its first object; the style keeps its place in the list, is outlined while one is held over it with Alt, and the replacement is one undo step; an object already linked to the style with its look changes nothing; without Alt the drop makes a new style (`art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`). - A graphic style dragged onto another style in the Graphic Styles panel with Alt held gives that style the dragged style's look; the replaced style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: the dragged style and the art linked to it stay as they are; the replaced style keeps its place in the list and is outlined while a style is held over it with Alt; the replacement is one undo step; a style dropped on itself, or on a style with the same look, changes nothing and records no undo step; without Alt the style moves (`graphicStyle.redefine {name, from}`, `a_style_dropped_on_another_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::redefine_from_a_style_gives_the_style_that_look`). + A graphic style dragged onto another style in the Graphic Styles panel with Alt held gives that style the dragged style's look; the replaced style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: the dragged style and the art linked to it stay as they are, including a path linked to the dragged style inside a graph series group that uses the replaced style; the replaced style keeps its place in the list and is outlined while a style is held over it with Alt; the replacement is one undo step; a style dropped on itself, or on a style with the same look, changes nothing and records no undo step; without Alt the style moves (`graphicStyle.redefine {name, from}`, `a_style_dropped_on_another_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::redefine_from_a_style_gives_the_style_that_look`, `cmd::graph::tests::redefining_a_graphic_style_from_another_style_keeps_a_mark_linked_to_it`). As VectorCraft's own rule, Redefine Graphic Style from an object also leaves a path inside such a series group, or a line or label inside a graph's Axes or Legend group that uses the style, with its look and its link when it is linked to another style (`redefining_a_graphic_style_from_an_object_keeps_a_mark_linked_to_another_style`, `redefining_a_graphic_style_keeps_a_legend_label_linked_to_another_style`). In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`). In the Graphic Styles panel's thumbnail and list views, right-clicking a style item opens its context menu offering Graphic Style Options…, Duplicate Graphic Style (or Duplicate Graphic Styles when multiple styles are selected), Delete Graphic Style (or Delete Graphic Styles), Redefine Graphic Style (enabled when canvas art is selected), and Break Link to Graphic Style (enabled when the selection is linked to this style). Right-clicking an unselected style selects it first, while right-clicking an item in an existing multi-selection preserves the multi-selection. Default Graphic Style disables Options and Delete. Secondary button hold still triggers large preview on tiles/rows. Tests: `right_click_context_menu_in_graphic_styles_panel`, `right_click_context_menu_default_style_disables_options_and_delete`, and `right_click_context_menu_preserves_multiselection_and_works_in_list_view` in `crates/ui-egui/src/panels/graphic_styles.rs`. Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`). @@ -2499,6 +2499,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The contour passes of the two-path boolean operations, Offset Path, compound shapes and Intertwine test the list of shapes that cover each face instead of a flag for every shape, so each test's time follows how many shapes cover the face rather than how many shapes there are. The contours, their order and the output are the same. The many-shape boolean that compound shapes use takes 0.75 to 0.83 billion CPU cycles on its thread instead of 1.28 to 1.33 billion to unite 10,000 squares that do not touch, and 2.27 to 2.30 billion instead of 2.43 to 2.47 billion for 1,500 members of two squares each over 3,000 overlapping squares (dev build, six runs of each, alternating, while other builds were running). Pathfinder › Unite and the other commands that unite filled paths sweep a single input once instead of twice when its own sweep neither splits nor drops any of its segments and no two of its segments lie within twice the sweep tolerance. The output is the same. Unite on one compound path of 4,000 rings takes 485 to 542 ms instead of 872 to 1,008 ms, and on one zigzag polygon of 20,000 teeth 70 to 76 ms instead of 118 to 130 ms (release build, medians of three alternating rounds of five runs, while other builds were running). With more than 10,000 type on a path objects selected, the Selection and Direct Selection tools neither draw nor hit-test the objects' brackets. + The on-canvas widgets of the selection (the type, pie, side count and corner widgets, the Objects on Path, Mirror, Grid and Radial Repeat controls, the Image Trace Split divider and the center point) first check that an object is of a kind that has the widget, and only then whether it is editable, which on a locked artboard measures the art of the layer object holding it. The widgets shown are the same. With a group of 5,000 rectangles selected on a locked artboard, each widget took 2.1 to 2.3 ms of thread CPU time a call with the editability check first and under 0.01 ms without it (Linux x86_64, optimized test build, median of 7 runs of 100 calls; `widget_order_perf` in `crates/tools`). With no artboard locked, both orders take under 0.01 ms a call for that group. The renderer outlines the stroke of a path object with more than 1,024 path elements, without dashes or a width profile, only in and around the view, with a margin of the view's size on each side, and outlines it again when the view moves past that margin. The pixels are the same. At 1600 × 1200, the frame after one anchor of an open path of 200,000 anchors moves takes 28 to 30 ms instead of 103 ms, and with a closed path of 50,000 anchors 10 ms instead of 30 ms (`cargo run --release -p vectorcraft-engine --example anchor_bench`). The renderer outlines a dashed stroke of such a path the same way, without a width profile, and draws its dashes and dots in the same places as when the whole path is dashed, so the pixels are the same. A pattern too fine to draw is drawn solid, as before, and its stroke is outlined near the view too. At 1600 × 1200, the frame after one anchor moves takes 14 ms instead of 102 ms with a filled closed path of 50,000 anchors and a stroke of 6 pt dashes and 4 pt gaps (`cargo run --release -p vectorcraft-engine --example anchor_bench`, which now includes that document). When anchors of a path or compound path of 1,024 anchors or more are added or deleted, or a subpath is closed or opened, the next frame writes again only the path elements from the first anchor that changed to the last, and the closing segment when an end anchor changed or the subpath was closed or opened. It measures again only the runs of segments that held them; a run grows or shrinks with the segments added or deleted, and one that grows past 256 segments is split. When a member gains or loses subpaths, the renderer makes the path of that member again. When a compound path gains or loses members, it makes the path of those members and of every member between the first and the last of them again. An edit that adds or deletes anchors in, closes or opens more than 16 subpaths makes the whole path again. The pixels and the cull bounds are the same. @@ -2994,7 +2995,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## Path Precision Tools add-on: Tangent Circle Tool (2026-11-17) -A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, and circles too small or too large for three of their points to give them back in floating point; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13)